repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
Gonaz/keras-tuner
|
[
"f8264811d4744abb4f0fdab480e8a4e6ddf91c4e"
] |
[
"tutorials/tunable_xception_cifar10/tunable_xception_cifar10.py"
] |
[
"# Copyright 2019 The Keras Tuner 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\n\"\"\"Example on how to use Tunable Xception.\"\"\"\n\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.datasets import cifar10\nfrom kerastuner.applications import HyperXception\nfrom kerastuner import RandomSearch\n\n# Import the Cifar10 dataset.\nNUM_CLASSES = 10\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\ny_train = to_categorical(y_train, NUM_CLASSES)\ny_test = to_categorical(y_test, NUM_CLASSES)\n\n# Import an hypertunable version of Xception.\nhypermodel = HyperXception(\n input_shape=x_train.shape[1:],\n classes=NUM_CLASSES)\n\n# Initialize the hypertuner: we should find the model that maximixes the\n# validation accuracy, using 40 trials in total.\ntuner = RandomSearch(\n hypermodel,\n objective='val_accuracy',\n max_trials=40,\n project_name='cifar10_xception',\n directory='test_directory')\n\n# Display search overview.\ntuner.search_space_summary()\n\n# Performs the hypertuning.\ntuner.search(x_train, y_train, epochs=10, validation_split=0.1)\n\n# Show the best models, their hyperparameters, and the resulting metrics.\ntuner.results_summary()\n\n# Retrieve the best model.\nbest_model = tuner.get_best_models(num_models=1)[0]\n\n# Evaluate the best model.\nloss, accuracy = best_model.evaluate(x_test, y_test)\nprint('loss:', loss)\nprint('accuracy:', accuracy)\n"
] |
[
[
"tensorflow.keras.utils.to_categorical",
"tensorflow.keras.datasets.cifar10.load_data"
]
] |
willprice/pytorch-lightning
|
[
"94bba4059ce3dc13799d0fd59592f3bcfbbf19c4"
] |
[
"pytorch_lightning/accelerators/ddp2_backend.py"
] |
[
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License\n\nimport os\n\nimport torch\n\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.utilities import AMPType\nfrom pytorch_lightning.utilities.distributed import rank_zero_only\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom pytorch_lightning.core.step_result import Result\nfrom pytorch_lightning.accelerators.base_backend import Accelerator\n\ntry:\n from hydra.utils import to_absolute_path, get_original_cwd\n from hydra.core.hydra_config import HydraConfig\nexcept ImportError:\n HYDRA_AVAILABLE = False\nelse:\n HYDRA_AVAILABLE = True\n\ntry:\n from apex import amp\nexcept ImportError:\n amp = None\n\n\nclass DDP2Backend(Accelerator):\n\n def __init__(self, trainer):\n super().__init__(trainer)\n self.task_idx = None\n\n def setup(self, model):\n self._resolve_task_idx()\n\n self.trainer.model = model\n\n def _resolve_task_idx(self):\n if self.trainer.is_slurm_managing_tasks:\n self.task_idx = int(os.environ['SLURM_LOCALID'])\n else:\n # torchelastic or general non_slurm ddp2\n try:\n self.task_idx = int(os.environ['LOCAL_RANK'])\n except Exception as e:\n m = 'ddp2 only works in SLURM or via torchelastic with the WORLD_SIZE, LOCAL_RANK, GROUP_RANK flags'\n raise MisconfigurationException(m)\n\n def train(self):\n model = self.trainer.model\n self.ddp_train(process_idx=self.task_idx, mp_queue=None, model=model)\n\n def ddp_train(self, process_idx, mp_queue, model, is_master=False, proc_offset=0):\n \"\"\"\n Entry point for ddp\n\n Args:\n process_idx:\n mp_queue: multiprocessing queue\n model:\n is_master:\n proc_offset:\n\n Returns:\n\n \"\"\"\n # offset the process id if requested\n process_idx = process_idx + proc_offset\n\n # show progressbar only on progress_rank 0\n if (self.trainer.node_rank != 0 or process_idx != 0) and self.trainer.progress_bar_callback is not None:\n self.trainer.progress_bar_callback.disable()\n\n self.trainer.local_rank = self.trainer.node_rank\n self.trainer.global_rank = self.trainer.node_rank\n self.trainer.world_size = self.trainer.num_nodes\n\n # set warning rank\n rank_zero_only.rank = self.trainer.global_rank\n\n # set up server using proc 0's ip address\n # try to init for 20 times at max in case ports are taken\n # where to store ip_table\n model.trainer = self.trainer\n model.init_ddp_connection(\n self.trainer.global_rank,\n self.trainer.world_size,\n self.trainer.is_slurm_managing_tasks\n )\n\n # call setup after the ddp process has connected\n self.trainer.call_setup_hook(model)\n\n # on world_size=0 let everyone know training is starting\n if self.trainer.is_global_zero:\n log.info('-' * 100)\n log.info(f'distributed_backend={self.trainer.distributed_backend}')\n log.info(f'All DDP processes registered. Starting ddp with {self.trainer.world_size} processes')\n log.info('-' * 100)\n\n # MODEL\n # copy model to each gpu\n if self.trainer.on_gpu:\n gpu_idx = process_idx\n\n # when using ddp, the master process (proc 0) continues running as the main one\n # this means that the local rank will always be 0\n # (even if cuda visible devices has other visible gpus)\n # this means that the master process needs to pull the 0th visible index as the device number\n if is_master:\n available_gpus = os.environ['CUDA_VISIBLE_DEVICES'].split(',')\n gpu_idx = int(available_gpus[self.trainer.local_rank])\n\n self.trainer.root_gpu = gpu_idx\n torch.cuda.set_device(self.trainer.root_gpu)\n model.cuda(self.trainer.root_gpu)\n\n # CHOOSE OPTIMIZER\n # allow for lr schedulers as well\n optimizers, lr_schedulers, optimizer_frequencies = self.trainer.init_optimizers(model)\n self.trainer.optimizers = optimizers\n self.trainer.lr_schedulers = lr_schedulers\n self.trainer.optimizer_frequencies = optimizer_frequencies\n\n # set model properties before going into wrapper\n self.trainer.copy_trainer_model_properties(model)\n\n # AMP - run through amp wrapper before going to distributed DP\n if self.trainer.amp_backend == AMPType.APEX:\n model, optimizers = model.configure_apex(amp, model, self.trainer.optimizers, self.trainer.amp_level)\n self.trainer.optimizers = optimizers\n self.trainer.reinit_scheduler_properties(self.trainer.optimizers, self.trainer.lr_schedulers)\n\n # DDP2 uses all GPUs on the machine\n device_ids = self.trainer.data_parallel_device_ids\n\n # allow user to configure ddp\n model = model.configure_ddp(model, device_ids)\n\n # set up training routine\n self.trainer.setup_training(model)\n\n # train or test\n results = self.trainer.train_or_test()\n\n # get original model\n model = self.trainer.get_model()\n\n # persist info in ddp_spawn\n self.trainer.transfer_distrib_spawn_state_on_fit_end(model, mp_queue, results)\n\n # clean up memory\n torch.cuda.empty_cache()\n\n def training_step(self, args):\n if self.trainer.amp_backend == AMPType.NATIVE:\n with torch.cuda.amp.autocast():\n output = self.trainer.model(*args)\n else:\n output = self.trainer.model(*args)\n return output\n\n def validation_step(self, args):\n output = self.training_step(args)\n return output\n\n def test_step(self, args):\n output = self.training_step(args)\n return output\n\n def training_step_end(self, output):\n if isinstance(output, Result):\n output.dp_reduce()\n return output\n\n def validation_step_end(self, output):\n if isinstance(output, Result):\n output.dp_reduce()\n return output\n\n def test_step_end(self, output):\n if isinstance(output, Result):\n output.dp_reduce()\n return output\n"
] |
[
[
"torch.cuda.empty_cache",
"torch.cuda.set_device",
"torch.cuda.amp.autocast"
]
] |
jmhernan/NIreland_NLP
|
[
"c360c4978452e80575db2e0eed9ef540ed83b5c6"
] |
[
"class_nn/embeddings_google.py"
] |
[
"######################################################\n### Builds NN using google embeddings, parameters ###\n### Uses: justifications_clean_text_ohe.csv ###\n###### Collapses justifications to 6 categories. ###\n###### Stems and tokenizes words ###\n### Next step: Sarah needs to talk through w Jose ###\n### What is the difference bw this NN and the one ###\n### built by \"baseline_neural_network.py\"? ###\n######################################################\n\nimport numpy as np\nimport pandas as pd\nimport nltk\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.text import Tokenizer\nfrom keras import models\nfrom keras import layers\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.utils import np_utils\nfrom keras import utils\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import Pipeline\nimport os\nfrom nltk.stem import PorterStemmer\nfrom sklearn.model_selection import train_test_split\nfrom gensim.models import KeyedVectors\n\n\n\n## Set the file pathway and download corpus\n\nthis_file_path = os.path.abspath(__file__)\nfolder_root = os.path.split(this_file_path)[0]\nrepo_root = os.path.split(folder_root)[0]\nrepo_path = os.path.join(repo_root)\n\nPATH_TO_GV = os.path.join(folder_root, 'wordvec') + '/'\n\ndf = pd.read_csv(os.path.join(repo_path, 'justifications_clean_text_ohe.csv'))\n\n# Collapse justification categories from 12 to 6 -- approach #2\ndf['just_category_6'] = df['justification_cat']\ndf['just_category_6'] = df['just_category_6'].replace(['J_Emergency-Policy', 'J_Intelligence', 'J_Last-resort', 'J_Utilitarian-Deterrence', 'J_Law-and-order'], 'J_Security')\ndf['just_category_6'] = df['just_category_6'].replace(['J_Legal_Procedure'], 'J_Legal')\ndf['just_category_6'] = df['just_category_6'].replace(['J_Political-Strategic'], 'J_Political')\ndf['just_category_6'] = df['just_category_6'].replace(['J_Denial', 'J_Intl-Domestic_Precedent'], 'J_DenyHRVio') #\ndf['just_category_6'] = df['just_category_6'].replace(['J_Development-Unity'], 'J_Misc')\ndf['just_categories'] = df['just_category_6']\n\n# Create a unique number id for each justification category\ncol = ['just_categories', 'clean_text'] \ndf = df[col]\ndf = df[pd.notnull(df['clean_text'])]\ndf.columns = ['just_categories', 'clean_text']\ndf['category_id'] = df['just_categories'].factorize()[0]\ncategory_id_df = df[['just_categories', 'category_id']].drop_duplicates().sort_values('category_id')\ncategory_to_id = dict(category_id_df.values)\nid_to_category = dict(category_id_df[['category_id', 'just_categories']].values)\ndf.head()\n\n######################################\n### Stem sentences outside of grid ###\n######################################\n\nps = PorterStemmer()\n\ndef stem_sentences(sentence):\n tokens = sentence.split()\n stemmed_tokens = [ps.stem(token) for token in tokens]\n return ' '.join(stemmed_tokens)\n\ndf['stem_text'] = df['clean_text'].apply(stem_sentences)\n\n#############################################\n### Divide into training and testing data ###\n#############################################\n\n#sentences = df['stem_text'].values # include stopwords, stemmed\nsentences = df['clean_text'] # include stopwords, unstemmed\ny = df['just_categories']\n\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(sentences)\nsequences = tokenizer.texts_to_sequences(sentences)\n\nword_index = tokenizer.word_index # word and their token # ordered by most frequent\nprint('Found %s unique tokens.' % len(word_index))\n\nmax_words = 5153 # total words of vocabulary we will consider\n\nnum_words = [len(words.split()) for words in sentences]\nmax_seq_len = max(num_words) + 1\n\nfrom keras.preprocessing.sequence import pad_sequences\n\ntext_tok = pad_sequences(sequences, maxlen=max_seq_len+1)\ntext_tok.shape\nnp.mean(text_tok > 0)\n\nfrom keras.utils import to_categorical\n\nencoder = LabelEncoder()\nencoder.fit(y)\nlabels = encoder.transform(y)\n\nnum_classes = np.max(labels) + 1\nlabels = utils.to_categorical(labels, num_classes)\n\nprint('Shape of data tensor:', text_tok.shape)\nprint('Shape of label tensor:', labels.shape)\n\n# split training data into test, validation\nx_train, x_test, y_train, y_test = train_test_split(text_tok, labels, test_size=0.2, random_state = 42)\n\n# Prepare embedding matrix\nword_vector_dim=100\nvocabulary_size= max_words+1\nembedding_matrix = np.zeros((vocabulary_size, word_vector_dim))\n\nnb_filters = 64\nfilter_size_a = 2\ndrop_rate = 0.5\nmy_optimizer = 'adam'\n\nfrom keras.layers import Input, Embedding, Dropout, Conv1D, GlobalMaxPooling1D, Dense, Concatenate, MaxPooling1D, Flatten\nfrom keras.models import Model, load_model\nfrom keras.layers import SpatialDropout1D\n\nmy_input = Input(shape=(None,))\nembedding = Embedding(input_dim=embedding_matrix.shape[0], input_length=max_seq_len,\n output_dim=word_vector_dim, trainable=True,)(my_input)\n \nx = Conv1D(filters = nb_filters, kernel_size = filter_size_a,\n activation = 'relu',)(embedding)\nx = SpatialDropout1D(drop_rate)(x)\nx = MaxPooling1D(pool_size=5)(x)\nx = Flatten()(x)\nx = Dense(128, activation='relu')(x)\nprob = Dense(6, activation = 'softmax',)(x)\nmodel = Model(my_input, prob)\n \nmodel.compile(loss='categorical_crossentropy', optimizer = my_optimizer,\n metrics = ['accuracy']) \n\nmodel.fit(x_train, y_train, # Target vector\n epochs=20, # Three epochs\n verbose=1, # No output\n batch_size=100, # Number of observations per batch\n validation_data=(x_test, y_test))\n\n# add the google embeddings \n\n# Prepare embedding matrix\nword_vectors = KeyedVectors.load_word2vec_format(PATH_TO_GV + 'GoogleNews-vectors-negative300.bin', binary=True)\n\nword_vector_dim=300\nvocabulary_size= max_words + 1\nembedding_matrix = np.zeros((vocabulary_size, word_vector_dim))\n\nfor word, i in word_index.items():\n if i>=max_words:\n continue\n try:\n embedding_vector = word_vectors[word]\n embedding_matrix[i] = embedding_vector\n except KeyError:\n embedding_matrix[i]=np.random.normal(0,np.sqrt(0.25),word_vector_dim)\n\n\nlen(embedding_matrix)\nembedding_matrix.shape\ntype(embedding_matrix)\n\nnonzero_elements = np.count_nonzero(np.count_nonzero(embedding_matrix, axis=1))\nnonzero_elements / max_words\n\n# Setting parameters for the NN\nnb_filters = 128\nfilter_size_a = 3\ndrop_rate = 0.5\nmy_optimizer = 'adam'\n\nfrom keras.layers import Input, Embedding, Dropout, Conv1D, GlobalMaxPooling1D, Dense, Concatenate, MaxPooling1D, Flatten\nfrom keras.models import Model, load_model\n\n## Build the neural network\n\nmy_input = Input(shape=(max_seq_len+1,))\n\nembedding = Embedding(input_dim=embedding_matrix.shape[0], # vocab size, including the 0-th word used for padding\n output_dim=word_vector_dim,\n weights=[embedding_matrix], # we pass our pre-trained embeddings\n input_length=max_seq_len+1,\n trainable=True\n )(my_input)\n\n# Kernel size is how big your window is. Putting x number of words into the NN together at a time from each sentence.\nx = Conv1D(filters = nb_filters, kernel_size = filter_size_a,\n activation = 'relu',)(embedding)\n\nx = MaxPooling1D(pool_size=5)(x)\n\nx = Flatten()(x)\n\nx = Dense(128, activation='relu')(x)\n\nprob = Dense(6, activation = 'softmax',)(x)\nmodel = Model(my_input, prob)\n \nmodel.compile(loss='categorical_crossentropy', optimizer = my_optimizer,\n metrics = ['accuracy']) \n\nx = model.fit(x_train, y_train, # Target vector\n epochs=20, # Three epochs\n verbose=1, # No output\n batch_size=100, # Number of observations per batch\n validation_data=(x_test, y_test))\n"
] |
[
[
"pandas.notnull",
"numpy.sqrt",
"sklearn.model_selection.train_test_split",
"numpy.max",
"numpy.mean",
"numpy.count_nonzero",
"sklearn.preprocessing.LabelEncoder",
"numpy.zeros"
]
] |
tom01h/deep-learning-from-scratch
|
[
"acb3c31976cd736b4abd21c3e8ab81c3bf0eb9bb"
] |
[
"ch07/train_convnet.py"
] |
[
"# coding: utf-8\nimport sys, os\nsys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定\nimport pickle\nimport time\nimport cupy as cp\n#import numpy as cp\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom dataset.cifar10 import load_cifar10\nfrom simple_convnet import SimpleConvNet\nfrom common.trainer import Trainer\n\n# データの読み込み\n(x_train, t_train), (x_test, t_test) = load_cifar10(normalize=False, flatten=False, one_hot_label=True)\n\nx_train = x_train * 2.0 - 255\nx_test = x_test * 2.0 - 255\n\nif os.path.exists(\"ttarray.pkl\"):\n with open(\"ttarray.pkl\", 'rb') as f:\n t_train = pickle.load(f)\n print(\"Loaded Teacher array!\")\n\n# 処理に時間のかかる場合はデータを削減 \n#train_mask = np.random.choice(x_train.shape[0], 3000)\n#x_train = x_train[train_mask]\n#t_train = t_train[train_mask]\n\nmax_epochs = 25\n\nnetwork = SimpleConvNet(input_dim=(3,32,32),\n conv_param = {'filter_num': (32, 32, 64), 'filter_size': 3, 'pad': 1, 'stride': 1},\n hidden_size=512, output_size=10, weight_init_std=0.01)\n \ntrainer = Trainer(network, x_train, t_train, x_test, t_test,\n epochs=max_epochs, mini_batch_size=100,\n optimizer='Adam', optimizer_param={'lr': 0.001},\n evaluate_sample_num_per_epoch=1000, early_stopping=10)\nstart = time.time()\ntrainer.train()\nelapsed_time = time.time() - start\nprint (\"elapsed_time:{0}\".format(elapsed_time) + \"[sec]\")\n\n# パラメータの保存\nnetwork.save_params(\"params.pkl\")\nprint(\"Saved Network Parameters!\")\n\n# グラフの描画\nmarkers = {'train': 'o', 'test': 's'}\nx = np.arange(trainer.current_epoch)\nplt.plot(x, trainer.train_acc_list, marker='o', label='train', markevery=2)\nplt.plot(x, trainer.test_acc_list, marker='s', label='test', markevery=2)\nplt.xlabel(\"epochs\")\nplt.ylabel(\"accuracy\")\nplt.ylim(0, 1.0)\nplt.legend(loc='lower right')\nplt.show()\n\nnp.set_printoptions(threshold=50)\nprint(np.round(trainer.test_acc_list,3))\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.ylim",
"numpy.set_printoptions",
"matplotlib.pyplot.plot",
"numpy.round",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
stanford-policylab/surveilling-surveillance
|
[
"bbb9a147927a6342eecfe07ffa756b3acdb63f35"
] |
[
"detection/models/detection/yolo/backbone.py"
] |
[
"'''\nABOUT THIS SCRIPT:\nThis is a yolov3 implementation that constructs the appropriate\nyolov3 model layers and performs forward runs as per these modules\n\nThis script is a slightly modified version of the follwoing repo:\nhttps://github.com/eriklindernoren/PyTorch-YOLOv3.git\n\n'''\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom .utils import (slice_boundary,\n parse_model_config,\n to_cpu,\n build_targets)\n\nfrom . import constants as C\n\n\ndef create_modules(module_defs, ignore_width):\n \"\"\"\n Constructs module list of layer blocks from module configuration in module_defs\n \"\"\"\n hyperparams = module_defs.pop(0)\n output_filters = [int(hyperparams[\"channels\"])]\n module_list = nn.ModuleList()\n for module_i, module_def in enumerate(module_defs):\n modules = nn.Sequential()\n\n if module_def[\"type\"] == \"convolutional\":\n bn = int(module_def[\"batch_normalize\"])\n filters = int(module_def[\"filters\"])\n kernel_size = int(module_def[\"size\"])\n pad = (kernel_size - 1) // 2\n modules.add_module(\n f\"conv_{module_i}\",\n nn.Conv2d(\n in_channels=output_filters[-1],\n out_channels=filters,\n kernel_size=kernel_size,\n stride=int(module_def[\"stride\"]),\n padding=pad,\n bias=not bn,\n ),\n )\n if bn:\n modules.add_module(f\"batch_norm_{module_i}\", nn.BatchNorm2d(\n filters, momentum=0.9, eps=1e-5))\n if module_def[\"activation\"] == \"leaky\":\n modules.add_module(f\"leaky_{module_i}\", nn.LeakyReLU(0.1))\n\n elif module_def[\"type\"] == \"maxpool\":\n kernel_size = int(module_def[\"size\"])\n stride = int(module_def[\"stride\"])\n if kernel_size == 2 and stride == 1:\n modules.add_module(\n f\"_debug_padding_{module_i}\", nn.ZeroPad2d((0, 1, 0, 1)))\n maxpool = nn.MaxPool2d(\n kernel_size=kernel_size,\n stride=stride,\n padding=int(\n (kernel_size - 1) // 2))\n modules.add_module(f\"maxpool_{module_i}\", maxpool)\n\n elif module_def[\"type\"] == \"upsample\":\n upsample = Upsample(scale_factor=int(\n module_def[\"stride\"]), mode=\"nearest\")\n modules.add_module(f\"upsample_{module_i}\", upsample)\n\n elif module_def[\"type\"] == \"route\":\n layers = [int(x) for x in module_def[\"layers\"].split(\",\")]\n filters = sum([output_filters[1:][i] for i in layers])\n modules.add_module(f\"route_{module_i}\", EmptyLayer())\n\n elif module_def[\"type\"] == \"shortcut\":\n filters = output_filters[1:][int(module_def[\"from\"])]\n modules.add_module(f\"shortcut_{module_i}\", EmptyLayer())\n\n elif module_def[\"type\"] == \"yolo\":\n anchor_idxs = [int(x) for x in module_def[\"mask\"].split(\",\")]\n # Extract anchors\n anchors = [int(x) for x in module_def[\"anchors\"].split(\",\")]\n anchors = [(anchors[i], anchors[i + 1])\n for i in range(0, len(anchors), 2)]\n anchors = [anchors[i] for i in anchor_idxs]\n num_classes = int(module_def[\"classes\"])\n img_size = int(hyperparams[\"height\"])\n # Define detection layer\n yolo_layer = YOLOLayer(anchors, num_classes, ignore_width, img_size)\n modules.add_module(f\"yolo_{module_i}\", yolo_layer)\n # Register module list and number of output filters\n module_list.append(modules)\n output_filters.append(filters)\n\n return hyperparams, module_list\n\n\nclass Upsample(nn.Module):\n \"\"\" nn.Upsample is deprecated \"\"\"\n\n def __init__(self, scale_factor, mode=\"nearest\"):\n super(Upsample, self).__init__()\n self.scale_factor = scale_factor\n self.mode = mode\n\n def forward(self, x):\n x = F.interpolate(x, scale_factor=self.scale_factor, mode=self.mode)\n return x\n\n\nclass EmptyLayer(nn.Module):\n \"\"\"Placeholder for 'route' and 'shortcut' layers\"\"\"\n\n def __init__(self):\n super(EmptyLayer, self).__init__()\n\n\nclass YOLOLayer(nn.Module):\n \"\"\"Detection layer\"\"\"\n\n def __init__(self, anchors, num_classes, ignore_width=32, img_dim=416):\n super(YOLOLayer, self).__init__()\n self.anchors = anchors\n self.num_anchors = len(anchors)\n self.num_classes = num_classes\n self.ignore_width = ignore_width\n self.ignore_thres = 0.5\n self.mse_loss = nn.MSELoss()\n self.bce_loss = nn.BCELoss()\n self.obj_scale = 1\n self.noobj_scale = 100\n self.metrics = {}\n self.img_dim = img_dim\n self.grid_size = 0 # grid size\n\n def compute_grid_offsets(self, grid_size, cuda=True):\n self.grid_size = grid_size\n g = self.grid_size\n FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n self.stride = self.img_dim / self.grid_size\n # Calculate offsets for each grid\n self.grid_x = torch.arange(g).repeat(\n g, 1).view([1, 1, g, g]).type(FloatTensor)\n self.grid_y = torch.arange(g).repeat(\n g, 1).t().view([1, 1, g, g]).type(FloatTensor)\n self.scaled_anchors = FloatTensor(\n [(a_w / self.stride, a_h / self.stride) for a_w, a_h in self.anchors])\n self.anchor_w = self.scaled_anchors[:, 0:1].view(\n (1, self.num_anchors, 1, 1))\n self.anchor_h = self.scaled_anchors[:, 1:2].view(\n (1, self.num_anchors, 1, 1))\n\n def forward(self, x, targets=None, image_size=416, return_metrics=False):\n # Tensors for cuda support\n FloatTensor = torch.cuda.FloatTensor if x.is_cuda else torch.FloatTensor\n self.img_dim = image_size\n num_samples = x.size(0)\n grid_size = x.size(2)\n\n prediction = (\n x.view(num_samples, self.num_anchors,\n self.num_classes + 5, grid_size, grid_size)\n .permute(0, 1, 3, 4, 2)\n .contiguous()\n )\n\n # Get outputs\n x = torch.sigmoid(prediction[..., 0]) # Center x\n y = torch.sigmoid(prediction[..., 1]) # Center y\n w = prediction[..., 2] # Width\n h = prediction[..., 3] # Height\n pred_conf = torch.sigmoid(prediction[..., 4]) # Conf\n pred_cls = torch.sigmoid(prediction[..., 5:]) # Cls pred.\n\n if grid_size != self.grid_size:\n self.compute_grid_offsets(grid_size, cuda=x.is_cuda)\n\n # Add offset and scale with anchors\n pred_boxes = FloatTensor(prediction[..., :4].shape)\n pred_boxes[..., 0] = x.data + self.grid_x\n pred_boxes[..., 1] = y.data + self.grid_y\n pred_boxes[..., 2] = torch.exp(w.data) * self.anchor_w\n pred_boxes[..., 3] = torch.exp(h.data) * self.anchor_h\n\n # Only keep predictions inside the boundary\n # Note: Due to FPN, predictions across different scales are combined\n # Need to adjust slice boundary accordingly\n assert (grid_size * self.ignore_width) % C.SIZE == 0\n boundary = grid_size * self.ignore_width // C.SIZE\n output = torch.cat(\n (slice_boundary(\n pred_boxes, boundary).view(\n num_samples, -1, 4) * self.stride, slice_boundary(\n pred_conf, boundary).view(\n num_samples, -1, 1), pred_cls.view(\n num_samples, -1, self.num_classes), ), -1, )\n if targets is None:\n return output, 0\n\n iou_scores, obj_mask, noobj_mask, tx, ty, tw, th, tconf =\\\n build_targets(\n pred_boxes=pred_boxes,\n target=targets,\n anchors=self.scaled_anchors,\n ignore_thres=self.ignore_thres,\n )\n\n # Remove the boundary from predictions, ground truth, and masks\n # when computing the loss.\n tensors = [pred_boxes, pred_conf, tconf, x, tx, y, ty,\n w, tw, h, th, iou_scores, obj_mask, noobj_mask]\n (pred_boxes, pred_conf, tconf, x, tx, y, ty,\n w, tw, h, th, iou_scores, obj_mask, noobj_mask) = [\n slice_boundary(tensor, boundary)\n for tensor in tensors\n ]\n # Loss : Mask outputs to ignore non-existing objects (except with conf.\n # loss)\n loss_x = self.mse_loss(x[obj_mask.bool()], tx[obj_mask.bool()])\n loss_y = self.mse_loss(y[obj_mask.bool()], ty[obj_mask.bool()])\n loss_w = self.mse_loss(w[obj_mask.bool()], tw[obj_mask.bool()])\n loss_h = self.mse_loss(h[obj_mask.bool()], th[obj_mask.bool()])\n loss_conf_obj = self.bce_loss(\n pred_conf[obj_mask.bool()], tconf[obj_mask.bool()])\n loss_conf_noobj = self.bce_loss(\n pred_conf[noobj_mask.bool()], tconf[noobj_mask.bool()])\n loss_conf = self.obj_scale * loss_conf_obj + self.noobj_scale * loss_conf_noobj\n\n if obj_mask.bool().sum().item() == 0:\n total_loss = self.noobj_scale * loss_conf_noobj\n else:\n # Ignore useless classification loss\n total_loss = loss_x + loss_y + loss_w + loss_h + loss_conf\n\n if torch.isnan(total_loss).item():\n import pdb\n pdb.set_trace()\n\n if not return_metrics:\n return output, total_loss\n else:\n # Metrics\n conf_obj = pred_conf[obj_mask.bool()].mean()\n conf_noobj = pred_conf[noobj_mask.bool()].mean()\n conf50 = (pred_conf > 0.5).float()\n iou50 = (iou_scores > 0.5).float()\n iou75 = (iou_scores > 0.75).float()\n detected_mask = conf50 * tconf\n precision = torch.sum(iou50 * detected_mask) / \\\n (conf50.sum() + 1e-16)\n recall50 = torch.sum(iou50 * detected_mask) / \\\n (obj_mask.sum() + 1e-16)\n recall75 = torch.sum(iou75 * detected_mask) / \\\n (obj_mask.sum() + 1e-16)\n\n self.metrics = {\n \"loss\": to_cpu(total_loss).item(),\n \"x\": to_cpu(loss_x).item(),\n \"y\": to_cpu(loss_y).item(),\n \"w\": to_cpu(loss_w).item(),\n \"h\": to_cpu(loss_h).item(),\n \"conf\": to_cpu(loss_conf).item(),\n \"recall50\": to_cpu(recall50).item(),\n \"recall75\": to_cpu(recall75).item(),\n \"precision\": to_cpu(precision).item(),\n \"conf_obj\": to_cpu(conf_obj).item(),\n \"conf_noobj\": to_cpu(conf_noobj).item(),\n \"grid_size\": grid_size,\n }\n return output, total_loss, self.metrics\n\n\nclass Darknet(nn.Module):\n \"\"\"YOLOv3 object detection model\"\"\"\n\n def __init__(self, config_path, ignore_width, num_classes=80, img_size=416):\n super(Darknet, self).__init__()\n self.module_defs = parse_model_config(config_path, num_classes)\n self.hyperparams, self.module_list = create_modules(\n self.module_defs, ignore_width)\n self.yolo_layers = [\n layer[0] for layer in self.module_list if hasattr(\n layer[0], \"metrics\")]\n self.img_size = img_size\n self.seen = 0\n self.header_info = np.array([0, 0, 0, self.seen, 0], dtype=np.int32)\n\n def forward(self, x, targets):\n img_dim = x.shape[2]\n loss = 0\n layer_outputs, yolo_outputs = [], []\n for i, (module_def, module) in enumerate(\n zip(self.module_defs, self.module_list)):\n if module_def[\"type\"] in [\"convolutional\", \"upsample\", \"maxpool\"]:\n x = module(x)\n elif module_def[\"type\"] == \"route\":\n x = torch.cat([layer_outputs[int(layer_i)]\n for layer_i in module_def[\"layers\"].split(\",\")], 1)\n elif module_def[\"type\"] == \"shortcut\":\n layer_i = int(module_def[\"from\"])\n x = layer_outputs[-1] + layer_outputs[layer_i]\n elif module_def[\"type\"] == \"yolo\":\n outputs = module[0](x, targets, img_dim)\n x, layer_loss = module[0](x, targets, img_dim)\n loss += layer_loss\n yolo_outputs.append(x)\n layer_outputs.append(x)\n yolo_outputs = to_cpu(torch.cat(yolo_outputs, 1))\n return loss, yolo_outputs\n\n def infer(self, x):\n loss, yolo_outputs = self.forward(x, None)\n return yolo_outputs\n\n def load_darknet_weights(self, weights_path):\n \"\"\"Parses and loads the weights stored in 'weights_path'\"\"\"\n\n # Open the weights file\n with open(weights_path, \"rb\") as f:\n # First five are header values\n header = np.fromfile(f, dtype=np.int32, count=5)\n self.header_info = header # Needed to write header when saving weights\n self.seen = header[3] # number of images seen during training\n weights = np.fromfile(f, dtype=np.float32) # The rest are weights\n\n # Establish cutoff for loading backbone weights\n cutoff = None\n if \"darknet53.conv.74\" in weights_path:\n cutoff = 75\n\n ptr = 0\n for i, (module_def, module) in enumerate(\n zip(self.module_defs, self.module_list)):\n if i == cutoff:\n break\n if module_def[\"type\"] == \"convolutional\":\n conv_layer = module[0]\n if module_def[\"batch_normalize\"]:\n # Load BN bias, weights, running mean and running variance\n bn_layer = module[1]\n num_b = bn_layer.bias.numel() # Number of biases\n # Bias\n bn_b = torch.from_numpy(\n weights[ptr: ptr + num_b]).view_as(bn_layer.bias)\n bn_layer.bias.data.copy_(bn_b)\n ptr += num_b\n # Weight\n bn_w = torch.from_numpy(\n weights[ptr: ptr + num_b]).view_as(bn_layer.weight)\n bn_layer.weight.data.copy_(bn_w)\n ptr += num_b\n # Running Mean\n bn_rm = torch.from_numpy(\n weights[ptr: ptr + num_b]).view_as(bn_layer.running_mean)\n bn_layer.running_mean.data.copy_(bn_rm)\n ptr += num_b\n # Running Var\n bn_rv = torch.from_numpy(\n weights[ptr: ptr + num_b]).view_as(bn_layer.running_var)\n bn_layer.running_var.data.copy_(bn_rv)\n ptr += num_b\n else:\n # Load conv. bias\n num_b = conv_layer.bias.numel()\n conv_b = torch.from_numpy(\n weights[ptr: ptr + num_b]).view_as(conv_layer.bias)\n conv_layer.bias.data.copy_(conv_b)\n ptr += num_b\n # Load conv. weights\n num_w = conv_layer.weight.numel()\n conv_w = torch.from_numpy(\n weights[ptr: ptr + num_w]).view_as(conv_layer.weight)\n conv_layer.weight.data.copy_(conv_w)\n ptr += num_w\n\n def save_darknet_weights(self, path, cutoff=-1):\n \"\"\"\n @:param path - path of the new weights file\n @:param cutoff - save layers between 0 and cutoff (cutoff = -1 -> all are saved)\n \"\"\"\n fp = open(path, \"wb\")\n self.header_info[3] = self.seen\n self.header_info.tofile(fp)\n\n # Iterate through layers\n for i, (module_def, module) in enumerate(\n zip(self.module_defs[:cutoff], self.module_list[:cutoff])):\n if module_def[\"type\"] == \"convolutional\":\n conv_layer = module[0]\n # If batch norm, load bn first\n if module_def[\"batch_normalize\"]:\n bn_layer = module[1]\n bn_layer.bias.data.cpu().numpy().tofile(fp)\n bn_layer.weight.data.cpu().numpy().tofile(fp)\n bn_layer.running_mean.data.cpu().numpy().tofile(fp)\n bn_layer.running_var.data.cpu().numpy().tofile(fp)\n # Load conv bias\n else:\n conv_layer.bias.data.cpu().numpy().tofile(fp)\n # Load conv weights\n conv_layer.weight.data.cpu().numpy().tofile(fp)\n\n fp.close()\n"
] |
[
[
"torch.nn.Sequential",
"torch.sigmoid",
"numpy.fromfile",
"torch.isnan",
"torch.cat",
"torch.nn.ModuleList",
"torch.sum",
"torch.from_numpy",
"torch.arange",
"torch.nn.BCELoss",
"torch.exp",
"torch.nn.LeakyReLU",
"torch.nn.functional.interpolate",
"torch.nn.BatchNorm2d",
"torch.nn.ZeroPad2d",
"numpy.array",
"torch.nn.MSELoss"
]
] |
TopoXLab/TopoCount
|
[
"eb93de2bc40d4421ea39c1b80d5c4c4829f3e369"
] |
[
"my_dataset_test.py"
] |
[
"from torch.utils.data import Dataset\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport cv2\nfrom torchvision import transforms\nimport random\nfrom PIL import Image\nimport glob\n\n\nclass CrowdDataset(Dataset):\n '''\n crowdDataset\n '''\n def __init__(self, img_root, gt_dot_root, split_txt_filepath=None, phase='train', aug=0, normalize=True, fixed_size=-1, max_side=-1):\n '''\n img_root: the root path of images.\n gt_dot_root: the root path of ground-truth dot map.\n phase: train or test\n split_txt_filepath: text file containing list of images to include in the dataset. If none, then use all jpg images in img_root\n '''\n self.img_root=img_root\n self.gt_dot_root=gt_dot_root\n self.phase=phase\n self.split_txt_filepath = split_txt_filepath\n\n if(split_txt_filepath is None):\n self.img_names=[filename for filename in os.listdir(img_root) \\\n if os.path.isfile(os.path.join(img_root,filename))]\n else:\n img_list = np.loadtxt(split_txt_filepath, dtype=str) \n self.img_names=[filename + '.jpg' for filename in img_list[:,0] \\\n if os.path.isfile(os.path.join(img_root,filename+ '.jpg'))]\n\n self.n_samples=len(self.img_names)\n\n self.aug=aug\n self.normalize = normalize;\n self.fixed_size = fixed_size\n self.max_side = max_side\n\n print('self.aug', self.aug)\n print('self.fixed_size', self.fixed_size)\n\n def __len__(self):\n return self.n_samples\n\n def __getitem__(self,index):\n assert index <= len(self), 'index range error'\n img_name=self.img_names[index]\n img=plt.imread(os.path.join(self.img_root,img_name))/255# convert from [0,255] to [0,1]\n \n if len(img.shape)==2: # expand grayscale image to three channel.\n img=img[:,:,np.newaxis]\n img=np.concatenate((img,img,img),2)\n img=img[:,:,0:3]\n\n gtdot_path = os.path.join(self.gt_dot_root,img_name.replace('.jpg','_gt_dots.npy'));\n if(os.path.isfile(gtdot_path)):\n gt_dot=np.load(gtdot_path)\n else:\n gtdot_path = os.path.join(self.gt_dot_root,img_name.replace('.jpg','.npy'));\n if(os.path.isfile(gtdot_path)):\n gt_dot=np.load(gtdot_path)\n else:\n gt_dot=np.zeros((img.shape[0], img.shape[1]))\n\n \n if random.randint(0,1)==1 and self.phase=='train':\n img=img[:,::-1].copy() # horizontal flip\n gt_dot=gt_dot[:,::-1].copy() # horizontal flip\n \n if(self.phase=='train' and self.max_side > 0):\n h = img.shape[0]\n w = img.shape[1]\n h2 = h\n w2 = w\n crop = False\n if(h > self.max_side):\n h2 = self.max_side\n crop = True\n if(w > self.max_side):\n w2 = self.max_side\n crop = True\n if(crop):\n y=0\n x=0\n if(not (h2 ==h)):\n y = np.random.randint(0, high = h-h2)\n if(not (w2 ==w)):\n x = np.random.randint(0, high = w-w2)\n img = img[y:y+h2, x:x+w2, :]\r\n gt_dot = gt_dot[y:y+h2, x:x+w2]\r\n\n \n if ((self.aug > 0 and self.phase=='train')or (self.fixed_size > 0)):\n i = -1\n img_pil = Image.fromarray(img.astype(np.uint8)*255);\n if(self.fixed_size < 0):\n i, j, h, w = transforms.RandomCrop.get_params(img_pil, output_size=(img.shape[0]//4, img.shape[1]//4))\r\n elif(self.fixed_size < img.shape[0] or self.fixed_size < img.shape[1]):\r\n i, j, h, w = transforms.RandomCrop.get_params(img_pil, output_size=(min(self.fixed_size,img.shape[0]), min(self.fixed_size,img.shape[1])))\r\n #print('i, j, h, w',i, j, h, w)\r\n if(i >= 0):\r\n img = img[i:i+h, j:j+w, :]\r\n gt_dot = gt_dot[i:i+h, j:j+w]\r\n\n\n max_scale = 16\n if max_scale>1: # fix image and gt to match model.\n #ds_rows=int(img.shape[0]//max_scale)*max_scale\n #ds_cols=int(img.shape[1]//max_scale)*max_scale\n #img = img[:ds_rows, :ds_cols, :]\n #gt_dmap = gt_dmap[:ds_rows, :ds_cols]\n #gt_dot = gt_dot[:ds_rows, :ds_cols]\n ds_rows=int(img.shape[0]//max_scale)*max_scale\n ds_cols=int(img.shape[1]//max_scale)*max_scale\n pad_y1 = 0\n pad_y2 = 0\n pad_x1 = 0\n pad_x2 = 0\n if(ds_rows < img.shape[0]):\n pad_y1 = (max_scale - (img.shape[0] - ds_rows))//2\n pad_y2 = (max_scale - (img.shape[0] - ds_rows)) - pad_y1\n if(ds_cols < img.shape[1]):\n pad_x1 = (max_scale - (img.shape[1] - ds_cols))//2\n pad_x2 = (max_scale - (img.shape[1] - ds_cols)) - pad_x1\n img = np.pad(img, ((pad_y1,pad_y2),(pad_x1,pad_x2),(0,0)), 'constant', constant_values=(1,) )# padding constant differs by dataset based on bg color\n gt_dot = np.pad(gt_dot, ((pad_y1,pad_y2),(pad_x1,pad_x2)), 'constant', constant_values=(0,) )# padding constant differs by dataset based on bg color\n\n gt_dot=gt_dot[np.newaxis,:,:]\n gt_dot_tensor=torch.tensor(gt_dot,dtype=torch.float)\n\n img=img.transpose((2,0,1)) # convert to order (channel,rows,cols)\n img_tensor=torch.tensor(img,dtype=torch.float)\n if(self.normalize):\n img_tensor=transforms.functional.normalize(img_tensor,mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n return img_tensor,gt_dot_tensor,img_name\n\n\n"
] |
[
[
"numpy.pad",
"torch.tensor",
"numpy.concatenate",
"numpy.load",
"numpy.zeros",
"numpy.loadtxt",
"numpy.random.randint"
]
] |
guoshuhong/yolo4_SVHN
|
[
"fb91d5c21a3ff2b6f8e977e7de5b91b1ecf3394e"
] |
[
"predict.py"
] |
[
"#-------------------------------------#\n# 对单张图片进行预测\n#-------------------------------------#\nfrom yolo import YOLO\nfrom PIL import Image\nimport os\nimport time\nimport pandas as pd\nimport numpy as np\n\nyolo = YOLO()\n\nwhile True:\n filelist = os.listdir()\n img = input('Input image filename:')\n try:\n image = Image.open(img)\n except:\n print('Open Error! Try again!')\n continue\n else:\n r_image = yolo.detect_image(image)\n r_image.show()\n\n# TIANCHI\n# filelist = os.listdir(\"mchar_test_a\")\n# cnt = -1\n# test_label_pred = [\"123\"]*40000\n# for img in filelist:\n# try:\n# image = Image.open(\"mchar_test_a/\" + img)\n# except:\n# print('Open Error! Try again!')\n# continue\n# else:\n# cnt += 1\n# print(cnt)\n# # if cnt == 10 :\n# # break\n# # r_image = yolo.detect_image(image ,test_label_pred, cnt)\n# test_label_pred = yolo.detect_image(image ,test_label_pred, cnt)\n# # time.sleep(2)\n# # r_image.show()\n\ndf_submit = pd.read_csv('mchar_sample_submit_A.csv')\ndf_submit['file_code'] = test_label_pred\ndf_submit.to_csv('submit9-12.csv', index=None)"
] |
[
[
"pandas.read_csv"
]
] |
EivindFa/benfords_law
|
[
"6f2a0ab3f63d21b2caeef8f54922972b10d2b1b7"
] |
[
"benford.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport math\nfrom scipy import stats\n\n# data source: https://ourworldindata.org/coronavirus-source-data\n\n\ndef setup(csv_filename, country):\n df = pd.read_csv(csv_filename)\n df = df.loc[: , [\"location\", \"date\", \"new_cases\" ]]\n df = df[df[\"location\"] == country]\n # Data prep\n df = df[df[\"new_cases\"].notna()] # remove not a number-rows\n df = df[df[\"new_cases\"] > 0]\n df.drop_duplicates()\n print(df.head())\n return df\n\ndef statistics(df):\n print(\"Dataset size\", len(df[\"new_cases\"].tolist())) \n\ndef calculate_first_digit(df):\n new_cases = df[\"new_cases\"]\n first_digit = []\n for row in df[\"new_cases\"]: # get first digit\n try:\n first_digit.append(int(str(row)[:1]))\n except:\n first_digit.append(0)\n print(row)\n df[\"first_digit\"] = first_digit\n df = df.drop(df[df.first_digit <= 0].index) # drop rows with 0 values\n n = len(df[\"first_digit\"].tolist())\n count_first_digit = df[\"first_digit\"].value_counts(sort=False)#count number of 1's, 2's, 3's and so on\n count_first_digit.to_frame().to_numpy()\n total_count = count_first_digit.sum() # number of numbers in list. Equal to len(df[\"first_digit\"].tolist())\n percentage = []\n for elem in count_first_digit:\n p = float(\"{:.4f}\".format( elem / total_count))\n percentage.append(p)\n x = np.linspace(1,9,9)\n percentage = dict(zip(x, percentage))\n return df, percentage\n\ndef calculate_first_two_digits(df):\n first_two = []\n for row in df[\"new_cases\"]:\n temp_int = int(row*10)\n first_two.append(int(str(temp_int)[:2]))\n df[\"first_two\"] = first_two\n\n count_first_two = df[\"first_two\"].value_counts(sort=False)[1:]\n print(count_first_two)\n count_first_two.to_numpy()\n total_count = count_first_two.sum()\n percentage = []\n for elem in count_first_two:\n percentage.append(float(\"{:.4f}\".format( elem / total_count)))\n return df, percentage\n\ndef plot_figure(percentage, perfect_benford):\n _x = np.linspace(1, 9, 9)\n plt.plot(_x,percentage, label=\"first digit benford\") # calculated perfentage\n plt.plot(_x, list(perfect_benford.values()), label=\"perfect benford\")\n plt.xlabel(\"Digits\")\n plt.ylabel(\"Percentage\")\n plt.legend()\n plt.show()\n\ndef get_perfect_benford():\n x = np.linspace(1,9,9)\n y = [0.31, 0.176, 0.125, 0.097,0.079, 0.067, 0.058, 0.051, 0.046]\n return dict(zip(x,y))\n\ndef pearson_coefficient(list_a, list_b):\n assert (len(list_a) != 0)\n assert (len(list_b) != 0) # list b is perfect benford\n sum_a = sum(list_a)\n sum_b = sum(list_b)\n mean_a = float(sum_a / len(list_a))\n mean_b = float(sum_b / len(list_b))\n list_mean_a = [(x - mean_a) for x in list_a]\n list_mean_b = [(y - mean_b) for y in list_b]\n numerator = sum(x * y for x,y in zip(list_mean_a, list_mean_b))\n denominator = math.sqrt(sum(x*x for x in list_mean_a) * sum(y * y for y in list_mean_b))\n if (denominator != 0):\n p_value = numerator / denominator\n else: \n p_value = 0\n print(\"------ Pearson coefficient --------\")\n print(p_value)\n return p_value\n\ndef mantissa_arc_test(list_a):\n \"\"\"\n The mantissa arc test. \n :parm list_a: df[\"new_cases\"]\n :return: p-value and a plot\n \"\"\" \n x_coordinates = [(math.cos(2*math.pi * (math.log10(x) % 1))) for x in list_a] # abscissa - x-coordinate for the mantissa\n y_coordinates = [(math.sin(2*math.pi * (math.log10(x) % 1))) for x in list_a] # ordinate\n\n x_nominator = sum(math.cos(2*math.pi * (math.log10(x) % 1)) for x in list_a)\n y_nominator = sum(math.sin(2*math.pi * (math.log10(x) % 1)) for x in list_a)\n x_coordinate = x_nominator / len(list_a) # Center of mass\n y_coordinate = y_nominator / len(list_a) # Center of mass\n\n L_squared = (x_coordinate)**2 + (y_coordinate)**2 \n p_value = 1 - math.exp(-L_squared * len(list_a))\n print(\"--------- p-value ---------\")\n print(p_value)\n \n ''' Plotting '''\n plt.scatter(x_coordinates, y_coordinates)\n plt.plot(x_coordinate, y_coordinate, 'o', color=\"red\") # center of mass\n plt.axhline(y=0, color='k')\n plt.axvline(x=0, color='k')\n plt.show()\n\n### TODO: implement chi-squared\ndef chi_squared(df, perfect_benford):\n ''' \n #observed, expected ....\n H0: status_que_hypothesis\n '''\n sample_size = len(df[\"new_cases\"].tolist())\n benford_distribution = [sample_size*x for x in perfect_benford] # expected distribution\n count_first_digit = df[\"first_digit\"].value_counts(sort=False)\n residual_squared = [math.pow(x-y, 2) / y for x,y in zip(count_first_digit, benford_distribution)]\n degrees_of_freedom = (9-1)*(2-1)\n p_value= stats.chi2.pdf(sum(residual_squared), degrees_of_freedom)\n print(\"chi squared p-value: \",p_value)\n #print(\"residual\", residual)\n #print(benford_distribution) \n #print(\"Not implemented yet\")\n \n\n\ndef main():\n df = setup(\"owid-covid-data.csv\",\"Belgium\") #csv_filename, country\n statistics(df) # Get info about the dataset\n df, percentage = calculate_first_digit(df)\n print(df.head())\n chi_squared(df, list(get_perfect_benford().values()))\n pearson = pearson_coefficient(list(percentage.values()), get_perfect_benford())\n mantissa_arc_test(df[\"new_cases\"].tolist())\n plot_figure(list(percentage.values()), get_perfect_benford())\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.axvline",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
yanzhicong/realistic-ssl-evaluation-pytorch
|
[
"d0ea3349765f8642e97dce57cf319f703b7f1e42"
] |
[
"test_dataset.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport argparse, math, time, json, os\n\nfrom lib import wrn, transform\nfrom config import config\nimport vis\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--dataset\", \"-d\", default=\"cifar10\", type=str, help=\"dataset name : [svhn, cifar10]\")\nparser.add_argument(\"--root\", \"-r\", default=\"data\", type=str, help=\"dataset dir\")\nparser.add_argument(\"--poison-data-ratio\", default=0.0, type=float)\n\n\n\n\nargs = parser.parse_args()\n\n\n\nplotter = vis.Plotter()\n\nprint(\"dataset : {}\".format(args.dataset))\n\n\ndataset_cfg = config[args.dataset]\n\nl_train_dataset = dataset_cfg[\"dataset\"](args.root, \"l_train\")\nu_train_dataset = dataset_cfg[\"dataset\"](args.root, \"u_train\")\n\n\nimages = l_train_dataset.dataset['images']\nlabels = l_train_dataset.dataset['labels']\n\nprint(images.shape, images.dtype, np.max(images), np.min(images))\nprint(labels.shape, labels.dtype, np.unique(labels), np.max(labels), np.min(labels))\n\nfor c in np.unique(labels):\n print(\"\\t{} : {}\".format(c, np.sum(labels == c)))\n\nimages = u_train_dataset.dataset['images']\nlabels = u_train_dataset.dataset['labels']\n\nprint(images.shape, images.dtype, np.max(images), np.min(images))\nprint(labels.shape, labels.dtype, np.unique(labels), np.max(labels), np.min(labels))\n\nfor c in np.unique(labels):\n print(\"\\t{} : {}\".format(c, np.sum(labels == c)))\n\n\n\n"
] |
[
[
"numpy.max",
"numpy.min",
"numpy.sum",
"numpy.unique"
]
] |
ylsung/VL_adapter
|
[
"287409f383f89a11764fc45806864693a4d3e498",
"1799110fe55ad3badc031fe2a3718c1ba61b4fc5"
] |
[
"CLIP-ViL/clip/model.py",
"VL-T5/src/refcoco_model.py"
] |
[
"from collections import OrderedDict\nfrom typing import Tuple, Union\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\n\nclass VisualAdapter(nn.Module):\n \"\"\"Conventional Adapter layer, in which the weights of up and down sampler modules\n are parameters and are optimized.\"\"\"\n\n def __init__(self, input_dim, output_dim, adapter_kind, reduction_factor=16, use_bn=True, use_gate=True):\n super().__init__()\n self.adapter_kind = adapter_kind\n self.use_bn = use_bn\n\n if use_gate:\n self.gate = nn.Parameter(torch.zeros(1))\n else:\n self.gate = None\n\n if adapter_kind == \"bottleneck\":\n self.down_sample_size = input_dim // reduction_factor\n self.activation = nn.ReLU(inplace=True)\n self.down_sampler = nn.Conv2d(input_dim, self.down_sample_size, 1, bias=False)\n self.up_sampler = nn.Conv2d(self.down_sample_size, output_dim, 1, bias=False)\n\n if use_bn:\n self.bn1 = nn.BatchNorm2d(self.down_sample_size)\n self.bn2 = nn.BatchNorm2d(output_dim)\n\n elif adapter_kind == \"basic\":\n self.activation = nn.ReLU(inplace=True)\n self.conv = nn.Conv2d(input_dim, output_dim, 1, bias=False)\n\n if use_bn:\n self.bn = nn.BatchNorm2d(output_dim)\n\n else:\n raise NotImplementedError\n\n def forward(self, x):\n if self.adapter_kind == \"bottleneck\":\n z = self.down_sampler(x)\n z = self.bn1(z) if self.use_bn else z\n z = self.activation(z)\n output = self.up_sampler(z)\n output = self.bn2(output) if self.use_bn else output\n\n elif self.adapter_kind == \"basic\":\n output = self.conv(x)\n output = self.bn(output) if self.use_bn else output\n\n if self.gate is not None:\n output = self.gate * output\n\n return output\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, adapter_config=None):\n super().__init__()\n\n # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1\n self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n\n self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n\n self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()\n\n self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n\n self.relu = nn.ReLU(inplace=True)\n self.downsample = None\n self.stride = stride\n\n self.adapter = None\n\n if adapter_config is not None:\n self.adapter = VisualAdapter(planes, planes, \"basic\", adapter_config.reduction_factor, True, config.use_gate)\n\n if stride > 1 or inplanes != planes * Bottleneck.expansion:\n # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1\n self.downsample = nn.Sequential(OrderedDict([\n (\"-1\", nn.AvgPool2d(stride)),\n (\"0\", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),\n (\"1\", nn.BatchNorm2d(planes * self.expansion))\n ]))\n\n def forward(self, x: torch.Tensor):\n identity = x\n\n out = self.relu(self.bn1(self.conv1(x)))\n\n if self.adapter is not None:\n adapter_out = self.adapter(out)\n out = self.bn2(self.conv2(out))\n out = self.relu(adapter_out + out)\n else:\n out = self.relu(self.bn2(self.conv2(out)))\n\n out = self.avgpool(out)\n out = self.bn3(self.conv3(out))\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n return out\n\n\nclass AttentionPool2d(nn.Module):\n def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):\n super().__init__()\n self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)\n self.k_proj = nn.Linear(embed_dim, embed_dim)\n self.q_proj = nn.Linear(embed_dim, embed_dim)\n self.v_proj = nn.Linear(embed_dim, embed_dim)\n self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)\n self.num_heads = num_heads\n\n def forward(self, x):\n x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC\n x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC\n x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC\n x, _ = F.multi_head_attention_forward(\n query=x, key=x, value=x,\n embed_dim_to_check=x.shape[-1],\n num_heads=self.num_heads,\n q_proj_weight=self.q_proj.weight,\n k_proj_weight=self.k_proj.weight,\n v_proj_weight=self.v_proj.weight,\n in_proj_weight=None,\n in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),\n bias_k=None,\n bias_v=None,\n add_zero_attn=False,\n dropout_p=0,\n out_proj_weight=self.c_proj.weight,\n out_proj_bias=self.c_proj.bias,\n use_separate_proj_weight=True,\n training=self.training,\n need_weights=False\n )\n\n return x[0]\n\n\nclass ModifiedResNet(nn.Module):\n \"\"\"\n A ResNet class that is similar to torchvision's but contains the following changes:\n - There are now 3 \"stem\" convolutions as opposed to 1, with an average pool instead of a max pool.\n - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1\n - The final pooling layer is a QKV attention instead of an average pool\n \"\"\"\n\n def __init__(self, layers, output_dim, heads, input_resolution=224, width=64, adapter_config=None):\n super().__init__()\n self.output_dim = output_dim\n self.input_resolution = input_resolution\n\n self.adapter_config = adapter_config\n\n # the 3-layer stem\n self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(width // 2)\n self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(width // 2)\n self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)\n self.bn3 = nn.BatchNorm2d(width)\n self.avgpool = nn.AvgPool2d(2)\n self.relu = nn.ReLU(inplace=True)\n\n # residual layers\n self._inplanes = width # this is a *mutable* variable used during construction\n self.layer1 = self._make_layer(width, layers[0])\n self.layer2 = self._make_layer(width * 2, layers[1], stride=2)\n self.layer3 = self._make_layer(width * 4, layers[2], stride=2)\n self.layer4 = self._make_layer(width * 8, layers[3], stride=2)\n\n embed_dim = width * 32 # the ResNet feature dimension\n self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)\n\n def _make_layer(self, planes, blocks, stride=1):\n layers = [Bottleneck(self._inplanes, planes, stride, adapter_config=self.adapter_config)]\n\n self._inplanes = planes * Bottleneck.expansion\n for _ in range(1, blocks):\n layers.append(Bottleneck(self._inplanes, planes, adapter_config=self.adapter_config))\n\n return nn.Sequential(*layers)\n\n def forward(self, x, skip_last_layer=False):\n def stem(x):\n for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]:\n x = self.relu(bn(conv(x)))\n x = self.avgpool(x)\n return x\n\n x = x.type(self.conv1.weight.dtype)\n x = stem(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n if not skip_last_layer:\n x = self.attnpool(x)\n\n return x\n\n\nclass LayerNorm(nn.LayerNorm):\n \"\"\"Subclass torch's LayerNorm to handle fp16.\"\"\"\n\n def forward(self, x: torch.Tensor):\n orig_type = x.dtype\n ret = super().forward(x.type(torch.float32))\n return ret.type(orig_type)\n\n\nclass QuickGELU(nn.Module):\n def forward(self, x: torch.Tensor):\n return x * torch.sigmoid(1.702 * x)\n\n\nclass ResidualAttentionBlock(nn.Module):\n def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):\n super().__init__()\n\n self.attn = nn.MultiheadAttention(d_model, n_head)\n self.ln_1 = LayerNorm(d_model)\n self.mlp = nn.Sequential(OrderedDict([\n (\"c_fc\", nn.Linear(d_model, d_model * 4)),\n (\"gelu\", QuickGELU()),\n (\"c_proj\", nn.Linear(d_model * 4, d_model))\n ]))\n self.ln_2 = LayerNorm(d_model)\n self.attn_mask = attn_mask\n\n def attention(self, x: torch.Tensor, text_mask=None):\n if text_mask is None:\n text_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None\n return self.attn(x, x, x, need_weights=False, attn_mask=text_mask)[0]\n\n def forward(self, x: torch.Tensor, text_mask = None):\n x = x + self.attention(self.ln_1(x), text_mask = text_mask)\n x = x + self.mlp(self.ln_2(x))\n return x\n\n\nclass Transformer(nn.Module):\n def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):\n super().__init__()\n self.width = width\n self.layers = layers\n self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])\n\n def forward(self, x: torch.Tensor, text_mask=None):\n for layer in self.resblocks:\n x = layer(x, text_mask = text_mask)\n return x\n\n\nclass VisualTransformer(nn.Module):\n def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):\n super().__init__()\n self.input_resolution = input_resolution\n self.output_dim = output_dim\n self.heads = heads\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)\n\n scale = width ** -0.5\n self.class_embedding = nn.Parameter(scale * torch.randn(width))\n self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))\n self.ln_pre = LayerNorm(width)\n\n self.transformer = Transformer(width, layers, heads)\n\n self.ln_post = LayerNorm(width)\n self.proj = nn.Parameter(scale * torch.randn(width, output_dim))\n\n def forward(self, x: torch.Tensor, skip_last_layer=False, text_embedding=None, text_mask=None):\n x = self.conv1(x) # shape = [*, width, grid, grid]\n x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]\n x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]\n x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]\n x = x + self.positional_embedding.to(x.dtype)\n x = self.ln_pre(x)\n\n x = x.permute(1, 0, 2) # NLD -> LND\n\n if text_embedding is not None:\n text_embedding = text_embedding.transpose(0, 1)\n joint_embeddings = torch.cat((text_embedding, x), dim=0)\n\n # Current language mask: batch x seq_len\n text_mask = torch.cat(\n (text_mask, torch.zeros(x.size(1), x.size(0)).float().to(x.device)),\n dim=1)\n \n # batch * heads x (seq_len + image_len)\n text_mask = torch.cat([text_mask for i in range(self.heads)], dim=0)\n # batch * heads x (seq_len + image_len) x (seq_len + image_len)\n text_mask = text_mask.unsqueeze(1).expand(text_mask.size(0), text_mask.size(1), text_mask.size(1))\n x = self.transformer(joint_embeddings, text_mask=text_mask)\n\n x = self.transformer(x)\n\n x = x.permute(1, 0, 2) # LND -> NLD\n \n if skip_last_layer:\n x = self.ln_post(x)\n else: \n x = x @ self.proj\n return x\n\nclass CLIP(nn.Module):\n def __init__(self,\n embed_dim: int,\n # vision\n image_resolution: int,\n vision_layers: Union[Tuple[int, int, int, int], int],\n vision_width: int,\n vision_patch_size: int,\n # text\n context_length: int,\n vocab_size: int,\n transformer_width: int,\n transformer_heads: int,\n transformer_layers: int,\n adapter_config,\n ):\n super().__init__()\n\n self.context_length = context_length\n\n if isinstance(vision_layers, (tuple, list)):\n vision_heads = vision_width * 32 // 64\n self.visual = ModifiedResNet(\n layers=vision_layers,\n output_dim=embed_dim,\n heads=vision_heads,\n input_resolution=image_resolution,\n width=vision_width,\n adapter_config=adapter_config,\n )\n else:\n vision_heads = vision_width // 64\n self.visual = VisualTransformer(\n input_resolution=image_resolution,\n patch_size=vision_patch_size,\n width=vision_width,\n layers=vision_layers,\n heads=vision_heads,\n output_dim=embed_dim\n )\n\n self.transformer = Transformer(\n width=transformer_width,\n layers=transformer_layers,\n heads=transformer_heads,\n attn_mask=self.build_attention_mask()\n )\n\n self.vocab_size = vocab_size\n self.token_embedding = nn.Embedding(vocab_size, transformer_width)\n self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))\n self.ln_final = LayerNorm(transformer_width)\n\n self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))\n self.logit_scale = nn.Parameter(torch.ones([]))\n\n self.initialize_parameters()\n\n def initialize_parameters(self):\n nn.init.normal_(self.token_embedding.weight, std=0.02)\n nn.init.normal_(self.positional_embedding, std=0.01)\n\n if isinstance(self.visual, ModifiedResNet):\n if self.visual.attnpool is not None:\n std = self.visual.attnpool.c_proj.in_features ** -0.5\n nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)\n nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)\n nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)\n nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)\n\n for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:\n for name, param in resnet_block.named_parameters():\n if name.endswith(\"bn3.weight\"):\n nn.init.zeros_(param)\n\n proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)\n attn_std = self.transformer.width ** -0.5\n fc_std = (2 * self.transformer.width) ** -0.5\n for block in self.transformer.resblocks:\n nn.init.normal_(block.attn.in_proj_weight, std=attn_std)\n nn.init.normal_(block.attn.out_proj.weight, std=proj_std)\n nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)\n nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)\n\n if self.text_projection is not None:\n nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)\n\n def build_attention_mask(self):\n # lazily create causal attention mask, with full attention between the vision tokens\n # pytorch uses additive attention mask; fill with -inf\n mask = torch.empty(self.context_length, self.context_length)\n mask.fill_(float(\"-inf\"))\n mask.triu_(1) # zero out the lower diagonal\n return mask\n\n @property\n def dtype(self):\n return self.visual.conv1.weight.dtype\n\n def encode_image(self, image):\n return self.visual(image.type(self.dtype))\n\n def encode_text(self, text):\n x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]\n\n x = x + self.positional_embedding.type(self.dtype)\n x = x.permute(1, 0, 2) # NLD -> LND\n x = self.transformer(x)\n x = x.permute(1, 0, 2) # LND -> NLD\n x = self.ln_final(x).type(self.dtype)\n\n # x.shape = [batch_size, n_ctx, transformer.width]\n # take features from the eot embedding (eot_token is the highest number in each sequence)\n x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection\n\n return x\n\n def forward(self, image, text):\n image_features = self.encode_image(image)\n text_features = self.encode_text(text)\n\n # normalized features\n image_features = image_features / image_features.norm(dim=-1, keepdim=True)\n text_features = text_features / text_features.norm(dim=-1, keepdim=True)\n\n # cosine similarity as logits\n logit_scale = self.logit_scale.exp()\n logits_per_image = logit_scale * image_features @ text_features.t()\n logits_per_text = logit_scale * text_features @ image_features.t()\n\n # shape = [global_batch_size, global_batch_size]\n return logits_per_image, logits_per_text\n\n\ndef convert_weights(model: nn.Module):\n \"\"\"Convert applicable model parameters to fp16\"\"\"\n\n def _convert_weights_to_fp16(l):\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):\n l.weight.data = l.weight.data.half()\n if l.bias is not None:\n l.bias.data = l.bias.data.half()\n\n if isinstance(l, nn.MultiheadAttention):\n for attr in [*[f\"{s}_proj_weight\" for s in [\"in\", \"q\", \"k\", \"v\"]], \"in_proj_bias\", \"bias_k\", \"bias_v\"]:\n tensor = getattr(l, attr)\n if tensor is not None:\n tensor.data = tensor.data.half()\n\n for name in [\"text_projection\", \"proj\"]:\n if hasattr(l, name):\n attr = getattr(l, name)\n if attr is not None:\n attr.data = attr.data.half()\n\n model.apply(_convert_weights_to_fp16)\n\n\ndef build_model(state_dict: dict, adapter_config):\n vit = \"visual.proj\" in state_dict\n\n if vit:\n vision_width = state_dict[\"visual.conv1.weight\"].shape[0]\n vision_layers = len([k for k in state_dict.keys() if k.startswith(\"visual.\") and k.endswith(\".attn.in_proj_weight\")])\n vision_patch_size = state_dict[\"visual.conv1.weight\"].shape[-1]\n grid_size = round((state_dict[\"visual.positional_embedding\"].shape[0] - 1) ** 0.5)\n image_resolution = vision_patch_size * grid_size\n else:\n counts: list = [len(set(k.split(\".\")[2] for k in state_dict if k.startswith(f\"visual.layer{b}\"))) for b in [1, 2, 3, 4]]\n vision_layers = tuple(counts)\n vision_width = state_dict[\"visual.layer1.0.conv1.weight\"].shape[0]\n output_width = round((state_dict[\"visual.attnpool.positional_embedding\"].shape[0] - 1) ** 0.5)\n vision_patch_size = None\n assert output_width ** 2 + 1 == state_dict[\"visual.attnpool.positional_embedding\"].shape[0]\n image_resolution = output_width * 32\n\n embed_dim = state_dict[\"text_projection\"].shape[1]\n context_length = state_dict[\"positional_embedding\"].shape[0]\n vocab_size = state_dict[\"token_embedding.weight\"].shape[0]\n transformer_width = state_dict[\"ln_final.weight\"].shape[0]\n transformer_heads = transformer_width // 64\n transformer_layers = len(set(k.split(\".\")[2] for k in state_dict if k.startswith(f\"transformer.resblocks\")))\n\n model = CLIP(\n embed_dim,\n image_resolution, vision_layers, vision_width, vision_patch_size,\n context_length, vocab_size, transformer_width, transformer_heads, transformer_layers, \n adapter_config\n )\n\n for key in [\"input_resolution\", \"context_length\", \"vocab_size\"]:\n del state_dict[key]\n\n #convert_weights(model)\n # model.load_state_dict(state_dict)\n\n try:\n model.load_state_dict(state_dict)\n except RuntimeError as err:\n print(\"Some keys are mismatched\")\n\n err = str(err).split(\"\\n\", 1)[1]\n print(err)\n\n model.load_state_dict(state_dict, strict=False)\n\n return model.eval()\n",
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nfrom modeling_t5 import VLT5\nclass VLT5RefCOCO(VLT5):\n def __init__(self, config):\n super().__init__(config)\n\n def train_step(self, batch):\n\n device = next(self.parameters()).device\n vis_feats = batch['vis_feats'].to(device)\n input_ids = batch['input_ids'].to(device)\n vis_pos = batch['boxes'].to(device)\n vis_attention_mask = batch['vis_attention_mask'].to(device)\n\n B, V_L = vis_feats.size()[:2]\n\n lm_labels = batch[\"target_ids\"].to(device)\n\n output = self(\n input_ids=input_ids,\n vis_inputs=(vis_feats, vis_pos),\n vis_attention_mask=vis_attention_mask,\n labels=lm_labels,\n return_dict=True\n )\n assert 'loss' in output\n\n lm_mask = (lm_labels != -100).float()\n B, L = lm_labels.size()\n\n loss = output['loss']\n\n loss = loss.view(B, L) * lm_mask\n\n loss = loss.sum(dim=1) / lm_mask.sum(dim=1).clamp(min=1) # B\n\n loss_mask = batch['exists_target'].to(device=device)\n\n loss = (loss * loss_mask).sum() / loss_mask.sum().clamp(min=1)\n\n result = {\n 'loss': loss\n }\n\n with torch.no_grad():\n logits = output['logits'].detach()\n # logits = logits.view(B, 2, self.config.vocab_size)\n logits = logits.view(B, L, self.config.vocab_size)\n\n # target = lm_labels[:, 0].view(B)\n\n pred = logits[:, 0].argmax(dim=1).view(B)\n # correct = pred == target\n\n pred = pred.cpu().numpy()\n\n correct = np.zeros([B])\n for i in range(B):\n correct[i] = pred[i] in batch['all_target_ids'][i]\n\n result['pred'] = pred\n result['correct'] = correct\n\n return result\n\n @torch.no_grad()\n def test_step(self, batch):\n self.eval()\n device = next(self.parameters()).device\n vis_feats = batch['vis_feats'].to(device)\n input_ids = batch['input_ids'].to(device)\n vis_pos = batch['boxes'].to(device)\n vis_attention_mask = batch['vis_attention_mask'].to(device)\n\n B, V_L = vis_feats.size()[:2]\n\n decoder_input_ids = torch.ones(B, 1, dtype=torch.long, device=device) * self.config.decoder_start_token_id\n\n output = self(\n input_ids=input_ids,\n vis_inputs=(vis_feats, vis_pos),\n vis_attention_mask=vis_attention_mask,\n decoder_input_ids=decoder_input_ids,\n return_dict=True\n )\n\n logits = output['logits'].detach()\n logits = logits.view(B, self.config.vocab_size)\n\n pred = logits.argmax(dim=1).view(B)\n pred = pred.cpu().numpy()\n\n correct = np.zeros([B])\n for i in range(B):\n correct[i] = pred[i] in batch['all_target_ids'][i]\n\n result = {}\n result['pred'] = pred\n result['correct'] = correct\n\n return result\n\nfrom modeling_bart import VLBart\nfrom collections import defaultdict\nclass VLBartRefCOCO(VLBart):\n def __init__(self, config):\n super().__init__(config)\n\n out_map = defaultdict(lambda: -1)\n for i in range(100):\n out_map[f'<vis_extra_id_{i}>'] = i\n\n self.out_map = out_map\n\n def train_step(self, batch):\n self.train()\n device = next(self.parameters()).device\n vis_feats = batch['vis_feats'].to(device)\n input_ids = batch['input_ids'].to(device)\n vis_pos = batch['boxes'].to(device)\n vis_attention_mask = batch['vis_attention_mask'].to(device)\n\n B, V_L = vis_feats.size()[:2]\n\n lm_labels = batch[\"target_ids\"].to(device)\n\n output = self(\n input_ids=input_ids,\n attention_mask=input_ids.ne(self.config.pad_token_id),\n vis_inputs=(vis_feats, vis_pos),\n vis_attention_mask=vis_attention_mask,\n labels=lm_labels,\n reduce_loss=True,\n return_dict=True\n )\n assert 'loss' in output\n\n # lm_mask = (lm_labels != -100).float()\n B, L = lm_labels.size()\n\n loss = output['loss']\n\n result = {\n 'loss': loss\n }\n\n with torch.no_grad():\n logits = output['logits'].detach().view(B, L, self.lm_head.out_features)[:, 1]\n logits = logits.view(B, self.lm_head.out_features)\n\n pred = logits.argmax(dim=1).view(B)\n pred = pred.cpu().numpy()\n pred = self.lm_head.out_features - pred - 1\n\n correct = np.zeros([B])\n for i in range(B):\n correct[i] = pred[i] in batch['all_targets'][i]\n\n result['pred'] = pred\n result['correct'] = correct\n\n return result\n\n @torch.no_grad()\n def test_step(self, batch):\n self.eval()\n device = next(self.parameters()).device\n vis_feats = batch['vis_feats'].to(device)\n input_ids = batch['input_ids'].to(device)\n vis_pos = batch['boxes'].to(device)\n vis_attention_mask = batch['vis_attention_mask'].to(device)\n\n B, V_L = vis_feats.size()[:2]\n\n decoder_input_ids = torch.tensor(\n [self.config.decoder_start_token_id, self.config.bos_token_id],\n dtype=torch.long, device=device).unsqueeze(0).expand(B, 2)\n\n output = self(\n input_ids=input_ids,\n attention_mask=input_ids.ne(self.config.pad_token_id),\n vis_inputs=(vis_feats, vis_pos),\n vis_attention_mask=vis_attention_mask,\n decoder_input_ids=decoder_input_ids,\n return_dict=True\n )\n\n logits = output['logits'].detach().view(B, 2, self.lm_head.out_features)[:, 1]\n logits = logits.view(B, self.lm_head.out_features)\n\n pred = logits.argmax(dim=1).view(B)\n pred = pred.cpu().numpy()\n\n pred = self.lm_head.out_features - pred - 1\n\n correct = np.zeros([B])\n for i in range(B):\n correct[i] = pred[i] in batch['all_targets'][i]\n\n result = {}\n result['pred'] = pred\n result['correct'] = correct\n\n return result\n"
] |
[
[
"torch.nn.Sequential",
"torch.sigmoid",
"torch.ones",
"torch.empty",
"torch.nn.MultiheadAttention",
"torch.cat",
"torch.zeros",
"torch.randn",
"torch.nn.init.zeros_",
"torch.nn.Conv2d",
"torch.arange",
"torch.nn.Embedding",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.Identity",
"torch.nn.init.normal_",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
],
[
"torch.ones",
"torch.no_grad",
"numpy.zeros",
"torch.tensor"
]
] |
hyliush/deep-time-series
|
[
"3fea4f62ea740c721c559a0d413e4b3a3e214b3e"
] |
[
"models/seq2seq/Transformer.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom layers.Transformer_EncDec import Decoder, DecoderLayer, Encoder, EncoderLayer, ConvLayer\nfrom layers.SelfAttention_Family import FullAttention, AttentionLayer\nfrom layers.Embed import DataEmbedding\nimport numpy as np\n\n\nclass Transformer(nn.Module):\n \"\"\"\n Vanilla Transformer with O(L^2) complexity\n \"\"\"\n def __init__(self, args):\n super(Transformer, self).__init__()\n self.args = args\n self.pred_len = args.pred_len\n self.output_attention = args.output_attention\n\n # Embedding\n self.enc_embedding = DataEmbedding(args.enc_in, args.d_model, args.embed, args.freq,\n args.dropout)\n self.dec_embedding = DataEmbedding(args.dec_in, args.d_model, args.embed, args.freq,\n args.dropout)\n # Encoder\n self.encoder = Encoder(\n [\n EncoderLayer(\n AttentionLayer(\n FullAttention(False, args.factor, attention_dropout=args.dropout,\n output_attention=args.output_attention), \n args.d_model, args.n_heads, mix=False),\n args.d_model,\n args.d_ff,\n dropout=args.dropout,\n activation=args.activation\n ) for l in range(args.e_layers)\n ],\n [\n ConvLayer(\n args.d_model\n ) for l in range(args.e_layers - 1)\n ] if args.distil else None,\n norm_layer=torch.nn.LayerNorm(args.d_model)\n )\n # Decoder\n self.decoder = Decoder(\n [\n DecoderLayer(\n AttentionLayer(\n FullAttention(True, args.factor, attention_dropout=args.dropout, output_attention=False),\n args.d_model, args.n_heads, mix=args.mix),\n AttentionLayer(\n FullAttention(False, args.factor, attention_dropout=args.dropout, output_attention=False),\n args.d_model, args.n_heads, mix=False),\n args.d_model,\n args.d_ff,\n dropout=args.dropout,\n activation=args.activation,\n )\n for l in range(args.d_layers)\n ],\n norm_layer=torch.nn.LayerNorm(args.d_model),\n projection=nn.Linear(args.d_model, args.out_size, bias=True)\n )\n\n def forward(self, x_enc, x_mark_enc, x_dec, x_mark_dec,\n enc_self_mask=None, dec_self_mask=None, dec_enc_mask=None):\n\n enc_out = self.enc_embedding(x_enc, x_mark_enc)\n enc_out, attns = self.encoder(enc_out, attn_mask=enc_self_mask)\n\n dec_out = self.dec_embedding(x_dec, x_mark_dec)\n dec_out = self.decoder(dec_out, enc_out, x_mask=dec_self_mask, cross_mask=dec_enc_mask)\n\n if self.output_attention:\n return dec_out[:, -self.pred_len:, :], attns\n else:\n return dec_out[:, -self.pred_len:, :] # [B, L, D]\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.LayerNorm"
]
] |
renskir/sv-channels
|
[
"284335dc20b775f9e90a7f77809acbb838308cd8"
] |
[
"scripts/genome_wide/add_win_channels.py"
] |
[
"import argparse\nimport logging\nfrom time import time\n\nimport numpy as np\nimport pysam\nfrom functions import (is_left_clipped, is_right_clipped, load_windows,\n save_windows)\n\n\ndef init_log(logfile):\n FORMAT = '%(asctime)s %(message)s'\n logging.basicConfig(format=FORMAT,\n filename=logfile,\n filemode='w',\n level=logging.INFO)\n\n\ndef parse_args():\n default_win = 25\n parser = argparse.ArgumentParser(\n description='Add window specific channels')\n\n parser.add_argument('-b',\n '--bam',\n type=str,\n default='../../data/test.bam',\n help=\"Specify input file (BAM)\")\n parser.add_argument('-w',\n '--win',\n type=int,\n default=default_win,\n help=\"Window size\")\n parser.add_argument('-i',\n '--input',\n type=str,\n default='./cnn/win' +\n str(default_win)+'/split_reads/windows/DEL/windows.npz',\n help=\"input file\")\n parser.add_argument('-o',\n '--output',\n type=str,\n default='./cnn/win' +\n str(default_win) +\n '/split_reads/windows/DEL/windows_en.npz',\n help=\"output file\")\n parser.add_argument('-l',\n '--logfile',\n default='./cnn/win' +\n str(default_win) +\n '/split_reads/windows/DEL/windows_en.log',\n help='File in which to write logs.')\n parser.add_argument('-lp',\n '--log_every_n_pos',\n type=int,\n default=1000,\n help='Write in log file every N positions')\n parser.add_argument('-p',\n '--padding',\n type=int,\n default=10,\n help=\"Length of the padding in between windows\")\n\n return parser.parse_args()\n\n\ndef get_channels():\n ch = [\n # All reads (clipped or not)\n 'F_AR_N', 'R_AR_N',\n # Split reads\n 'F_SR_L', 'F_SR_R', 'F_SR_B', 'R_SR_L', 'R_SR_R', 'R_SR_B', 'F_SR_N', 'R_SR_N',\n # Clipped reads\n 'F_CR_L', 'F_CR_R', 'R_CR_L', 'R_CR_R', 'F_CR_B', 'R_CR_B', 'F_CR_N', 'R_CR_N',\n # Discordant reads\n 'DR_F', 'DR_R',\n # SV type channels\n 'DUP_A', 'DUP_B', 'INV_A', 'INV_B', 'TRA_O', 'TRA_S'\n ]\n return {k: v for v, k in enumerate(ch)}\n\n\ndef update_channel(X, ch, counter, read, win_mid_pos, is_second_win, win_len, padding):\n if is_left_clipped(read) and not is_right_clipped(read):\n clipping = 'L'\n elif not is_left_clipped(read) and is_right_clipped(read):\n clipping = 'R'\n elif is_left_clipped(read) and is_right_clipped(read):\n clipping = 'B'\n else:\n clipping = 'N'\n\n if read.has_tag('SA'):\n clipped_state = 'SR'\n elif is_left_clipped(read) or is_right_clipped(read):\n clipped_state = 'CR'\n else:\n clipped_state = 'AR'\n\n orientation = 'R' if read.is_reverse else 'F'\n start_win = win_len + padding if is_second_win else 0\n end_win = win_len * 2 + padding if is_second_win else win_len\n abs_start = int(win_mid_pos - int(win_len / 2)) if win_len % 2 == 0 else \\\n int(win_mid_pos - int(win_len + 1 / 2))\n abs_end = int(win_mid_pos + int(win_len / 2)) if win_len % 2 == 0 else \\\n int(win_mid_pos + int(win_len + 1 / 2))\n start = max(read.reference_start, abs_start)\n end = min(read.reference_end, abs_end)\n rel_start = start_win + start - abs_start\n rel_end = start_win + end - abs_start\n\n assert rel_start >= 0\n assert rel_end >= 0\n assert start_win <= rel_start <= end_win\n assert start_win <= rel_end <= end_win\n\n skip = False\n if is_left_clipped(read):\n if (is_second_win and win_len + padding <= rel_start < win_len * 2 + padding) or \\\n (not is_second_win and 0 <= rel_start < win_len):\n rel_pos = rel_start\n else:\n skip = True\n elif is_right_clipped(read):\n if (is_second_win and win_len + padding <= rel_end < win_len * 2 + padding) or \\\n (not is_second_win and 0 <= rel_end < win_len):\n rel_pos = rel_end\n else:\n skip = True\n else:\n rel_pos = np.arange(max(start_win, rel_start), min(rel_end, end_win))\n\n if not skip:\n k = '_'.join([orientation, clipped_state, clipping])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n if not read.is_proper_pair:\n k = '_'.join(['DR', orientation])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n if read.is_reverse and not read.mate_is_reverse \\\n and read.reference_start < read.next_reference_start:\n k = '_'.join(['DUP', 'A'])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n if not read.is_reverse and read.mate_is_reverse \\\n and read.reference_start > read.next_reference_start:\n k = '_'.join(['DUP', 'B'])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n if read.is_reverse == read.mate_is_reverse:\n if read.reference_start < read.next_reference_start:\n k = '_'.join(['INV', 'B'])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n else:\n k = '_'.join(['INV', 'A'])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n if read.reference_name != read.next_reference_name:\n if read.is_reverse == read.mate_is_reverse:\n if read.reference_start < read.next_reference_start:\n k = '_'.join(['TRA', 'S'])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n else:\n k = '_'.join(['TRA', 'O'])\n if k in ch.keys():\n X[counter, rel_pos, ch[k]] += 1\n return X\n\n\ndef add_channels(args, aln):\n win = args.win if args.win % 2 == 0 else args.win + 1\n\n def get_reads(chrom, pos):\n return [read for read in aln.fetch(chrom, pos - int(win / 2), pos + int(win / 2))]\n\n # Load the windows\n logging.info(\"Loading windows...\")\n last_t = time()\n X, y = load_windows(args.input)\n logging.info(\"Windows loaded in %f seconds\" % (time() - last_t))\n\n # Load the channels\n ch = get_channels()\n # get starting time\n last_t = time()\n # Initialize numpy array\n X_enh = np.zeros(shape=(X.shape[:2] + (len(ch),)), dtype=np.int8)\n\n for i, p in enumerate(y.keys(), start=0):\n # Every n_r alignments, write log informations\n if not i % args.log_every_n_pos and i != 0:\n # Record the current time\n now_t = time()\n logging.info(\"%d positions processed (%f positions / s)\" %\n (i, args.log_every_n_pos / (now_t - last_t)))\n last_t = time()\n\n # Get genomic coordinates\n chrom1, pos1, chrom2, pos2, strand_info = p.split('_')\n pos1, pos2 = int(pos1), int(pos2)\n\n # Fetch reads overlapping each window\n win1_reads = get_reads(chrom1, pos1)\n win2_reads = get_reads(chrom2, pos2)\n\n # Which reads are in both windows?\n win1_read_names_set = {read.query_name for read in win1_reads}\n win2_read_names_set = {read.query_name for read in win2_reads}\n common_read_names = win1_read_names_set & win2_read_names_set\n\n # Only consider reads common to both windows\n win1_reads = {\n r for r in win1_reads if r.query_name in common_read_names and not r.is_unmapped}\n win2_reads = {\n r for r in win2_reads if r.query_name in common_read_names and not r.is_unmapped}\n\n for r in win1_reads:\n X_enh = update_channel(X_enh, ch, i, r, pos1,\n False, win, args.padding)\n\n for r in win2_reads:\n X_enh = update_channel(X_enh, ch, i, r, pos2,\n True, win, args.padding)\n\n for i in np.arange(X_enh.shape[2]):\n logging.info(\"win channels array: non-zero elements at index %d:%d\" %\n (i, np.argwhere(X_enh[i, :] != 0).shape[0]))\n\n X = np.concatenate((X, X_enh), axis=2)\n print(X.shape)\n\n for i in np.arange(X.shape[2]):\n logging.info(\"full channels array: NaN elements at index %d:%d\" %\n (i, len(np.argwhere(np.isnan(X[i, :])))))\n return X, y\n\n\ndef main():\n args = parse_args()\n init_log(args.logfile)\n t0 = time()\n\n with pysam.AlignmentFile(args.bam, \"rb\") as bam:\n X, y = add_channels(args, bam)\n save_windows(X, y, args.output)\n logging.info('Finished in %f seconds' % (time() - t0))\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.concatenate",
"numpy.arange",
"numpy.isnan",
"numpy.argwhere"
]
] |
omidsakhi/tpu_dist_gan
|
[
"c676540dcd7c9fc8eb3e01bb976ed6655e1c906d"
] |
[
"dist_input.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nimport math\n\nclass InputFunction(object): \n \n def __init__(self, noise_dim): \n self.noise_dim = noise_dim\n\n def points_on_circle(self, num, r):\n pi = 3.141592\n coords = [ (r * math.cos((2. / num) * i * pi) , r * math.sin((2. / num) * i * pi) ) for i in range(num)]\n return coords\n\n\n def __call__(self, params): \n batch_size = params['batch_size'] \n random_noise = tf.random_normal([batch_size, self.noise_dim])\n dist = tf.contrib.distributions # pylint: disable=E1101\n p = self.points_on_circle(8, 2.)\n gauss = dist.Mixture(\n cat=dist.Categorical(probs=[0.25 for _ in range(8)]), \n components=[\n dist.MultivariateNormalDiag(loc=p[i], scale_diag=[0.02, 0.02]) for i in range(8)\n ])\n samples = gauss.sample([batch_size])\n features = {\n 'samples': samples,\n 'random_noise': random_noise}\n\n return features\n"
] |
[
[
"tensorflow.random_normal"
]
] |
kar-thik/TensorFlow-Examples
|
[
"2097ad0a6faf55a4a9cee00cc1b0ae3454b178fc"
] |
[
"examples/1_Introduction/helloworld.py"
] |
[
"'''\nHelloWorld example using TensorFlow library.\n\nAuthor: Aymeric Damien\nProject: https://github.com/aymericdamien/TensorFlow-Examples/\n'''\n\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n# Simple hello world using TensorFlow\n\n# Create a Constant op\n# The op is added as a node to the default graph.\n#\n# The value returned by the constructor represents the output\n# of the Constant op.\nhello = tf.constant('Hello, TensorFlow!')\n\n# Start tf session\nsess = tf.Session()\n\n# Run the op\nprint(sess.run(hello))\n"
] |
[
[
"tensorflow.constant",
"tensorflow.Session"
]
] |
HeyItsRiddhi/cs207_riddhi_shah
|
[
"18d7d6f1fcad213ce35a93ee33c03620f8b06b65"
] |
[
"project/code/thermo.py"
] |
[
"\"\"\"Thermodynamics and Thermochemistry for Chemical Kinetics\nThis module contains a thermochem class with methods for \ncomputing the backward reaction rates for a set of \nreversible, elementary reactions.\n\"\"\"\n\nimport numpy as np\n\nclass thermochem:\n \"\"\"Methods for calculating the backward reaction rate.\n\n Cp_over_R: Returns specific heat of each specie given by \n the NASA polynomials.\n H_over_RT: Returns the enthalpy of each specie given by \n the NASA polynomials.\n S_over_R: Returns the entropy of each specie given by \n the NASA polynomials.\n backward_coeffs: Returns the backward reaction rate \n coefficient for reach reaction.\n\n Please see the notes in each routine for clarifications and \n warnings. You will need to customize these methods (and \n likely the entire class) to suit your own code base. \n Nevertheless, it is hoped that you will find these methods \n to be of some use.\n \"\"\"\n\n def __init__(self, rxnset):\n self.rxnset = rxnset\n self.p0 = 1.0e+05 # Pa\n self.R = 8.3144598 # J / mol / K\n self.gamma = np.sum(self.rxnset.nuij, axis=0)\n\n def Cp_over_R(self, T):\n\n # WARNING: This line will depend on your own data structures!\n # Be careful to get the correct coefficients for the appropriate \n # temperature range. That is, for T <= Tmid get the low temperature \n # range coeffs and for T > Tmid get the high temperature range coeffs.\n a = self.rxnset.nasa7_coeffs\n\n Cp_R = (a[:,0] + a[:,1] * T + a[:,2] * T**2.0 \n + a[:,3] * T**3.0 + a[:,4] * T**4.0)\n\n return Cp_R\n\n def H_over_RT(self, T):\n\n # WARNING: This line will depend on your own data structures!\n # Be careful to get the correct coefficients for the appropriate \n # temperature range. That is, for T <= Tmid get the low temperature \n # range coeffs and for T > Tmid get the high temperature range coeffs.\n a = self.rxnset.nasa7_coeffs\n\n H_RT = (a[:,0] + a[:,1] * T / 2.0 + a[:,2] * T**2.0 / 3.0 \n + a[:,3] * T**3.0 / 4.0 + a[:,4] * T**4.0 / 5.0 \n + a[:,5] / T)\n\n return H_RT\n \n\n def S_over_R(self, T):\n\n # WARNING: This line will depend on your own data structures!\n # Be careful to get the correct coefficients for the appropriate \n # temperature range. That is, for T <= Tmid get the low temperature \n # range coeffs and for T > Tmid get the high temperature range coeffs.\n a = self.rxnset.nasa7_coeffs\n\n S_R = (a[:,0] * np.log(T) + a[:,1] * T + a[:,2] * T**2.0 / 2.0 \n + a[:,3] * T**3.0 / 3.0 + a[:,4] * T**4.0 / 4.0 + a[:,6])\n\n return S_R\n\n def backward_coeffs(self, kf, T):\n\n # Change in enthalpy and entropy for each reaction\n delta_H_over_RT = np.dot(self.rxnset.nuij.T, self.H_over_RT(T))\n delta_S_over_R = np.dot(self.rxnset.nuij.T, self.S_over_R(T))\n\n # Negative of change in Gibbs free energy for each reaction \n delta_G_over_RT = delta_S_over_R - delta_H_over_RT\n\n # Prefactor in Ke\n fact = self.p0 / self.R / T\n\n # Ke\n kb = fact**self.gamma * np.exp(delta_G_over_RT)\n\n return kf / kb\n"
] |
[
[
"numpy.log",
"numpy.exp",
"numpy.sum"
]
] |
agroome/report_compliance
|
[
"9fc0050f6ebc3498528d46b9e0973855d1b8072f"
] |
[
"report_compliance.py"
] |
[
"import csv\r\nfrom dotenv import load_dotenv\r\nimport logging\r\n\r\nimport os\r\nimport datetime\r\nimport pandas as pd\r\nimport argparse\r\nimport time\r\nfrom collections import defaultdict, Counter\r\nfrom functools import partial\r\nfrom pathlib import Path\r\nfrom typing import List, Iterable\r\nfrom tenable.io import TenableIO\r\n\r\n\r\ndef timestamp_from_str(date_string: str, fmt: str = '%Y-%m-%d %H:%M') -> int:\r\n \"\"\"Provide date and optional time separated by a space '%m/%d/%Y[ %H:%M]' \"\"\"\r\n if ' ' not in date_string:\r\n date_string = f'{date_string} 00:00'\r\n try:\r\n return int(time.mktime(time.strptime(date_string, fmt)))\r\n except Exception as e:\r\n SystemExit(repr(e))\r\n\r\n\r\nenv_file = Path(__file__).parent / '.env'\r\nload_dotenv(env_file)\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--first-seen', help=\"first seen date mm/dd/yyyy [hh:mm]\")\r\nparser.add_argument('--last-seen', help=\"last seen date mm/dd/yyyy [hh:mm]\")\r\nparser.add_argument('--timeout', help=\"timeout in seconds, default no timeout\")\r\nparser.add_argument('--output-folder', default='.', help=\"report folders created under this location\")\r\nparser.add_argument('--log-level', default='INFO', help=\"defaults to INFO\")\r\nparser.add_argument('--status', default=('ERROR', 'WARNING', 'FAILED'), help=\"include records with status\")\r\nargs = parser.parse_args()\r\n\r\nnumeric_level = getattr(logging, args.log_level.upper(), None)\r\nif not isinstance(numeric_level, int):\r\n raise ValueError('Invalid log level: %s' % args.log_level)\r\n\r\nfirst_seen = timestamp_from_str(args.first_seen) if args.first_seen else None\r\nlast_seen = timestamp_from_str(args.last_seen) if args.last_seen else None\r\ntimeout = args.timeout if args.timeout else None\r\n\r\ndt = datetime.datetime.now()\r\noutput_folder = Path(args.output_folder) / str(dt.strftime('%Y-%m-%d'))\r\n\r\nlogfile = output_folder / 'compliance_export.log'\r\nlogging.basicConfig(filename=str(logfile), level=numeric_level)\r\n\r\ncompliance_fields = [\r\n 'actual_value', 'asset_uuid', 'audit_file', 'check_error', 'check_id', 'check_info', 'check_name',\r\n 'expected_value', 'first_seen', 'last_seen', 'plugin_id', 'reference', 'see_also', 'solution', 'status'\r\n]\r\n\r\n\r\ndef take(number: int, items: Iterable) -> List:\r\n \"\"\"Take number items from an iterable and return a list. (rather than load more_itertools)\"\"\"\r\n\r\n def take_items():\r\n for i, item in enumerate(items, start=1):\r\n yield item\r\n if i == number:\r\n break\r\n logging.debug('returning items')\r\n return [item for item in take_items()]\r\n\r\n\r\ndef first_item(list_, default=''):\r\n \"\"\"Return the first item in a list.\"\"\"\r\n return list_ and list_[0] or default\r\n\r\n\r\ndef parse_asset_record(record: dict, tags: List[str] = None) -> tuple:\r\n \"\"\"Process asset fields to leave ipv4, fqdn, hostname and any specified tags.\"\"\"\r\n out_record = {\r\n 'ipv4': first_item(record['ipv4s']),\r\n 'fqdn': first_item(record['fqdns']),\r\n 'hostname': first_item(record['hostnames']),\r\n }\r\n if tags is not None:\r\n out_record.update({tag['key']: tag['value'] for tag in record['tags'] if tag['key'] in tags})\r\n return record['id'], out_record\r\n\r\n\r\ndef process_records(records, status=('ERROR', 'WARNING', 'FAILED'), compute_age=True):\r\n \"\"\"Computes age for compliance records and reduces records on only those in status argument.\"\"\"\r\n included_status = set(status)\r\n for record in records:\r\n # only include records when record['status'] is in included_status\r\n if record['status'] not in included_status:\r\n continue\r\n if compute_age:\r\n _first_seen = pd.to_datetime(record['first_seen'])\r\n _last_seen = pd.to_datetime(record['last_seen'])\r\n record['age'] = (_last_seen - _first_seen).days\r\n record['last_timestamp'] = int(_last_seen.timestamp())\r\n\r\n # some records have missing fields, let's do a copy here\r\n yield {field: record.get(field, '') for field in compliance_fields}\r\n\r\n\r\ndef inject_fields(records_in: Iterable[dict], payload_dict: dict, on_index: str):\r\n \"\"\"Generator that injects fields from payload[index] into record. For use in chaining generators.\"\"\"\r\n\r\n for record in records_in:\r\n try:\r\n # index the related record in payload dict\r\n yield {**record, **payload_dict[record[on_index]]}\r\n except KeyError:\r\n # payload dict is missing the entry for on_index\r\n fields = ['check_name', 'check_info', 'plugin_id']\r\n logging.warning(', '.join([f'{field}: {record[field]}' for field in fields]))\r\n logging.warning(f'payload with id {record[on_index]} not found, continuing')\r\n yield record\r\n\r\n\r\ndef summarize_compliance(data, summarize_by, include_error=True):\r\n fields = ['PASSED', 'WARNING', 'FAILED']\r\n data['count'] = 1\r\n if include_error:\r\n fields.append('ERROR')\r\n _data = (\r\n data\r\n .sort_values(by=['last_seen'], ascending=False)\r\n .groupby(by=['check_name', 'hostname'])\r\n .first()\r\n .reset_index()\r\n .pivot_table(index=summarize_by, columns='status', values='count', fill_value=0, aggfunc='sum')\r\n )\r\n _data['TOTAL'] = sum([_data[status] for status in fields])\r\n for field in fields:\r\n _data[f'%{field}'] = 100 * _data[field] / _data['TOTAL']\r\n _data[f'%{field}'].round(decimals=2)\r\n return _data\r\n\r\n\r\ndef summarize_data(csv_input_file, asset_dictionary, output_file):\r\n collector = defaultdict(lambda: defaultdict(Counter))\r\n with open(csv_input_file, newline='') as fobj:\r\n reader = csv.DictReader(fobj, dialect='excel')\r\n for row in reader:\r\n audit_file = row['audit_file']\r\n asset_uuid = row['asset_uuid']\r\n collector[audit_file][asset_uuid].update([row['status']])\r\n\r\n field_names = ['audit_file', 'asset_uuid', 'PASSED', 'WARNING', 'FAILED', 'ERROR']\r\n with open(output_file, 'w', newline='') as fobj:\r\n writer = csv.DictWriter(fobj, dialect='excel', fieldnames=field_names)\r\n writer.writeheader()\r\n for audit_file in collector:\r\n for uuid in collector['audit_file']:\r\n record = dict(audit_file=audit_file, asset_uuid=uuid)\r\n record.update(collector[audit_file][uuid])\r\n asset = asset_dictionary.get(uuid)\r\n if asset:\r\n record.update(asset)\r\n writer.writerow(record)\r\n\r\n\r\ndef main():\r\n\r\n if first_seen and not last_seen:\r\n logging.error('first_seen can only be used in combination with last seen')\r\n raise SystemExit('ERROR: first_seen can only be used in combination with last seen')\r\n\r\n tags = os.getenv('TAGS', '').split(',')\r\n\r\n if not os.path.exists(output_folder):\r\n os.mkdir(output_folder)\r\n\r\n tio = TenableIO()\r\n\r\n # parse asset records to reduce included fields and pop list values\r\n asset_parser = partial(parse_asset_record, tags=tags)\r\n asset_dictionary = dict(map(asset_parser, tio.exports.assets()))\r\n\r\n asset_fields = ['ipv4', 'fqdn', 'hostname']\r\n if tags is not None:\r\n asset_fields.extend(tags)\r\n\r\n # data pipeline export -> process_records -> inject_fields\r\n records_iterator = (\r\n inject_fields(\r\n process_records(\r\n tio.exports.compliance(first_seen=first_seen, last_seen=last_seen, timeout=timeout), status=('ERROR', 'WARNING', 'FAILED')), asset_dictionary, on_index='asset_uuid'\r\n )\r\n )\r\n\r\n fieldnames = compliance_fields + asset_fields + ['age', 'last_timestamp']\r\n\r\n records_per_chunk = 50000\r\n\r\n while True:\r\n records = take(records_per_chunk, records_iterator)\r\n if not records:\r\n break\r\n df = pd.DataFrame.from_records(records, columns=fieldnames)\r\n logging.debug(f'writing {len(df)} records')\r\n if 'audit_file' in df:\r\n for audit_file, data in df.groupby('audit_file'):\r\n logging.debug(f'process {len(data)} records from {audit_file}')\r\n audit_file = str(audit_file).replace('.audit', '.csv')\r\n data.to_csv(output_folder / audit_file, index=False, mode='a')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n"
] |
[
[
"pandas.DataFrame.from_records",
"pandas.to_datetime"
]
] |
MIXIAOXIN/detectron2-0.3-mxx
|
[
"3b4eb6da27b6360139228052690bce7a74b1268e"
] |
[
"detectron2/export/caffe2_inference.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\n\nimport logging\nimport numpy as np\nfrom itertools import count\nimport torch\nfrom caffe2.proto import caffe2_pb2\nfrom caffe2.python import core\n\nfrom .caffe2_modeling import META_ARCH_CAFFE2_EXPORT_TYPE_MAP, convert_batched_inputs_to_c2_format\nfrom .shared import ScopedWS, get_pb_arg_vali, get_pb_arg_vals, infer_device_type\n\nlogger = logging.getLogger(__name__)\n\n\n# ===== ref: mobile-vision's 'Caffe2Wrapper' class ======\nclass ProtobufModel(torch.nn.Module):\n \"\"\"\n Wrapper of a caffe2's protobuf model.\n It works just like nn.Module, but running caffe2 under the hood.\n Input/Output are Dict[str, tensor] whose keys are in external_input/output.\n \"\"\"\n\n _ids = count(0)\n\n def __init__(self, predict_net, init_net):\n logger.info(f\"Initializing ProtobufModel for: {predict_net.name} ...\")\n super().__init__()\n assert isinstance(predict_net, caffe2_pb2.NetDef)\n assert isinstance(init_net, caffe2_pb2.NetDef)\n # create unique temporary workspace for each instance\n self.ws_name = \"__tmp_ProtobufModel_{}__\".format(next(self._ids))\n self.net = core.Net(predict_net)\n\n logger.info(\"Running init_net once to fill the parameters ...\")\n with ScopedWS(self.ws_name, is_reset=True, is_cleanup=False) as ws:\n ws.RunNetOnce(init_net)\n uninitialized_external_input = []\n for blob in self.net.Proto().external_input:\n if blob not in ws.Blobs():\n uninitialized_external_input.append(blob)\n ws.CreateBlob(blob)\n ws.CreateNet(self.net)\n\n self._error_msgs = set()\n self._input_blobs = uninitialized_external_input\n\n def _infer_output_devices(self, inputs):\n \"\"\"\n Returns:\n list[str]: list of device for each external output\n \"\"\"\n\n def _get_device_type(torch_tensor):\n assert torch_tensor.device.type in [\"cpu\", \"cuda\"]\n assert torch_tensor.device.index == 0\n return torch_tensor.device.type\n\n predict_net = self.net.Proto()\n input_device_types = {\n (name, 0): _get_device_type(tensor) for name, tensor in zip(self._input_blobs, inputs)\n }\n device_type_map = infer_device_type(\n predict_net, known_status=input_device_types, device_name_style=\"pytorch\"\n )\n ssa, versions = core.get_ssa(predict_net)\n versioned_outputs = [(name, versions[name]) for name in predict_net.external_output]\n output_devices = [device_type_map[outp] for outp in versioned_outputs]\n return output_devices\n\n def forward(self, inputs):\n \"\"\"\n Args:\n inputs (tuple[torch.Tensor])\n\n Returns:\n dict[str, torch.Tensor]\n \"\"\"\n assert len(inputs) == len(self._input_blobs), (\n f\"Length of inputs ({len(inputs)}) \"\n f\"doesn't match the required input blobs: {self._input_blobs}\"\n )\n\n with ScopedWS(self.ws_name, is_reset=False, is_cleanup=False) as ws:\n for b, tensor in zip(self._input_blobs, inputs):\n ws.FeedBlob(b, tensor)\n\n try:\n ws.RunNet(self.net.Proto().name)\n except RuntimeError as e:\n if not str(e) in self._error_msgs:\n self._error_msgs.add(str(e))\n logger.warning(\"Encountered new RuntimeError: \\n{}\".format(str(e)))\n logger.warning(\"Catch the error and use partial results.\")\n\n c2_outputs = [ws.FetchBlob(b) for b in self.net.Proto().external_output]\n # Remove outputs of current run, this is necessary in order to\n # prevent fetching the result from previous run if the model fails\n # in the middle.\n for b in self.net.Proto().external_output:\n # Needs to create uninitialized blob to make the net runable.\n # This is \"equivalent\" to: ws.RemoveBlob(b) then ws.CreateBlob(b),\n # but there'no such API.\n ws.FeedBlob(b, f\"{b}, a C++ native class of type nullptr (uninitialized).\")\n\n # Cast output to torch.Tensor on the desired device\n output_devices = (\n self._infer_output_devices(inputs)\n if any(t.device.type != \"cpu\" for t in inputs)\n else [\"cpu\" for _ in self.net.Proto().external_output]\n )\n\n outputs = []\n for name, c2_output, device in zip(\n self.net.Proto().external_output, c2_outputs, output_devices\n ):\n if not isinstance(c2_output, np.ndarray):\n raise RuntimeError(\n \"Invalid output for blob {}, received: {}\".format(name, c2_output)\n )\n outputs.append(torch.Tensor(c2_output).to(device=device))\n # TODO change to tuple in the future\n return dict(zip(self.net.Proto().external_output, outputs))\n\n\nclass ProtobufDetectionModel(torch.nn.Module):\n \"\"\"\n A class works just like a pytorch meta arch in terms of inference, but running\n caffe2 model under the hood.\n \"\"\"\n\n def __init__(self, predict_net, init_net, *, convert_outputs=None):\n \"\"\"\n Args:\n predict_net, init_net (core.Net): caffe2 nets\n convert_outptus (callable): a function that converts caffe2\n outputs to the same format of the original pytorch model.\n By default, use the one defined in the caffe2 meta_arch.\n \"\"\"\n super().__init__()\n self.protobuf_model = ProtobufModel(predict_net, init_net)\n self.size_divisibility = get_pb_arg_vali(predict_net, \"size_divisibility\", 0)\n self.device = get_pb_arg_vals(predict_net, \"device\", b\"cpu\").decode(\"ascii\")\n\n if convert_outputs is None:\n meta_arch = get_pb_arg_vals(predict_net, \"meta_architecture\", b\"GeneralizedRCNN\")\n meta_arch = META_ARCH_CAFFE2_EXPORT_TYPE_MAP[meta_arch.decode(\"ascii\")]\n self._convert_outputs = meta_arch.get_outputs_converter(predict_net, init_net)\n else:\n self._convert_outputs = convert_outputs\n\n def _convert_inputs(self, batched_inputs):\n # currently all models convert inputs in the same way\n return convert_batched_inputs_to_c2_format(\n batched_inputs, self.size_divisibility, self.device\n )\n\n def forward(self, batched_inputs):\n c2_inputs = self._convert_inputs(batched_inputs)\n c2_results = self.protobuf_model(c2_inputs)\n return self._convert_outputs(batched_inputs, c2_inputs, c2_results)\n"
] |
[
[
"torch.Tensor"
]
] |
joycenerd/GenRep
|
[
"9cc21dd4b81d6649659308c42c192b0be73a040d"
] |
[
"main_unified_inverter.py"
] |
[
"from __future__ import print_function\n\nimport numpy as np\nimport os\nimport sys\nimport argparse\nimport time\nimport math\n\nimport torchvision.utils as vutils\nimport tensorboard_logger as tb_logger\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom torchvision import transforms, datasets\n\nfrom util import TwoCropTransform, AverageMeter, GansetDataset, GansteerDataset\nfrom util import adjust_learning_rate, warmup_learning_rate, accuracy\nfrom util import set_optimizer, save_model\nfrom networks.resnet_big import SupConResNet, SupCEResNet, SupInverterResNet, UnsupInverterResNet\nfrom losses import SupConLoss, SupInverterLoss, UnsupInverterLoss\nimport oyaml as yaml\n\ntry:\n import apex\n from apex import amp, optimizers\nexcept ImportError:\n pass\n\n\ndef parse_option():\n parser = argparse.ArgumentParser('argument for training')\n parser.add_argument('--encoding_type', type=str, default='contrastive',\n choices=['contrastive', 'crossentropy', 'inverter'])\n parser.add_argument('--print_freq', type=int, default=10,\n help='print frequency')\n parser.add_argument('--save_freq', type=int, default=20,\n help='save frequency')\n parser.add_argument('--batch_size', type=int, default=256,\n help='batch_size')\n parser.add_argument('--num_workers', type=int, default=16,\n help='num of workers to use')\n parser.add_argument('--epochs', type=int, default=200,\n help='number of training epochs')\n parser.add_argument('--showimg', action='store_true', help='display image in tensorboard')\n parser.add_argument('--removeimtf', action='store_true', help='on/off transformations for inverter')\n # optimization\n parser.add_argument('--learning_rate', type=float, default=0.03,\n help='learning rate')\n parser.add_argument('--lr_decay_epochs', type=str, default='120,160',\n help='where to decay lr, can be a list')\n parser.add_argument('--lr_decay_rate', type=float, default=0.1,\n help='decay rate for learning rate')\n parser.add_argument('--weight_decay', type=float, default=1e-4,\n help='weight decay')\n parser.add_argument('--momentum', type=float, default=0.9,\n help='momentum')\n\n # model dataset\n parser.add_argument('--model', type=str, default='resnet50')\n parser.add_argument('--dataset', type=str, default='biggan',\n choices=['biggan', 'cifar10', 'cifar100', 'imagenet100', 'imagenet100K', 'imagenet'], help='dataset')\n\n ## Ali: todo: this should be based on opt.encoding type and remove the default (revisit every default) and name of the model for saving\n # method\n parser.add_argument('--numcontrast', type=int, default=20,\n help='num of workers to use')\n parser.add_argument('--method', type=str, default='SimCLR',\n choices=['SupCon', 'SimCLR'], help='choose method')\n parser.add_argument('--walk_method', type=str, choices=['none', 'random', 'steer', 'pca'], help='choose method')\n\n # temperature\n parser.add_argument('--temp', type=float, default=0.1,\n help='temperature for loss function')\n\n # other setting\n parser.add_argument('--cosine', action='store_true', help='using cosine annealing')\n parser.add_argument('--syncBN', action='store_true',\n help='using synchronized batch normalization')\n parser.add_argument('--warm', action='store_true',\n help='warm-up for large batch training')\n parser.add_argument('--trial', type=str, default='0',\n help='id for recording multiple runs')\n\n # specifying folders\n parser.add_argument('-d', '--data_folder', type=str,\n default='/data/scratch-oc40/jahanian/ganclr_results/ImageNet100',\n help='the data folder')\n parser.add_argument('-s', '--cache_folder', type=str,\n default='/data/scratch-oc40/jahanian/ganclr_results/',\n help='the saving folder')\n\n opt = parser.parse_args()\n\n # set the path according to the environment\n opt.data_folder = opt.data_folder\n if opt.encoding_type == 'crossentropy':\n opt.method = 'SupCE'\n opt.model_path = os.path.join(opt.cache_folder, 'SupCE/{}_models'.format(opt.dataset))\n opt.tb_path = os.path.join(opt.cache_folder, 'SupCE/{}_tensorboard'.format(opt.dataset))\n elif opt.encoding_type == 'inverter': \n if opt.method == 'SupCon':\n opt.method = 'SupInv'\n elif opt.method == 'SimCLR':\n opt.method = 'UnsupInv'\n opt.model_path = os.path.join(opt.cache_folder, '{}/{}_models'.format(opt.method, opt.dataset))\n opt.tb_path = os.path.join(opt.cache_folder, '{}/{}_tensorboard'.format(opt.method, opt.dataset))\n\n else:\n opt.model_path = os.path.join(opt.cache_folder, '{}/{}_models'.format(opt.method, opt.dataset))\n opt.tb_path = os.path.join(opt.cache_folder, '{}/{}_tensorboard'.format(opt.method, opt.dataset))\n\n iterations = opt.lr_decay_epochs.split(',')\n opt.lr_decay_epochs = list([])\n for it in iterations:\n opt.lr_decay_epochs.append(int(it))\n\n opt.model_name = '{}_{}_{}_ncontrast.{}_lr_{}_decay_{}_bsz_{}_temp_{}_trial_{}'.\\\n format(opt.method, opt.dataset, opt.model, opt.numcontrast, opt.learning_rate, \n opt.weight_decay, opt.batch_size, opt.temp, opt.trial)\n\n if opt.encoding_type == 'inverter':\n opt.model_name = '{}_{}_{}_lr_{}_decay_{}_bsz_{}_temp_{}_trial_{}'.\\\n format(opt.method, opt.dataset, opt.model, opt.learning_rate, \n opt.weight_decay, opt.batch_size, opt.temp, opt.trial) \n\n if opt.cosine:\n opt.model_name = '{}_cosine'.format(opt.model_name)\n\n opt.model_name = '{}_{}'.format(opt.model_name, os.path.basename(opt.data_folder))\n # warm-up for large-batch training,\n if opt.batch_size > 256:\n opt.warm = True\n if opt.warm:\n opt.model_name = '{}_warm'.format(opt.model_name)\n opt.warmup_from = 0.01\n opt.warm_epochs = 10\n if opt.cosine:\n eta_min = opt.learning_rate * (opt.lr_decay_rate ** 3)\n opt.warmup_to = eta_min + (opt.learning_rate - eta_min) * (\n 1 + math.cos(math.pi * opt.warm_epochs / opt.epochs)) / 2\n else:\n opt.warmup_to = opt.learning_rate\n \n opt.tb_folder = os.path.join(opt.tb_path, opt.model_name)\n if not os.path.isdir(opt.tb_folder):\n os.makedirs(opt.tb_folder)\n\n opt.save_folder = os.path.join(opt.model_path, opt.model_name)\n if not os.path.isdir(opt.save_folder):\n os.makedirs(opt.save_folder)\n\n if opt.dataset == 'biggan' or opt.dataset == 'imagenet100' or opt.dataset == 'imagenet100K' or opt.dataset == 'imagenet':\n # or 256 as you like\n opt.img_size = 128\n opt.n_cls = 1000\n elif opt.dataset == 'cifar10' or opt.dataset == 'cifar100':\n opt.img_size = 32\n\n return opt\n\n\ndef set_loader(opt):\n # construct data loader\n if opt.dataset == 'cifar10':\n mean = (0.4914, 0.4822, 0.4465)\n std = (0.2023, 0.1994, 0.2010)\n elif opt.dataset == 'cifar100':\n mean = (0.5071, 0.4867, 0.4408)\n std = (0.2675, 0.2565, 0.2761)\n elif opt.dataset == 'biggan' or opt.dataset == 'imagenet100' or opt.dataset == 'imagenet100K' or opt.dataset == 'imagenet':\n mean = (0.485, 0.456, 0.406)\n std = (0.229, 0.224, 0.225)\n else:\n raise ValueError('dataset not supported: {}'.format(opt.dataset))\n normalize = transforms.Normalize(mean=mean, std=std)\n opt.mean = mean\n opt.std = std\n \n if opt.removeimtf:\n print('>>> removeimtf is ON.')\n train_transform = transforms.Compose([\n transforms.CenterCrop(size=int(opt.img_size*0.875)),\n transforms.ToTensor(),\n normalize,\n ])\n else:\n train_transform = transforms.Compose([\n transforms.RandomResizedCrop(size=int(opt.img_size*0.875), scale=(0.2, 1.)),\n transforms.RandomHorizontalFlip(),\n transforms.RandomApply([\n transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)\n ], p=0.8),\n transforms.RandomGrayscale(p=0.2),\n transforms.ToTensor(),\n normalize,\n ])\n \n \n\n# train_transform = transforms.Compose([\n# transforms.RandomResizedCrop(size=int(opt.img_size*0.875), scale=(0.2, 1.)),\n# transforms.RandomHorizontalFlip(),\n# transforms.RandomApply([\n# transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)\n# ], p=0.8),\n# transforms.RandomGrayscale(p=0.2),\n# transforms.ToTensor(),\n# normalize,\n# ])\n\n if opt.dataset == 'cifar10':\n train_dataset = datasets.CIFAR10(root=opt.data_folder,\n transform=TwoCropTransform(train_transform),\n download=True)\n elif opt.dataset == 'cifar100':\n train_dataset = datasets.CIFAR100(root=opt.data_folder,\n transform=TwoCropTransform(train_transform),\n download=True)\n elif opt.dataset == 'imagenet100' or opt.dataset == 'imagenet100K' or opt.dataset == 'imagenet':\n train_dataset = datasets.ImageFolder(root=os.path.join(opt.data_folder, 'train'),\n transform=TwoCropTransform(train_transform))\n elif opt.dataset == 'biggan':\n if opt.walk_method == 'random':\n train_dataset = GansetDataset(root_dir=os.path.join(opt.data_folder, 'train'), \n transform=train_transform, numcontrast=opt.numcontrast, \n method=opt.method) \n\n elif opt.walk_method == 'steer':\n train_dataset = GansteerDataset(root_dir=os.path.join(opt.data_folder, 'train'), \n transform=train_transform, numcontrast=opt.numcontrast, \n method=opt.method) \n elif opt.walk_method == 'none':\n train_dataset = datasets.ImageFolder(root=os.path.join(opt.data_folder, 'train'),\n transform=TwoCropTransform(train_transform))\n ## Ali: ToDo: elif opt.walk_method == 'pca'...\n else:\n raise ValueError(opt.dataset)\n\n train_sampler = None\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=opt.batch_size, shuffle=(train_sampler is None),\n num_workers=opt.num_workers, pin_memory=True, sampler=train_sampler)\n\n return train_loader\n\n\ndef set_model(opt):\n if opt.encoding_type == 'contrastive':\n model = SupConResNet(name=opt.model, img_size=int(opt.img_size*0.875))\n criterion = SupConLoss(temperature=opt.temp)\n\n elif opt.encoding_type == 'crossentropy':\n model = SupCEResNet(name=opt.model, num_classes=opt.n_cls, img_size=int(opt.img_size*0.875))\n criterion = torch.nn.CrossEntropyLoss()\n\n elif opt.encoding_type == 'inverter':\n if opt.method == 'SupInv':\n model = SupInverterResNet(name=opt.model, img_size=int(opt.img_size*0.875))\n criterion = SupInverterLoss()\n elif opt.method == 'UnsupInv':\n model = UnsupInverterResNet(name=opt.model, img_size=int(opt.img_size*0.875))\n criterion = UnsupInverterLoss()\n\n # enable synchronized Batch Normalization\n if opt.syncBN:\n model = apex.parallel.convert_syncbn_model(model)\n\n if torch.cuda.is_available():\n if torch.cuda.device_count() > 1:\n model.encoder = torch.nn.DataParallel(model.encoder)\n model = model.cuda()\n criterion = criterion.cuda()\n cudnn.benchmark = True\n\n return model, criterion\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, opt):\n \"\"\"one epoch training\"\"\"\n model.train()\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n\n # top1 = AverageMeter()\n top1 = 0 ##Ali ToDo: deal with this top1\n end = time.time()\n\n ## Ali: Todo: this data loading depends on if we generate positive on the fly or load them. if loading then we have data[0] and data[1]\n ## so we need to check for opt.encoding_type (currently it's good for SupCon with gan data, i.e., positive pairs are from gan)\n\n # for idx, (images, labels) in enumerate(train_loader):\n # data_time.update(time.time() - end)\n print(\"Start train\")\n # t1 = time.time()\n\n for idx, data in enumerate(train_loader):\n # print('batch loading time', time.time() - t1)\n # t2 = time.time()\n if len(data) == 2:\n images = data[0]\n labels = data[1]\n elif len(data) == 3:\n images = data[:2]\n labels = data[2]\n elif len(data) == 4:\n images = data[:2]\n labels = data[2] \n labels_class = data[3]\n elif len(data) == 5:\n images = data[:2]\n labels = data[2] \n labels_class = data[3]\n z_vect = data[4] \n else:\n raise NotImplementedError\n \n data_time.update(time.time() - end)\n if opt.encoding_type == 'crossentropy':\n # We only pick one of images\n images = images[1]\n elif opt.encoding_type == 'inverter':\n # We only pick one of images and that's anchor\n# images = images[0] # <== this is for pairing z_anchor and anchor\n images = images[1] # <== this is for pairing z_anchor and anchor\n\n # also only pick z_vect[0] ToDo: if alwasy the case just send z anchor (channel 0) from loader, but make sure image is also images[0]\n z_vect = z_vect[0].cuda(non_blocking=True) \n\n elif opt.encoding_type == 'contrastive':\n ims = images[0]\n anchors = images[1]\n images = torch.cat([images[0].unsqueeze(1), images[1].unsqueeze(1)],\n dim=1)\n # print('2) images shape', images.shape)\n\n images = images.view(-1, 3, int(opt.img_size*0.875), int(opt.img_size*0.875)).cuda(non_blocking=True)\n # print('3) images shape', images.shape)\n\n labels = labels.cuda(non_blocking=True)\n bsz = labels.shape[0]\n # warm-up learning rate\n warmup_learning_rate(opt, epoch, idx, len(train_loader), optimizer)\n # compute loss\n\n if opt.encoding_type == 'contrastive':\n features = model(images)\n features = features.view(bsz, 2, -1)\n if opt.method == 'SupCon':\n loss = criterion(features, labels)\n elif opt.method == 'SimCLR':\n loss = criterion(features)\n else:\n raise ValueError('contrastive method not supported: {}'.\n format(opt.method))\n elif opt.encoding_type == 'crossentropy':\n output = model(images)\n loss = criterion(output, labels)\n acc1, acc5 = accuracy(output, labels, topk=(1, 5))\n top1.update(acc1[0], bsz)\n elif opt.encoding_type == 'inverter':\n top1 = 0\n #print('images.shape:', images.shape)\n output = model(images.cuda()) # images.shape: [256, 3, 112, 112]\n if opt.method == 'SupInv':\n loss, loss_z, loss_y = criterion(output, z_vect, labels) #how many images as images? output is z and y and z_vect[0] is zs and z_vect[1] are y and are shape [256, 128] and [256, 1000]\n elif opt.method == 'UnsupInv':\n loss = criterion(output, z_vect) #how many images as images? output is z and y and z_vect[0] is zs and z_vect[1] are y and are shape [256, 128] and [256, 1000]\n\n ## Ali: ToDo deal with this top1 \n # acc1, acc5 = accuracy(output, labels, topk=(1, 5))\n # top1.update(acc1[0], bsz)\n top1 = 0\n\n else:\n raise NotImplementedError\n # t3 = time.time()\n # print('{}- spent time before loss update: {}'.format(idx, t3 - t2)) \n # update metric\n losses.update(loss.item(), bsz)\n\n # SGD\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # t4 = time.time()\n # print('{}- spent after before loss update: {}'.format(idx, t4 - t3)) \n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n # print info\n if (idx + 1) % opt.print_freq == 0:\n if opt.encoding_type == 'crossentropy':\n print('Train: [{0}][{1}/{2}]\\t'\n 'BT {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'DT {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'loss {loss.val:.3f} ({loss.avg:.3f})\\t'\n 'Acc@1 {top1.val:.3f} ({top1.avg:.3f})'.format(\n epoch, idx + 1, len(train_loader), batch_time=batch_time,\n data_time=data_time, loss=losses, top1=top1))\n else:\n print('Train: [{0}][{1}/{2}]\\t'\n 'BT {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'DT {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'loss {loss.val:.3f} ({loss.avg:.3f})'.format(\n epoch, idx + 1, len(train_loader), batch_time=batch_time,\n data_time=data_time, loss=losses))\n sys.stdout.flush()\n # t1 = time.time()\n other_metrics = {}\n\n if opt.encoding_type == 'crossentropy':\n other_metrics['top1_acc'] = top1.avg\n elif opt.encoding_type == 'contrastive':\n if opt.showimg:\n other_metrics['image'] = [ims[:8], anchors[:8]]\n elif opt.encoding_type == 'inverter':\n if opt.showimg:\n other_metrics['image'] = [images[:8]]\n\n\n if opt.method == 'SupInv':\n return losses.avg, other_metrics, loss_z, loss_y\n elif opt.method == 'UnsupInv':\n return losses.avg, other_metrics, loss\n\n else:\n return losses.avg, other_metrics\n\n\ndef main():\n opt = parse_option()\n\n with open(os.path.join(opt.save_folder, 'optE.yml'), 'w') as f:\n yaml.dump(vars(opt), f, default_flow_style=False)\n\n # build data loader\n # opt.encoding_type tells us how to get training data\n train_loader = set_loader(opt)\n\n # build model and criterion\n # opt.encoding_type tells us what to put as the head; choices are:\n # contrastive -> mlp or linear\n # crossentropy -> one linear for pred_y\n # inverter -> one linear for pred_z and one linear for pred_y\n model, criterion = set_model(opt)\n\n # build optimizer\n optimizer = set_optimizer(opt, model)\n\n # tensorboard\n logger = tb_logger.Logger(logdir=opt.tb_folder, flush_secs=2)\n\n # training routine\n for epoch in range(1, opt.epochs + 1):\n adjust_learning_rate(opt, optimizer, epoch)\n\n # train for one epoch\n time1 = time.time()\n if opt.method == 'SupInv':\n loss, other_metrics,loss_z, loss_y = train(train_loader, model, criterion, optimizer, epoch, opt)\n logger.log_value('total loss', loss, epoch)\n logger.log_value('loss_z', loss_z, epoch)\n logger.log_value('loss_y', loss_y, epoch)\n elif opt.method == 'UnsupInv':\n loss, other_metrics,loss = train(train_loader, model, criterion, optimizer, epoch, opt)\n logger.log_value('loss_z', loss, epoch)\n else:\n loss, other_metrics = train(train_loader, model, criterion, optimizer, epoch, opt)\n logger.log_value('loss', loss, epoch)\n time2 = time.time()\n print('epoch {}, total time {:.2f}'.format(epoch, time2 - time1))\n\n # tensorboard logger\n # logger.log_value('loss', loss, epoch)\n logger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch)\n for metric_name, metric_value in other_metrics.items():\n if metric_name == 'image':\n images = metric_value\n anchors = images[0]\n otherims = images[1]\n bs = anchors.shape[0]\n grid_images = vutils.make_grid(\n torch.cat((anchors, otherims)), nrow=bs)\n grid_images *= np.array(opt.std)[:, None, None]\n grid_images += np.array(opt.mean)[:, None, None]\n grid_images = (255*grid_images.cpu().numpy()).astype(np.uint8)\n grid_images = grid_images[None, :].transpose(0,2,3,1)\n logger.log_images(metric_name, grid_images, epoch)\n else:\n logger.log_value(metric_name, metric_value, epoch)\n\n if epoch % opt.save_freq == 0:\n save_file = os.path.join(\n opt.save_folder, 'ckpt_epoch_{epoch}.pth'.format(epoch=epoch))\n save_model(model, optimizer, opt, epoch, save_file)\n\n # save the last model\n save_file = os.path.join(\n opt.save_folder, 'last.pth')\n save_model(model, optimizer, opt, opt.epochs, save_file)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.nn.DataParallel",
"torch.cuda.is_available",
"torch.cuda.device_count",
"numpy.array"
]
] |
KoenvanLoon/EWS
|
[
"3447921ec2140f29fd69d5b140b5eba2f244bccd"
] |
[
"EWS/EWS_weekly.py"
] |
[
"\"\"\"\r\nEWS - Early Warning Signals\r\nEWS_weekly\r\n\r\n@authors: KoenvanLoon & TijmenJanssen\r\n\"\"\"\r\n\r\nfrom pcraster import *\r\nimport numpy as np\r\nimport os\r\nimport time\r\n\r\nimport EWSPy as ews\r\nimport EWS_configuration as cfg\r\nimport NULL_models_timeseries_weekly as temp_NULL\r\nimport NULL_models_spatial_weekly as spat_NULL\r\nimport EWS_StateVariables as ews_sv\r\n\r\n\r\n# State variables for EWS calculations\r\n\"\"\"\r\nVariables (state variables) can be both 'ews_sv.variables_weekly' or 'ews_sv.variables_hourly' for calculating\r\nearly-warning signals for the week or hour model respectively. State variables present in EWS_StateVariables.py can\r\nbe added through the configuration.\r\n\r\nArgs:\r\n-----\r\n\r\nvariables : The state variables for which calculations are done.\r\n\r\n\"\"\"\r\n\r\nvariables = ews_sv.variables_weekly\r\n\r\n\r\n# Spatial interval\r\n\"\"\"\r\nThe spatial interval differs if a cutoff point is selected or not. If there is a cutoff point, no calculations are done\r\non spatial datasets after this point.\r\n\r\nArgs:\r\n-----\r\n\r\nspatial_ews_interval : 2D numpy array containing the time steps at which a spatial dataset was created.\r\n\r\n\"\"\"\r\n\r\nif not cfg.cutoff:\r\n spatial_ews_interval = np.arange(cfg.interval_map_snapshots, cfg.number_of_timesteps_weekly +\r\n cfg.interval_map_snapshots, cfg.interval_map_snapshots)\r\nelif cfg.cutoff:\r\n spatial_ews_interval = np.arange(cfg.interval_map_snapshots, cfg.cutoff_point + cfg.interval_map_snapshots,\r\n cfg.interval_map_snapshots)\r\n\r\n\r\n# Time series to time windows\r\n\"\"\"\r\nDivides a time series (2D numpy array) into an array of evenly sized time windows (2D numpy arrays). If remaining data-\r\npoints do not fill the last time window, they are dropped from the stack of time windows.\r\n\r\nArgs:\r\n-----\r\n\r\ntimeseries : A 2D numpy array containing data points of a early-warning signal.\r\n\r\nwindow_size : The size (int) of the windows into which the time series is to be divided.\r\n\r\nwindow_overlap : The number (int) of data points in the window equal to the last data points of the previous time \r\n window.\r\n\r\nReturns:\r\n-----\r\n\r\nview : A 3D numpy array containing evenly sized time windows (2D numpy arrays).\r\n\r\n ! - Note that the amount of data points in 'view' does not need to be equal to the amount of data points in \r\n 'timeseries' due to the possibility of dropping data points if they do not fill the last time window completely.\r\n\r\n\"\"\"\r\n\r\n\r\ndef time_series2time_windows(timeseries, window_size=100, window_overlap=0):\r\n actual_window_overlap = window_size - window_overlap\r\n sh = (timeseries.size - window_size + 1, window_size)\r\n st = timeseries.strides * 2\r\n if window_overlap != 0:\r\n view = np.lib.stride_tricks.as_strided(timeseries, strides=st, shape=sh)[0::actual_window_overlap]\r\n elif window_overlap == 0:\r\n view = np.lib.stride_tricks.as_strided(timeseries, strides=st, shape=sh)[0::window_size]\r\n return view\r\n\r\n\r\n# Generate datasets (initial)\r\n\"\"\"\r\nInitializes dataset generation. Datasets are generated for method(s) selected in the configuration when \r\ngenerate_dummy_datasets is set to True. \r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py \r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\nnr_realizations : int, the number of datasets generated.\r\n\r\nmethod1 : bool, selects whether this method is utilized.\r\n\r\nmethod2 : bool, selects whether this method is utilized.\r\n\r\nmethod3 : bool, selects whether this method is utilized.\r\n\r\n\"\"\"\r\n\r\n\r\ndef generate_datasets_init(variable, path='./1/', nr_realizations=1, method1=False, method2=False, method3=False):\r\n if variable.temporal:\r\n state_variable_timeseries, files_present = temporal_data_file_loading(variable, path=path)\r\n\r\n if files_present:\r\n if state_variable_timeseries.ndim == 1:\r\n # Detrending: 'None', 'Gaussian'\r\n state_variable_timeseries = generate_datasets_main(variable, state_variable_timeseries,\r\n temp_NULL.detrend_, nr_realizations=nr_realizations,\r\n path=path)\r\n # Generate dummy datasets\r\n if method1:\r\n generate_datasets_main(variable, state_variable_timeseries, temp_NULL.method1_,\r\n nr_realizations=nr_realizations, path=path)\r\n if method2:\r\n generate_datasets_main(variable, state_variable_timeseries, temp_NULL.method2_,\r\n nr_realizations=nr_realizations, path=path)\r\n if method3:\r\n generate_datasets_main(variable, state_variable_timeseries, temp_NULL.method3_,\r\n nr_realizations=nr_realizations, path=path)\r\n else:\r\n print(f\"Multiple dimensions are currently not supported for generated datasets, so no datasets are being \"\r\n f\"generated for {variable.name}.\")\r\n\r\n if variable.spatial:\r\n state_variable_snapshots, files_present = spatial_data_file_loading(variable, path=path)\r\n if files_present:\r\n state_variable_snapshots = np.asarray(state_variable_snapshots)\r\n\r\n # Generate dummy datasets\r\n # Detrending: 'None', 'Linear', 'Gaussian'\r\n state_variable_snapshots = generate_datasets_main(variable, state_variable_snapshots, spat_NULL.detrend_,\r\n nr_realizations=nr_realizations, path=path)\r\n if method1:\r\n generate_datasets_main(variable, state_variable_snapshots, spat_NULL.method1_,\r\n nr_realizations=nr_realizations, path=path)\r\n if method2:\r\n generate_datasets_main(variable, state_variable_snapshots, spat_NULL.method2_,\r\n nr_realizations=nr_realizations, path=path)\r\n if method3:\r\n generate_datasets_main(variable, state_variable_snapshots, spat_NULL.method3_,\r\n nr_realizations=nr_realizations, path=path)\r\n\r\n\r\n# Generate datasets (main)\r\n\"\"\"\r\nInitializes dataset generation. Datasets are generated for method(s) selected in the configuration when \r\ngenerate_dummy_datasets is set to True. \r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py\r\n\r\nstate_variable : The data for which datasets are to be generated. Can be either temporal or spatial data.\r\n\r\nmethod : function, either detrend_, method1_, method2_ or method3_ from the spatial or temporal null models.\r\n\r\nnr_realizations : int, the number of datasets generated.\r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\nRerturns:\r\n-----\r\n\r\ndetrended_data : Optional return, only returns when method==detrend_ for time series.\r\n\r\n\"\"\"\r\n\r\n\r\ndef generate_datasets_main(variable, state_variable, method, nr_realizations=1, path='./1/'):\r\n print(f\"Started generating dataset(s) for {variable.name} using {method.__name__}\")\r\n detrended_data = method(state_variable, realizations=nr_realizations, path=path, file_name=variable.name)\r\n print(f\"Finished generating dataset(s) for {variable.name} using {method.__name__} \\n\")\r\n if method.__name__ == temp_NULL.detrend_.__name__:\r\n return detrended_data\r\n\r\n\r\n# Calculate EWS generated datasets (initial)\r\n\"\"\"\r\nInitializes calculation of generated datasets by passing them to the ews_calculations_main() function. \r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py \r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\nnr_realizations : int, the number of datasets generated.\r\n\r\ntimer_on : bool, selects whether calculation time is shown in the console.\r\n\r\nmethod1 , method2 , method3 : bool, selects whether this method is utilized.\r\n\r\n\"\"\"\r\n\r\n\r\ndef ews_calculations_generated_datasets_init(variable, path='./1/', nr_realizations=1, timer_on=False, method1=False,\r\n method2=False, method3=False):\r\n generated_number_length = ews.generated_number_length(nr_realizations)\r\n\r\n if cfg.save_detrended_data and variable.temporal:\r\n ews_calculations_generated_datasets_main(variable, 'dtr', gen_nr_len=generated_number_length, path=path,\r\n nr_realizations=1, timer_on=timer_on)\r\n if method1:\r\n ews_calculations_generated_datasets_main(variable, 'm1g', gen_nr_len=generated_number_length, path=path,\r\n nr_realizations=nr_realizations, timer_on=timer_on)\r\n if method2:\r\n ews_calculations_generated_datasets_main(variable, 'm2g', gen_nr_len=generated_number_length, path=path,\r\n nr_realizations=nr_realizations, timer_on=timer_on)\r\n if method3:\r\n ews_calculations_generated_datasets_main(variable, 'm3g', gen_nr_len=generated_number_length, path=path,\r\n nr_realizations=nr_realizations, timer_on=timer_on)\r\n\r\n\r\n# Calculate EWS generated datasets (main)\r\n\"\"\"\r\nInitializes calculation of generated datasets by passing them to the ews_calculations_init() function.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py \r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\nnr_realizations : int, the number of datasets generated.\r\n\r\nmethod1 , method2, method3 : bool, selects whether this method is utilized.\r\n\r\n\"\"\"\r\n\r\n\r\ndef ews_calculations_generated_datasets_main(variable, method, gen_nr_len=4, path='./1/', nr_realizations=1, timer_on=False):\r\n for realization in range(nr_realizations):\r\n generated_number_string = method + str(realization).zfill(gen_nr_len) + '/'\r\n dir_name = os.path.join(path + generated_number_string)\r\n ews_calculations_init(variable, path=dir_name, timer_on=timer_on)\r\n\r\n\r\n# Loading temporal data file(s)\r\n\"\"\"\r\nLoads files containing temporal data.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py \r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\nReturns:\r\n-----\r\n\r\nstate_variable_timeseries : the timeseries containing the temporal data.\r\n\r\nEWS_calculations : bool, whether the datafiles are found and if EWS calculations can be performed.\r\n\r\n\"\"\"\r\n\r\n\r\ndef temporal_data_file_loading(variable, path='./1/'):\r\n state_variable_timeseries = []\r\n EWS_calculations = True\r\n if variable.datatype == 'numpy':\r\n file_name = ews.file_name_str(variable.name, cfg.number_of_timesteps_weekly)\r\n if os.path.exists(path + file_name + \".numpy.txt\"):\r\n state_variable_timeseries = np.loadtxt(path + file_name + \".numpy.txt\")\r\n else:\r\n print(f\"{file_name}.numpy.txt not found in {path}\")\r\n EWS_calculations = False\r\n else:\r\n print(f\"Datatype for {variable.name} currently not supported.\")\r\n EWS_calculations = False\r\n\r\n return state_variable_timeseries, EWS_calculations\r\n\r\n\r\n# Dividing timeseries into windows\r\n\"\"\"\r\nDivides a timeseries (optionally of multiple locations) (2D or 3D numpy array) into multiple windows.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py \r\n\r\nstate_variable_timeseries : The timeseries (2D or 3D numpy array) of the state variable.\r\n\r\nReturns:\r\n-----\r\n\r\nstack_of_windows : 3D numpy array containing the timeseries subdivided into windows.\r\n\r\nnr_dim : int, the number of dimensions of the original timeseries.\r\n\r\nstack_x , stack_y : x and y component of a stack of windows for multiple locations before flattening.\r\n\r\n\"\"\"\r\n\r\n\r\ndef window_stacker(variable, state_variable_timeseries):\r\n nr_dim = state_variable_timeseries.ndim\r\n if nr_dim == 1:\r\n if cfg.cutoff:\r\n state_variable_timeseries = state_variable_timeseries[:cfg.cutoff_point]\r\n stack_of_windows = time_series2time_windows(state_variable_timeseries, variable.window_size,\r\n variable.window_overlap)\r\n stack_x, stack_y = np.asarray(stack_of_windows).shape\r\n else:\r\n stack_of_windows = [0.0] * np.asarray(state_variable_timeseries).shape[1]\r\n for k, timeseries in enumerate(state_variable_timeseries.T):\r\n if cfg.cutoff:\r\n stack_of_windows[k] = time_series2time_windows(timeseries[:cfg.cutoff_point],\r\n variable.window_size, variable.window_overlap)\r\n elif not cfg.cutoff:\r\n stack_of_windows[k] = time_series2time_windows(timeseries, variable.window_size,\r\n variable.window_overlap)\r\n stack_x, stack_y, stack_z = np.asarray(stack_of_windows).shape\r\n stack_of_windows = np.asarray(stack_of_windows).reshape(-1, stack_z)\r\n return stack_of_windows, nr_dim, stack_x, stack_y\r\n\r\n\r\n# Loading spatial data file(s)\r\n\"\"\"\r\nLoads files containing spatial data.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py \r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\nReturns:\r\n-----\r\n\r\nstate_variable_snapshots : the snapshots containing the spatial data.\r\n\r\nEWS_calculations : bool, whether the datafiles are found and if EWS calculations can be performed.\r\n\r\n\"\"\"\r\n\r\n\r\ndef spatial_data_file_loading(variable, path='./1/'):\r\n state_variable_snapshots = [0.0] * len(spatial_ews_interval)\r\n EWS_calculations = True\r\n if variable.datatype == 'numpy':\r\n for k, timestep in enumerate(spatial_ews_interval):\r\n file_name = ews.file_name_str(variable.name, timestep)\r\n if os.path.exists(path + file_name + \".numpy.txt\"):\r\n state_variable_snapshots[k] = np.loadtxt(path + file_name + 'numpy.txt')\r\n else:\r\n print(f\"{file_name}.numpy.txt not found in {path}.\")\r\n EWS_calculations = False\r\n\r\n if variable.datatype == 'map':\r\n for k, timestep in enumerate(spatial_ews_interval):\r\n file_name = ews.file_name_str(variable.name, timestep)\r\n if os.path.exists(path + file_name):\r\n state_variable_snapshots[k] = pcr2numpy(readmap(path + file_name), np.NaN)\r\n else:\r\n print(f\"{file_name} not found in {path}.\")\r\n EWS_calculations = False\r\n else:\r\n print(f\"Datatype for {variable.name} currently not supported.\")\r\n EWS_calculations = False\r\n\r\n return state_variable_snapshots, EWS_calculations\r\n\r\n\r\n# Calculating and saving EWS\r\n\"\"\"\r\nCalculates early-warning signals and saves the results.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py\r\n\r\ndata : The spatial or temporal data from the model.\r\n\r\nmethod_name : str, element of the name under which the EWS is saved which refers to the dimension (s for spatial, t for\r\n temporal) and the statistic/method (e.g. mn for mean).\r\n \r\nmethod_function : function, selects the statistic/method used to calculate the (possible) EWS.\r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\nnr_dim : int, the number of dimensions of the original timeseries.\r\n\r\nstack_x , stack_y : x and y component of a stack of windows for multiple locations before flattening.\r\n\r\n\"\"\"\r\n\r\n\r\ndef ews_calc_and_save(variable, data, method_name, method_function, path='./1/', nr_dim=1, stack_x=1, stack_y=1):\r\n fpath = os.path.join(path + variable.name + method_name)\r\n signal = method_function(data)\r\n if nr_dim > 1:\r\n signal = signal.reshape(stack_x, stack_y)\r\n np.savetxt(fpath + '.numpy.txt', signal)\r\n\r\n\r\n# Initializing calculating and saving EWS for temporal data\r\n\"\"\"\r\nInitializes calculating early-warning signals and saving the results for temporal data.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py\r\n\r\nstate_variable_timeseries : The temporal data from the model.\r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\n\"\"\"\r\n\r\n\r\ndef temporal_ews_calculations(variable, state_variable_timeseries, path='./1/'):\r\n stack_of_windows, nr_dim, stack_x, stack_y = window_stacker(variable, state_variable_timeseries)\r\n\r\n ews_calc_and_save(variable, stack_of_windows, '.t.mn', ews.temporal_mean, path=path, nr_dim=nr_dim, stack_x=stack_x,\r\n stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.std', ews.temporal_std, path=path, nr_dim=nr_dim, stack_x=stack_x,\r\n stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.var', ews.temporal_var, path=path, nr_dim=nr_dim, stack_x=stack_x,\r\n stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.cv', ews.temporal_cv, path=path, nr_dim=nr_dim, stack_x=stack_x,\r\n stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.skw', ews.temporal_skw, path=path, nr_dim=nr_dim, stack_x=stack_x,\r\n stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.krt', ews.temporal_krt, path=path, nr_dim=nr_dim, stack_x=stack_x,\r\n stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.acr', ews.temporal_autocorrelation, path=path, nr_dim=nr_dim,\r\n stack_x=stack_x, stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.AR1', ews.temporal_AR1, path=path, nr_dim=nr_dim, stack_x=stack_x,\r\n stack_y=stack_y)\r\n ews_calc_and_save(variable, stack_of_windows, '.t.rr', ews.temporal_returnrate, path=path, nr_dim=nr_dim,\r\n stack_x=stack_x, stack_y=stack_y)\r\n\r\n # Temporal dfa TODO - returns 3-4 values, save only 1?\r\n fpath = os.path.join(path + variable.name + '.t.dfa')\r\n _, _, _, temporal_statistic = ews.temporal_dfa(stack_of_windows, window_size=variable.window_size)\r\n # scales, fluct, coeff, propagator (== temporal statistic)\r\n if nr_dim > 1:\r\n temporal_statistic = temporal_statistic.reshape(stack_x, stack_y)\r\n np.savetxt(fpath + '.numpy.txt', temporal_statistic)\r\n\r\n # Temporal cond. het. TODO - returns 2 values, save only 1?\r\n fpath = os.path.join(path + variable.name + '.t.coh')\r\n save_p = True\r\n if save_p and nr_dim == 1:\r\n temporal_statistic = [[0.0], [0.0]]\r\n statistic, p_val = ews.temporal_cond_het(stack_of_windows)\r\n temporal_statistic[0] = statistic\r\n temporal_statistic[1] = p_val\r\n else:\r\n temporal_statistic, _ = ews.temporal_cond_het(stack_of_windows) # _ is the p-value of the test, not saved\r\n if nr_dim > 1:\r\n temporal_statistic = temporal_statistic.reshape(stack_x, stack_y)\r\n np.savetxt(fpath + '.numpy.txt', temporal_statistic)\r\n\r\n\r\n# Initializing calculating and saving EWS for spatial data\r\n\"\"\"\r\nInitializes calculating early-warning signals and saving the results for spatial data.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py\r\n\r\nstate_variable_maps : The spatial data from the model.\r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\n\"\"\"\r\n\r\n\r\ndef spatial_ews_calculations(variable, state_variable_maps, path='./1/'):\r\n ews_calc_and_save(variable, state_variable_maps, '.s.mn', ews.spatial_mean, path=path)\r\n ews_calc_and_save(variable, state_variable_maps, '.s.std', ews.spatial_std, path=path)\r\n ews_calc_and_save(variable, state_variable_maps, '.s.var', ews.spatial_var, path=path)\r\n ews_calc_and_save(variable, state_variable_maps, '.s.skw', ews.spatial_skw, path=path)\r\n ews_calc_and_save(variable, state_variable_maps, '.s.krt', ews.spatial_krt, path=path)\r\n ews_calc_and_save(variable, state_variable_maps, '.s.mI', ews.spatial_corr, path=path)\r\n\r\n\r\n# Initializing calculating and saving EWS for both spatial and temporal data\r\n\"\"\"\r\nInitializes calculating early-warning signals and saving the results for both temporal and spatial data.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py\r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\ntimer_on : bool, selects whether calculation time is shown in the console.\r\n\r\n\"\"\"\r\n\r\n\r\ndef ews_calculations_init(variable, path='./1/', timer_on=False):\r\n if variable.temporal:\r\n if cfg.mean_timeseries_data:\r\n ews_calculations_main(variable, temporal_data_file_loading, temporal_ews_calculations, path=path,\r\n timer_on=timer_on)\r\n elif not cfg.mean_timeseries_data:\r\n print(f\"Mean timeseries data == False in the configuration, could not calculate EWS for \"\r\n f\"{variable.name}.\")\r\n elif variable.spatial:\r\n if cfg.map_data:\r\n ews_calculations_main(variable, spatial_data_file_loading, spatial_ews_calculations, path=path,\r\n timer_on=timer_on)\r\n elif not cfg.map_data:\r\n print(f\"Map data == False in the configuration, could not calculate EWS for {variable.name}.\")\r\n\r\n\r\n# Initializing calculating and saving EWS for either spatial and temporal data\r\n\"\"\"\r\nInitializes calculating early-warning signals and saving the results for either temporal and spatial data.\r\n\r\nArgs:\r\n-----\r\n\r\nvariable : The state variable from the variable class presented in EWS_StateVariables.py\r\n\r\nloading_function : function, refers to temporal_data_file_loading() or spatial_data_file_loading().\r\n\r\ncalculation_function : function, refers to temporal_ews_calculations() or spatial_ews_calculations().\r\n\r\npath : str, the filepath where the original dataset can be found.\r\n\r\ntimer_on : bool, selects whether calculation time is shown in the console.\r\n\r\n\"\"\"\r\n\r\n\r\ndef ews_calculations_main(variable, loading_function, calculation_function, path='./1/', timer_on=False):\r\n state_variable, files_present = loading_function(variable, path=path)\r\n\r\n if files_present:\r\n print(f\"Started EWS calculations for {variable.name} in {path}\")\r\n if timer_on:\r\n start_time = time.time()\r\n\r\n calculation_function(variable, state_variable, path=path)\r\n\r\n if timer_on:\r\n end_time = time.time()\r\n print(f\"Elapsed time for EWS calculations for {variable.name} in {path} equals:\", end_time - start_time,\r\n '\\n')\r\n\r\n\r\n# EWS calculations & optional data generation and EWS calculations for results of the weekly model\r\n\"\"\"\r\nStarts calculations, optional data generation & calculations for results of the weekly model. Takes no arguments and \r\nreturns nothing, as settings from the configuration are used instead. Calculations are saved on disk.\r\n\r\n\"\"\"\r\n\r\n\r\ndef EWS_weekly_calculations():\r\n start_time = time.time()\r\n for realization in range(1, cfg.nrOfSamples + 1):\r\n for variable in variables:\r\n ews_calculations_init(variable, path=f'./{realization}/', timer_on=True)\r\n if cfg.generate_dummy_datasets:\r\n generate_datasets_init(variable, path=f'./{realization}/', nr_realizations=cfg.nr_generated_datasets,\r\n method1=cfg.method_1, method2=cfg.method_2, method3=cfg.method_3)\r\n ews_calculations_generated_datasets_init(variable, path=f'./{realization}/',\r\n nr_realizations=cfg.nr_generated_datasets,\r\n timer_on=True, method1=cfg.method_1, method2=cfg.method_2,\r\n method3=cfg.method_3)\r\n end_time = time.time() - start_time\r\n print(f\"Total elapsed time equals: {end_time} seconds\")\r\n\r\n\r\n# EWS calculations & optional data generation and EWS calculations for results of the hourly model\r\n\"\"\"\r\nStarts calculations, optional data generation & calculations for results of the hourly model. Takes no arguments and \r\nreturns nothing, as settings from the configuration are used instead. Calculations are saved on disk.\r\n\r\n\"\"\"\r\n\r\n\r\ndef EWS_hourly_calculations():\r\n start_time = time.time()\r\n for i in range(cfg.stepsTotal):\r\n fpath = str(i).zfill(2)\r\n for variable in variables:\r\n ews_calculations_init(variable, path=f'./h{fpath}/', timer_on=True)\r\n end_time = time.time() - start_time\r\n print(f\"Total elapsed time equals: {end_time} seconds\")\r\n\r\n\r\nEWS_weekly_calculations()\r\n"
] |
[
[
"numpy.asarray",
"numpy.arange",
"numpy.lib.stride_tricks.as_strided",
"numpy.savetxt",
"numpy.loadtxt"
]
] |
spark1729/scikit-image
|
[
"65d525bcd5f30604c9a71c3480355580e9db7162"
] |
[
"skimage/_shared/testing.py"
] |
[
"\"\"\"Testing utilities.\"\"\"\n\n\nimport os\nimport re\nfrom tempfile import NamedTemporaryFile\n\nfrom numpy import testing\nimport numpy as np\nfrom skimage._shared._warnings import expected_warnings\nimport warnings\n\nfrom .. import data, io, img_as_uint, img_as_float, img_as_int, img_as_ubyte\n\n\nSKIP_RE = re.compile(\"(\\s*>>>.*?)(\\s*)#\\s*skip\\s+if\\s+(.*)$\")\n\n\ndef _assert_less(a, b, msg=None):\n message = \"%r is not lower than %r\" % (a, b)\n if msg is not None:\n message += \": \" + msg\n assert a < b, message\n\n\ndef _assert_greater(a, b, msg=None):\n message = \"%r is not greater than %r\" % (a, b)\n if msg is not None:\n message += \": \" + msg\n assert a > b, message\n\n\ntry:\n from nose.tools import assert_less\nexcept ImportError:\n assert_less = _assert_less\n\ntry:\n from nose.tools import assert_greater\nexcept ImportError:\n assert_greater = _assert_greater\n\n\ndef doctest_skip_parser(func):\n \"\"\" Decorator replaces custom skip test markup in doctests\n\n Say a function has a docstring::\n\n >>> something # skip if not HAVE_AMODULE\n >>> something + else\n >>> something # skip if HAVE_BMODULE\n\n This decorator will evaluate the expression after ``skip if``. If this\n evaluates to True, then the comment is replaced by ``# doctest: +SKIP``. If\n False, then the comment is just removed. The expression is evaluated in the\n ``globals`` scope of `func`.\n\n For example, if the module global ``HAVE_AMODULE`` is False, and module\n global ``HAVE_BMODULE`` is False, the returned function will have docstring::\n\n >>> something # doctest: +SKIP\n >>> something + else\n >>> something\n\n \"\"\"\n lines = func.__doc__.split('\\n')\n new_lines = []\n for line in lines:\n match = SKIP_RE.match(line)\n if match is None:\n new_lines.append(line)\n continue\n code, space, expr = match.groups()\n\n try:\n # Works as a function decorator\n if eval(expr, func.__globals__):\n code = code + space + \"# doctest: +SKIP\"\n except AttributeError:\n # Works as a class decorator\n if eval(expr, func.__init__.__globals__):\n code = code + space + \"# doctest: +SKIP\"\n\n new_lines.append(code)\n func.__doc__ = \"\\n\".join(new_lines)\n return func\n\n\ndef roundtrip(img, plugin, suffix):\n \"\"\"Save and read an image using a specified plugin\"\"\"\n if not '.' in suffix:\n suffix = '.' + suffix\n temp_file = NamedTemporaryFile(suffix=suffix, delete=False)\n temp_file.close()\n fname = temp_file.name\n io.imsave(fname, img, plugin=plugin)\n new = io.imread(fname, plugin=plugin)\n try:\n os.remove(fname)\n except Exception:\n pass\n return new\n\n\ndef color_check(plugin, fmt='png'):\n \"\"\"Check roundtrip behavior for color images.\n\n All major input types should be handled as ubytes and read\n back correctly.\n \"\"\"\n img = img_as_ubyte(data.chelsea())\n r1 = roundtrip(img, plugin, fmt)\n testing.assert_allclose(img, r1)\n\n img2 = img > 128\n r2 = roundtrip(img2, plugin, fmt)\n testing.assert_allclose(img2.astype(np.uint8), r2)\n\n img3 = img_as_float(img)\n with expected_warnings(['precision loss|unclosed file']):\n r3 = roundtrip(img3, plugin, fmt)\n testing.assert_allclose(r3, img)\n\n with expected_warnings(['precision loss']):\n img4 = img_as_int(img)\n if fmt.lower() in (('tif', 'tiff')):\n img4 -= 100\n with expected_warnings(['sign loss']):\n r4 = roundtrip(img4, plugin, fmt)\n testing.assert_allclose(r4, img4)\n else:\n with expected_warnings(['sign loss|precision loss|unclosed file']):\n r4 = roundtrip(img4, plugin, fmt)\n testing.assert_allclose(r4, img_as_ubyte(img4))\n\n img5 = img_as_uint(img)\n with expected_warnings(['precision loss|unclosed file']):\n r5 = roundtrip(img5, plugin, fmt)\n testing.assert_allclose(r5, img)\n\n\ndef mono_check(plugin, fmt='png'):\n \"\"\"Check the roundtrip behavior for images that support most types.\n\n All major input types should be handled.\n \"\"\"\n\n img = img_as_ubyte(data.moon())\n r1 = roundtrip(img, plugin, fmt)\n testing.assert_allclose(img, r1)\n\n img2 = img > 128\n r2 = roundtrip(img2, plugin, fmt)\n testing.assert_allclose(img2.astype(np.uint8), r2)\n\n img3 = img_as_float(img)\n with expected_warnings(['precision|unclosed file|\\A\\Z']):\n r3 = roundtrip(img3, plugin, fmt)\n if r3.dtype.kind == 'f':\n testing.assert_allclose(img3, r3)\n else:\n testing.assert_allclose(r3, img_as_uint(img))\n\n with expected_warnings(['precision loss']):\n img4 = img_as_int(img)\n if fmt.lower() in (('tif', 'tiff')):\n img4 -= 100\n with expected_warnings(['sign loss|\\A\\Z']):\n r4 = roundtrip(img4, plugin, fmt)\n testing.assert_allclose(r4, img4)\n else:\n with expected_warnings(['precision loss|sign loss|unclosed file']):\n r4 = roundtrip(img4, plugin, fmt)\n testing.assert_allclose(r4, img_as_uint(img4))\n\n img5 = img_as_uint(img)\n r5 = roundtrip(img5, plugin, fmt)\n testing.assert_allclose(r5, img5)\n\n\ndef setup_test():\n \"\"\"Default package level setup routine for skimage tests.\n\n Import packages known to raise errors, and then\n force warnings to raise errors. \n Set a random seed\n \"\"\"\n warnings.simplefilter('default')\n from scipy import signal, ndimage, special, optimize, linalg\n from scipy.io import loadmat\n from skimage import viewer, filter\n np.random.seed(0)\n warnings.simplefilter('error') \n\n\ndef teardown_test():\n \"\"\"Default package level teardown routine for skimage tests.\n\n Restore warnings to default behavior\n \"\"\"\n warnings.simplefilter('default')\n\n\nif __name__ == '__main__':\n color_check('pil')\n mono_check('pil')\n mono_check('pil', 'bmp')\n mono_check('pil', 'tiff')\n"
] |
[
[
"numpy.random.seed",
"numpy.testing.assert_allclose"
]
] |
KlrShaK/Oxford_flowers102-using-Tensorflow
|
[
"7966a0ead1ce0175fbb1d9d658da3ec915e2d77a"
] |
[
"Classifier/oxford_flower102.py"
] |
[
"import tensorflow as tf\r\nimport tensorflow_datasets as tfds\r\nimport matplotlib.pyplot as plt\r\nfrom acc_plotter import plot_accuracy\r\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\r\n\r\ndataset_name = 'oxford_flowers102'\r\n\r\ntrain_dataset = tfds.load(dataset_name, split=tfds.Split.TRAIN)\r\nval_dataset = tfds.load(dataset_name, split=tfds.Split.VALIDATION)\r\nprint(train_dataset)\r\nprint(val_dataset)\r\n\r\ncp_path = 'best_weights.hdf5'\r\ncp_callback = tf.keras.callbacks.ModelCheckpoint(cp_path, save_best_only=True, save_weights_only=True, verbose=2)\r\n\r\npre_trained_model = InceptionV3(include_top=False, weights= 'imagenet', input_shape=(300,300,3))\r\npre_trained_model.trainable = False\r\n\r\ndef preprocessing(features):\r\n image = tf.image.resize(features['image'], size=(300,300))\r\n print('Final image shape',image)\r\n if tf.random.uniform(()) > 0.5:\r\n image = tf.image.random_flip_left_right(image)\r\n image = tf.image.random_saturation(image, lower= 0, upper=5)\r\n image = tf.image.random_brightness(image, 0.2)\r\n image = tf.divide(image, 255.0)\r\n label = features['label']\r\n print('labels shape :',label)\r\n label = tf.one_hot(features['label'], 102)\r\n return image, label\r\n\r\ndef solution_model():\r\n train_data= train_dataset.map(preprocessing).batch(32)\r\n val_data= val_dataset.map(preprocessing).batch(32)\r\n # for x in train_data:\r\n # print(x[0].numpy())\r\n # print(x[1].numpy())\r\n # plt.imshow(x[0][0])\r\n # plt.show()\r\n\r\n model = tf.keras.Sequential(\r\n [\r\n pre_trained_model,\r\n tf.keras.layers.Flatten(),\r\n tf.keras.layers.Dense(1024, activation='relu'),\r\n tf.keras.layers.Dropout(0.6),\r\n tf.keras.layers.Dense(1024, activation= 'relu'),\r\n tf.keras.layers.Dropout(0.5),\r\n tf.keras.layers.Dense(102, activation='softmax')\r\n ]\r\n )\r\n model.compile(optimizer=tf.optimizers.Adam(lr=5.42e-6), loss='categorical_crossentropy', metrics=['accuracy'])\r\n model.summary()\r\n\r\n try:\r\n model.load_weights(cp_path) # ('best_weights_67%.hdf5') #'best_weights_63%.hdf5'\r\n print('Weights Loaded !!!')\r\n except:\r\n print('No Previous Weights Found !!!')\r\n\r\n history = model.fit(train_data, epochs=60, verbose=1, validation_data=val_data, callbacks=[cp_callback])\r\n plot_accuracy(history)\r\n\r\n\r\n return model\r\n\r\nif __name__ == '__main__':\r\n model = solution_model()\r\n model.save('model.h5')\r\n"
] |
[
[
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.image.random_brightness",
"tensorflow.image.random_flip_left_right",
"tensorflow.keras.layers.Dense",
"tensorflow.random.uniform",
"tensorflow.divide",
"tensorflow.image.random_saturation",
"tensorflow.image.resize",
"tensorflow.one_hot",
"tensorflow.optimizers.Adam",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.applications.inception_v3.InceptionV3"
]
] |
rickyHong/Pennylane-repl
|
[
"f18e5f233f84b91bbac8e61cebdee77c66fafd79"
] |
[
"pennylane/plugins/default_gaussian.py"
] |
[
"# Copyright 2018-2019 Xanadu Quantum Technologies Inc.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# pylint: disable=inconsistent-return-statements\n\"\"\"\nThe :code:`default.gaussian` plugin is meant to be used as a template for writing PennyLane\ndevice plugins for new CV backends.\n\nIt implements the necessary :class:`~pennylane._device.Device` methods as well as all built-in\n:mod:`continuous-variable Gaussian operations <pennylane.ops.cv>`, and provides a very simple simulation of a\nGaussian-based quantum circuit architecture.\n\"\"\"\n# pylint: disable=attribute-defined-outside-init,too-many-arguments\nimport numpy as np\n\nfrom scipy.special import factorial as fac\n\nimport pennylane as qml\nfrom pennylane import Device\n\n# tolerance for numerical errors\ntolerance = 1e-10\n\n\n#========================================================\n# auxillary functions\n#========================================================\n\ndef partitions(s, include_singles=True):\n \"\"\"Partitions a sequence into all groupings of pairs and singles of elements.\n\n Args:\n s (sequence): the sequence to partition\n include_singles (bool): if False, only partitions into pairs\n is returned.\n\n Returns:\n tuple: returns a nested tuple, containing all partitions of the sequence.\n \"\"\"\n # pylint: disable=too-many-branches\n if len(s) == 2:\n if include_singles:\n yield (s[0],), (s[1],)\n\n yield tuple(s),\n else:\n # pull off a single item and partition the rest\n if include_singles:\n if len(s) > 1:\n item_partition = (s[0],)\n rest = s[1:]\n rest_partitions = partitions(rest, include_singles)\n for p in rest_partitions:\n yield ((item_partition),) + p\n else:\n yield tuple(s),\n\n # pull off a pair of items and partition the rest\n for idx1 in range(1, len(s)):\n item_partition = (s[0], s[idx1])\n rest = s[1:idx1] + s[idx1+1:]\n rest_partitions = partitions(rest, include_singles)\n for p in rest_partitions:\n yield ((item_partition),) + p\n\n\ndef fock_prob(mu, cov, event, hbar=2.):\n r\"\"\"Returns the probability of detection of a particular PNR detection event.\n\n For more details, see:\n\n * Kruse, R., Hamilton, C. S., Sansoni, L., Barkhofen, S., Silberhorn, C., & Jex, I.\n \"A detailed study of Gaussian Boson Sampling.\" `arXiv:1801.07488. (2018).\n <https://arxiv.org/abs/1801.07488>`_\n\n * Hamilton, C. S., Kruse, R., Sansoni, L., Barkhofen, S., Silberhorn, C., & Jex, I.\n \"Gaussian boson sampling.\" `Physical review letters, 119(17), 170501. (2017).\n <https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.119.170501>`_\n\n Args:\n mu (array): length-:math:`2N` means vector\n cov (array): :math:`2N\\times 2N` covariance matrix\n event (array): length-:math:`N` array of non-negative integers representing the\n PNR detection event of the multi-mode system.\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`.\n\n Returns:\n float: probability of detecting the event\n \"\"\"\n # number of modes\n N = len(mu)//2\n I = np.identity(N)\n\n # mean displacement of each mode\n alpha = (mu[:N] + 1j*mu[N:])/np.sqrt(2*hbar)\n # the expectation values (<a_1>, <a_2>,...,<a_N>, <a^\\dagger_1>, ..., <a^\\dagger_N>)\n beta = np.concatenate([alpha, alpha.conj()])\n\n x = cov[:N, :N]*2/hbar\n xp = cov[:N, N:]*2/hbar\n p = cov[N:, N:]*2/hbar\n # the (Hermitian) matrix elements <a_i^\\dagger a_j>\n aidaj = (x+p+1j*(xp-xp.T)-2*I)/4\n # the (symmetric) matrix elements <a_i a_j>\n aiaj = (x-p+1j*(xp+xp.T))/4\n\n # calculate the covariance matrix sigma_Q appearing in the Q function:\n # Q(alpha) = exp[-(alpha-beta).sigma_Q^{-1}.(alpha-beta)/2]/|sigma_Q|\n Q = np.block([[aidaj, aiaj.conj()], [aiaj, aidaj.conj()]]) + np.identity(2*N)\n\n # inverse Q matrix\n Qinv = np.linalg.inv(Q)\n # 1/sqrt(|Q|)\n sqrt_Qdet = 1/np.sqrt(np.linalg.det(Q).real)\n\n prefactor = np.exp(-beta @ Qinv @ beta.conj()/2)\n\n if np.all(np.array(event) == 0):\n # all PNRs detect the vacuum state\n return (prefactor*sqrt_Qdet).real/np.prod(fac(event))\n\n # the matrix X_n = [[0, I_n], [I_n, 0]]\n O = np.zeros_like(I)\n X = np.block([[O, I], [I, O]])\n\n gamma = X @ Qinv.conj() @ beta\n\n # For each mode, repeat the mode number event[i] times\n ind = [i for sublist in [[idx]*j for idx, j in enumerate(event)] for i in sublist]\n # extend the indices for xp-ordering of the Gaussian state\n ind += [i+N for i in ind]\n\n if np.linalg.norm(beta) < tolerance:\n # state has no displacement\n part = partitions(ind, include_singles=False)\n else:\n part = partitions(ind, include_singles=True)\n\n # calculate Hamilton's A matrix: A = X.(I-Q^{-1})*\n A = X @ (np.identity(2*N)-Qinv).conj()\n summation = np.sum([np.prod([gamma[i[0]] if len(i) == 1 else A[i] for i in p]) for p in part])\n\n return (prefactor*sqrt_Qdet*summation).real/np.prod(fac(event))\n\n\n#========================================================\n# parametrized gates\n#========================================================\n\ndef rotation(phi):\n \"\"\"Rotation in the phase space.\n\n Args:\n phi (float): rotation parameter\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n return np.array([[np.cos(phi), -np.sin(phi)],\n [np.sin(phi), np.cos(phi)]])\n\n\ndef displacement(state, wire, alpha, hbar=2):\n \"\"\"Displacement in the phase space.\n\n Args:\n state (tuple): contains means vector and covariance matrix\n wire (int): wire that the displacement acts on\n alpha (float): complex displacement\n\n Returns:\n tuple: contains the vector of means and covariance matrix\n \"\"\"\n mu = state[0]\n mu[wire] += alpha.real*np.sqrt(2*hbar)\n mu[wire+len(mu)//2] += alpha.imag*np.sqrt(2*hbar)\n return mu, state[1]\n\n\ndef squeezing(r, phi):\n \"\"\"Squeezing in the phase space.\n\n Args:\n r (float): squeezing magnitude\n phi (float): rotation parameter\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n cp = np.cos(phi)\n sp = np.sin(phi)\n ch = np.cosh(r)\n sh = np.sinh(r)\n return np.array([[ch-cp*sh, -sp*sh],\n [-sp*sh, ch+cp*sh]])\n\n\ndef quadratic_phase(s):\n \"\"\"Quadratic phase shift.\n\n Args:\n s (float): gate parameter\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n return np.array([[1, 0],\n [s, 1]])\n\n\ndef beamsplitter(theta, phi):\n r\"\"\"Beamsplitter.\n\n Args:\n theta (float): transmittivity angle (:math:`t=\\cos\\theta`)\n phi (float): phase angle (:math:`r=e^{i\\phi}\\sin\\theta`)\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n cp = np.cos(phi)\n sp = np.sin(phi)\n ct = np.cos(theta)\n st = np.sin(theta)\n\n S = np.array([[ct, -cp*st, 0, -st*sp],\n [cp*st, ct, -st*sp, 0],\n [0, st*sp, ct, -cp*st],\n [st*sp, 0, cp*st, ct]])\n\n return S\n\n\ndef two_mode_squeezing(r, phi):\n\n \"\"\"Two-mode squeezing.\n\n Args:\n r (float): squeezing magnitude\n phi (float): rotation parameter\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n cp = np.cos(phi)\n sp = np.sin(phi)\n ch = np.cosh(r)\n sh = np.sinh(r)\n\n S = np.array([[ch, cp*sh, 0, sp*sh],\n [cp*sh, ch, sp*sh, 0],\n [0, sp*sh, ch, -cp*sh],\n [sp*sh, 0, -cp*sh, ch]])\n\n return S\n\n\ndef controlled_addition(s):\n \"\"\"CX gate.\n\n Args:\n s (float): gate parameter\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n S = np.array([[1, 0, 0, 0],\n [s, 1, 0, 0],\n [0, 0, 1, -s],\n [0, 0, 0, 1]])\n\n return S\n\n\ndef controlled_phase(s):\n \"\"\"CZ gate.\n\n Args:\n s (float): gate parameter\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n S = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, s, 1, 0],\n [s, 0, 0, 1]])\n\n return S\n\n\ndef interferometer(U):\n \"\"\"Interferometer\n\n Args:\n U (array): unitary matrix\n\n Returns:\n array: symplectic transformation matrix\n \"\"\"\n N = 2*len(U)\n X = U.real\n Y = U.imag\n rows = np.arange(N).reshape(2, -1).T.flatten()\n S = np.vstack([np.hstack([X, -Y]),\n np.hstack([Y, X])])[:, rows][rows]\n\n return S\n\n#========================================================\n# Arbitrary states and operators\n#========================================================\n\ndef squeezed_cov(r, phi, hbar=2):\n r\"\"\"Returns the squeezed covariance matrix of a squeezed state.\n\n Args:\n r (float): the squeezing magnitude\n p (float): the squeezing phase :math:`\\phi`\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n Returns:\n array: the squeezed state\n \"\"\"\n cov = np.array([[np.exp(-2*r), 0],\n [0, np.exp(2*r)]]) * hbar/2\n\n R = rotation(phi/2)\n\n return R @ cov @ R.T\n\n\ndef vacuum_state(wires, hbar=2.):\n r\"\"\"Returns the vacuum state.\n\n Args:\n basis (str): Returns the vector of means and the covariance matrix\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n Returns:\n array: the vacuum state\n \"\"\"\n means = np.zeros((2*wires))\n cov = np.identity(2*wires) * hbar/2\n state = [means, cov]\n return state\n\n\ndef coherent_state(a, phi=0, hbar=2.):\n r\"\"\"Returns a coherent state.\n\n Args:\n a (complex) : the displacement\n phi (float): the phase\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n Returns:\n array: the coherent state\n \"\"\"\n alpha = a*np.exp(1j*phi)\n means = np.array([alpha.real, alpha.imag]) * np.sqrt(2*hbar)\n cov = np.identity(2) * hbar/2\n state = [means, cov]\n return state\n\n\ndef squeezed_state(r, phi, hbar=2.):\n r\"\"\"Returns a squeezed state.\n\n Args:\n r (float): the squeezing magnitude\n phi (float): the squeezing phase :math:`\\phi`\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n\n Returns:\n array: the squeezed state\n \"\"\"\n means = np.zeros((2))\n state = [means, squeezed_cov(r, phi, hbar)]\n return state\n\n\ndef displaced_squeezed_state(a, phi_a, r, phi_r, hbar=2.):\n r\"\"\"Returns a squeezed coherent state\n\n Args:\n a (real): the displacement magnitude\n phi_a (real): the displacement phase\n r (float): the squeezing magnitude\n phi_r (float): the squeezing phase :math:`\\phi_r`\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n\n Returns:\n array: the squeezed coherent state\n \"\"\"\n alpha = a * np.exp(1j*phi_a)\n means = np.array([alpha.real, alpha.imag]) * np.sqrt(2*hbar)\n state = [means, squeezed_cov(r, phi_r, hbar)]\n return state\n\n\ndef thermal_state(nbar, hbar=2.):\n r\"\"\"Returns a thermal state.\n\n Args:\n nbar (float): the mean photon number\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n\n Returns:\n array: the thermal state\n \"\"\"\n means = np.zeros([2])\n state = [means, (2*nbar+1)*np.identity(2)*hbar/2]\n return state\n\n\ndef gaussian_state(mu, cov, hbar=2.):\n r\"\"\"Returns a Gaussian state.\n\n This is simply a bare wrapper function,\n since the means vector and covariance matrix\n can be passed via the parameters unchanged.\n\n Note that both the means vector and covariance\n matrix should be in :math:`(\\x_1,\\dots, \\x_N, \\p_1, \\dots, \\p_N)`\n ordering.\n\n Args:\n mu (array): vector means. Must be length-:math:`2N`,\n where N is the number of modes\n cov (array): covariance matrix. Must be dimension :math:`2N\\times 2N`,\n where N is the number of modes\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n\n Returns:\n tuple: the mean and covariance matrix of the Gaussian state\n \"\"\"\n # pylint: disable=unused-argument\n return mu, cov\n\n\ndef set_state(state, wire, mu, cov):\n r\"\"\"Inserts a single mode Gaussian into the\n state representation of the complete system.\n\n Args:\n state (tuple): contains means vector\n and covariance matrix of existing state\n wire (int): wire corresponding to the new Gaussian state\n mu (array): vector of means to insert\n cov (array): covariance matrix to insert\n\n Returns:\n tuple: contains the vector of means and covariance matrix.\n \"\"\"\n mu0 = state[0]\n cov0 = state[1]\n N = len(mu0)//2\n\n # insert the new state into the means vector\n mu0[[wire, wire+N]] = mu\n\n # insert the new state into the covariance matrix\n ind = np.concatenate([np.array([wire]), np.array([wire])+N])\n rows = ind.reshape(-1, 1)\n cols = ind.reshape(1, -1)\n cov0[rows, cols] = cov\n\n return mu0, cov0\n\n\n#========================================================\n# expectations\n#========================================================\n\n\ndef photon_number(mu, cov, wires, params, total_wires, hbar=2.):\n r\"\"\"Calculates the mean photon number for a given one-mode state.\n\n Args:\n mu (array): length-2 vector of means\n cov (array): :math:`2\\times 2` covariance matrix\n wires (Sequence[int]): wires to calculate the expectation for\n params (None): no parameters are used for this expectation value\n total_wires (int): total number of wires in the system\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n\n Returns:\n tuple: contains the photon number expectation and variance\n \"\"\"\n # pylint: disable=unused-argument\n ex = (np.trace(cov) + mu.T @ mu)/(2*hbar) - 1/2\n var = (np.trace(cov @ cov) + 2*mu.T @ cov @ mu)/(2*hbar**2) - 1/4\n return ex, var\n\n\ndef homodyne(phi=None):\n \"\"\"Function factory that returns the Homodyne expectation of a one mode state.\n\n Args:\n phi (float): the default phase space axis to perform the Homodyne measurement\n\n Returns:\n function: A function that accepts a single mode means vector, covariance matrix,\n and phase space angle phi, and returns the quadrature expectation\n value and variance.\n \"\"\"\n if phi is not None:\n def _homodyne(mu, cov, wires, params, total_wires, hbar=2.):\n \"\"\"Arbitrary angle homodyne expectation.\"\"\"\n # pylint: disable=unused-argument\n rot = rotation(phi)\n muphi = rot.T @ mu\n covphi = rot.T @ cov @ rot\n return muphi[0], covphi[0, 0]\n return _homodyne\n\n def _homodyne(mu, cov, wires, params, total_wires, hbar=2.):\n \"\"\"Arbitrary angle homodyne expectation.\"\"\"\n # pylint: disable=unused-argument\n rot = rotation(params[0])\n muphi = rot.T @ mu\n covphi = rot.T @ cov @ rot\n return muphi[0], covphi[0, 0]\n return _homodyne\n\n\ndef poly_quad_expectations(mu, cov, wires, params, total_wires, hbar=2.):\n r\"\"\"Calculates the expectation and variance for an arbitrary\n polynomial of quadrature operators.\n\n Args:\n mu (array): vector of means\n cov (array): covariance matrix\n wires (Sequence[int]): wires to calculate the expectation for\n params (array): a :math:`(2N+1)\\times (2N+1)` array containing the linear\n and quadratic coefficients of the quadrature operators\n :math:`(\\I, \\x_0, \\p_0, \\x_1, \\p_1,\\dots)`\n total_wires (int): total number of wires in the system\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n\n Returns:\n tuple: the mean and variance of the quadrature-polynomial observable\n \"\"\"\n Q = params[0]\n\n # HACK, we need access to the Poly instance in order to expand the matrix!\n # TODO: maybe we should make heisenberg_obs a class method or a static method to avoid this being a 'hack'?\n op = qml.ops.PolyXP(Q, wires=wires)\n Q = op.heisenberg_obs(total_wires)\n\n if Q.ndim == 1:\n d = np.r_[Q[1::2], Q[2::2]]\n return d.T @ mu + Q[0], d.T @ cov @ d\n\n # convert to the (I, x1,x2,..., p1,p2...) ordering\n M = np.vstack((Q[0:1, :], Q[1::2, :], Q[2::2, :]))\n M = np.hstack((M[:, 0:1], M[:, 1::2], M[:, 2::2]))\n d1 = M[1:, 0]\n d2 = M[0, 1:]\n\n A = M[1:, 1:]\n d = d1 + d2\n k = M[0, 0]\n\n d2 = 2*A @ mu + d\n k2 = mu.T @ A @ mu + mu.T @ d + k\n\n ex = np.trace(A @ cov) + k2\n var = 2*np.trace(A @ cov @ A @ cov) + d2.T @ cov @ d2\n\n modes = np.arange(2*total_wires).reshape(2, -1).T\n groenewald_correction = np.sum([np.linalg.det(hbar*A[:, m][n]) for m in modes for n in modes])\n var -= groenewald_correction\n\n return ex, var\n\n\ndef fock_expectation(mu, cov, wires, params, total_wires, hbar=2.):\n r\"\"\"Calculates the expectation and variance of a Fock state probability.\n\n Args:\n mu (array): length-:math:`2N` vector of means\n cov (array): :math:`2N\\times 2N` covariance matrix\n wires (Sequence[int]): wires to calculate the expectation for\n params (Sequence[int]): the Fock state to return the expectation value for\n total_wires (int): total number of wires in the system\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n\n Returns:\n tuple: the Fock state expectation and variance\n \"\"\"\n # pylint: disable=unused-argument\n ex = fock_prob(mu, cov, params[0], hbar=hbar)\n\n # var[|n><n|] = E[|n><n|^2] - E[|n><n|]^2 = E[|n><n|] - E[|n><n|]^2\n var = ex - ex**2\n return ex, var\n\n\ndef identity(*_, **__):\n r\"\"\"Returns 1.\n\n Returns:\n tuple: the Fock state expectation and variance\n \"\"\"\n return 1, 0\n\n\n#========================================================\n# device\n#========================================================\n\n\nclass DefaultGaussian(Device):\n r\"\"\"Default Gaussian device for PennyLane.\n\n Args:\n wires (int): the number of modes to initialize the device in\n shots (int): How many times the circuit should be evaluated (or sampled) to estimate\n the expectation values.\n If ``analytic == True``, then the number of shots is ignored\n in the calculation of expectation values and variances, and only controls the number\n of samples returned by ``sample``.\n hbar (float): (default 2) the value of :math:`\\hbar` in the commutation\n relation :math:`[\\x,\\p]=i\\hbar`\n analytic (bool): indicates if the device should calculate expectations\n and variances analytically\n \"\"\"\n name = 'Default Gaussian PennyLane plugin'\n short_name = 'default.gaussian'\n pennylane_requires = '0.8'\n version = '0.8.0'\n author = 'Xanadu Inc.'\n\n _capabilities = {\"model\": \"cv\"}\n\n _operation_map = {\n 'Beamsplitter': beamsplitter,\n 'ControlledAddition': controlled_addition,\n 'ControlledPhase': controlled_phase,\n 'Displacement': displacement,\n 'QuadraticPhase': quadratic_phase,\n 'Rotation': rotation,\n 'Squeezing': squeezing,\n 'TwoModeSqueezing': two_mode_squeezing,\n 'CoherentState': coherent_state,\n 'DisplacedSqueezedState': displaced_squeezed_state,\n 'SqueezedState': squeezed_state,\n 'ThermalState': thermal_state,\n 'GaussianState': gaussian_state,\n 'Interferometer': interferometer\n }\n\n _observable_map = {\n 'NumberOperator': photon_number,\n 'X': homodyne(0),\n 'P': homodyne(np.pi/2),\n 'QuadOperator': homodyne(None),\n 'PolyXP': poly_quad_expectations,\n 'FockStateProjector': fock_expectation,\n 'Identity': identity\n }\n\n _circuits = {}\n\n def __init__(self, wires, *, shots=1000, hbar=2, analytic=True):\n super().__init__(wires, shots)\n self.eng = None\n self.hbar = hbar\n self.analytic = analytic\n\n self.reset()\n\n def pre_apply(self):\n self.reset()\n\n def apply(self, operation, wires, par):\n if operation == 'Displacement':\n self._state = displacement(self._state, wires[0], par[0]*np.exp(1j*par[1]))\n return # we are done here\n\n if operation == 'GaussianState':\n if wires != list(range(self.num_wires)):\n raise ValueError(\"GaussianState means vector or covariance matrix is \"\n \"the incorrect size for the number of subsystems.\")\n self._state = self._operation_map[operation](*par, hbar=self.hbar)\n return # we are done here\n\n if 'State' in operation:\n # set the new device state\n mu, cov = self._operation_map[operation](*par, hbar=self.hbar)\n # state preparations only act on at most 1 subsystem\n self._state = set_state(self._state, wires[0], mu, cov)\n return # we are done here\n\n # get the symplectic matrix\n S = self._operation_map[operation](*par)\n\n # expand the symplectic to act on the proper subsystem\n S = self.expand(S, wires)\n\n # apply symplectic matrix to the means vector\n means = S @ self._state[0]\n # apply symplectic matrix to the covariance matrix\n cov = S @ self._state[1] @ S.T\n\n self._state = [means, cov]\n\n def expand(self, S, wires):\n r\"\"\"Expands a Symplectic matrix S to act on the entire subsystem.\n\n Args:\n S (array): a :math:`2M\\times 2M` Symplectic matrix\n wires (Sequence[int]): the wires of the modes that S acts on\n\n Returns:\n array: the resulting :math:`2N\\times 2N` Symplectic matrix\n \"\"\"\n if self.num_wires == 1:\n # total number of wires is 1, simply return the matrix\n return S\n\n N = self.num_wires\n w = np.asarray(wires)\n\n if np.any(w < 0) or np.any(w >= N) or len(set(w)) != len(w):\n raise ValueError(\"Invalid target subsystems provided in 'wires' argument.\")\n\n M = len(S) // 2\n S2 = np.identity(2 * N)\n\n if M != len(wires):\n raise ValueError('Incorrect number of subsystems for provided operation.')\n\n S2[w.reshape(-1, 1), w.reshape(1, -1)] = S[:M, :M].copy() # XX\n S2[(w + N).reshape(-1, 1), (w + N).reshape(1, -1)] = S[M:, M:].copy() # PP\n S2[w.reshape(-1, 1), (w + N).reshape(1, -1)] = S[:M, M:].copy() # XP\n S2[(w + N).reshape(-1, 1), w.reshape(1, -1)] = S[M:, :M].copy() # PX\n\n return S2\n\n def expval(self, observable, wires, par):\n if observable == \"PolyXP\":\n mu, cov = self._state\n else:\n mu, cov = self.reduced_state(wires)\n\n ev, var = self._observable_map[observable](mu, cov, wires, par, self.num_wires, hbar=self.hbar)\n\n if not self.analytic:\n # estimate the ev\n # use central limit theorem, sample normal distribution once, only ok if n_eval is large\n # (see https://en.wikipedia.org/wiki/Berry%E2%80%93Esseen_theorem)\n ev = np.random.normal(ev, np.sqrt(var / self.shots))\n\n return ev\n\n def var(self, observable, wires, par):\n mu, cov = self.reduced_state(wires)\n _, var = self._observable_map[observable](mu, cov, wires, par, hbar=self.hbar, total_wires=self.num_wires)\n return var\n\n def cov(self, observable1, wires1, par1, observable2, wires2, par2):\n # assume for now that the wires are disjoint\n wires = wires1 + wires2\n\n if observable1 != \"NumberOperator\" or observable2 != \"NumberOperator\":\n raise Exception(\"Only NumberOperator supported so far.\")\n \n # For now we just assume the observables are number operators...\n # see Dodonov et al., Multidimensional Hermite polynomial and photon distribution\n # They use (p, q) ordering instead of (q, p), but in this case it does not matter because the \n # matrices Lambda are the same in both orderings\n\n mu, cov = self.reduced_state(wires)\n #mu *= np.sqrt(2*self.hbar)\n #cov *= self.hbar/2\n\n Lambda1 = np.zeros((4, 4))\n Lambda1[0, 0] = 1\n Lambda1[2, 2] = 1\n Lambda2 = np.zeros((4, 4))\n Lambda2[1, 1] = 1\n Lambda2[3, 3] = 1\n\n #return .125 * np.trace(Lambda1 @ cov @ Lambda2 @ cov) + .5 * np.dot(mu, Lambda1 @ cov @ Lambda2 @ mu)\n return (np.trace(Lambda1 @ cov @ Lambda2 @ (cov + 2 * np.outer(mu, mu)))) /(2*self.hbar**2)\n\n def sample(self, observable, wires, par):\n \"\"\"Return a sample of an observable.\n\n .. note::\n\n The ``default.gaussian`` plugin only supports sampling\n from :class:`~.X`, :class:`~.P`, and :class:`~.QuadOperator`\n observables.\n\n Args:\n observable (str): name of the observable\n wires (Sequence[int]): subsystems the observable is to be measured on\n par (tuple): parameters for the observable\n\n Returns:\n array[float]: samples in an array of dimension ``(n, num_wires)``\n \"\"\"\n if len(wires) != 1:\n raise ValueError(\"Only one mode can be measured in homodyne.\")\n\n if observable == \"X\":\n phi = 0.0\n elif observable == \"P\":\n phi = np.pi/2\n elif observable == \"QuadOperator\":\n phi = par[0]\n else:\n raise NotImplementedError(\"default.gaussian does not support sampling {}\".format(observable))\n\n mu, cov = self.reduced_state(wires)\n rot = rotation(phi)\n\n muphi = rot.T @ mu\n covphi = rot.T @ cov @ rot\n\n stdphi = np.sqrt(covphi[0, 0])\n meanphi = muphi[0]\n return np.random.normal(meanphi, stdphi, self.shots)\n\n def reset(self):\n \"\"\"Reset the device\"\"\"\n # init the state vector to |00..0>\n self._state = vacuum_state(self.num_wires, self.hbar)\n\n def reduced_state(self, wires):\n r\"\"\" Returns the vector of means and the covariance matrix of the specified wires.\n\n Args:\n wires (int of Sequence[int]): indices of the requested wires\n\n Returns:\n tuple (means, cov): means is an array containing the vector of means,\n and cov is a square array containing the covariance matrix\n \"\"\"\n if wires == list(range(self.num_wires)):\n # reduced state is full state\n return self._state\n\n # reduce rho down to specified subsystems\n if isinstance(wires, int):\n wires = [wires]\n\n if np.any(np.array(wires) > self.num_wires):\n raise ValueError(\"The specified wires cannot \"\n \"be larger than the number of subsystems.\")\n\n ind = np.concatenate([np.array(wires), np.array(wires)+self.num_wires])\n rows = ind.reshape(-1, 1)\n cols = ind.reshape(1, -1)\n\n return self._state[0][ind], self._state[1][rows, cols]\n\n @property\n def operations(self):\n return set(self._operation_map.keys())\n\n @property\n def observables(self):\n return set(self._observable_map.keys())\n"
] |
[
[
"numpy.sqrt",
"numpy.asarray",
"numpy.zeros_like",
"numpy.any",
"numpy.exp",
"numpy.trace",
"numpy.hstack",
"numpy.arange",
"numpy.sin",
"numpy.linalg.det",
"numpy.block",
"scipy.special.factorial",
"numpy.outer",
"numpy.zeros",
"numpy.cosh",
"numpy.linalg.inv",
"numpy.identity",
"numpy.array",
"numpy.cos",
"numpy.sinh",
"numpy.linalg.norm",
"numpy.random.normal",
"numpy.vstack"
]
] |
autobotasia/autoface
|
[
"8283a089c824acc62640899864111cf6962cb692"
] |
[
"utils/clustering.py"
] |
[
"\"\"\" Face Cluster \"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport importlib\nimport argparse\nimport facenet\nimport os\nimport math\ndef face_distance(face_encodings, face_to_compare):\n \"\"\"\n Given a list of face encodings, compare them to a known face encoding and get a euclidean distance\n for each comparison face. The distance tells you how similar the faces are.\n :param faces: List of face encodings to compare\n :param face_to_compare: A face encoding to compare against\n :return: A numpy ndarray with the distance for each face in the same order as the 'faces' array\n \"\"\"\n import numpy as np\n if len(face_encodings) == 0:\n return np.empty((0))\n\n #return 1/np.linalg.norm(face_encodings - face_to_compare, axis=1)\n return np.sum(face_encodings*face_to_compare,axis=1)\n\ndef load_model(model_dir, meta_file, ckpt_file):\n model_dir_exp = os.path.expanduser(model_dir)\n saver = tf.train.import_meta_graph(os.path.join(model_dir_exp, meta_file))\n saver.restore(tf.get_default_session(), os.path.join(model_dir_exp, ckpt_file))\n\ndef _chinese_whispers(encoding_list, threshold=0.75, iterations=20):\n \"\"\" Chinese Whispers Algorithm\n\n Modified from Alex Loveless' implementation,\n http://alexloveless.co.uk/data/chinese-whispers-graph-clustering-in-python/\n\n Inputs:\n encoding_list: a list of facial encodings from face_recognition\n threshold: facial match threshold,default 0.6\n iterations: since chinese whispers is an iterative algorithm, number of times to iterate\n\n Outputs:\n sorted_clusters: a list of clusters, a cluster being a list of imagepaths,\n sorted by largest cluster to smallest\n \"\"\"\n\n #from face_recognition.api import _face_distance\n from random import shuffle\n import networkx as nx\n # Create graph\n nodes = []\n edges = []\n\n image_paths, encodings = zip(*encoding_list)\n\n if len(encodings) <= 1:\n print (\"No enough encodings to cluster!\")\n return []\n\n for idx, face_encoding_to_check in enumerate(encodings):\n # Adding node of facial encoding\n node_id = idx+1\n\n # Initialize 'cluster' to unique value (cluster of itself)\n node = (node_id, {'cluster': image_paths[idx], 'path': image_paths[idx]})\n nodes.append(node)\n\n # Facial encodings to compare\n if (idx+1) >= len(encodings):\n # Node is last element, don't create edge\n break\n\n compare_encodings = encodings[idx+1:]\n distances = face_distance(compare_encodings, face_encoding_to_check)\n encoding_edges = []\n for i, distance in enumerate(distances):\n if distance > threshold:\n # Add edge if facial match\n edge_id = idx+i+2\n encoding_edges.append((node_id, edge_id, {'weight': distance}))\n\n edges = edges + encoding_edges\n\n G = nx.Graph()\n G.add_nodes_from(nodes)\n G.add_edges_from(edges)\n\n # Iterate\n for _ in range(0, iterations):\n cluster_nodes = G.nodes()\n #shuffle(cluster_nodes)\n for node in cluster_nodes:\n neighbors = G[node]\n clusters = {}\n\n for ne in neighbors:\n if isinstance(ne, int):\n if G.nodes[ne]['cluster'] in clusters:\n clusters[G.nodes[ne]['cluster']] += G[node][ne]['weight']\n else:\n clusters[G.nodes[ne]['cluster']] = G[node][ne]['weight']\n\n # find the class with the highest edge weight sum\n edge_weight_sum = 0\n max_cluster = 0\n #use the max sum of neighbor weights class as current node's class\n for cluster in clusters:\n if clusters[cluster] > edge_weight_sum:\n edge_weight_sum = clusters[cluster]\n max_cluster = cluster\n\n # set the class of target node to the winning local class\n G.nodes[node]['cluster'] = max_cluster\n\n clusters = {}\n\n # Prepare cluster output\n for (_, data) in G.nodes.items():\n cluster = data['cluster']\n path = data['path']\n\n if cluster:\n if cluster not in clusters:\n clusters[cluster] = []\n clusters[cluster].append(path)\n\n # Sort cluster output\n sorted_clusters = sorted(clusters.values(), key=len, reverse=True)\n\n return sorted_clusters\n\ndef cluster_facial_encodings(facial_encodings):\n \"\"\" Cluster facial encodings\n\n Intended to be an optional switch for different clustering algorithms, as of right now\n only chinese whispers is available.\n\n Input:\n facial_encodings: (image_path, facial_encoding) dictionary of facial encodings\n\n Output:\n sorted_clusters: a list of clusters, a cluster being a list of imagepaths,\n sorted by largest cluster to smallest\n\n \"\"\"\n\n if len(facial_encodings) <= 1:\n print (\"Number of facial encodings must be greater than one, can't cluster\")\n return []\n\n # Only use the chinese whispers algorithm for now\n sorted_clusters = _chinese_whispers(facial_encodings.items())\n return sorted_clusters\n\ndef compute_facial_encodings(sess,images_placeholder,embeddings,phase_train_placeholder,image_size,\n embedding_size,nrof_images,nrof_batches,emb_array,batch_size,paths):\n \"\"\" Compute Facial Encodings\n\n Given a set of images, compute the facial encodings of each face detected in the images and\n return them. If no faces, or more than one face found, return nothing for that image.\n\n Inputs:\n image_paths: a list of image paths\n\n Outputs:\n facial_encodings: (image_path, facial_encoding) dictionary of facial encodings\n\n \"\"\"\n\n for i in range(nrof_batches):\n start_index = i*batch_size\n end_index = min((i+1)*batch_size, nrof_images)\n paths_batch = paths[start_index:end_index]\n images = facenet.load_data(paths_batch, False, False, image_size)\n feed_dict = { images_placeholder:images, phase_train_placeholder:False }\n emb_array[start_index:end_index,:] = sess.run(embeddings, feed_dict=feed_dict)\n\n facial_encodings = {}\n for x in range(nrof_images):\n facial_encodings[paths[x]] = emb_array[x,:]\n\n\n return facial_encodings\n\ndef get_onedir(paths):\n dataset = []\n path_exp = os.path.expanduser(paths)\n if os.path.isdir(path_exp):\n images = os.listdir(path_exp)\n image_paths = [os.path.join(path_exp,img) for img in images]\n\n for x in image_paths:\n if os.path.getsize(x)>0:\n dataset.append(x)\n \n return dataset \n\n\ndef main(args):\n \"\"\" Main\n\n Given a list of images, save out facial encoding data files and copy\n images into folders of face clusters.\n\n \"\"\"\n from os.path import join, basename, exists\n from os import makedirs\n import numpy as np\n import shutil\n import sys\n\n if not exists(args.output):\n makedirs(args.output)\n\n with tf.Graph().as_default():\n with tf.Session() as sess:\n image_paths = get_onedir(args.input)\n #image_list, label_list = facenet.get_image_paths_and_labels(train_set)\n\n meta_file, ckpt_file = facenet.get_model_filenames(os.path.expanduser(args.model_dir))\n \n print('Metagraph file: %s' % meta_file)\n print('Checkpoint file: %s' % ckpt_file)\n load_model(args.model_dir, meta_file, ckpt_file)\n \n # Get input and output tensors\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n \n image_size = images_placeholder.get_shape()[1]\n print(\"image_size:\",image_size)\n embedding_size = embeddings.get_shape()[1]\n \n # Run forward pass to calculate embeddings\n print('Runnning forward pass on images') \n\n nrof_images = len(image_paths)\n nrof_batches = int(math.ceil(1.0*nrof_images / args.batch_size))\n emb_array = np.zeros((nrof_images, embedding_size))\n facial_encodings = compute_facial_encodings(sess,images_placeholder,embeddings,phase_train_placeholder,image_size,\n embedding_size,nrof_images,nrof_batches,emb_array,args.batch_size,image_paths)\n sorted_clusters = cluster_facial_encodings(facial_encodings)\n num_cluster = len(sorted_clusters)\n \n # Copy image files to cluster folders\n for idx, cluster in enumerate(sorted_clusters):\n #save all the cluster\n cluster_dir = join(args.output, str(idx))\n if not exists(cluster_dir):\n makedirs(cluster_dir)\n for path in cluster:\n shutil.copy(path, join(cluster_dir, basename(path)))\n\ndef parse_args():\n \"\"\"Parse input arguments.\"\"\"\n import argparse\n parser = argparse.ArgumentParser(description='Get a shape mesh (t-pose)')\n parser.add_argument('--model_dir', type=str, help='model dir', required=True)\n parser.add_argument('--batch_size', type=int, help='batch size', required=30)\n parser.add_argument('--input', type=str, help='Input dir of images', required=True)\n parser.add_argument('--output', type=str, help='Output dir of clusters', required=True)\n args = parser.parse_args()\n\n return args\n\nif __name__ == '__main__':\n \"\"\" Entry point \"\"\"\n main(parse_args())\n"
] |
[
[
"tensorflow.get_default_session",
"tensorflow.Graph",
"tensorflow.Session",
"tensorflow.get_default_graph",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
]
] |
bo-ke/cybo
|
[
"612f30b0466b4ed6d04f5c2128b133367b55e576"
] |
[
"cybo/models/stack_propagation_slu.py"
] |
[
"# -*- coding: utf-8 -*-\n'''\n@author: kebo\n@contact: [email protected]\n\n@version: 1.0\n@file: stack_propagation_slu.py\n@time: 2021/02/23 01:01:13\n\n这一行开始写关于本文件的说明与解释\n\n\n'''\nimport tensorflow as tf\nfrom typing import Dict\n\nfrom cybo.data.vocabulary import Vocabulary\nfrom cybo.modules.attentions import SelfAttentionLayer\nfrom cybo.losses.slu_loss import slu_loss_func\n# from cybo.metrics.slu_overall_acc_metric import SluTokenLevelIntentOverallAcc\nfrom cybo.metrics.nlu_acc_metric import NluAccMetric, Metric\nfrom cybo.losses.token_classification_loss import TokenClassificationLoss\nfrom cybo.models.model import Model\n\n\nclass StackPropagationSlu(Model):\n def __init__(\n self, embedding_dim, hidden_dim, dropout_rate,\n vocab: Vocabulary, *args, **kwargs):\n super().__init__(vocab=vocab, *args, **kwargs)\n\n _vocab_size = self._vocab.get_vocab_size(\"text\")\n _intent_size = self._vocab.get_vocab_size(\"intent\")\n _slot_size = self._vocab.get_vocab_size(\"tags\")\n\n self.embedding = tf.keras.layers.Embedding(\n _vocab_size, embedding_dim, mask_zero=True)\n self.bi_lstm = tf.keras.layers.Bidirectional(\n tf.keras.layers.LSTM(hidden_dim, return_sequences=True))\n self.attention_layer = SelfAttentionLayer(\n hidden_dim=1024, output_dim=128,\n dropout_rate=dropout_rate)\n self.dropout1 = tf.keras.layers.Dropout(rate=dropout_rate)\n\n self.concat = tf.keras.layers.Concatenate()\n\n self.intent_decoder_cell = tf.keras.layers.LSTMCell(units=64)\n self.slot_decoder_cell = tf.keras.layers.LSTMCell(units=64)\n self.intent_decoder_dropout = tf.keras.layers.Dropout(\n rate=dropout_rate)\n self.slot_decoder_dropout = tf.keras.layers.Dropout(rate=dropout_rate)\n\n self.intent_liner_layer = tf.keras.layers.Dense(\n units=_intent_size)\n self.slot_liner_layer = tf.keras.layers.Dense(\n units=_slot_size)\n\n self.intent_embedding = tf.keras.layers.Embedding(_intent_size, 8)\n self.slot_embedding = tf.keras.layers.Embedding(_slot_size, 32)\n self._intent_loss = TokenClassificationLoss()\n self._slot_loss = TokenClassificationLoss()\n\n def init_metrics(self) -> Dict[str, Metric]:\n return {\"nlu_acc\": NluAccMetric()}\n\n # @tf.function()\n def call(self, input_ids, intent_ids=None, tags_ids=None, mask=None,\n training=True):\n x = self.embedding(input_ids) # (b, s, e)\n x = self.dropout1(x, training=training)\n h = self.bi_lstm(x) # (b, s, 2e)\n c = self.attention_layer(h) # (b, s, 2e)\n e = self.concat([h, c])\n\n # intent_decoder\n _intent_h_state, _intent_c_state = tf.zeros(\n [x.shape[0], 64]), tf.zeros([x.shape[0], 64])\n # (b, 64)\n _slot_h_state, _slot_c_state = tf.zeros(\n [x.shape[0], 64]), tf.zeros([x.shape[0], 64])\n # (b, 64)\n # https://stackoverflow.com/questions/64567161/tensorflow-cannot-be-accessed-here-it-is-defined-in-another-function-or-code-b\n y_intent, y_slot = tf.TensorArray(\n dtype=tf.float32, size=0, dynamic_size=True), tf.TensorArray(\n dtype=tf.float32, size=0, dynamic_size=True)\n # y_intent, y_slot = [], []\n prev_intent_tensor = tf.zeros([x.shape[0], 8])\n prev_slot_tensor = tf.zeros([x.shape[0], 32])\n for i in tf.range(x.shape[1]):\n _hidden = e[:, i, :]\n _intent_hidden = tf.concat([_hidden, prev_intent_tensor], axis=-1)\n # 添加dropout\n _intent_hidden = self.intent_decoder_dropout(\n _intent_hidden, training=training)\n _intent_h_state, (_intent_h_state, _intent_c_state) = self.intent_decoder_cell(\n _intent_hidden, states=[_intent_h_state, _intent_c_state])\n _h_intent_i = self.intent_liner_layer(_intent_h_state)\n y_intent = y_intent.write(i, _h_intent_i)\n # y_intent.append(_h_intent_i)\n prev_intent_tensor = self.intent_embedding(\n tf.argmax(_h_intent_i, axis=-1))\n # slot_decoder\n _slot_hidden = tf.concat(\n [_hidden, _h_intent_i, prev_slot_tensor],\n axis=-1)\n # 添加dropout\n _slot_hidden = self.slot_decoder_dropout(\n _slot_hidden, training=training)\n _slot_h_state, (_slot_h_state, _slot_c_state) = self.slot_decoder_cell(\n _slot_hidden, states=[_slot_h_state, _slot_c_state])\n _h_slot_i = self.slot_liner_layer(_slot_h_state)\n y_slot = y_slot.write(i, _h_slot_i)\n # y_slot.append(_h_slot_i)\n prev_slot_tensor = self.slot_embedding(\n tf.argmax(_h_slot_i, axis=-1))\n # 注意不可用reshape transpose与reshape结果是不一样的\n # 错误写法: tf.reshape(y_intent.stack(), [x.shape[0], x.shape[1], -1])\n y_intent = tf.transpose(y_intent.stack(), [1, 0, 2])\n y_slot = tf.transpose(y_slot.stack(), [1, 0, 2])\n\n o_intent = self.get_o_intent(intent_pred=y_intent, mask=x._keras_mask)\n\n output_dict = {\"intent_logits\": o_intent, \"slot_logits\": y_slot}\n if intent_ids is not None and tags_ids is not None:\n _intent_ids = tf.broadcast_to(intent_ids, tags_ids.shape)\n active_loss = tags_ids != -100\n\n _intent_loss = self._intent_loss.compute_loss(\n y_true=tf.boolean_mask(_intent_ids, active_loss),\n y_pred=tf.boolean_mask(y_intent, active_loss))\n _slot_loss = self._slot_loss.compute_loss(\n y_true=tags_ids, y_pred=y_slot)\n output_dict[\"loss\"] = _intent_loss + _slot_loss\n self._metrics[\"nlu_acc\"].update_state(\n y_true=[intent_ids, tags_ids],\n y_pred=[o_intent, y_slot])\n return output_dict\n\n @staticmethod\n def get_o_intent(intent_pred, mask):\n mask = tf.cast(mask, dtype=tf.int32)\n o_intent = tf.argmax(intent_pred, axis=-1)\n seq_lengths = tf.reduce_sum(mask, axis=-1)\n # 取token_level_intent most_common 作为query intent\n # https://www.tensorflow.org/api_docs/python/tf/unique_with_counts\n\n def get_max_count_intent(_intent):\n _y, _idx, _count = tf.unique_with_counts(_intent)\n _intent = _y[tf.argmax(_count)]\n return [_intent]\n\n o_intent = tf.convert_to_tensor(\n [get_max_count_intent(o_intent[i][: seq_lengths[i]])\n for i in range(len(seq_lengths))], dtype=tf.int32)\n return o_intent\n"
] |
[
[
"tensorflow.keras.layers.Concatenate",
"tensorflow.boolean_mask",
"tensorflow.concat",
"tensorflow.range",
"tensorflow.keras.layers.Embedding",
"tensorflow.zeros",
"tensorflow.keras.layers.Dense",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.argmax",
"tensorflow.TensorArray",
"tensorflow.broadcast_to",
"tensorflow.keras.layers.LSTM",
"tensorflow.unique_with_counts",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.LSTMCell"
]
] |
arash-safari/vp
|
[
"377e0172112157b79690b32349481a17e7590063"
] |
[
"image/pixelsnail.py"
] |
[
"# Copyright (c) Xi Chen\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Borrowed from https://github.com/neocxi/pixelsnail-public and ported it to PyTorch\n\nfrom math import sqrt\nfrom functools import partial, lru_cache\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\ndef wn_linear(in_dim, out_dim):\n return nn.utils.weight_norm(nn.Linear(in_dim, out_dim))\n\n\nclass WNConv2d(nn.Module):\n def __init__(\n self,\n in_channel,\n out_channel,\n kernel_size,\n stride=1,\n padding=0,\n bias=True,\n activation=None,\n ):\n super().__init__()\n\n self.conv = nn.utils.weight_norm(\n nn.Conv2d(\n in_channel,\n out_channel,\n kernel_size,\n stride=stride,\n padding=padding,\n bias=bias,\n )\n )\n\n self.out_channel = out_channel\n\n if isinstance(kernel_size, int):\n kernel_size = [kernel_size, kernel_size]\n\n self.kernel_size = kernel_size\n\n self.activation = activation\n\n def forward(self, input):\n out = self.conv(input)\n\n if self.activation is not None:\n out = self.activation(out)\n\n return out\n\n\ndef shift_down(input, size=1):\n return F.pad(input, [0, 0, size, 0])[:, :, : input.shape[2], :]\n\n\ndef shift_right(input, size=1):\n return F.pad(input, [size, 0, 0, 0])[:, :, :, : input.shape[3]]\n\n\nclass CausalConv2d(nn.Module):\n def __init__(\n self,\n in_channel,\n out_channel,\n kernel_size,\n stride=1,\n padding='downright',\n activation=None,\n ):\n super().__init__()\n\n if isinstance(kernel_size, int):\n kernel_size = [kernel_size] * 2\n\n self.kernel_size = kernel_size\n\n if padding == 'downright':\n pad = [kernel_size[1] - 1, 0, kernel_size[0] - 1, 0]\n\n elif padding == 'down' or padding == 'causal':\n pad = kernel_size[1] // 2\n\n pad = [pad, pad, kernel_size[0] - 1, 0]\n\n self.causal = 0\n if padding == 'causal':\n self.causal = kernel_size[1] // 2\n\n self.pad = nn.ZeroPad2d(pad)\n\n self.conv = WNConv2d(\n in_channel,\n out_channel,\n kernel_size,\n stride=stride,\n padding=0,\n activation=activation,\n )\n\n def forward(self, input):\n out = self.pad(input)\n\n if self.causal > 0:\n self.conv.conv.weight_v.data[:, :, -1, self.causal :].zero_()\n\n out = self.conv(out)\n\n return out\n\n\nclass GatedResBlock(nn.Module):\n def __init__(\n self,\n in_channel,\n channel,\n kernel_size,\n conv='wnconv2d',\n activation=nn.ELU,\n dropout=0.1,\n auxiliary_channel=0,\n condition_dim=0,\n ):\n super().__init__()\n\n if conv == 'wnconv2d':\n conv_module = partial(WNConv2d, padding=kernel_size // 2)\n\n elif conv == 'causal_downright':\n conv_module = partial(CausalConv2d, padding='downright')\n\n elif conv == 'causal':\n conv_module = partial(CausalConv2d, padding='causal')\n\n self.activation = activation(inplace=True)\n self.conv1 = conv_module(in_channel, channel, kernel_size)\n\n if auxiliary_channel > 0:\n self.aux_conv = WNConv2d(auxiliary_channel, channel, 1)\n\n self.dropout = nn.Dropout(dropout)\n\n self.conv2 = conv_module(channel, in_channel * 2, kernel_size)\n\n if condition_dim > 0:\n # self.condition = nn.Linear(condition_dim, in_channel * 2, bias=False)\n self.condition = WNConv2d(condition_dim, in_channel * 2, 1, bias=False)\n\n self.gate = nn.GLU(1)\n\n def forward(self, input, aux_input=None, condition=None):\n out = self.conv1(self.activation(input))\n # print('gateblock condition:{}'.format(condition))\n if aux_input is not None:\n out = out + self.aux_conv(self.activation(aux_input))\n\n out = self.activation(out)\n out = self.dropout(out)\n out = self.conv2(out)\n\n if condition is not None:\n condition = self.condition(condition)\n # print('condition: {}, out: {}'.format(condition.shape,out.shape))\n out += condition\n # out = out + condition.view(condition.shape[0], 1, 1, condition.shape[1])\n\n out = self.gate(out)\n out += input\n\n return out\n\n\n@lru_cache(maxsize=64)\ndef causal_mask(size):\n shape = [size, size]\n mask = np.triu(np.ones(shape), k=1).astype(np.uint8).T\n start_mask = np.ones(size).astype(np.float32)\n start_mask[0] = 0\n\n return (\n torch.from_numpy(mask).unsqueeze(0),\n torch.from_numpy(start_mask).unsqueeze(1),\n )\n\n\nclass CausalAttention(nn.Module):\n def __init__(self, query_channel, key_channel, channel, n_head=8, dropout=0.1):\n super().__init__()\n\n self.query = wn_linear(query_channel, channel)\n self.key = wn_linear(key_channel, channel)\n self.value = wn_linear(key_channel, channel)\n\n self.dim_head = channel // n_head\n self.n_head = n_head\n\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, query, key):\n batch, _, height, width = key.shape\n\n def reshape(input):\n return input.view(batch, -1, self.n_head, self.dim_head).transpose(1, 2)\n\n query_flat = query.view(batch, query.shape[1], -1).transpose(1, 2)\n key_flat = key.view(batch, key.shape[1], -1).transpose(1, 2)\n query = reshape(self.query(query_flat))\n key = reshape(self.key(key_flat)).transpose(2, 3)\n value = reshape(self.value(key_flat))\n\n attn = torch.matmul(query, key) / sqrt(self.dim_head)\n mask, start_mask = causal_mask(height * width)\n mask = mask.type_as(query)\n start_mask = start_mask.type_as(query)\n attn = attn.masked_fill(mask == 0, -1e4)\n attn = torch.softmax(attn, 3) * start_mask\n attn = self.dropout(attn)\n\n out = attn @ value\n out = out.transpose(1, 2).reshape(\n batch, height, width, self.dim_head * self.n_head\n )\n out = out.permute(0, 3, 1, 2)\n\n return out\n\n\nclass PixelBlock(nn.Module):\n def __init__(\n self,\n in_channel,\n channel,\n kernel_size,\n n_res_block,\n attention=True,\n dropout=0.1,\n condition_dim=0,\n ):\n super().__init__()\n\n resblocks = []\n for i in range(n_res_block):\n resblocks.append(\n GatedResBlock(\n in_channel,\n channel,\n kernel_size,\n conv='causal',\n dropout=dropout,\n condition_dim=condition_dim,\n )\n )\n\n self.resblocks = nn.ModuleList(resblocks)\n\n self.attention = attention\n\n if attention:\n self.key_resblock = GatedResBlock(\n in_channel * 2 + 2, in_channel, 1, dropout=dropout\n )\n self.query_resblock = GatedResBlock(\n in_channel + 2, in_channel, 1, dropout=dropout\n )\n\n self.causal_attention = CausalAttention(\n in_channel + 2, in_channel * 2 + 2, in_channel // 2, dropout=dropout\n )\n\n self.out_resblock = GatedResBlock(\n in_channel,\n in_channel,\n 1,\n auxiliary_channel=in_channel // 2,\n dropout=dropout,\n )\n\n else:\n self.out = WNConv2d(in_channel + 2, in_channel, 1)\n\n def forward(self, input, background, condition=None):\n out = input\n\n for resblock in self.resblocks:\n # print('resblock condition:{}'.shape(condition.shape))\n out = resblock(out, condition=condition)\n\n if self.attention:\n key_cat = torch.cat([input, out, background], 1)\n key = self.key_resblock(key_cat)\n query_cat = torch.cat([out, background], 1)\n query = self.query_resblock(query_cat)\n attn_out = self.causal_attention(query, key)\n out = self.out_resblock(out, attn_out)\n\n else:\n bg_cat = torch.cat([out, background], 1)\n out = self.out(bg_cat)\n\n return out\n\n\nclass CondResNet(nn.Module):\n def __init__(self, in_channel, channel, kernel_size, n_res_block):\n super().__init__()\n\n blocks = [WNConv2d(in_channel, channel, kernel_size, padding=kernel_size // 2)]\n\n for i in range(n_res_block):\n blocks.append(GatedResBlock(channel, channel, kernel_size))\n\n self.blocks = nn.Sequential(*blocks)\n\n def forward(self, input):\n return self.blocks(input)\n\n\nclass PixelSNAIL(nn.Module):\n def __init__(\n self,\n shape,\n n_class,\n channel,\n kernel_size,\n n_block,\n n_res_block,\n res_channel,\n attention=True,\n dropout=0.1,\n n_cond_res_block=0,\n cond_res_channel=0,\n cond_res_kernel=3,\n n_out_res_block=0,\n ):\n super().__init__()\n\n channels, height, width = shape\n\n self.n_class = n_class\n\n if kernel_size % 2 == 0:\n kernel = kernel_size + 1\n\n else:\n kernel = kernel_size\n\n self.horizontal = CausalConv2d(\n n_class, channel, [kernel // 2, kernel], padding='down'\n )\n self.vertical = CausalConv2d(\n n_class, channel, [(kernel + 1) // 2, kernel // 2], padding='downright'\n )\n\n coord_x = (torch.arange(height).float() - height / 2) / height\n coord_x = coord_x.view(1, 1, height, 1).expand(1, 1, height, width)\n coord_y = (torch.arange(width).float() - width / 2) / width\n coord_y = coord_y.view(1, 1, 1, width).expand(1, 1, height, width)\n self.register_buffer('background', torch.cat([coord_x, coord_y], 1))\n\n self.blocks = nn.ModuleList()\n\n for i in range(n_block):\n self.blocks.append(\n PixelBlock(\n channel,\n res_channel,\n kernel_size,\n n_res_block,\n attention=attention,\n dropout=dropout,\n condition_dim=cond_res_channel,\n )\n )\n\n if n_cond_res_block > 0:\n self.cond_resnet = CondResNet(\n n_class, cond_res_channel, cond_res_kernel, n_cond_res_block\n )\n\n out = []\n\n for i in range(n_out_res_block):\n out.append(GatedResBlock(channel, res_channel, 1))\n\n out.extend([nn.ELU(inplace=True), WNConv2d(channel, n_class, 1)])\n\n self.out = nn.Sequential(*out)\n\n def forward(self, input, condition=None, cache=None):\n if cache is None:\n cache = {}\n batch, height, width = input.shape\n input = (\n F.one_hot(input, self.n_class).permute(0, 3, 1, 2).type_as(self.background)\n )\n horizontal = shift_down(self.horizontal(input))\n vertical = shift_right(self.vertical(input))\n out = horizontal + vertical\n\n background = self.background[:, :, :height, :].expand(batch, 2, height, width)\n\n if condition is not None:\n if 'condition' in cache:\n condition = cache['condition']\n condition = condition[:, :, :height, :]\n\n else:\n condition = (\n F.one_hot(condition, self.n_class)\n .permute(0, 3, 1, 2)\n .type_as(self.background)\n )\n condition = self.cond_resnet(condition)\n condition = F.interpolate(condition, scale_factor=2)\n cache['condition'] = condition.detach().clone()\n condition = condition[:, :, :height, :]\n\n for block in self.blocks:\n out = block(out, background, condition=condition)\n\n out = self.out(out)\n\n return out, cache\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.nn.GLU",
"torch.softmax",
"torch.cat",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.ELU",
"torch.from_numpy",
"numpy.ones",
"torch.nn.Linear",
"torch.matmul",
"torch.nn.functional.interpolate",
"torch.arange",
"torch.nn.functional.one_hot",
"torch.nn.ZeroPad2d",
"torch.nn.functional.pad"
]
] |
tpmp-inra/ipso_cli
|
[
"6de4097dcb1536b546d9e2cdeb61057e5f931537"
] |
[
"ipapi/base/ipt_loose_pipeline.py"
] |
[
"from ipapi.tools.folders import ipso_folders\r\nfrom uuid import uuid4\r\nimport json\r\nfrom datetime import datetime as dt\r\nfrom timeit import default_timer as timer\r\nimport itertools\r\nfrom typing import Union\r\nimport logging\r\nimport csv\r\nimport os\r\n\r\nimport numpy as np\r\n\r\nfrom ipapi.base.ipt_abstract import IptParam, IptBase, IptParamHolder\r\nfrom ipapi.base.ipt_functional import get_ipt_class\r\nfrom ipapi.base import ip_common as ipc\r\nfrom ipapi.base.ipt_strict_pipeline import IptStrictPipeline\r\nfrom ipapi.base.ip_abstract import BaseImageProcessor\r\nimport ipapi.tools.error_holder as eh\r\nfrom ipapi.tools.common_functions import format_time\r\nfrom ipapi.tools.regions import RectangleRegion\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\nlast_script_version = \"0.2.0.0\"\r\n\r\n\r\nclass MosaicData(object):\r\n def __init__(self, pipeline, enabled, images):\r\n super().__init__()\r\n self.enabled = enabled\r\n self.images = images\r\n if isinstance(self.images, str):\r\n self.images = [\r\n [i for i in line.split(\",\")] for line in self.images.split(\"\\n\")\r\n ]\r\n self.pipeline = pipeline\r\n\r\n\r\nclass PipelineSettings(IptParamHolder):\r\n def __init__(self, pipeline, **kwargs):\r\n self.update_feedback_items = []\r\n super(PipelineSettings, self).__init__(**kwargs)\r\n self.mosaic = MosaicData(\r\n pipeline=pipeline,\r\n enabled=kwargs.get(\"mosaic_enabled\", kwargs.get(\"build_mosaic\", True) == 1),\r\n images=kwargs.get(\r\n \"mosaic_images\", kwargs.get(\"mosaic_items\", [[\"source\", \"mask\"]])\r\n ),\r\n )\r\n\r\n def build_params(self):\r\n self.add_checkbox(\r\n name=\"show_tool_result\",\r\n desc=\"Show a result image for each tool\",\r\n default_value=1,\r\n )\r\n self.add_checkbox(\r\n name=\"show_group_result\",\r\n desc=\"Show a result image for each group\",\r\n default_value=0,\r\n )\r\n self.add_checkbox(\r\n name=\"debug_mode\",\r\n desc=\"Display debug images\",\r\n default_value=0,\r\n hint=\"Display module's intermediary images\",\r\n )\r\n self.add_checkbox(\r\n name=\"allow_step_mosaics\",\r\n desc=\"Allow mosaics for steps\",\r\n default_value=1,\r\n hint=\"If checked, some steps will return mosaics instead of single images\",\r\n )\r\n self.add_checkbox(\r\n name=\"show_source_image\",\r\n desc=\"Show source image/mask for each tool\",\r\n default_value=0,\r\n )\r\n self.add_checkbox(\r\n name=\"tool_group_name_watermark\",\r\n desc=\"Add a watermark with the name of the generating source to each output image\",\r\n default_value=0,\r\n )\r\n self.add_combobox(\r\n name=\"stop_on\",\r\n desc=\"Stop processing on error level\",\r\n default_value=eh.ERR_LVL_EXCEPTION,\r\n values={i: eh.error_level_to_str(i) for i in [0, 10, 20, 30, 35, 40, 50]},\r\n hint=\"If any error of the selected level or higher happens the process will halt\",\r\n )\r\n\r\n def params_to_dict(\r\n self,\r\n include_input: bool = True,\r\n include_output: bool = False,\r\n include_neutral: bool = False,\r\n ):\r\n dic = {}\r\n for p in self.gizmos:\r\n if (\r\n (include_input and p.is_input)\r\n or (include_output and p.is_output)\r\n or (include_neutral and p.is_neutral)\r\n ):\r\n dic[p.name] = p.value\r\n dic[\"mosaic_enabled\"] = self.mosaic.enabled\r\n dic[\"mosaic_images\"] = self.mosaic.images\r\n return dic\r\n\r\n def items(self):\r\n return self.gizmos + [self.mosaic]\r\n\r\n @property\r\n def node_count(self):\r\n return len(self.items())\r\n\r\n\r\nclass Node(object):\r\n def __init__(self, **kwargs):\r\n self.uuid = kwargs.get(\"uuid\", str(uuid4()))\r\n if not self.uuid:\r\n self.uuid = str(uuid4())\r\n self.parent = kwargs.get(\"parent\")\r\n self.last_result = {}\r\n\r\n def get_relevant_image(self, exclude_demo: bool = False):\r\n if not exclude_demo:\r\n demo_image = self.last_result.get(\"demo_image\", None)\r\n if demo_image is not None:\r\n ri = demo_image\r\n\r\n if self.output_type == ipc.IO_IMAGE:\r\n ri = self.last_result.get(\r\n \"image\", np.full((100, 100, 3), ipc.C_FUCHSIA, np.uint8)\r\n )\r\n elif self.output_type == ipc.IO_MASK:\r\n ri = self.last_result.get(\r\n \"mask\", np.full((100, 100, 3), ipc.C_FUCHSIA, np.uint8)\r\n )\r\n elif self.output_type in [ipc.IO_DATA, ipc.IO_ROI, ipc.IO_NONE]:\r\n ri = self.last_result.get(\r\n \"image\",\r\n self.last_result.get(\r\n \"mask\", np.full((100, 100, 3), ipc.C_FUCHSIA, np.uint8)\r\n ),\r\n )\r\n else:\r\n ri = np.full((100, 100, 3), ipc.C_FUCHSIA, np.uint8)\r\n\r\n if self.root.parent.tool_group_name_watermark:\r\n ri = ri.copy()\r\n BaseImageProcessor.draw_text(\r\n img=ri,\r\n text=self.name,\r\n fnt_color=ipc.C_WHITE,\r\n background_color=ipc.C_BLACK,\r\n )\r\n\r\n return ri\r\n\r\n def get_feedback_image(self, data: dict):\r\n demo_image = data.get(\"demo_image\", None)\r\n if demo_image is not None:\r\n fi = demo_image\r\n else:\r\n mask = data.get(\"mask\", None)\r\n image = data.get(\"image\", None)\r\n if (\r\n mask is not None\r\n and image is not None\r\n and self.root.parent.allow_step_mosaics\r\n ):\r\n h = max(mask.shape[0], image.shape[0])\r\n w = max(mask.shape[1], image.shape[1])\r\n canvas = ipc.enclose_image(\r\n a_cnv=np.full(\r\n shape=(h + 4, w * 2 + 6, 3),\r\n fill_value=ipc.C_SILVER,\r\n dtype=np.uint8,\r\n ),\r\n img=image,\r\n rect=RectangleRegion(left=2, top=2, width=w, height=h),\r\n )\r\n fi = ipc.enclose_image(\r\n a_cnv=canvas,\r\n img=np.dstack((mask, mask, mask)),\r\n rect=RectangleRegion(left=w + 4, top=2, width=w, height=h),\r\n )\r\n\r\n elif mask is not None:\r\n fi = mask\r\n elif image is not None:\r\n fi = image\r\n else:\r\n fi = np.full((100, 100, 3), ipc.C_FUCHSIA, np.uint8)\r\n\r\n if self.root.parent.tool_group_name_watermark:\r\n fi = fi.copy()\r\n BaseImageProcessor.draw_text(\r\n img=fi,\r\n text=self.name,\r\n fnt_color=ipc.C_WHITE,\r\n background_color=ipc.C_BLACK,\r\n )\r\n\r\n return fi\r\n\r\n def do_call_back(\r\n self,\r\n call_back,\r\n res,\r\n msg,\r\n data,\r\n is_progress=True,\r\n force_call_back=False,\r\n **kwargs,\r\n ):\r\n if call_back is not None:\r\n call_back(\r\n eh.error_level_to_str(res),\r\n msg,\r\n data\r\n if call_back is not None\r\n and (force_call_back or not self.root.parent.silent)\r\n else None,\r\n self.absolute_index + 1 if is_progress else -1,\r\n self.absolute_count if is_progress else -1,\r\n )\r\n else:\r\n if isinstance(res, int) and (res >= logging.WARNING):\r\n eh.log_data(log_msg=msg, log_level=res, target_logger=logger)\r\n md = np.array(self.root.parent.settings.mosaic.images)\r\n wrapper = self.root.parent.wrapper\r\n needed_images = wrapper.forced_storage_images_list\r\n if isinstance(data, (GroupNode, ModuleNode)):\r\n dn = data.name\r\n if dn in md:\r\n self.root.parent.stored_mosaic_images[dn] = self.get_relevant_image()\r\n if dn in needed_images:\r\n wrapper.store_image(\r\n image=self.get_relevant_image(exclude_demo=True),\r\n text=dn,\r\n force_store=True,\r\n )\r\n elif isinstance(data, BaseImageProcessor):\r\n for d in data.image_list:\r\n if d[\"name\"] in md:\r\n self.root.parent.stored_mosaic_images[d[\"name\"]] = d[\"image\"]\r\n\r\n self.root.parent.update_error_level(res)\r\n\r\n @property\r\n def root(self):\r\n root = self\r\n while root.parent is not None and not isinstance(root.parent, LoosePipeline):\r\n root = root.parent\r\n return root\r\n\r\n @property\r\n def absolute_index(self):\r\n if isinstance(self, GroupNode):\r\n if isinstance(self.parent, LoosePipeline):\r\n return self.absolute_count\r\n lst = self.root.as_pivot_list(index=self, types=(\"groups\"))\r\n elif isinstance(self, ModuleNode):\r\n lst = self.root.as_pivot_list(index=self, types=(\"modules\"))\r\n else:\r\n return -2\r\n return len(lst.get(\"before\", ()))\r\n\r\n @property\r\n def absolute_count(self):\r\n if isinstance(self, GroupNode):\r\n return len(list(self.root.iter_items(types=(\"groups\"))))\r\n elif isinstance(self, ModuleNode):\r\n return len(list(self.root.iter_items(types=(\"modules\"))))\r\n else:\r\n return -2\r\n\r\n @property\r\n def stop_processing(self):\r\n return self.root.parent.stop_processing\r\n\r\n @stop_processing.setter\r\n def stop_processing(self, value):\r\n self.root.parent.stop_processing = value\r\n\r\n @property\r\n def is_module(self):\r\n return isinstance(self, ModuleNode)\r\n\r\n @property\r\n def is_group(self):\r\n return isinstance(self, GroupNode)\r\n\r\n @property\r\n def is_root(self):\r\n return isinstance(self.parent, LoosePipeline)\r\n\r\n\r\nclass ModuleNode(Node):\r\n def __init__(self, **kwargs):\r\n Node.__init__(self, **kwargs)\r\n self.enabled = kwargs.get(\"enabled\", 1)\r\n self.tool = kwargs.get(\"tool\")\r\n self.tool.owner = self\r\n\r\n def _execute_standard(self, tool, call_back=None, target_module: str = \"\"):\r\n res = {}\r\n wrapper = self.root.parent.wrapper\r\n if self.root.parent.show_source_image:\r\n if wrapper is not None and wrapper.current_image is not None:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=\"\",\r\n data={\r\n \"plant_name\": wrapper.plant,\r\n \"name\": f\"{self.name} (source image)\",\r\n \"image\": wrapper.current_image,\r\n \"luid\": wrapper.luid,\r\n \"data\": {},\r\n },\r\n )\r\n if wrapper is not None and wrapper.mask is not None:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=\"\",\r\n data={\r\n \"plant_name\": wrapper.plant,\r\n \"name\": f\"{self.name} (source mask)\",\r\n \"image\": wrapper.mask,\r\n \"luid\": wrapper.luid,\r\n \"data\": {},\r\n },\r\n )\r\n if tool.process_wrapper(wrapper=wrapper):\r\n # Get ROI\r\n if self.output_type == ipc.IO_ROI:\r\n func = getattr(tool, \"generate_roi\", None)\r\n if callable(func):\r\n roi = func(wrapper=wrapper)\r\n if roi is not None:\r\n res[\"roi\"] = roi\r\n if not wrapper.store_images:\r\n wrapper.store_image(\r\n image=roi.draw_to(\r\n dst_img=wrapper.current_image,\r\n line_width=max(4, wrapper.width // 200),\r\n ),\r\n text=self.name,\r\n force_store=True,\r\n )\r\n else:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.ERROR,\r\n msg=f\"Failed to generate ROI from {self.name}\",\r\n data=wrapper if self.root.parent.debug_mode else self,\r\n )\r\n # Get data\r\n if hasattr(tool, \"data_dict\"):\r\n res[\"data\"] = tool.data_dict\r\n # Get mask\r\n if self.output_type == ipc.IO_MASK:\r\n res[\"mask\"] = tool.result\r\n if tool.result is None:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.WARNING,\r\n msg=f\"Failed to generate mask from {self.name}\",\r\n data=None,\r\n )\r\n # Get image\r\n if (\r\n self.output_type in [ipc.IO_MASK, ipc.IO_NONE, ipc.IO_ROI]\r\n and tool.demo_image is not None\r\n ):\r\n res[\"image\"] = tool.demo_image\r\n elif self.output_type == ipc.IO_ROI:\r\n res[\"image\"] = wrapper.draw_rois(\r\n img=wrapper.current_image, rois=[res[\"roi\"]]\r\n )\r\n elif self.output_type == ipc.IO_DATA:\r\n if tool.demo_image is not None:\r\n res[\"image\"] = tool.demo_image\r\n else:\r\n res[\"image\"] = wrapper.current_image\r\n elif self.output_type == ipc.IO_IMAGE and isinstance(tool.result, np.ndarray):\r\n res[\"image\"] = tool.result\r\n # Get demo image\r\n if tool.demo_image is not None:\r\n res[\"demo_image\"] = tool.demo_image\r\n\r\n return res\r\n\r\n def _execute_grid_search(self, call_back):\r\n def inner_call_back(res, msg, data, step, total):\r\n if call_back is not None:\r\n call_back(\r\n res,\r\n msg,\r\n data,\r\n step,\r\n total,\r\n )\r\n\r\n param_settings_list = [p.decode_grid_search_options() for p in self.tool.gizmos]\r\n size = 1\r\n for ps in param_settings_list:\r\n if len(ps) > 0:\r\n size *= len(ps)\r\n inner_call_back(\r\n res=\"GRID_SEARCH_START\",\r\n msg=\"\",\r\n data=None,\r\n step=0,\r\n total=size,\r\n )\r\n\r\n procs = list(itertools.product(*param_settings_list))\r\n keys = [p.name for p in self.tool.gizmos]\r\n wrapper = self.root.parent.wrapper\r\n\r\n for i, p in enumerate(procs):\r\n res = self._execute_standard(\r\n tool=self.tool.__class__(\r\n **{k: (int(v) if str.isdigit(v) else v) for k, v in zip(keys, p)}\r\n ),\r\n )\r\n inner_call_back(\r\n res=\"GRID_SEARCH_OK\" if res else \"GRID_SEARCH_NOK\",\r\n msg=\"Failed to process element\",\r\n data={\r\n \"plant_name\": wrapper.plant,\r\n \"name\": wrapper.short_name,\r\n \"image\": self.get_feedback_image(res),\r\n \"data\": res.get(\"data\", {}),\r\n \"luid\": wrapper.luid,\r\n },\r\n step=i + 1,\r\n total=size,\r\n )\r\n\r\n inner_call_back(\r\n res=\"GRID_SEARCH_END\",\r\n msg=\"\",\r\n data=None,\r\n step=size,\r\n total=size,\r\n )\r\n\r\n def execute(self, **kwargs):\r\n call_back = kwargs.get(\"call_back\", None)\r\n target_module = kwargs.get(\"target_module\", \"\")\r\n grid_search_mode = kwargs.get(\"grid_search_mode\", \"\")\r\n wrapper = self.root.parent.wrapper\r\n\r\n if not self.last_result:\r\n if hasattr(self.tool, \"output_path\") and self.root.parent.image_output_path:\r\n self.tool.output_path = self.root.parent.image_output_path\r\n if target_module == self.uuid and grid_search_mode:\r\n self._execute_grid_search(call_back=call_back)\r\n self.last_result = {}\r\n else:\r\n before = timer()\r\n self.last_result = self._execute_standard(\r\n tool=self.tool,\r\n call_back=call_back,\r\n target_module=target_module,\r\n )\r\n if self.root.parent.debug_mode:\r\n data = wrapper\r\n elif self.root.parent.show_tool_result:\r\n data = self\r\n else:\r\n data = None\r\n if self.last_result:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=f\"Successfully processed {self.name} in {format_time(timer() - before)}\",\r\n data=data,\r\n )\r\n else:\r\n if ipc.ToolFamily.ASSERT in self.tool.use_case:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.ERROR,\r\n msg=f'Assertion \"{self.tool.name}\" failed for {self.name}',\r\n data=wrapper\r\n if self.root.parent.debug_mode or self.uuid == target_module\r\n else self,\r\n )\r\n else:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.ERROR,\r\n msg=f\"Failed to process {self.name} in {format_time(timer() - before)}\",\r\n data=wrapper\r\n if self.root.parent.debug_mode or self.uuid == target_module\r\n else self,\r\n )\r\n\r\n return self.last_result\r\n\r\n def invalidate(self):\r\n self.last_result = {}\r\n\r\n def copy(self, parent):\r\n return ModuleNode(\r\n parent=parent,\r\n tool=self.tool,\r\n enabled=self.enabled,\r\n uuid=self.uuid,\r\n )\r\n\r\n def to_code(self, indent: int):\r\n pass\r\n\r\n def to_json(self):\r\n return {\r\n \"node_type\": \"module\",\r\n \"tool\": self.tool.to_json(),\r\n \"enabled\": self.enabled,\r\n \"uuid\": self.uuid,\r\n }\r\n\r\n @classmethod\r\n def from_json(cls, parent, json_data: dict):\r\n if json_data[\"node_type\"] != \"module\":\r\n return None\r\n tool = IptBase.from_json(json_data[\"tool\"])\r\n if isinstance(tool, Exception):\r\n eh.log_data(\r\n log_msg=f\"Failed to load module: {repr(tool)}\",\r\n log_level=eh.ERR_LVL_EXCEPTION,\r\n target_logger=logger,\r\n )\r\n elif isinstance(tool, IptBase):\r\n return ModuleNode(\r\n tool=tool,\r\n parent=parent,\r\n enabled=json_data[\"enabled\"],\r\n uuid=json_data[\"uuid\"],\r\n )\r\n\r\n def sugar_name(self):\r\n if self.tool.has_param(\"roi_name\") and self.tool.get_value_of(\"roi_name\"):\r\n return f'{self.tool.name} {self.tool.get_value_of(\"roi_name\")}'\r\n elif self.tool.has_param(\"channel\"):\r\n return f'{self.tool.name} {self.tool.get_value_of(\"channel\")}'\r\n elif self.tool.name == \"Morphology\":\r\n return f'{self.tool.name} {self.tool.get_value_of(\"morph_op\")}'\r\n elif self.tool.has_param(\"roi_names\") and self.tool.get_value_of(\"roi_names\"):\r\n return f'{self.tool.name} {self.tool.get_value_of(\"roi_names\")}'\r\n else:\r\n return self.tool.name\r\n\r\n @property\r\n def input_type(self):\r\n if isinstance(self.tool, IptBase):\r\n return self.tool.input_type\r\n else:\r\n return ipc.IO_NONE\r\n\r\n @property\r\n def output_type(self):\r\n if isinstance(self.tool, IptBase):\r\n return self.tool.output_type\r\n else:\r\n return ipc.IO_NONE\r\n\r\n @property\r\n def name(self):\r\n sn = self.sugar_name()\r\n nodes = [\r\n node\r\n for node in self.root.as_pivot_list(index=self, types=(\"modules\",))[\"before\"]\r\n if node.sugar_name() == sn\r\n ]\r\n return sn if len(nodes) == 0 else f\"{sn} ({len(nodes)})\"\r\n\r\n\r\nclass GroupNode(Node):\r\n\r\n default_execution_filters = {\r\n k: \"\" for k in [\"experiment\", \"plant\", \"date\", \"time\", \"camera\", \"view_option\"]\r\n }\r\n\r\n def __init__(self, **kwargs):\r\n Node.__init__(self, **kwargs)\r\n self.merge_mode = kwargs.get(\"merge_mode\")\r\n self.name = kwargs.get(\"name\", \"\")\r\n self.nodes = kwargs.get(\"nodes\", [])\r\n self.source = kwargs.get(\"source\", \"source\")\r\n self.no_delete = kwargs.get(\"no_delete\", False)\r\n self.execute_filters = kwargs.get(\r\n \"execute_filters\",\r\n self.default_execution_filters,\r\n )\r\n self.last_result = {}\r\n\r\n def add_module(self, tool, enabled=1, uuid: str = \"\") -> ModuleNode:\r\n new_module = ModuleNode(parent=self, tool=tool, enabled=enabled, uuid=uuid)\r\n self.nodes.append(new_module)\r\n return new_module\r\n\r\n def add_group(\r\n self,\r\n merge_mode: str,\r\n name: str = \"\",\r\n source=\"\",\r\n no_delete: bool = False,\r\n uuid: str = \"\",\r\n ):\r\n # Set source\r\n if not source:\r\n if len(self.nodes) > 0 and isinstance(self.nodes[-1], GroupNode):\r\n source = self.nodes[-1].uuid\r\n elif len(self.nodes) == 0:\r\n source = \"source\"\r\n else:\r\n source = \"last_output\"\r\n # Set unique name\r\n root = self.root\r\n group_names = [group.name for group in root.iter_items(types=(\"groups\",))]\r\n if not name or name in group_names:\r\n if not name:\r\n name = \"Group\"\r\n i = 1\r\n while f\"{name} {i}\" in group_names:\r\n i += 1\r\n name = f\"{name} {i}\"\r\n # Create group\r\n new_node = GroupNode(\r\n parent=self, merge_mode=merge_mode, name=name, source=source, uuid=uuid\r\n )\r\n self.nodes.append(new_node)\r\n return new_node\r\n\r\n def remove_node(self, node: Union[int, object]):\r\n if isinstance(node, int):\r\n node = self.nodes[node]\r\n if not isinstance(node, GroupNode) or not node.no_delete:\r\n self.root.invalidate(node)\r\n self.nodes.remove(node)\r\n\r\n def insert_node(self, index, node):\r\n if isinstance(node, GroupNode) or isinstance(node, ModuleNode):\r\n self.nodes.insert(min(0, max(index, len(self.nodes))), node)\r\n\r\n def get_source_image(self, source: str, call_back):\r\n wrapper = self.root.parent.wrapper\r\n if source == \"source\":\r\n return wrapper.source_image\r\n elif source == \"last_output\":\r\n nodes = self.root.as_pivot_list(index=self)\r\n for node in reversed(nodes[\"before\"]):\r\n if (\r\n node.enabled\r\n and node.output_type == ipc.IO_IMAGE\r\n and node.last_result.get(\"image\", None) is not None\r\n ):\r\n return node.last_result[\"image\"]\r\n break\r\n else:\r\n return wrapper.current_image\r\n else:\r\n node = self.root.find_by_uuid(source)\r\n if (\r\n node is None\r\n or node.last_result.get(\"image\", None) is None\r\n or node.enabled == 0\r\n ):\r\n self.last_result = {}\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.WARNING,\r\n msg=f\"{self.name} - Failed to retrieve source {source}, selecting last output instead\",\r\n data=None,\r\n is_progress=False,\r\n )\r\n return self.get_source_image(source=\"last_output\", call_back=call_back)\r\n else:\r\n return node.last_result.get(\"image\")\r\n\r\n def execute(self, **kwargs):\r\n before = timer()\r\n call_back = kwargs.get(\"call_back\", None)\r\n target_module = kwargs.get(\"target_module\", \"\")\r\n wrapper = self.root.parent.wrapper\r\n\r\n wrapper.current_image = self.get_source_image(\r\n source=self.source, call_back=call_back\r\n )\r\n\r\n rois = []\r\n only_rois = False\r\n for node in self.nodes:\r\n if not node.enabled:\r\n continue\r\n if node.output_type != ipc.IO_ROI:\r\n break\r\n else:\r\n only_rois = True\r\n\r\n is_current_image_changed = False\r\n\r\n def add_roi(wrapper: BaseImageProcessor, roi_list: list, roi, node):\r\n if roi is None:\r\n logger.warning(f\"Missing ROI for {node.name}\")\r\n else:\r\n if isinstance(roi, list):\r\n roi_list.extend(roi)\r\n wrapper.add_rois(roi_list=roi)\r\n else:\r\n roi_list.append(roi)\r\n wrapper.add_roi(new_roi=roi)\r\n\r\n if self.merge_mode == ipc.MERGE_MODE_NONE:\r\n for node in self.nodes:\r\n if not node.enabled:\r\n continue\r\n if node.is_group and not node.matches_filters:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=f\"Group {node.name} did not match filters, skipped\",\r\n data=None,\r\n is_progress=False,\r\n )\r\n continue\r\n res = node.execute(**kwargs)\r\n if self.stop_processing:\r\n return res\r\n if res:\r\n if node.output_type == ipc.IO_DATA:\r\n wrapper.csv_data_holder.data_list.update(res[\"data\"])\r\n elif node.output_type == ipc.IO_ROI:\r\n add_roi(\r\n wrapper=wrapper,\r\n roi_list=rois,\r\n roi=res.get(\"roi\", None),\r\n node=node,\r\n )\r\n else:\r\n self.last_result[\"outcome\"] = False\r\n if node.uuid == target_module:\r\n self.stop_processing = True\r\n return self.last_result\r\n elif self.merge_mode == ipc.MERGE_MODE_CHAIN:\r\n for node in self.nodes:\r\n if not node.enabled:\r\n continue\r\n if node.is_group and not node.matches_filters:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=f\"Group {node.name} did not match filters, skipped\",\r\n data=None,\r\n is_progress=False,\r\n )\r\n continue\r\n res = node.execute(**kwargs)\r\n if self.stop_processing:\r\n return res\r\n if res:\r\n if node.output_type == ipc.IO_IMAGE:\r\n wrapper.current_image = res[\"image\"]\r\n is_current_image_changed = True\r\n elif node.output_type == ipc.IO_MASK:\r\n wrapper.mask = res[\"mask\"]\r\n elif node.output_type == ipc.IO_DATA:\r\n wrapper.csv_data_holder.data_list.update(res[\"data\"])\r\n elif node.output_type == ipc.IO_ROI:\r\n add_roi(\r\n wrapper=wrapper,\r\n roi_list=rois,\r\n roi=res.get(\"roi\", None),\r\n node=node,\r\n )\r\n else:\r\n self.last_result[\"outcome\"] = False\r\n if node.uuid == target_module:\r\n self.stop_processing = True\r\n return node.last_result\r\n elif self.merge_mode in [ipc.MERGE_MODE_AND, ipc.MERGE_MODE_OR]:\r\n images = []\r\n for node in self.nodes:\r\n if not node.enabled:\r\n continue\r\n if node.is_group and not node.matches_filters:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=f\"Group {node.name} did not match filters, skipped\",\r\n data=None,\r\n is_progress=False,\r\n )\r\n continue\r\n res = node.execute(**kwargs)\r\n if self.stop_processing:\r\n return res\r\n if res:\r\n if node.output_type == ipc.IO_IMAGE:\r\n images.append(res[\"image\"])\r\n elif node.output_type == ipc.IO_MASK:\r\n images.append(res[\"mask\"])\r\n elif node.output_type == ipc.IO_ROI:\r\n add_roi(\r\n wrapper=wrapper,\r\n roi_list=rois,\r\n roi=res.get(\"roi\", None),\r\n node=node,\r\n )\r\n else:\r\n self.last_result[\"outcome\"] = False\r\n if node.uuid == target_module:\r\n self.stop_processing = True\r\n return node.last_result\r\n if self.merge_mode == ipc.MERGE_MODE_AND:\r\n res = wrapper.multi_and(images)\r\n else:\r\n res = wrapper.multi_or(images)\r\n if self.output_type == ipc.IO_IMAGE:\r\n wrapper.current_image = res\r\n is_current_image_changed = True\r\n elif self.output_type == ipc.IO_MASK:\r\n wrapper.mask = res\r\n else:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.ERROR,\r\n msg=f'Invalid output type \"{self.output_type}\" for merge mode \"{self.merge_mode}\" in {self.name}',\r\n data=None,\r\n is_progress=False,\r\n )\r\n self.last_result[\"outcome\"] = False\r\n else:\r\n pass\r\n\r\n if only_rois and rois:\r\n self.last_result[\"roi\"] = rois\r\n self.last_result[\"image\"] = wrapper.draw_rois(\r\n img=wrapper.current_image, rois=rois\r\n )\r\n elif is_current_image_changed or (len(wrapper.image_list) == 0):\r\n self.last_result[\"image\"] = wrapper.current_image\r\n else:\r\n self.last_result[\"image\"] = wrapper.image_list[-1][\"image\"]\r\n self.last_result[\"mask\"] = wrapper.mask\r\n self.last_result[\"data\"] = wrapper.csv_data_holder.data_list\r\n\r\n if self.is_root:\r\n if self.parent.settings.mosaic.enabled:\r\n self.root.parent.mosaic = wrapper.build_mosaic(\r\n image_names=self.parent.settings.mosaic.images,\r\n images_dict=self.parent.stored_mosaic_images,\r\n )\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=f\"Pipeline processed in {format_time(timer() - before)}\",\r\n data={\r\n \"name\": f\"{wrapper.luid}_final_mosaic\",\r\n \"image\": self.root.parent.mosaic,\r\n \"data\": self.last_result[\"data\"],\r\n \"plant_name\": \"unknown\" if wrapper is None else wrapper.plant,\r\n \"luid\": wrapper.luid,\r\n },\r\n force_call_back=True,\r\n is_progress=False,\r\n )\r\n else:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=f\"Processed {wrapper.luid} in {format_time(timer() - before)}\",\r\n data=self\r\n if self.root.parent.show_group_result or self.root.parent.silent\r\n else None,\r\n force_call_back=True,\r\n is_progress=False,\r\n )\r\n elif not target_module:\r\n self.do_call_back(\r\n call_back=call_back,\r\n res=logging.INFO,\r\n msg=f\"Successfully processed {self.name}, merge mode: {self.merge_mode} in {format_time(timer() - before)}\",\r\n data=self if self.root.parent.show_group_result else None,\r\n is_progress=False,\r\n )\r\n\r\n return self.last_result\r\n\r\n def copy(self, parent):\r\n return GroupNode(\r\n parent=parent,\r\n merge_mode=self.merge_mode,\r\n name=self.name,\r\n source=self.source,\r\n nodes=[node.copy(parent=self) for node in self.nodes],\r\n execute_filters=self.execute_filters,\r\n )\r\n\r\n def to_code(self, indent: int):\r\n pass\r\n\r\n def get_parent(self, item):\r\n for node in self.nodes:\r\n if hasattr(node, \"uuid\"):\r\n if item.uuid == node.uuid:\r\n return self\r\n elif isinstance(node, GroupNode):\r\n parent = node.get_parent(item)\r\n if parent is not None:\r\n return parent\r\n return None\r\n\r\n def to_json(self):\r\n return dict(\r\n node_type=\"group\",\r\n merge_mode=self.merge_mode,\r\n name=self.name,\r\n uuid=self.uuid,\r\n source=self.source,\r\n no_delete=self.no_delete,\r\n nodes=[node.to_json() for node in self.nodes],\r\n execute_filters=self.execute_filters,\r\n )\r\n\r\n @classmethod\r\n def from_json(cls, parent, json_data: dict):\r\n res = cls(\r\n parent=parent,\r\n merge_mode=json_data[\"merge_mode\"],\r\n name=json_data[\"name\"],\r\n uuid=json_data[\"uuid\"],\r\n no_delete=json_data[\"no_delete\"],\r\n source=json_data[\"source\"],\r\n execute_filters=json_data.get(\r\n \"execute_filters\", cls.default_execution_filters\r\n ),\r\n )\r\n for node in json_data[\"nodes\"]:\r\n if node[\"node_type\"] == \"module\":\r\n res.nodes.append(ModuleNode.from_json(parent=res, json_data=node))\r\n elif node[\"node_type\"] == \"group\":\r\n res.nodes.append(GroupNode.from_json(parent=res, json_data=node))\r\n else:\r\n eh.log_data(\r\n log_msg=f\"Unknown node type: {node['node_type']}\",\r\n log_level=logging.ERROR,\r\n target_logger=logger,\r\n )\r\n return res\r\n\r\n def modules(self):\r\n return [node for node in self.nodes if isinstance(node, ModuleNode)]\r\n\r\n def groups(self):\r\n return [node for node in self.nodes if isinstance(node, GroupNode)]\r\n\r\n def module(self, index) -> ModuleNode:\r\n lst = self.modules()\r\n if len(lst) > index:\r\n return lst[index]\r\n else:\r\n return None\r\n\r\n def group(self, index) -> Node:\r\n lst = self.groups()\r\n if len(lst) > index:\r\n return lst[index]\r\n else:\r\n return None\r\n\r\n def iter_items(self, types: tuple = (\"groups\", \"modules\")):\r\n def parse_children_(parent):\r\n for node in parent.nodes:\r\n if ((\"groups\" in types) and isinstance(node, GroupNode)) or (\r\n (\"modules\" in types) and isinstance(node, ModuleNode)\r\n ):\r\n yield node\r\n if isinstance(node, GroupNode):\r\n yield from parse_children_(node)\r\n\r\n if ((\"groups\" in types) and isinstance(self, GroupNode)) or (\r\n (\"modules\" in types) and isinstance(self, ModuleNode)\r\n ):\r\n yield self\r\n yield from parse_children_(self)\r\n\r\n def as_pivot_list(self, index, types: tuple = (\"groups\", \"modules\")) -> dict:\r\n \"\"\"Splits all nodes in three classes\r\n * before: all nodes before index\r\n * pivot: index\r\n * after: all nodes after index\r\n \"\"\"\r\n nodes = [node for node in self.iter_items(types)]\r\n if index not in nodes:\r\n return {}\r\n res = {\"before\": [], \"pivot\": index, \"after\": []}\r\n matched_uuid = False\r\n for node in nodes:\r\n if node.uuid == index.uuid:\r\n matched_uuid = True\r\n continue\r\n if matched_uuid:\r\n res[\"after\"].append(node)\r\n else:\r\n res[\"before\"].append(node)\r\n return res\r\n\r\n def find_by_uuid(self, uuid):\r\n if self.uuid == uuid:\r\n return self\r\n for node in self.iter_items():\r\n if node.uuid == uuid:\r\n return node\r\n else:\r\n return None\r\n\r\n def find_by_name(self, name):\r\n \"\"\"Returns the node that matches exactly the name\r\n There's no warranty that names are unique\"\"\"\r\n for node in self.iter_items():\r\n if node.name == name:\r\n return node\r\n else:\r\n return None\r\n\r\n def check_input(self, node) -> bool:\r\n if isinstance(node, GroupNode):\r\n if self.merge_mode in [ipc.MERGE_MODE_AND, ipc.MERGE_MODE_OR]:\r\n has_image, has_mask = False, False\r\n for node in self.nodes:\r\n if node.output_type in [ipc.IO_DATA, ipc.IO_NONE, ipc.IO_ROI]:\r\n return False\r\n elif node.output_type == ipc.IO_IMAGE:\r\n has_image = True\r\n elif node.output_type == ipc.IO_MASK:\r\n has_mask = True\r\n else:\r\n return False\r\n if has_image and has_mask:\r\n return False\r\n if isinstance(node, GroupNode) and node.module_count > 0:\r\n n = node.module(0)\r\n else:\r\n n = node\r\n if isinstance(n, GroupNode):\r\n return True\r\n pivot_list = self.as_pivot_list(index=n, types=(\"modules\"))\r\n if not pivot_list:\r\n return False\r\n if len(pivot_list[\"before\"]) > 0:\r\n if n.input_type == ipc.IO_DATA:\r\n needed_output = ipc.IO_DATA\r\n elif n.input_type == ipc.IO_IMAGE:\r\n return True\r\n elif n.input_type == ipc.IO_MASK:\r\n needed_output = ipc.IO_MASK\r\n elif n.input_type == ipc.IO_NONE:\r\n return True\r\n elif n.input_type == ipc.IO_ROI:\r\n needed_output = ipc.IO_ROI\r\n for node in pivot_list[\"before\"]:\r\n if node.output_type in needed_output:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return n.input_type in (ipc.IO_IMAGE)\r\n\r\n def invalidate(self, node):\r\n pivot_list = self.as_pivot_list(index=node)\r\n node.last_result = {}\r\n for node in pivot_list[\"after\"]:\r\n if isinstance(node, ModuleNode):\r\n node.invalidate()\r\n elif isinstance(node, GroupNode):\r\n node.last_result = {}\r\n\r\n @property\r\n def input_type(self):\r\n if len(self.nodes) == 0:\r\n return ipc.IO_NONE\r\n else:\r\n return self.nodes[0].input_type\r\n\r\n @property\r\n def output_type(self):\r\n if len(self.nodes) == 0:\r\n return ipc.IO_NONE\r\n else:\r\n return self.nodes[-1].output_type\r\n\r\n @property\r\n def node_count(self):\r\n return len(self.nodes)\r\n\r\n @property\r\n def group_count(self):\r\n return len(self.groups())\r\n\r\n @property\r\n def module_count(self):\r\n return len(self.modules())\r\n\r\n @property\r\n def enabled(self):\r\n if self.node_count == 0:\r\n return 0\r\n else:\r\n has_enabled = False\r\n has_disabled = False\r\n for node in self.nodes:\r\n if isinstance(node, GroupNode):\r\n enabled_state = node.enabled\r\n if enabled_state == 0:\r\n has_disabled = True\r\n elif enabled_state == 1:\r\n return 1\r\n elif enabled_state == 2:\r\n has_enabled = True\r\n elif isinstance(node, ModuleNode):\r\n if node.enabled:\r\n has_enabled = True\r\n else:\r\n has_disabled = True\r\n if has_enabled and has_disabled:\r\n return 1\r\n return 2 if has_enabled else 0\r\n\r\n @enabled.setter\r\n def enabled(self, value):\r\n for node in self.nodes:\r\n node.enabled = value\r\n\r\n @property\r\n def matches_filters(self):\r\n wrapper = self.root.parent.wrapper\r\n for k, v in self.execute_filters.items():\r\n current_filter = [filter_ for filter_ in IptParam.decode_string(v) if filter_]\r\n if not current_filter:\r\n continue\r\n if not hasattr(wrapper, k) or getattr(wrapper, k) not in current_filter:\r\n return False\r\n return True\r\n\r\n\r\nclass LoosePipeline(object):\r\n def __init__(self, **kwargs):\r\n self.root: GroupNode = GroupNode(\r\n merge_mode=ipc.MERGE_MODE_CHAIN, name=\"Pipeline\", parent=self\r\n )\r\n self.target_data_base = None\r\n self.settings: PipelineSettings = PipelineSettings(pipeline=self)\r\n self.last_wrapper_luid = \"\"\r\n self.use_cache = True\r\n self.image_output_path = \"\"\r\n self.name = \"\"\r\n self.description = \"Please insert description\"\r\n self.stored_mosaic_images = {}\r\n self._stop_processing = False\r\n self.set_template(kwargs.get(\"template\", None))\r\n self.silent = False\r\n self.mosaic = None\r\n self.wrapper: BaseImageProcessor = None\r\n self.error_level = logging.INFO\r\n\r\n self.set_callbacks()\r\n\r\n def __repr__(self):\r\n return json.dumps(self.to_json(), indent=2, sort_keys=False)\r\n\r\n def __str__(self):\r\n return f\"Pipeline {self.name}\"\r\n\r\n def set_template(self, template):\r\n if isinstance(template, str):\r\n if template == \"default\":\r\n self.root.add_group(\r\n name=\"Fix image\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=\"source\",\r\n uuid=\"fix_image\",\r\n )\r\n self.root.add_group(\r\n name=\"Pre process image\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=self.root.group(0).uuid,\r\n uuid=\"pre_process_image\",\r\n )\r\n self.root.add_group(\r\n name=\"Build mask\",\r\n merge_mode=ipc.MERGE_MODE_AND,\r\n source=self.root.group(1).uuid,\r\n uuid=\"build_mask\",\r\n )\r\n self.root.add_group(\r\n name=\"Clean mask\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=self.root.group(1).uuid,\r\n uuid=\"clean_mask\",\r\n )\r\n self.root.add_group(\r\n name=\"Extract features\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=self.root.group(0).uuid,\r\n uuid=\"extract_features\",\r\n )\r\n elif template == \"legacy\":\r\n self.root.add_group(\r\n name=\"ROIs from raw image\",\r\n merge_mode=ipc.MERGE_MODE_NONE,\r\n source=\"source\",\r\n uuid=\"roi_raw\",\r\n )\r\n self.root.add_group(\r\n name=\"Fix image\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=\"source\",\r\n uuid=\"fix_image\",\r\n )\r\n self.root.add_group(\r\n name=\"Pre process image\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=\"fix_image\",\r\n uuid=\"pre_process_image\",\r\n )\r\n self.root.add_group(\r\n name=\"ROIs from raw pre processed image\",\r\n merge_mode=ipc.MERGE_MODE_NONE,\r\n source=\"pre_process_image\",\r\n uuid=\"roi_pre_processed\",\r\n )\r\n self.root.add_group(\r\n name=\"Build mask\",\r\n merge_mode=ipc.MERGE_MODE_AND,\r\n source=\"pre_process_image\",\r\n uuid=\"build_mask\",\r\n )\r\n self.root.add_group(\r\n name=\"Apply ROIS\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=self.root.group(1).uuid,\r\n uuid=\"apply_roi\",\r\n )\r\n self.root.add_group(\r\n name=\"Clean mask\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=\"pre_process_image\",\r\n uuid=\"clean_mask\",\r\n )\r\n self.root.add_group(\r\n name=\"Assert mask position\",\r\n merge_mode=ipc.MERGE_MODE_NONE,\r\n source=self.root.group(1).uuid,\r\n uuid=\"assert_mask_position\",\r\n )\r\n self.root.add_group(\r\n name=\"Extract features\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=\"fix_image\",\r\n uuid=\"extract_features\",\r\n )\r\n self.root.add_group(\r\n name=\"Build images\",\r\n merge_mode=ipc.MERGE_MODE_CHAIN,\r\n source=\"fix_image\",\r\n uuid=\"build_images\",\r\n )\r\n\r\n def add_module(self, operator, target_group: str = \"\") -> bool:\r\n if not target_group:\r\n target_group = self.root\r\n else:\r\n target_group = self.root.find_by_uuid(target_group)\r\n if target_group is None or operator is None:\r\n return False\r\n target_group.add_module(tool=operator)\r\n return True\r\n\r\n def execute(\r\n self,\r\n src_image: Union[str, BaseImageProcessor],\r\n silent_mode: bool = False,\r\n additional_data: dict = {},\r\n write_data: bool = False,\r\n target_data_base=None,\r\n overwrite_data: bool = False,\r\n store_images: bool = True,\r\n options=None,\r\n **kwargs,\r\n ):\r\n # Override settings\r\n self.error_level = logging.INFO\r\n self.stop_processing = False\r\n self.silent = silent_mode\r\n self.text_result = \"\"\r\n\r\n # Build/retrieve wrapper\r\n if isinstance(src_image, str):\r\n self.wrapper = BaseImageProcessor(\r\n src_image,\r\n options=options,\r\n database=target_data_base,\r\n )\r\n elif isinstance(src_image, BaseImageProcessor):\r\n self.wrapper = src_image\r\n else:\r\n logger.error(f\"Unknown source {str(src_image)}\")\r\n self.error_level = logging.ERROR\r\n self.text_result = \"Source error\"\r\n return False\r\n\r\n # Check wrapper\r\n if self.wrapper is None:\r\n if isinstance(src_image, str):\r\n logger.error(f\"Unable to build wrapper from file '{src_image}''\")\r\n else:\r\n logger.error(\"Unable to retrieve wrapper.\")\r\n self.error_level = logging.ERROR\r\n self.text_result = \"Wrapper error\"\r\n return False\r\n elif os.path.isfile(self.wrapper.csv_file_path) and overwrite_data is False:\r\n self.error_level = logging.INFO\r\n self.text_result = \"Skipped\"\r\n return True\r\n elif not self.wrapper.check_source_image():\r\n if isinstance(src_image, str):\r\n logger.error(f\"Image seems to be corrupted '{src_image}''\")\r\n else:\r\n logger.error(\"Image seems to be corrupted.\")\r\n self.text_result = \"Corrupted image\"\r\n self.error_level = logging.ERROR\r\n return False\r\n\r\n # Override wrapper settings\r\n if self.last_wrapper_luid != self.wrapper.luid:\r\n self.invalidate()\r\n self.last_wrapper_luid = self.wrapper.luid\r\n self.wrapper.lock = True\r\n self.wrapper.target_database = target_data_base\r\n self.wrapper.store_images = store_images and (\r\n self.root.parent.debug_mode or bool(kwargs.get(\"target_module\", \"\"))\r\n )\r\n for module in self.root.iter_items(types=(\"modules\",)):\r\n self.wrapper.forced_storage_images_list.extend(module.tool.required_images)\r\n if self.image_output_path:\r\n pass\r\n elif options is None:\r\n self.image_output_path = ipso_folders.get_path(\r\n key=\"image_output\",\r\n force_creation=False,\r\n )\r\n else:\r\n self.image_output_path = self.wrapper.dst_path\r\n\r\n # Prepare data holder\r\n self.wrapper.init_data_holder()\r\n\r\n # Execute pipeline\r\n self.root.execute(**kwargs)\r\n\r\n # Update data with forced key value pairs\r\n for k, v in additional_data.items():\r\n self.wrapper.csv_data_holder.update_csv_value(key=k, value=v, force_pair=True)\r\n\r\n if write_data is True:\r\n try:\r\n with open(self.wrapper.csv_file_path, \"w\", newline=\"\") as csv_file_:\r\n wr = csv.writer(csv_file_, quoting=csv.QUOTE_NONE)\r\n wr.writerow(self.wrapper.csv_data_holder.header_to_list())\r\n wr.writerow(self.wrapper.csv_data_holder.data_to_list())\r\n except Exception as e:\r\n logger.exception(f\"Failed to write image data because {repr(e)}\")\r\n\r\n index = kwargs.get(\"index\", -1)\r\n total = kwargs.get(\"total\", -1)\r\n if index >= 0 and total >= 0:\r\n eh.log_data(\r\n log_msg=(\r\n f'{\"OK\" if self.error_level < self.stop_on else \"FAIL\"} - '\r\n + f\"{(index + 1):{len(str(total))}d}/{total} >>> \"\r\n + self.wrapper.name\r\n ),\r\n log_level=self.error_level,\r\n target_logger=logger,\r\n )\r\n\r\n index = kwargs.get(\"index\", -1)\r\n total = kwargs.get(\"total\", -1)\r\n if index >= 0 and total >= 0:\r\n eh.log_data(\r\n log_msg=(\r\n f'{\"OK\" if self.error_level < self.stop_on else \"FAIL\"} - '\r\n + f\"{(index + 1):{len(str(total))}d}/{total} >>> \"\r\n + self.wrapper.name\r\n ),\r\n log_level=self.error_level,\r\n target_logger=logger,\r\n )\r\n\r\n return self.error_level < self.stop_on\r\n\r\n def targeted_callback(self, param: IptParam):\r\n if param.name == \"debug_mode\":\r\n if self.root.nodes:\r\n self.root.invalidate(self.root)\r\n else:\r\n print(f\"{param.name} was set\")\r\n\r\n def set_callbacks(self):\r\n p = self.settings.find_by_name(name=\"debug_mode\")\r\n if p is not None:\r\n p.on_change = self.targeted_callback\r\n\r\n def invalidate(self):\r\n self.stored_mosaic_images = {}\r\n for node in self.root.iter_items():\r\n if isinstance(node, ModuleNode):\r\n node.invalidate()\r\n elif isinstance(node, GroupNode):\r\n node.last_result = {}\r\n\r\n def save(self, file_name: str) -> bool:\r\n try:\r\n with open(file_name, \"w\") as f:\r\n json.dump(self.to_json(), f, indent=2)\r\n except Exception as e:\r\n logger.exception(\r\n f'Failed to save pipeline \"{repr(e)}\"',\r\n )\r\n return False\r\n else:\r\n return True\r\n\r\n @classmethod\r\n def load(cls, file_name: str):\r\n with open(file_name, \"r\") as f:\r\n return cls.from_json(json_data=json.load(f))\r\n\r\n def copy(self):\r\n return self.__class__.from_json(self.to_json())\r\n\r\n def get_parent(self, item: Union[GroupNode, ModuleNode]) -> GroupNode:\r\n return self.root.get_parent(item=item)\r\n\r\n def remove_item(self, item: Union[GroupNode, ModuleNode]):\r\n self.root.remove_node(item)\r\n\r\n def to_code(self):\r\n pass\r\n\r\n def to_json(self):\r\n save_dict = {\r\n \"title\": \"IPSO Phen pipeline V2\",\r\n \"name\": self.name,\r\n \"description\": self.description,\r\n \"date\": dt.now().strftime(\"%Y_%b_%d_%H-%M-%S\"),\r\n \"version\": last_script_version,\r\n }\r\n # Add settings\r\n save_dict[\"settings\"] = self.settings.params_to_dict()\r\n # Add root node\r\n save_dict[\"Pipeline\"] = self.root.to_json()\r\n return save_dict\r\n\r\n @classmethod\r\n def from_json(cls, json_data: dict):\r\n if json_data[\"title\"].lower() == \"ipso phen pipeline v2\":\r\n res = cls()\r\n res.name = json_data[\"name\"]\r\n res.description = json_data[\"description\"]\r\n res.settings = PipelineSettings(pipeline=res, **json_data[\"settings\"])\r\n res.root = GroupNode.from_json(parent=res, json_data=json_data[\"Pipeline\"])\r\n elif json_data[\"title\"].lower() == \"ipso phen pipeline\":\r\n res = cls(template=\"default_groups\")\r\n tmp = IptStrictPipeline.from_json(json_data=json_data)\r\n\r\n # Import basic data\r\n res.name = tmp.name\r\n res.description = \"Pipeline imported from old format, please check data\"\r\n\r\n # Import settings\r\n for setting in res.settings.gizmos:\r\n p = tmp.settings.find_by_name(setting.name)\r\n if p is not None:\r\n setting.value = p.value\r\n\r\n # create groups\r\n res.set_template(template=\"legacy\")\r\n\r\n # Import nodes & modules\r\n for uuid, kinds in zip(\r\n [\r\n \"roi_raw\",\r\n \"fix_image\",\r\n \"pre_process_image\",\r\n \"roi_pre_processed\",\r\n \"build_mask\",\r\n ],\r\n [\r\n ipc.ToolFamily.ROI_RAW_IMAGE_STR,\r\n [ipc.ToolFamily.WHITE_BALANCE, ipc.ToolFamily.EXPOSURE_FIXING],\r\n ipc.ToolFamily.PRE_PROCESSING,\r\n ipc.ToolFamily.ROI_PP_IMAGE_STR,\r\n ipc.ToolFamily.THRESHOLD,\r\n ],\r\n ):\r\n src_group = tmp.get_operators(constraints={\"kind\": kinds})\r\n dst_group = res.root.find_by_uuid(uuid=uuid)\r\n for tool_dict in src_group:\r\n dst_group.add_module(\r\n tool=tool_dict[\"tool\"].copy(),\r\n enabled=tool_dict[\"enabled\"],\r\n uuid=tool_dict[\"uuid\"],\r\n )\r\n res.root.find_by_uuid(uuid=\"build_mask\").merge_mode = (\r\n ipc.MERGE_MODE_AND\r\n if tmp.merge_method == \"multi_and\"\r\n else ipc.MERGE_MODE_OR\r\n )\r\n\r\n rois = tmp.get_operators(\r\n constraints={\r\n \"kind\": [\r\n ipc.ToolFamily.ROI_PP_IMAGE_STR,\r\n ipc.ToolFamily.ROI_RAW_IMAGE_STR,\r\n ]\r\n }\r\n )\r\n dst_group = res.root.find_by_uuid(uuid=\"apply_roi\")\r\n for tool_dict in rois:\r\n ipt = tool_dict[\"tool\"]\r\n roi_type = ipt.get_value_of(\"roi_type\")\r\n if roi_type not in [\r\n \"keep\",\r\n \"delete\",\r\n \"erode\",\r\n \"dilate\",\r\n \"open\",\r\n \"close\",\r\n ]:\r\n continue\r\n dst_group.add_module(\r\n tool=get_ipt_class(class_name=\"IptApplyRoi\")(\r\n roi_names=ipt.get_value_of(\"roi_name\"),\r\n roi_selection_mode=\"all_named\",\r\n roi_type=roi_type,\r\n input_source=\"mask\",\r\n output_mode=\"mask\",\r\n )\r\n )\r\n\r\n dst_group = res.root.find_by_uuid(uuid=\"assert_mask_position\")\r\n for tool_dict in rois:\r\n ipt = tool_dict[\"tool\"]\r\n if ipt.get_value_of(\"roi_type\") not in [\"enforce\"]:\r\n continue\r\n dst_group.add_module(\r\n tool=get_ipt_class(class_name=\"IptAssertMaskPosition\")(\r\n roi_names=ipt.get_value_of(\"roi_name\"),\r\n roi_selection_mode=\"all_named\",\r\n )\r\n )\r\n\r\n for uuid, kinds in zip(\r\n [\"clean_mask\", \"extract_features\", \"build_images\"],\r\n [\r\n ipc.ToolFamily.MASK_CLEANUP,\r\n ipc.ToolFamily.FEATURE_EXTRACTION,\r\n ipc.ToolFamily.IMAGE_GENERATOR,\r\n ],\r\n ):\r\n src_group = tmp.get_operators(constraints={\"kind\": kinds})\r\n dst_group = res.root.find_by_uuid(uuid=uuid)\r\n for tool_dict in src_group:\r\n dst_group.add_module(\r\n tool=tool_dict[\"tool\"].copy(),\r\n enabled=tool_dict[\"enabled\"],\r\n uuid=tool_dict[\"uuid\"],\r\n )\r\n else:\r\n res = cls()\r\n res.name = (\r\n f'Failed to load unknown pipeline type \"{json_data[\"title\"].lower()}\"'\r\n )\r\n\r\n if res.stop_on < 10:\r\n res.stop_on = 35\r\n res.set_callbacks()\r\n return res\r\n\r\n def update_error_level(self, error_level):\r\n self.error_level = max(self.error_level, error_level)\r\n\r\n @property\r\n def node_count(self):\r\n return len(self.root.nodes)\r\n\r\n @property\r\n def threshold_only(self):\r\n return self.settings.get_value_of(\"threshold_only\") == 1\r\n\r\n @threshold_only.setter\r\n def threshold_only(self, value):\r\n self.settings.set_value_of(\r\n key=\"threshold_only\", value=1 if value is True else 0, update_widgets=False\r\n )\r\n\r\n @property\r\n def debug_mode(self):\r\n return self.settings.get_value_of(\"debug_mode\") == 1\r\n\r\n @debug_mode.setter\r\n def debug_mode(self, value):\r\n self.settings.set_value_of(\r\n key=\"debug_mode\", value=1 if value is True else 0, update_widgets=False\r\n )\r\n\r\n @property\r\n def show_tool_result(self):\r\n return self.settings.get_value_of(\"show_tool_result\") == 1\r\n\r\n @show_tool_result.setter\r\n def show_tool_result(self, value):\r\n self.settings.set_value_of(\r\n key=\"show_tool_result\", value=1 if value is True else 0, update_widgets=False\r\n )\r\n\r\n @property\r\n def show_group_result(self):\r\n return self.settings.get_value_of(\"show_group_result\") == 1\r\n\r\n @show_group_result.setter\r\n def show_group_result(self, value):\r\n self.settings.set_value_of(\r\n key=\"show_group_result\", value=1 if value is True else 0, update_widgets=False\r\n )\r\n\r\n @property\r\n def tool_group_name_watermark(self):\r\n return self.settings.get_value_of(\"tool_group_name_watermark\") == 1\r\n\r\n @tool_group_name_watermark.setter\r\n def tool_group_name_watermark(self, value):\r\n self.settings.set_value_of(\r\n key=\"tool_group_name_watermark\",\r\n value=1 if value is True else 0,\r\n update_widgets=False,\r\n )\r\n\r\n @property\r\n def stop_on(self) -> int:\r\n return self.settings.get_value_of(\"stop_on\")\r\n\r\n @stop_on.setter\r\n def stop_on(self, value: int):\r\n self.settings.set_value_of(\"stop_on\", value)\r\n\r\n @property\r\n def last_image(self):\r\n return self.settings.get_value_of(\"last_image\")\r\n\r\n @last_image.setter\r\n def last_image(self, value):\r\n self.settings.set_value_of(\"last_image\", value)\r\n\r\n @property\r\n def allow_step_mosaics(self):\r\n return self.settings.get_value_of(\"allow_step_mosaics\")\r\n\r\n @allow_step_mosaics.setter\r\n def allow_step_mosaics(self, value):\r\n self.settings.set_value_of(\"allow_step_mosaics\", value)\r\n\r\n @property\r\n def show_source_image(self):\r\n return self.settings.get_value_of(\"show_source_image\")\r\n\r\n @show_source_image.setter\r\n def show_source_image(self, value):\r\n self.settings.set_value_of(\"show_source_image\", value)\r\n\r\n @property\r\n def stop_processing(self):\r\n return self._stop_processing or self.error_level >= self.stop_on\r\n\r\n @stop_processing.setter\r\n def stop_processing(self, value):\r\n self._stop_processing = value\r\n"
] |
[
[
"numpy.array",
"numpy.dstack",
"numpy.full"
]
] |
prashankkadam/Maer_1
|
[
"e201866429a1231df7f439797ef100f9e4e6da37"
] |
[
"Database_test_git.py"
] |
[
"# -*- coding:/ utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 23 12:07:20 2019\r\nThis piece of software is bound by The MIT License (MIT)\r\nCopyright (c) 2019 Prashank Kadam\r\nCode written by : Prashank Kadam\r\nUser name - ADM-PKA187\r\nEmail ID : [email protected]\r\nCreated on - Tue Jul 30 09:12:00 2019\r\nversion : 1.0\r\n\"\"\" \r\n\r\nimport pyodbc \r\nimport pandas as pd\r\n\r\nconn = pyodbc.connect('Driver={########################};'\r\n 'Server=##########################;'\r\n 'Database=########################;'\r\n 'uid=####################;'\r\n 'pwd=######################;'\r\n 'Trusted_Connection=###;')\r\n\r\ncursor = conn.cursor()\r\n\r\n#Getting all the tables in the database\r\n#for table_name in cursor.tables(tableType='TABLE'):\r\n #print(table_name)\r\n\r\n# Coverting the SELECT query into a pandas dataframe\r\nsql = 'SELECT TOP 10 * FROM db.table'\r\ndata = pd.read_sql(sql, conn)\r\n\r\nprint(data.columns)\r\n\r\ndata.to_excel(r'C:\\Users\\ADM-PKA187\\Desktop\\Dastabase\\db_test.xlsx')\r\n\r\n \r\n \r\n \r\n"
] |
[
[
"pandas.read_sql"
]
] |
NeehaK/pandas
|
[
"0815c433b58920c658f1be9c7eb00cf7e75a3e2b"
] |
[
"pandas/core/indexes/datetimelike.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nBase and utility classes for tseries type pandas objects.\n\"\"\"\nimport warnings\nimport operator\nfrom datetime import datetime, timedelta\n\nfrom pandas import compat\nfrom pandas.compat.numpy import function as nv\nfrom pandas.core.tools.timedeltas import to_timedelta\n\nimport numpy as np\n\nfrom pandas._libs import lib, iNaT, NaT\nfrom pandas._libs.tslibs.period import Period\nfrom pandas._libs.tslibs.timedeltas import delta_to_nanoseconds\nfrom pandas._libs.tslibs.timestamps import round_ns\n\nfrom pandas.core.dtypes.common import (\n _ensure_int64,\n is_dtype_equal,\n is_float,\n is_integer,\n is_list_like,\n is_scalar,\n is_bool_dtype,\n is_offsetlike,\n is_categorical_dtype,\n is_datetime_or_timedelta_dtype,\n is_float_dtype,\n is_integer_dtype,\n is_object_dtype,\n is_string_dtype,\n is_datetime64_dtype,\n is_datetime64tz_dtype,\n is_period_dtype,\n is_timedelta64_dtype)\nfrom pandas.core.dtypes.generic import (\n ABCIndex, ABCSeries, ABCDataFrame, ABCPeriodIndex, ABCIndexClass)\nfrom pandas.core.dtypes.missing import isna\nfrom pandas.core import common as com, algorithms, ops\nfrom pandas.core.algorithms import checked_add_with_arr\nfrom pandas.errors import NullFrequencyError, PerformanceWarning\nimport pandas.io.formats.printing as printing\n\nfrom pandas.core.indexes.base import Index, _index_shared_docs\nfrom pandas.util._decorators import Appender, cache_readonly\nimport pandas.core.dtypes.concat as _concat\nimport pandas.tseries.frequencies as frequencies\nfrom pandas.tseries.offsets import Tick, DateOffset\n\nimport pandas.core.indexes.base as ibase\n_index_doc_kwargs = dict(ibase._index_doc_kwargs)\n\n\nclass DatelikeOps(object):\n \"\"\" common ops for DatetimeIndex/PeriodIndex, but not TimedeltaIndex \"\"\"\n\n def strftime(self, date_format):\n return np.asarray(self.format(date_format=date_format),\n dtype=compat.text_type)\n strftime.__doc__ = \"\"\"\n Return an array of formatted strings specified by date_format, which\n supports the same string format as the python standard library. Details\n of the string format can be found in `python string format doc <{0}>`__\n\n Parameters\n ----------\n date_format : str\n date format string (e.g. \"%Y-%m-%d\")\n\n Returns\n -------\n ndarray of formatted strings\n \"\"\".format(\"https://docs.python.org/3/library/datetime.html\"\n \"#strftime-and-strptime-behavior\")\n\n\nclass TimelikeOps(object):\n \"\"\" common ops for TimedeltaIndex/DatetimeIndex, but not PeriodIndex \"\"\"\n\n _round_doc = (\n \"\"\"\n {op} the data to the specified `freq`.\n\n Parameters\n ----------\n freq : str or Offset\n The frequency level to {op} the index to. Must be a fixed\n frequency like 'S' (second) not 'ME' (month end). See\n :ref:`frequency aliases <timeseries.offset_aliases>` for\n a list of possible `freq` values.\n\n Returns\n -------\n DatetimeIndex, TimedeltaIndex, or Series\n Index of the same type for a DatetimeIndex or TimedeltaIndex,\n or a Series with the same index for a Series.\n\n Raises\n ------\n ValueError if the `freq` cannot be converted.\n\n Examples\n --------\n **DatetimeIndex**\n\n >>> rng = pd.date_range('1/1/2018 11:59:00', periods=3, freq='min')\n >>> rng\n DatetimeIndex(['2018-01-01 11:59:00', '2018-01-01 12:00:00',\n '2018-01-01 12:01:00'],\n dtype='datetime64[ns]', freq='T')\n \"\"\")\n\n _round_example = (\n \"\"\">>> rng.round('H')\n DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00',\n '2018-01-01 12:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Series**\n\n >>> pd.Series(rng).dt.round(\"H\")\n 0 2018-01-01 12:00:00\n 1 2018-01-01 12:00:00\n 2 2018-01-01 12:00:00\n dtype: datetime64[ns]\n \"\"\")\n\n _floor_example = (\n \"\"\">>> rng.floor('H')\n DatetimeIndex(['2018-01-01 11:00:00', '2018-01-01 12:00:00',\n '2018-01-01 12:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Series**\n\n >>> pd.Series(rng).dt.floor(\"H\")\n 0 2018-01-01 11:00:00\n 1 2018-01-01 12:00:00\n 2 2018-01-01 12:00:00\n dtype: datetime64[ns]\n \"\"\"\n )\n\n _ceil_example = (\n \"\"\">>> rng.ceil('H')\n DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00',\n '2018-01-01 13:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Series**\n\n >>> pd.Series(rng).dt.ceil(\"H\")\n 0 2018-01-01 12:00:00\n 1 2018-01-01 12:00:00\n 2 2018-01-01 13:00:00\n dtype: datetime64[ns]\n \"\"\"\n )\n\n def _round(self, freq, rounder):\n # round the local times\n values = _ensure_datetimelike_to_i8(self)\n result = round_ns(values, rounder, freq)\n result = self._maybe_mask_results(result, fill_value=NaT)\n\n attribs = self._get_attributes_dict()\n if 'freq' in attribs:\n attribs['freq'] = None\n if 'tz' in attribs:\n attribs['tz'] = None\n return self._ensure_localized(\n self._shallow_copy(result, **attribs))\n\n @Appender((_round_doc + _round_example).format(op=\"round\"))\n def round(self, freq, *args, **kwargs):\n return self._round(freq, np.round)\n\n @Appender((_round_doc + _floor_example).format(op=\"floor\"))\n def floor(self, freq):\n return self._round(freq, np.floor)\n\n @Appender((_round_doc + _ceil_example).format(op=\"ceil\"))\n def ceil(self, freq):\n return self._round(freq, np.ceil)\n\n\nclass DatetimeIndexOpsMixin(object):\n \"\"\" common ops mixin to support a unified interface datetimelike Index \"\"\"\n\n def equals(self, other):\n \"\"\"\n Determines if two Index objects contain the same elements.\n \"\"\"\n if self.is_(other):\n return True\n\n if not isinstance(other, ABCIndexClass):\n return False\n elif not isinstance(other, type(self)):\n try:\n other = type(self)(other)\n except Exception:\n return False\n\n if not is_dtype_equal(self.dtype, other.dtype):\n # have different timezone\n return False\n\n # ToDo: Remove this when PeriodDtype is added\n elif isinstance(self, ABCPeriodIndex):\n if not isinstance(other, ABCPeriodIndex):\n return False\n if self.freq != other.freq:\n return False\n\n return np.array_equal(self.asi8, other.asi8)\n\n def __iter__(self):\n return (self._box_func(v) for v in self.asi8)\n\n @staticmethod\n def _join_i8_wrapper(joinf, dtype, with_indexers=True):\n \"\"\" create the join wrapper methods \"\"\"\n\n @staticmethod\n def wrapper(left, right):\n if isinstance(left, (np.ndarray, ABCIndex, ABCSeries)):\n left = left.view('i8')\n if isinstance(right, (np.ndarray, ABCIndex, ABCSeries)):\n right = right.view('i8')\n results = joinf(left, right)\n if with_indexers:\n join_index, left_indexer, right_indexer = results\n join_index = join_index.view(dtype)\n return join_index, left_indexer, right_indexer\n return results\n\n return wrapper\n\n def _evaluate_compare(self, other, op):\n \"\"\"\n We have been called because a comparison between\n 8 aware arrays. numpy >= 1.11 will\n now warn about NaT comparisons\n \"\"\"\n\n # coerce to a similar object\n if not isinstance(other, type(self)):\n if not is_list_like(other):\n # scalar\n other = [other]\n elif is_scalar(lib.item_from_zerodim(other)):\n # ndarray scalar\n other = [other.item()]\n other = type(self)(other)\n\n # compare\n result = op(self.asi8, other.asi8)\n\n # technically we could support bool dtyped Index\n # for now just return the indexing array directly\n mask = (self._isnan) | (other._isnan)\n if is_bool_dtype(result):\n result[mask] = False\n return result\n\n result[mask] = iNaT\n try:\n return Index(result)\n except TypeError:\n return result\n\n def _ensure_localized(self, result):\n \"\"\"\n ensure that we are re-localized\n\n This is for compat as we can then call this on all datetimelike\n indexes generally (ignored for Period/Timedelta)\n\n Parameters\n ----------\n result : DatetimeIndex / i8 ndarray\n\n Returns\n -------\n localized DTI\n \"\"\"\n\n # reconvert to local tz\n if getattr(self, 'tz', None) is not None:\n if not isinstance(result, ABCIndexClass):\n result = self._simple_new(result)\n result = result.tz_localize(self.tz)\n return result\n\n @property\n def _box_func(self):\n \"\"\"\n box function to get object from internal representation\n \"\"\"\n raise com.AbstractMethodError(self)\n\n def _box_values(self, values):\n \"\"\"\n apply box func to passed values\n \"\"\"\n return lib.map_infer(values, self._box_func)\n\n def _box_values_as_index(self):\n \"\"\"\n return object Index which contains boxed values\n \"\"\"\n from pandas.core.index import Index\n return Index(self._box_values(self.asi8), name=self.name, dtype=object)\n\n def _format_with_header(self, header, **kwargs):\n return header + list(self._format_native_types(**kwargs))\n\n @Appender(_index_shared_docs['__contains__'] % _index_doc_kwargs)\n def __contains__(self, key):\n try:\n res = self.get_loc(key)\n return is_scalar(res) or type(res) == slice or np.any(res)\n except (KeyError, TypeError, ValueError):\n return False\n\n contains = __contains__\n\n def __getitem__(self, key):\n \"\"\"\n This getitem defers to the underlying array, which by-definition can\n only handle list-likes, slices, and integer scalars\n \"\"\"\n\n is_int = is_integer(key)\n if is_scalar(key) and not is_int:\n raise IndexError(\"only integers, slices (`:`), ellipsis (`...`), \"\n \"numpy.newaxis (`None`) and integer or boolean \"\n \"arrays are valid indices\")\n\n getitem = self._data.__getitem__\n if is_int:\n val = getitem(key)\n return self._box_func(val)\n else:\n if com.is_bool_indexer(key):\n key = np.asarray(key)\n if key.all():\n key = slice(0, None, None)\n else:\n key = lib.maybe_booleans_to_slice(key.view(np.uint8))\n\n attribs = self._get_attributes_dict()\n\n is_period = isinstance(self, ABCPeriodIndex)\n if is_period:\n freq = self.freq\n else:\n freq = None\n if isinstance(key, slice):\n if self.freq is not None and key.step is not None:\n freq = key.step * self.freq\n else:\n freq = self.freq\n\n attribs['freq'] = freq\n\n result = getitem(key)\n if result.ndim > 1:\n # To support MPL which performs slicing with 2 dim\n # even though it only has 1 dim by definition\n if is_period:\n return self._simple_new(result, **attribs)\n return result\n\n return self._simple_new(result, **attribs)\n\n @property\n def freqstr(self):\n \"\"\"\n Return the frequency object as a string if its set, otherwise None\n \"\"\"\n if self.freq is None:\n return None\n return self.freq.freqstr\n\n @cache_readonly\n def inferred_freq(self):\n \"\"\"\n Tryies to return a string representing a frequency guess,\n generated by infer_freq. Returns None if it can't autodetect the\n frequency.\n \"\"\"\n try:\n return frequencies.infer_freq(self)\n except ValueError:\n return None\n\n def _nat_new(self, box=True):\n \"\"\"\n Return Index or ndarray filled with NaT which has the same\n length as the caller.\n\n Parameters\n ----------\n box : boolean, default True\n - If True returns a Index as the same as caller.\n - If False returns ndarray of np.int64.\n \"\"\"\n result = np.zeros(len(self), dtype=np.int64)\n result.fill(iNaT)\n if not box:\n return result\n\n attribs = self._get_attributes_dict()\n if not is_period_dtype(self):\n attribs['freq'] = None\n return self._simple_new(result, **attribs)\n\n # Try to run function on index first, and then on elements of index\n # Especially important for group-by functionality\n def map(self, f):\n try:\n result = f(self)\n\n # Try to use this result if we can\n if isinstance(result, np.ndarray):\n result = Index(result)\n\n if not isinstance(result, Index):\n raise TypeError('The map function must return an Index object')\n return result\n except Exception:\n return self.astype(object).map(f)\n\n def sort_values(self, return_indexer=False, ascending=True):\n \"\"\"\n Return sorted copy of Index\n \"\"\"\n if return_indexer:\n _as = self.argsort()\n if not ascending:\n _as = _as[::-1]\n sorted_index = self.take(_as)\n return sorted_index, _as\n else:\n sorted_values = np.sort(self._ndarray_values)\n attribs = self._get_attributes_dict()\n freq = attribs['freq']\n\n if freq is not None and not isinstance(self, ABCPeriodIndex):\n if freq.n > 0 and not ascending:\n freq = freq * -1\n elif freq.n < 0 and ascending:\n freq = freq * -1\n attribs['freq'] = freq\n\n if not ascending:\n sorted_values = sorted_values[::-1]\n\n return self._simple_new(sorted_values, **attribs)\n\n @Appender(_index_shared_docs['take'] % _index_doc_kwargs)\n def take(self, indices, axis=0, allow_fill=True,\n fill_value=None, **kwargs):\n nv.validate_take(tuple(), kwargs)\n indices = _ensure_int64(indices)\n\n maybe_slice = lib.maybe_indices_to_slice(indices, len(self))\n if isinstance(maybe_slice, slice):\n return self[maybe_slice]\n\n taken = self._assert_take_fillable(self.asi8, indices,\n allow_fill=allow_fill,\n fill_value=fill_value,\n na_value=iNaT)\n\n # keep freq in PeriodIndex, reset otherwise\n freq = self.freq if isinstance(self, ABCPeriodIndex) else None\n return self._shallow_copy(taken, freq=freq)\n\n def get_duplicates(self):\n values = Index.get_duplicates(self)\n return self._simple_new(values)\n\n _can_hold_na = True\n\n _na_value = NaT\n \"\"\"The expected NA value to use with this index.\"\"\"\n\n @cache_readonly\n def _isnan(self):\n \"\"\" return if each value is nan\"\"\"\n return (self.asi8 == iNaT)\n\n @property\n def asobject(self):\n \"\"\"Return object Index which contains boxed values.\n\n .. deprecated:: 0.23.0\n Use ``astype(object)`` instead.\n\n *this is an internal non-public method*\n \"\"\"\n warnings.warn(\"'asobject' is deprecated. Use 'astype(object)'\"\n \" instead\", FutureWarning, stacklevel=2)\n return self.astype(object)\n\n def _convert_tolerance(self, tolerance, target):\n tolerance = np.asarray(to_timedelta(tolerance, box=False))\n if target.size != tolerance.size and tolerance.size > 1:\n raise ValueError('list-like tolerance size must match '\n 'target index size')\n return tolerance\n\n def _maybe_mask_results(self, result, fill_value=None, convert=None):\n \"\"\"\n Parameters\n ----------\n result : a ndarray\n convert : string/dtype or None\n\n Returns\n -------\n result : ndarray with values replace by the fill_value\n\n mask the result if needed, convert to the provided dtype if its not\n None\n\n This is an internal routine\n \"\"\"\n\n if self.hasnans:\n if convert:\n result = result.astype(convert)\n if fill_value is None:\n fill_value = np.nan\n result[self._isnan] = fill_value\n return result\n\n def tolist(self):\n \"\"\"\n return a list of the underlying data\n \"\"\"\n return list(self.astype(object))\n\n def min(self, axis=None, *args, **kwargs):\n \"\"\"\n Return the minimum value of the Index or minimum along\n an axis.\n\n See also\n --------\n numpy.ndarray.min\n \"\"\"\n nv.validate_min(args, kwargs)\n\n try:\n i8 = self.asi8\n\n # quick check\n if len(i8) and self.is_monotonic:\n if i8[0] != iNaT:\n return self._box_func(i8[0])\n\n if self.hasnans:\n min_stamp = self[~self._isnan].asi8.min()\n else:\n min_stamp = i8.min()\n return self._box_func(min_stamp)\n except ValueError:\n return self._na_value\n\n def argmin(self, axis=None, *args, **kwargs):\n \"\"\"\n Returns the indices of the minimum values along an axis.\n See `numpy.ndarray.argmin` for more information on the\n `axis` parameter.\n\n See also\n --------\n numpy.ndarray.argmin\n \"\"\"\n nv.validate_argmin(args, kwargs)\n\n i8 = self.asi8\n if self.hasnans:\n mask = self._isnan\n if mask.all():\n return -1\n i8 = i8.copy()\n i8[mask] = np.iinfo('int64').max\n return i8.argmin()\n\n def max(self, axis=None, *args, **kwargs):\n \"\"\"\n Return the maximum value of the Index or maximum along\n an axis.\n\n See also\n --------\n numpy.ndarray.max\n \"\"\"\n nv.validate_max(args, kwargs)\n\n try:\n i8 = self.asi8\n\n # quick check\n if len(i8) and self.is_monotonic:\n if i8[-1] != iNaT:\n return self._box_func(i8[-1])\n\n if self.hasnans:\n max_stamp = self[~self._isnan].asi8.max()\n else:\n max_stamp = i8.max()\n return self._box_func(max_stamp)\n except ValueError:\n return self._na_value\n\n def argmax(self, axis=None, *args, **kwargs):\n \"\"\"\n Returns the indices of the maximum values along an axis.\n See `numpy.ndarray.argmax` for more information on the\n `axis` parameter.\n\n See also\n --------\n numpy.ndarray.argmax\n \"\"\"\n nv.validate_argmax(args, kwargs)\n\n i8 = self.asi8\n if self.hasnans:\n mask = self._isnan\n if mask.all():\n return -1\n i8 = i8.copy()\n i8[mask] = 0\n return i8.argmax()\n\n @property\n def _formatter_func(self):\n raise com.AbstractMethodError(self)\n\n def _format_attrs(self):\n \"\"\"\n Return a list of tuples of the (attr,formatted_value)\n \"\"\"\n attrs = super(DatetimeIndexOpsMixin, self)._format_attrs()\n for attrib in self._attributes:\n if attrib == 'freq':\n freq = self.freqstr\n if freq is not None:\n freq = \"'%s'\" % freq\n attrs.append(('freq', freq))\n return attrs\n\n @cache_readonly\n def _resolution(self):\n return frequencies.Resolution.get_reso_from_freq(self.freqstr)\n\n @cache_readonly\n def resolution(self):\n \"\"\"\n Returns day, hour, minute, second, millisecond or microsecond\n \"\"\"\n return frequencies.Resolution.get_str(self._resolution)\n\n def _convert_scalar_indexer(self, key, kind=None):\n \"\"\"\n we don't allow integer or float indexing on datetime-like when using\n loc\n\n Parameters\n ----------\n key : label of the slice bound\n kind : {'ix', 'loc', 'getitem', 'iloc'} or None\n \"\"\"\n\n assert kind in ['ix', 'loc', 'getitem', 'iloc', None]\n\n # we don't allow integer/float indexing for loc\n # we don't allow float indexing for ix/getitem\n if is_scalar(key):\n is_int = is_integer(key)\n is_flt = is_float(key)\n if kind in ['loc'] and (is_int or is_flt):\n self._invalid_indexer('index', key)\n elif kind in ['ix', 'getitem'] and is_flt:\n self._invalid_indexer('index', key)\n\n return (super(DatetimeIndexOpsMixin, self)\n ._convert_scalar_indexer(key, kind=kind))\n\n def _add_datelike(self, other):\n raise TypeError(\"cannot add {cls} and {typ}\"\n .format(cls=type(self).__name__,\n typ=type(other).__name__))\n\n def _sub_datelike(self, other):\n raise com.AbstractMethodError(self)\n\n def _add_nat(self):\n \"\"\"Add pd.NaT to self\"\"\"\n if is_period_dtype(self):\n raise TypeError('Cannot add {cls} and {typ}'\n .format(cls=type(self).__name__,\n typ=type(NaT).__name__))\n\n # GH#19124 pd.NaT is treated like a timedelta for both timedelta\n # and datetime dtypes\n return self._nat_new(box=True)\n\n def _sub_nat(self):\n \"\"\"Subtract pd.NaT from self\"\"\"\n # GH#19124 Timedelta - datetime is not in general well-defined.\n # We make an exception for pd.NaT, which in this case quacks\n # like a timedelta.\n # For datetime64 dtypes by convention we treat NaT as a datetime, so\n # this subtraction returns a timedelta64 dtype.\n # For period dtype, timedelta64 is a close-enough return dtype.\n result = self._nat_new(box=False)\n return result.view('timedelta64[ns]')\n\n def _sub_period(self, other):\n return NotImplemented\n\n def _add_offset(self, offset):\n raise com.AbstractMethodError(self)\n\n def _addsub_offset_array(self, other, op):\n \"\"\"\n Add or subtract array-like of DateOffset objects\n\n Parameters\n ----------\n other : Index, np.ndarray\n object-dtype containing pd.DateOffset objects\n op : {operator.add, operator.sub}\n\n Returns\n -------\n result : same class as self\n \"\"\"\n assert op in [operator.add, operator.sub]\n if len(other) == 1:\n return op(self, other[0])\n\n warnings.warn(\"Adding/subtracting array of DateOffsets to \"\n \"{cls} not vectorized\"\n .format(cls=type(self).__name__), PerformanceWarning)\n\n res_values = op(self.astype('O').values, np.array(other))\n kwargs = {}\n if not is_period_dtype(self):\n kwargs['freq'] = 'infer'\n return self._constructor(res_values, **kwargs)\n\n @classmethod\n def _add_datetimelike_methods(cls):\n \"\"\"\n add in the datetimelike methods (as we may have to override the\n superclass)\n \"\"\"\n\n def __add__(self, other):\n from pandas import DateOffset\n\n other = lib.item_from_zerodim(other)\n if isinstance(other, (ABCSeries, ABCDataFrame)):\n return NotImplemented\n\n # scalar others\n elif other is NaT:\n result = self._add_nat()\n elif isinstance(other, (Tick, timedelta, np.timedelta64)):\n result = self._add_delta(other)\n elif isinstance(other, DateOffset):\n # specifically _not_ a Tick\n result = self._add_offset(other)\n elif isinstance(other, (datetime, np.datetime64)):\n result = self._add_datelike(other)\n elif is_integer(other):\n # This check must come after the check for np.timedelta64\n # as is_integer returns True for these\n result = self.shift(other)\n\n # array-like others\n elif is_timedelta64_dtype(other):\n # TimedeltaIndex, ndarray[timedelta64]\n result = self._add_delta(other)\n elif is_offsetlike(other):\n # Array/Index of DateOffset objects\n result = self._addsub_offset_array(other, operator.add)\n elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other):\n # DatetimeIndex, ndarray[datetime64]\n return self._add_datelike(other)\n elif is_integer_dtype(other) and self.freq is None:\n # GH#19123\n raise NullFrequencyError(\"Cannot shift with no freq\")\n elif is_float_dtype(other):\n # Explicitly catch invalid dtypes\n raise TypeError(\"cannot add {dtype}-dtype to {cls}\"\n .format(dtype=other.dtype,\n cls=type(self).__name__))\n\n else: # pragma: no cover\n return NotImplemented\n\n if result is NotImplemented:\n return NotImplemented\n elif not isinstance(result, Index):\n # Index.__new__ will choose appropriate subclass for dtype\n result = Index(result)\n res_name = ops.get_op_result_name(self, other)\n result.name = res_name\n return result\n\n cls.__add__ = __add__\n\n def __radd__(self, other):\n # alias for __add__\n return self.__add__(other)\n cls.__radd__ = __radd__\n\n def __sub__(self, other):\n from pandas import Index\n\n other = lib.item_from_zerodim(other)\n if isinstance(other, (ABCSeries, ABCDataFrame)):\n return NotImplemented\n\n # scalar others\n elif other is NaT:\n result = self._sub_nat()\n elif isinstance(other, (Tick, timedelta, np.timedelta64)):\n result = self._add_delta(-other)\n elif isinstance(other, DateOffset):\n # specifically _not_ a Tick\n result = self._add_offset(-other)\n elif isinstance(other, (datetime, np.datetime64)):\n result = self._sub_datelike(other)\n elif is_integer(other):\n # This check must come after the check for np.timedelta64\n # as is_integer returns True for these\n result = self.shift(-other)\n elif isinstance(other, Period):\n result = self._sub_period(other)\n\n # array-like others\n elif is_timedelta64_dtype(other):\n # TimedeltaIndex, ndarray[timedelta64]\n result = self._add_delta(-other)\n elif is_offsetlike(other):\n # Array/Index of DateOffset objects\n result = self._addsub_offset_array(other, operator.sub)\n elif is_datetime64_dtype(other) or is_datetime64tz_dtype(other):\n # DatetimeIndex, ndarray[datetime64]\n result = self._sub_datelike(other)\n elif isinstance(other, Index):\n raise TypeError(\"cannot subtract {cls} and {typ}\"\n .format(cls=type(self).__name__,\n typ=type(other).__name__))\n elif is_integer_dtype(other) and self.freq is None:\n # GH#19123\n raise NullFrequencyError(\"Cannot shift with no freq\")\n\n elif is_float_dtype(other):\n # Explicitly catch invalid dtypes\n raise TypeError(\"cannot subtract {dtype}-dtype from {cls}\"\n .format(dtype=other.dtype,\n cls=type(self).__name__))\n else: # pragma: no cover\n return NotImplemented\n\n if result is NotImplemented:\n return NotImplemented\n elif not isinstance(result, Index):\n # Index.__new__ will choose appropriate subclass for dtype\n result = Index(result)\n res_name = ops.get_op_result_name(self, other)\n result.name = res_name\n return result\n\n cls.__sub__ = __sub__\n\n def __rsub__(self, other):\n if is_datetime64_dtype(other) and is_timedelta64_dtype(self):\n # ndarray[datetime64] cannot be subtracted from self, so\n # we need to wrap in DatetimeIndex and flip the operation\n from pandas import DatetimeIndex\n return DatetimeIndex(other) - self\n return -(self - other)\n cls.__rsub__ = __rsub__\n\n def __iadd__(self, other):\n # alias for __add__\n return self.__add__(other)\n cls.__iadd__ = __iadd__\n\n def __isub__(self, other):\n # alias for __sub__\n return self.__sub__(other)\n cls.__isub__ = __isub__\n\n def _add_delta(self, other):\n return NotImplemented\n\n def _add_delta_td(self, other):\n \"\"\"\n Add a delta of a timedeltalike\n return the i8 result view\n \"\"\"\n\n inc = delta_to_nanoseconds(other)\n new_values = checked_add_with_arr(self.asi8, inc,\n arr_mask=self._isnan).view('i8')\n if self.hasnans:\n new_values[self._isnan] = iNaT\n return new_values.view('i8')\n\n def _add_delta_tdi(self, other):\n \"\"\"\n Add a delta of a TimedeltaIndex\n return the i8 result view\n \"\"\"\n\n # delta operation\n if not len(self) == len(other):\n raise ValueError(\"cannot add indices of unequal length\")\n\n self_i8 = self.asi8\n other_i8 = other.asi8\n new_values = checked_add_with_arr(self_i8, other_i8,\n arr_mask=self._isnan,\n b_mask=other._isnan)\n if self.hasnans or other.hasnans:\n mask = (self._isnan) | (other._isnan)\n new_values[mask] = iNaT\n return new_values.view('i8')\n\n def isin(self, values):\n \"\"\"\n Compute boolean array of whether each index value is found in the\n passed set of values\n\n Parameters\n ----------\n values : set or sequence of values\n\n Returns\n -------\n is_contained : ndarray (boolean dtype)\n \"\"\"\n if not isinstance(values, type(self)):\n try:\n values = type(self)(values)\n except ValueError:\n return self.astype(object).isin(values)\n\n return algorithms.isin(self.asi8, values.asi8)\n\n def shift(self, n, freq=None):\n \"\"\"\n Specialized shift which produces a DatetimeIndex\n\n Parameters\n ----------\n n : int\n Periods to shift by\n freq : DateOffset or timedelta-like, optional\n\n Returns\n -------\n shifted : DatetimeIndex\n \"\"\"\n if freq is not None and freq != self.freq:\n if isinstance(freq, compat.string_types):\n freq = frequencies.to_offset(freq)\n offset = n * freq\n result = self + offset\n\n if hasattr(self, 'tz'):\n result.tz = self.tz\n\n return result\n\n if n == 0:\n # immutable so OK\n return self\n\n if self.freq is None:\n raise NullFrequencyError(\"Cannot shift with no freq\")\n\n start = self[0] + n * self.freq\n end = self[-1] + n * self.freq\n attribs = self._get_attributes_dict()\n attribs['start'] = start\n attribs['end'] = end\n return type(self)(**attribs)\n\n def repeat(self, repeats, *args, **kwargs):\n \"\"\"\n Analogous to ndarray.repeat\n \"\"\"\n nv.validate_repeat(args, kwargs)\n if isinstance(self, ABCPeriodIndex):\n freq = self.freq\n else:\n freq = None\n return self._shallow_copy(self.asi8.repeat(repeats),\n freq=freq)\n\n @Appender(_index_shared_docs['where'] % _index_doc_kwargs)\n def where(self, cond, other=None):\n other = _ensure_datetimelike_to_i8(other)\n values = _ensure_datetimelike_to_i8(self)\n result = np.where(cond, values, other).astype('i8')\n\n result = self._ensure_localized(result)\n return self._shallow_copy(result,\n **self._get_attributes_dict())\n\n def summary(self, name=None):\n \"\"\"\n return a summarized representation\n \"\"\"\n formatter = self._formatter_func\n if len(self) > 0:\n index_summary = ', %s to %s' % (formatter(self[0]),\n formatter(self[-1]))\n else:\n index_summary = ''\n\n if name is None:\n name = type(self).__name__\n result = '%s: %s entries%s' % (printing.pprint_thing(name),\n len(self), index_summary)\n if self.freq:\n result += '\\nFreq: %s' % self.freqstr\n\n # display as values, not quoted\n result = result.replace(\"'\", \"\")\n return result\n\n def _concat_same_dtype(self, to_concat, name):\n \"\"\"\n Concatenate to_concat which has the same class\n \"\"\"\n attribs = self._get_attributes_dict()\n attribs['name'] = name\n\n if not isinstance(self, ABCPeriodIndex):\n # reset freq\n attribs['freq'] = None\n\n if getattr(self, 'tz', None) is not None:\n return _concat._concat_datetimetz(to_concat, name)\n else:\n new_data = np.concatenate([c.asi8 for c in to_concat])\n return self._simple_new(new_data, **attribs)\n\n def astype(self, dtype, copy=True):\n if is_object_dtype(dtype):\n return self._box_values_as_index()\n elif is_string_dtype(dtype) and not is_categorical_dtype(dtype):\n return Index(self.format(), name=self.name, dtype=object)\n elif is_integer_dtype(dtype):\n return Index(self.values.astype('i8', copy=copy), name=self.name,\n dtype='i8')\n elif (is_datetime_or_timedelta_dtype(dtype) and\n not is_dtype_equal(self.dtype, dtype)) or is_float_dtype(dtype):\n # disallow conversion between datetime/timedelta,\n # and conversions for any datetimelike to float\n msg = 'Cannot cast {name} to dtype {dtype}'\n raise TypeError(msg.format(name=type(self).__name__, dtype=dtype))\n return super(DatetimeIndexOpsMixin, self).astype(dtype, copy=copy)\n\n\ndef _ensure_datetimelike_to_i8(other):\n \"\"\" helper for coercing an input scalar or array to i8 \"\"\"\n if is_scalar(other) and isna(other):\n other = iNaT\n elif isinstance(other, ABCIndexClass):\n # convert tz if needed\n if getattr(other, 'tz', None) is not None:\n other = other.tz_localize(None).asi8\n else:\n other = other.asi8\n else:\n try:\n other = np.array(other, copy=False).view('i8')\n except TypeError:\n # period array cannot be coerces to int\n other = Index(other).asi8\n return other\n"
] |
[
[
"pandas.tseries.frequencies.to_offset",
"pandas._libs.tslibs.timedeltas.delta_to_nanoseconds",
"pandas.core.dtypes.concat._concat_datetimetz",
"pandas.core.common.AbstractMethodError",
"pandas.compat.numpy.function.validate_argmax",
"pandas.core.dtypes.common.is_dtype_equal",
"numpy.asarray",
"pandas.core.dtypes.common.is_datetime64tz_dtype",
"numpy.concatenate",
"numpy.any",
"numpy.iinfo",
"pandas.core.dtypes.common.is_datetime64_dtype",
"pandas.core.dtypes.common._ensure_int64",
"numpy.where",
"pandas.Index",
"pandas.core.tools.timedeltas.to_timedelta",
"pandas.DatetimeIndex",
"pandas.tseries.frequencies.Resolution.get_str",
"pandas._libs.lib.map_infer",
"pandas.core.ops.get_op_result_name",
"pandas.errors.NullFrequencyError",
"pandas.core.dtypes.common.is_float_dtype",
"pandas.core.dtypes.common.is_float",
"pandas.core.dtypes.common.is_string_dtype",
"pandas.core.dtypes.common.is_offsetlike",
"pandas.core.dtypes.common.is_categorical_dtype",
"pandas.core.dtypes.common.is_list_like",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.util._decorators.Appender",
"pandas.tseries.frequencies.Resolution.get_reso_from_freq",
"pandas.core.algorithms.checked_add_with_arr",
"pandas.core.dtypes.common.is_timedelta64_dtype",
"pandas.core.dtypes.common.is_period_dtype",
"pandas.compat.numpy.function.validate_argmin",
"numpy.array",
"pandas.Index.get_duplicates",
"pandas.core.dtypes.common.is_bool_dtype",
"numpy.array_equal",
"pandas.core.algorithms.isin",
"pandas.core.common.is_bool_indexer",
"pandas.core.dtypes.common.is_scalar",
"pandas.compat.numpy.function.validate_max",
"pandas.core.dtypes.common.is_integer",
"numpy.sort",
"pandas.io.formats.printing.pprint_thing",
"pandas.compat.numpy.function.validate_min",
"pandas.tseries.frequencies.infer_freq",
"pandas.core.dtypes.common.is_object_dtype",
"pandas._libs.lib.item_from_zerodim",
"pandas.core.dtypes.missing.isna",
"pandas.core.dtypes.common.is_datetime_or_timedelta_dtype",
"pandas._libs.tslibs.timestamps.round_ns",
"pandas.compat.numpy.function.validate_repeat"
]
] |
toddrme2178/pyfda
|
[
"c20355fb36ace6902aebd1a6bc6c1a71771b84f4"
] |
[
"pyfda/filter_designs/cheby1.py"
] |
[
"# -*- coding: utf-8 -*-\n#\n# This file is part of the pyFDA project hosted at https://github.com/chipmuenk/pyfda\n#\n# Copyright © pyFDA Project Contributors\n# Licensed under the terms of the MIT License\n# (see file LICENSE in root directory for details)\n\n\"\"\"\nDesign Chebychev 1 filters (LP, HP, BP, BS) with fixed or minimum order, return\nthe filter design in zpk (zeros, poles, gain) or second-order sections (sos) format.\n\nAttention:\nThis class is re-instantiated dynamically every time the filter design method\nis selected, calling its __init__ method.\n\nAPI version info: \n 1.0: initial working release\n 1.1: - copy A_PB -> A_PB2 and A_SB -> A_SB2 for BS / BP designs\n - mark private methods as private\n 1.2: new API using fil_save (enable SOS features when available)\n 1.3: new public methods destruct_UI + construct_UI (no longer called by __init__)\n 1.4: module attribute `filter_classes` contains class name and combo box name\n instead of class attribute `name`\n `FRMT` is now a class attribute\n 2.0: Specify the parameters for each subwidget as tuples in a dict where the\n first element controls whether the widget is visible and / or enabled.\n This dict is now called self.rt_dict. When present, the dict self.rt_dict_add\n is read and merged with the first one.\n 2.1: Remove empty methods construct_UI and destruct_UI and attributes \n self.wdg and self.hdl\n \n :2.2: Rename `filter_classes` -> `classes`, remove Py2 compatibility \n\"\"\"\nimport scipy.signal as sig\nfrom scipy.signal import cheb1ord\n \nfrom pyfda.pyfda_lib import fil_save, SOS_AVAIL, lin2unit\nfrom pyfda.pyfda_qt_lib import qfilter_warning\nfrom .common import Common\n\n__version__ = \"2.2\"\n\nclasses = {'Cheby1':'Chebychev 1'} #: Dict containing class name : display name\n\nclass Cheby1(object):\n if SOS_AVAIL:\n FRMT = 'sos' # output format of filter design routines 'zpk' / 'ba' / 'sos'\n else:\n FRMT = 'zpk'\n \n def __init__(self):\n \n self.ft = 'IIR'\n\n c = Common()\n self.rt_dict = c.rt_base_iir\n\n self.rt_dict_add = {\n 'COM':{'man':{'msg':('a',\n r\"Enter the filter order <b><i>N</i></b> and the critical frequency \"\n \"or frequencies <b><i>F<sub>C</sub></i></b> where the gain first drops below \"\n \"the maximum ripple \"\n \"<b><i>-A<sub>PB</sub></i></b> allowed below unity gain in the \"\n \"passband.\")}, \n },\n 'LP': {'man':{}, 'min':{}},\n 'HP': {'man':{}, 'min':{}},\n 'BS': {'man':{}, 'min':{}},\n 'BP': {'man':{}, 'min':{}},\n }\n\n self.info = \"\"\"\n**Chebychev Type 1 filters**\n\nmaximize the rate of cutoff between the frequency response’s passband and stopband,\nat the expense of passband ripple :math:`A_PB` and increased ringing in\nthe step response. The stopband drops monotonously. \n\nType I filters roll off faster than Type II, but Type II filters do not\nhave any ripple in the passband.\n\nThe passband has a constant ripple (equiripple) with a total of :math:`N` maxima\nand minima (for example, a 5th-order filter has 3 maxima and 2 minima). Consequently,\nthe DC gain is unity for odd-order low-pass filters, and :math:`-A_PB` dB for even-order filters.\n\nFor a manual filter design, the order :math:`N`, the passband ripple :math:`A_PB` and\nthe critical frequency / frequencies :math:`F_C` where the gain drops below\n:math:`-A_PB` have to be specified.\n\nThe ``cheb1ord()`` helper routine calculates the minimum order :math:`N` and the \ncritical passband frequency :math:`F_C` from passband / stopband specifications.\n\n**Design routines:**\n\n``scipy.signal.cheby1()``, ``scipy.signal.cheb1ord()``\n\n \"\"\"\n\n self.info_doc = []\n self.info_doc.append('cheby1()\\n========')\n self.info_doc.append(sig.cheby1.__doc__)\n self.info_doc.append('cheb1ord()\\n==========')\n self.info_doc.append(sig.cheb1ord.__doc__)\n \n #--------------------------------------------------------------------------\n def _get_params(self, fil_dict):\n \"\"\"\n Translate parameters from filter dictionary to instance\n parameters, scaling / transforming them if needed.\n \"\"\"\n self.analog = False # set to True for analog filters\n\n self.N = fil_dict['N']\n # Frequencies are normalized to f_Nyq = f_S/2, ripple specs are in dB\n self.F_PB = fil_dict['F_PB'] * 2\n self.F_SB = fil_dict['F_SB'] * 2\n self.F_C = fil_dict['F_C'] * 2\n self.F_PB2 = fil_dict['F_PB2'] * 2\n self.F_SB2 = fil_dict['F_SB2'] * 2\n self.F_C2 = fil_dict['F_C2'] * 2\n self.F_PBC = None\n\n self.A_PB = lin2unit(fil_dict['A_PB'], 'IIR', 'A_PB', unit='dB')\n self.A_SB = lin2unit(fil_dict['A_SB'], 'IIR', 'A_SB', unit='dB')\n\n \n # cheby1 filter routines support only one amplitude spec for\n # pass- and stop band each\n if str(fil_dict['rt']) == 'BS':\n fil_dict['A_PB2'] = fil_dict['A_PB']\n elif str(fil_dict['rt']) == 'BP':\n fil_dict['A_SB2'] = fil_dict['A_SB']\n\n def _test_N(self):\n \"\"\"\n Warn the user if the calculated order is too high for a reasonable filter\n design.\n \"\"\"\n if self.N > 30:\n return qfilter_warning(None, self.N, \"Chebychev 1\")\n else:\n return True\n\n\n def _save(self, fil_dict, arg):\n \"\"\"\n Convert results of filter design to all available formats (pz, ba, sos)\n and store them in the global filter dictionary. \n \n Corner frequencies and order calculated for minimum filter order are \n also stored to allow for an easy subsequent manual filter optimization.\n \"\"\"\n fil_save(fil_dict, arg, self.FRMT, __name__)\n\n # For min. filter order algorithms, update filter dictionary with calculated\n # new values for filter order N and corner frequency(s) F_PBC\n if str(fil_dict['fo']) == 'min': \n fil_dict['N'] = self.N\n\n if str(fil_dict['rt']) == 'LP' or str(fil_dict['rt']) == 'HP':\n fil_dict['F_C'] = self.F_PBC / 2. # HP or LP - single corner frequency\n else: # BP or BS - two corner frequencies\n fil_dict['F_C'] = self.F_PBC[0] / 2.\n fil_dict['F_C2'] = self.F_PBC[1] / 2.\n \n#------------------------------------------------------------------------------\n#\n# DESIGN ROUTINES\n#\n#------------------------------------------------------------------------------\n\n # LP: F_PB < F_SB ---------------------------------------------------------\n def LPmin(self, fil_dict):\n self._get_params(fil_dict)\n self.N, self.F_PBC = cheb1ord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,\n analog=self.analog)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_PBC,\n btype='low', analog=self.analog, output=self.FRMT))\n \n def LPman(self, fil_dict):\n self._get_params(fil_dict)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_C,\n btype='low', analog=self.analog, output=self.FRMT))\n\n # HP: F_SB < F_PB ---------------------------------------------------------\n def HPmin(self, fil_dict):\n self._get_params(fil_dict)\n self.N, self.F_PBC = cheb1ord(self.F_PB,self.F_SB, self.A_PB,self.A_SB,\n analog=self.analog)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_PBC,\n btype='highpass', analog=self.analog, output=self.FRMT))\n\n def HPman(self, fil_dict):\n self._get_params(fil_dict)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_C,\n btype='highpass', analog=self.analog, output=self.FRMT))\n\n # For BP and BS, A_PB, F_PB and F_stop have two elements each:\n\n # BP: F_SB[0] < F_PB[0], F_SB[1] > F_PB[1] --------------------------------\n def BPmin(self, fil_dict):\n self._get_params(fil_dict)\n self.N, self.F_PBC = cheb1ord([self.F_PB, self.F_PB2],\n [self.F_SB, self.F_SB2], self.A_PB,self.A_SB, analog=self.analog)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_PBC,\n btype='bandpass', analog=self.analog, output=self.FRMT))\n\n def BPman(self, fil_dict):\n self._get_params(fil_dict)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB,[self.F_C,self.F_C2],\n btype='bandpass', analog=self.analog, output=self.FRMT))\n\n\n # BS: F_SB[0] > F_PB[0], F_SB[1] < F_PB[1] --------------------------------\n def BSmin(self, fil_dict):\n self._get_params(fil_dict)\n self.N, self.F_PBC = cheb1ord([self.F_PB, self.F_PB2],\n [self.F_SB, self.F_SB2], self.A_PB,self.A_SB, analog = self.analog)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB, self.F_PBC,\n btype='bandstop', analog=self.analog, output=self.FRMT))\n\n def BSman(self, fil_dict):\n self._get_params(fil_dict)\n if not self._test_N():\n return -1\n self._save(fil_dict, sig.cheby1(self.N, self.A_PB, [self.F_C,self.F_C2],\n btype='bandstop', analog=self.analog, output=self.FRMT))\n\n\n#------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n filt = Cheby1() # instantiate filter\n import pyfda.filterbroker as fb # importing filterbroker initializes all its globals\n filt.LPman(fb.fil[0]) # design a low-pass with parameters from global dict\n print(fb.fil[0][filt.FRMT]) # return results in default format"
] |
[
[
"scipy.signal.cheby1",
"scipy.signal.cheb1ord"
]
] |
VSCHY/download_SatPP
|
[
"58ccffbce639496afdb54bbf41cd965f2c3b7037"
] |
[
"IMERG_LR/main.py"
] |
[
"import sys\nsys.path.append(\"./library\")\nimport requests \nfrom datetime import date, timedelta\nimport numpy as np \nimport os \nimport subprocess\nimport time\nimport multiprocessing\nimport random\nimport glob\nfrom imerg_func import *\nimport download_function as down\nfrom calendar import monthrange\nimport configparser\n\nconfig=configparser.ConfigParser()\nconfig.read(\"config.def\")\noutput=config.get(\"OverAll\", \"output\")\ntemp_dir=config.get(\"OverAll\", \"temp_dir\")\nnumproc=config.getint(\"OverAll\", \"numproc\", fallback = 1)\n\n##########################################\n\nclass download:\n def __init__(self, output, temp_dir):\n self.output = output\n self.temp_dir = temp_dir\n os.chdir(self.temp_dir)\n\n def download_month(self, year, month):\n output = self.output+\"{0}/{1:02}/\".format(year, month)\n # \n if not os.path.exists(output):\n os.makedirs(output)\n dmon = self.output+\"{0}/\".format(year, month)+\"3B-HHR-L.MS.MRG.3IMERG.daily.month\"+str(month).zfill(2)+str(year)+\".nc\"\n if not os.path.isfile(dmon):\n\n d = monthrange(year, month)[1]\n for i in range(1,d+1):\n t0 = time.time()\n if len([name for name in os.listdir(temp_dir) if os.path.isfile(name)])>0:\n down.empty_directory(temp_dir)\n datet = \"{0}{1:02}{2:02}\".format(year, month, i)\n filen = output+\"3B-HHR-L.MS.MRG.3IMERG.\"+datet+\".nc\"\n if __name__ == \"__main__\":\n pool = multiprocessing.Pool(processes=numproc)\n if not os.path.isfile(filen): \n L = down.get_HH_urls_day(year, month, i)\n numfile = 0\n while numfile <48:\n if __name__ == \"__main__\":\n pool.map(down.download, L)\n numfile = len([name for name in os.listdir('.') if os.path.isfile(name)])\n if __name__ == \"__main__\":\n pool.close()\n ds = imerg_xarray_from_date(temp_dir, \"{0}-{1}-{2}\".format(year,month,i), \"Late\")\n ds.to_netcdf(path=filen, unlimited_dims = [\"time\"])\n ds.close()\n t1 = time.time()\n print(\"FINAL TIME - {0}/{1}/{2}\".format(i,month,year), int(t1-t0), \"s.\")\n subprocess.check_call([\"cdo\", \"mergetime\",output+\"*.nc\", dmon])\n down.empty_directory(output)\n \n##########################################\n\nif __name__ == \"__main__\":\n d = download(output,temp_dir)\n # Define list of years\n # ex : YEAR = [2019]\n YEAR = [2019]\n # Define list of months\n # ex : MONTH = np.arange(1,12)\n MONTH = np.arange(1,2)\n for y in YEAR:\n for m in MONTH:\n d.download_month(y, m)\n\n"
] |
[
[
"numpy.arange"
]
] |
arielmakestuff/loadlimit
|
[
"70d3d23eecfe7922699098ea4901cc8673d14576"
] |
[
"loadlimit/util.py"
] |
[
"# -*- coding: utf-8 -*-\n# loadlimit/util.py\n# Copyright (C) 2016 authors and contributors (see AUTHORS file)\n#\n# This module is released under the MIT License.\n\n\"\"\"Utility objects and functions\"\"\"\n\n# ============================================================================\n# Imports\n# ============================================================================\n\n\n# Stdlib imports\nimport argparse\nfrom collections import ChainMap\nfrom collections.abc import Sequence\nfrom enum import Enum\nfrom functools import partial\nimport json\nimport logging\n\n# Third-party imports\nfrom pandas import Timestamp\nfrom pytz import UTC\n\n# Local imports\n\n\n# ============================================================================\n# Globals\n# ============================================================================\n\n\nLogLevel = Enum('LogLevel', [(k, v) for k, v in logging._nameToLevel.items()\n if k not in ['WARN', 'NOTSET']])\n\n\nTZ_UTC = UTC\n\n\n# ============================================================================\n# Date utils\n# ============================================================================\n\n\ndef now(tzinfo=None):\n \"\"\"Generate the current datetime.\n\n Defaults to UTC timezone.\n\n \"\"\"\n tzinfo = 'UTC' if tzinfo is None else tzinfo\n return Timestamp.now(tz=tzinfo)\n\n\n# ============================================================================\n# Namespace\n# ============================================================================\n\n\nclass Namespace(argparse.Namespace):\n \"\"\"Namespace extended with bool check\n\n The bool check is to report whether the namespace is empty or not\n\n \"\"\"\n\n def __bool__(self):\n \"\"\"Return True if attributes are being stored\"\"\"\n return self != self.__class__()\n\n\n# ============================================================================\n# Async Iterator\n# ============================================================================\n\n\nclass AsyncIterator:\n \"\"\"Async wrapper around a non-async iterator\"\"\"\n\n def __init__(self, obj):\n self._it = iter(obj)\n\n def __aiter__(self):\n return self\n\n async def __anext__(self):\n try:\n value = next(self._it)\n except StopIteration:\n raise StopAsyncIteration\n return value\n\n\naiter = AsyncIterator\n\n\nasync def ageniter(gen):\n \"\"\"Wrap an iterator in an async generator\"\"\"\n for item in gen:\n yield item\n\n\n# ============================================================================\n# Logger\n# ============================================================================\n\n\nclass Logger:\n \"\"\"Help make logging easier\"\"\"\n __slots__ = ('_logger', '_kwargs', '_lognames')\n\n def __init__(self, *, logger=None, name=None):\n if name is None:\n name = __name__.partition('.')[0]\n self._logger = (logging.getLogger(name) if logger is None\n else logger)\n self._kwargs = {}\n self._lognames = frozenset(l.name.lower() for l in LogLevel)\n\n def __getattr__(self, name):\n \"\"\"Return a logger method\"\"\"\n if name not in self._lognames:\n raise ValueError('Unknown log function name: {}'.format(name))\n level = getattr(LogLevel, name.upper())\n return partial(self.log, level)\n\n def log(self, level, message, *args, exc_info=None, **kwargs):\n \"\"\"Log message at the given level\"\"\"\n if not isinstance(level, LogLevel):\n msg = ('level expected LogLevel, got {} instead'.\n format(type(level).__name__))\n raise TypeError(msg)\n kwargs = ChainMap(kwargs, self._kwargs)\n logger = self._logger\n func = getattr(logger, level.name.lower())\n func = func if exc_info is None else partial(func, exc_info=exc_info)\n msg = message.format(*args, **kwargs)\n func(msg)\n\n @property\n def msgkwargs(self):\n \"\"\"Update message kwargs\"\"\"\n return self._kwargs\n\n @property\n def logger(self):\n \"\"\"Return the underlying logger object\"\"\"\n return self._logger\n\n\n# ============================================================================\n# Event container\n# ============================================================================\n\n\nEventType = Enum('EventType', ['start', 'init_start', 'init_end',\n 'warmup_start', 'warmup_end', 'end'])\n\n\nclass Event(Sequence):\n __slots__ = ('_val', )\n\n def __init__(self, event_type, timestamp=None, *, logger=None):\n if not isinstance(event_type, EventType):\n msg = 'event_type arg expected {} object, got {} object instead'\n raise TypeError(msg.format(EventType.__name__,\n type(event_type).__name__))\n if timestamp is None:\n timestamp = now()\n\n if not isinstance(timestamp, Timestamp):\n msg = 'timestamp arg expected {} object, got {} object instead'\n raise TypeError(msg.format(Timestamp.__name__,\n type(timestamp).__name__))\n\n if not isinstance(logger, (type(None), Logger)):\n msg = 'logger arg expected {} object, got {} object instead'\n raise TypeError(msg.format(Logger.__name__, type(logger).__name__))\n\n self._val = (event_type, timestamp)\n\n if logger is not None:\n msg = dict(name=event_type.name, timestamp=str(timestamp))\n logger.info('EVENT: {}', json.dumps(msg))\n\n def __getitem__(self, key):\n return self._val[key]\n\n def __len__(self):\n return len(self._val)\n\n @property\n def type(self):\n \"\"\"Return the event type\"\"\"\n return self._val[0]\n\n @property\n def timestamp(self):\n \"\"\"Return the event timestamp\"\"\"\n return self._val[1]\n\n\n# ============================================================================\n#\n# ============================================================================\n"
] |
[
[
"pandas.Timestamp.now"
]
] |
jacksonlli/learn-hippo
|
[
"7695d22e73c334b6d9df7e35cb6e30855db187fe"
] |
[
"src/models/LCALSTM_after.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pdb\nfrom models.EM import EM\nfrom torch.distributions import Categorical\nfrom models.initializer import initialize_weights\n\n# constants\n# number of vector signal (lstm gates)\nN_VSIG = 3\n# number of scalar signal (sigma)\nN_SSIG = 1\n# the ordering in the cache\nscalar_signal_names = ['input strength']\nvector_signal_names = ['f', 'i', 'o']\nsigmoid = nn.Sigmoid()\n\n\nclass LCALSTM_after(nn.Module):\n\n def __init__(\n self, input_dim, output_dim, rnn_hidden_dim, dec_hidden_dim,\n kernel='cosine', dict_len=2, weight_init_scheme='ortho',\n cmpt=.8, em_gate=.3, add_penalty_dim=True\n ):\n super(LCALSTM_after, self).__init__()\n self.cmpt = cmpt\n self.em_gate = em_gate\n if add_penalty_dim:\n self.input_dim = input_dim + 1\n else:\n self.input_dim = input_dim\n # self.input_dim = input_dim + 1\n self.rnn_hidden_dim = rnn_hidden_dim\n self.n_hidden_total = (N_VSIG + 1) * rnn_hidden_dim + N_SSIG\n # rnn module\n self.i2h = nn.Linear(self.input_dim, self.n_hidden_total)\n self.h2h = nn.Linear(rnn_hidden_dim, self.n_hidden_total)\n # deicion module\n self.ih = nn.Linear(rnn_hidden_dim, dec_hidden_dim)\n self.actor = nn.Linear(dec_hidden_dim, output_dim)\n self.critic = nn.Linear(dec_hidden_dim, 1)\n # memory\n self.hpc = nn.Linear(\n rnn_hidden_dim + rnn_hidden_dim + dec_hidden_dim, N_SSIG\n )\n self.em = EM(dict_len, rnn_hidden_dim, kernel)\n # the RL mechanism\n self.weight_init_scheme = weight_init_scheme\n self.init_model()\n\n def init_model(self):\n # add name fields\n self.n_ssig = N_SSIG\n self.n_vsig = N_VSIG\n self.vsig_names = vector_signal_names\n self.ssig_names = scalar_signal_names\n # init params\n initialize_weights(self, self.weight_init_scheme)\n\n def get_init_states(self, scale=.1, device='cpu'):\n h_0_ = sample_random_vector(self.rnn_hidden_dim, scale)\n c_0_ = sample_random_vector(self.rnn_hidden_dim, scale)\n return (h_0_, c_0_)\n\n def forward(self, x_t, hc_prev, beta=1):\n # unpack activity\n (h_prev, c_prev) = hc_prev\n h_prev = h_prev.view(h_prev.size(1), -1)\n c_prev = c_prev.view(c_prev.size(1), -1)\n x_t = x_t.view(x_t.size(1), -1)\n # transform the input info\n preact = self.i2h(x_t) + self.h2h(h_prev)\n # get all gate values\n gates = preact[:, : N_VSIG * self.rnn_hidden_dim].sigmoid()\n c_t_new = preact[:, N_VSIG * self.rnn_hidden_dim + N_SSIG:].tanh()\n # split input(write) gate, forget gate, output(read) gate\n f_t = gates[:, :self.rnn_hidden_dim]\n o_t = gates[:, self.rnn_hidden_dim:2 * self.rnn_hidden_dim]\n i_t = gates[:, -self.rnn_hidden_dim:]\n # new cell state = gated(prev_c) + gated(new_stuff)\n c_t = torch.mul(c_prev, f_t) + torch.mul(i_t, c_t_new)\n # make 1st decision attempt\n h_t = torch.mul(o_t, c_t.tanh())\n dec_act_t = F.relu(self.ih(h_t))\n # recall / encode\n # hpc_input_t = torch.cat([c_t, dec_act_t], dim=1)\n # inps_t = sigmoid(self.hpc(hpc_input_t))\n # [inps_t, comp_t] = torch.squeeze(phi_t)\n m_t = self.recall(c_t, self.em_gate)\n hpc_input_t = torch.cat([m_t, c_t, dec_act_t], dim=1)\n em_g_t = sigmoid(self.hpc(hpc_input_t))\n cm_t = c_t + m_t * em_g_t\n self.encode(cm_t)\n # make final dec\n h_t = torch.mul(o_t, cm_t.tanh())\n dec_act_t = F.relu(self.ih(h_t))\n pi_a_t = _softmax(self.actor(dec_act_t), beta)\n value_t = self.critic(dec_act_t)\n # reshape data\n h_t = h_t.view(1, h_t.size(0), -1)\n cm_t = cm_t.view(1, cm_t.size(0), -1)\n # scache results\n scalar_signal = [em_g_t, 0, 0]\n vector_signal = [f_t, i_t, o_t]\n misc = [h_t, m_t, cm_t, dec_act_t, self.em.get_vals()]\n cache = [vector_signal, scalar_signal, misc]\n return pi_a_t, value_t, (h_t, cm_t), cache\n\n def recall(self, c_t, inps_t, comp_t=None):\n \"\"\"run the \"pattern completion\" procedure\n\n Parameters\n ----------\n c_t : torch.tensor, vector\n cell state\n leak_t : torch.tensor, scalar\n LCA param, leak\n comp_t : torch.tensor, scalar\n LCA param, lateral inhibition\n inps_t : torch.tensor, scalar\n LCA param, input strength / feedforward weights\n\n Returns\n -------\n tensor, tensor\n updated cell state, recalled item\n\n \"\"\"\n if comp_t is None:\n comp_t = self.cmpt\n\n if self.em.retrieval_off:\n m_t = torch.zeros_like(c_t)\n else:\n # retrieve memory\n m_t = self.em.get_memory(c_t, leak=0, comp=comp_t, w_input=inps_t)\n return m_t\n\n def encode(self, cm_t):\n if not self.em.encoding_off:\n self.em.save_memory(cm_t)\n\n def pick_action(self, action_distribution):\n \"\"\"action selection by sampling from a multinomial.\n\n Parameters\n ----------\n action_distribution : 1d torch.tensor\n action distribution, pi(a|s)\n\n Returns\n -------\n torch.tensor(int), torch.tensor(float)\n sampled action, log_prob(sampled action)\n\n \"\"\"\n m = Categorical(action_distribution)\n a_t = m.sample()\n log_prob_a_t = m.log_prob(a_t)\n return a_t, log_prob_a_t\n\n def init_em_config(self):\n self.flush_episodic_memory()\n self.encoding_off()\n self.retrieval_off()\n\n def flush_episodic_memory(self):\n self.em.flush()\n\n def encoding_off(self):\n self.em.encoding_off = True\n\n def retrieval_off(self):\n self.em.retrieval_off = True\n\n def encoding_on(self):\n self.em.encoding_off = False\n\n def retrieval_on(self):\n self.em.retrieval_off = False\n\n\ndef sample_random_vector(n_dim, scale=.1):\n return torch.randn(1, 1, n_dim) * scale\n\n\ndef _softmax(z, beta):\n \"\"\"helper function, softmax with beta\n\n Parameters\n ----------\n z : torch tensor, has 1d underlying structure after torch.squeeze\n the raw logits\n beta : float, >0\n softmax temp, big value -> more \"randomness\"\n\n Returns\n -------\n 1d torch tensor\n a probability distribution | beta\n\n \"\"\"\n assert beta > 0\n # softmax the input to a valid PMF\n pi_a = F.softmax(torch.squeeze(z / beta), dim=0)\n # make sure the output is valid\n if torch.any(torch.isnan(pi_a)):\n raise ValueError(f'Softmax produced nan: {z} -> {pi_a}')\n return pi_a\n"
] |
[
[
"torch.isnan",
"torch.cat",
"torch.randn",
"torch.zeros_like",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.distributions.Categorical",
"torch.mul",
"torch.squeeze"
]
] |
rwalkerlewis/devito
|
[
"262364e5f2855ad01a281d517d400704b7667420",
"262364e5f2855ad01a281d517d400704b7667420"
] |
[
"examples/seismic/poroelastic/poroelastic_example.py",
"examples/seismic/tti/tti_example.py"
] |
[
"import numpy as np\nfrom argparse import ArgumentParser\n\nfrom devito.logger import info\nfrom examples.seismic.poroelastic import PoroelasticWaveSolver, demo_model\nfrom examples.seismic import AcquisitionGeometry\n\n\ndef poroelastic_setup(shape=(50, 50), spacing=(15.0, 15.0), tn=500., num=200, space_order=4, nbpml=10,\n constant=False, **kwargs):\n\n nrec = 2*shape[0]\n preset = 'constant-poroelastic' if constant else 'layers-poroelastic'\n model = demo_model(preset, space_order=space_order, shape=shape, nbpml=nbpml,\n dtype=kwargs.pop('dtype', np.float32), spacing=spacing)\n\n # Source and receiver geometries\n src_coordinates = np.empty((1, len(spacing)))\n src_coordinates[0, :] = np.array(model.domain_size) * .5\n if len(shape) > 1:\n src_coordinates[0, -1] = model.origin[-1] + 2 * spacing[-1]\n\n rec_coordinates = np.empty((nrec, len(spacing)))\n rec_coordinates[:, 0] = np.linspace(0., model.domain_size[0], num=nrec)\n if len(shape) > 1:\n rec_coordinates[:, 1] = np.array(model.domain_size)[1] * .5\n rec_coordinates[:, -1] = model.origin[-1] + 2 * spacing[-1]\n # Source frequency is in Hz\n geometry = AcquisitionGeometry(model, rec_coordinates, src_coordinates,\n t0=0.0, tn=tn, src_type='Ricker', f0=40)\n\n # Create solver object to provide relevant operators\n solver = PoroelasticWaveSolver(model, geometry, space_order=space_order, **kwargs)\n return solver\n\n\ndef run(shape=(50, 50), spacing=(20.0, 20.0), tn=1000.0, num=200,\n space_order=4, nbpml=40, autotune=False, constant=False, **kwargs):\n\n solver = poroelastic_setup(shape=shape, spacing=spacing, nbpml=nbpml, tn=tn,\n num=num, space_order=space_order, constant=constant, **kwargs)\n info(\"Applying Forward\")\n # Define receiver geometry (spread across x, just below surface)\n rec1, rec2, vx, vz, qx, qz, txx, tzz, txz, p, summary = solver.forward(autotune=autotune)\n\n # iPython debug option \n #import matplotlib.pyplot as plt \n #from IPython import embed;embed()\n return rec1, rec2, vx, vz, qx, qz, txx, tzz, txz, p, summary\n\n\nif __name__ == \"__main__\":\n description = (\"Example script for a set of poroelastic operators.\")\n parser = ArgumentParser(description=description)\n parser.add_argument('--2d', dest='dim2', default=True, action='store_true',\n help=\"Preset to determine the physical problem setup\")\n parser.add_argument('-a', '--autotune', default=False, action='store_true',\n help=\"Enable autotuning for block sizes\")\n parser.add_argument(\"-so\", \"--space_order\", default=4,\n type=int, help=\"Space order of the simulation\")\n parser.add_argument(\"--nbpml\", default=40,\n type=int, help=\"Number of PML layers around the domain\")\n parser.add_argument(\"-dse\", default=\"advanced\",\n choices=[\"noop\", \"basic\", \"advanced\",\n \"speculative\", \"aggressive\"],\n help=\"Devito symbolic engine (DSE) mode\")\n parser.add_argument(\"-dle\", default=\"advanced\",\n choices=[\"noop\", \"advanced\", \"speculative\"],\n help=\"Devito loop engine (DLEE) mode\")\n parser.add_argument(\"--constant\", default=True, action='store_true',\n help=\"Constant velocity model, default is a constant velocity model\")\n args = parser.parse_args()\n\n # 2D preset parameters\n if args.dim2:\n shape = (251, 641)\n spacing = (0.5, 0.5)\n num = 800\n dt = 1.0e-4\n tn = 0.05 #(num-1)*dt\n # 3D preset parameters\n else:\n shape = (150, 150, 150)\n spacing = (10.0, 10.0, 10.0)\n tn = 1250.0\n\n run(shape=shape, spacing=spacing, nbpml=args.nbpml, tn=tn, num=num, dle=args.dle,\n space_order=args.space_order, autotune=args.autotune, constant=args.constant,\n dse=args.dse)\n",
"import numpy as np\nfrom argparse import ArgumentParser\n\nfrom devito.logger import warning\nfrom examples.seismic import demo_model, AcquisitionGeometry\nfrom examples.seismic.tti import AnisotropicWaveSolver\n\n\ndef tti_setup(shape=(50, 50, 50), spacing=(20.0, 20.0, 20.0), tn=250.0,\n space_order=4, nbpml=10, preset='layers-tti', **kwargs):\n\n nrec = 101\n # Two layer model for true velocity\n model = demo_model(preset, shape=shape, spacing=spacing, nbpml=nbpml)\n # Source and receiver geometries\n src_coordinates = np.empty((1, len(spacing)))\n src_coordinates[0, :] = np.array(model.domain_size) * .5\n if len(shape) > 1:\n src_coordinates[0, -1] = model.origin[-1] + 2 * spacing[-1]\n\n rec_coordinates = np.empty((nrec, len(spacing)))\n rec_coordinates[:, 0] = np.linspace(0., model.domain_size[0], num=nrec)\n if len(shape) > 1:\n rec_coordinates[:, 1] = np.array(model.domain_size)[1] * .5\n rec_coordinates[:, -1] = model.origin[-1] + 2 * spacing[-1]\n geometry = AcquisitionGeometry(model, rec_coordinates, src_coordinates,\n t0=0.0, tn=tn, src_type='Ricker', f0=0.010)\n\n return AnisotropicWaveSolver(model, geometry,\n space_order=space_order, **kwargs)\n\n\ndef run(shape=(50, 50, 50), spacing=(20.0, 20.0, 20.0), tn=250.0,\n autotune=False, time_order=2, space_order=4, nbpml=10,\n kernel='centered', **kwargs):\n\n solver = tti_setup(shape, spacing, tn, space_order, nbpml, **kwargs)\n\n if space_order % 4 != 0:\n warning('WARNING: TTI requires a space_order that is a multiple of 4!')\n\n rec, u, v, summary = solver.forward(autotune=autotune, kernel=kernel)\n return summary.gflopss, summary.oi, summary.timings, [rec, u, v]\n\n\nif __name__ == \"__main__\":\n description = (\"Example script to execute a TTI forward operator.\")\n parser = ArgumentParser(description=description)\n parser.add_argument('--2d', dest='dim2', default=False, action='store_true',\n help=\"Preset to determine the physical problem setup\")\n parser.add_argument('--noazimuth', dest='azi', default=False, action='store_true',\n help=\"Whether or not to use an azimuth angle\")\n parser.add_argument('-a', '--autotune', default=False, action='store_true',\n help=\"Enable autotuning for block sizes\")\n parser.add_argument(\"-so\", \"--space_order\", default=4,\n type=int, help=\"Space order of the simulation\")\n parser.add_argument(\"--nbpml\", default=40,\n type=int, help=\"Number of PML layers around the domain\")\n parser.add_argument(\"-k\", dest=\"kernel\", default='centered',\n choices=['centered', 'shifted', 'staggered'],\n help=\"Choice of finite-difference kernel\")\n parser.add_argument(\"-dse\", default=\"advanced\",\n choices=[\"noop\", \"basic\", \"advanced\",\n \"speculative\", \"aggressive\"],\n help=\"Devito symbolic engine (DSE) mode\")\n parser.add_argument(\"-dle\", default=\"advanced\",\n choices=[\"noop\", \"advanced\", \"speculative\"],\n help=\"Devito loop engine (DLE) mode\")\n args = parser.parse_args()\n\n preset = 'layers-tti-noazimuth' if args.azi else 'layers-tti'\n # 3D preset parameters\n if args.dim2:\n shape = (150, 150)\n spacing = (10.0, 10.0)\n tn = 750.0\n else:\n shape = (50, 50, 50)\n spacing = (10.0, 10.0, 10.0)\n tn = 250.0\n\n run(shape=shape, spacing=spacing, nbpml=args.nbpml, tn=tn,\n space_order=args.space_order, autotune=args.autotune, dse=args.dse,\n dle=args.dle, kernel=args.kernel, preset=preset)\n"
] |
[
[
"numpy.array",
"numpy.linspace"
],
[
"numpy.array",
"numpy.linspace"
]
] |
anhlnt/age-gender-estimation
|
[
"0a1c3a289a33c96c586ae8219911dbe51724f6d9"
] |
[
"convert_savedmodel.py"
] |
[
"import tensorflow as tf\nfrom src.factory import get_model\nfrom omegaconf import OmegaConf\nfrom pathlib import Path\n\n\n\ndef getModel():\n weight_file = \"pretrained_models/EfficientNetB3_224_weights.26-3.15.hdf5\"\n model_name, img_size = Path(weight_file).stem.split(\"_\")[:2]\n print('model_name: ', model_name, 'img_size: ', img_size)\n img_size = int(img_size)\n cfg = OmegaConf.from_dotlist([f\"model.model_name={model_name}\", f\"model.img_size={img_size}\"])\n model = get_model(cfg)\n model.load_weights(weight_file)\n return model\n\ndef saveModel(model, path):\n tf.saved_model.save(model, path)\n\ndef main():\n model = getModel()\n savePath = 'pretrained_models/EfficientNetB3_224_weights.26-3.15'\n saveModel(model, savePath)\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"tensorflow.saved_model.save"
]
] |
ploomber/posts
|
[
"5f739cf04ff77932c34d5d3ad8d6d94dfe97f051"
] |
[
"hypervector/scripts/get.py"
] |
[
"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.11.4\n# kernelspec:\n# display_name: Python 3 (ipykernel)\n# language: python\n# name: python3\n# ---\n\nimport pandas as pd\nfrom sklearn.datasets import load_iris\n\n# + tags=[\"parameters\"]\n# extract_upstream=True in your pipeline.yaml file, if this task has\n# dependencies, list them them here (e.g. upstream = ['some_task']), otherwise\n# leave as None\nupstream = None\n\n# extract_product=False in your pipeline.yaml file, leave this as None, the\n# value in the YAML spec will be added here during task execution\nproduct = None\n# -\n\n\ndf = load_iris(as_frame=True)['frame']\n\ndf.head()\n\ndf.to_csv(product['data'], index=False)\n"
] |
[
[
"sklearn.datasets.load_iris"
]
] |
Peter42/iasi
|
[
"fc799d542c2bb80c3f559bc2f9e833ac330a5506"
] |
[
"iasi/evaluation.py"
] |
[
"from functools import partial\nimport math\nimport os\n\nimport luigi\nimport numpy as np\nimport pandas as pd\nfrom netCDF4 import Dataset, Group, Variable\nfrom sklearn.model_selection import ParameterGrid\n\nfrom iasi.composition import Composition\nfrom iasi.compression import CompressDataset, SelectSingleVariable, DecompressDataset\nfrom iasi.file import MoveVariables, FileTask\nfrom iasi.metrics import Covariance\nfrom iasi.quadrant import Quadrant, AssembleFourQuadrants\nfrom iasi.util import CustomTask\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass EvaluationTask(FileTask):\n gases = luigi.ListParameter()\n variables = luigi.ListParameter()\n threshold_values = luigi.ListParameter(default=[1e-2, 1e-3, 1e-4, 1e-5])\n ancestor = None\n\n def requires(self):\n compression_parameter = {\n 'ancestor': [self.ancestor],\n 'file': [self.file],\n 'dst': [self.dst],\n 'threshold': self.threshold_values,\n 'gas': self.gases,\n 'variable': self.variables\n }\n compressed_param_grid = list(ParameterGrid(compression_parameter))\n tasks = [SelectSingleVariable(**params)\n for params in compressed_param_grid]\n # for uncompressed dataset we do not need multiple threshold values\n uncompressed_parameter = {\n 'ancestor': ['MoveVariables'],\n 'file': [self.file],\n 'dst': [self.dst],\n 'threshold': [0],\n 'gas': self.gases,\n 'variable': self.variables\n }\n uncompressed_param_grid = list(ParameterGrid(uncompressed_parameter))\n single_variables = tasks + \\\n [SelectSingleVariable(**params)\n for params in uncompressed_param_grid]\n # exclude cross average kernel from atmospheric temperature.\n # atmospheric temperature has only avk and noise matrix\n filtered = filter(lambda task: not(task.gas == 'Tatm') or not(\n task.variable == 'Tatmxavk'), single_variables)\n return {\n 'single': filtered,\n 'original': MoveVariables(dst=self.dst, file=self.file)\n }\n\n\nclass EvaluationCompressionSize(EvaluationTask):\n ancestor = 'CompressDataset'\n\n def output_directory(self):\n return 'compression-summary'\n\n def output_extension(self):\n return '.csv'\n\n def size_in_kb(self, file):\n return int(os.path.getsize(file) / (1000))\n\n def run(self):\n # get size for all parameters\n df = pd.DataFrame()\n for task, input in zip(self.requires()['single'], self.input()['single']):\n df = df.append({\n 'gas': task.gas,\n 'variable': task.variable,\n 'ancestor': task.ancestor,\n 'size': self.size_in_kb(input.path),\n 'threshold': task.threshold\n }, ignore_index=True)\n with self.output().temporary_path() as target:\n df.to_csv(target, index=False)\n\n\nclass EvaluationErrorEstimation(FileTask):\n file = luigi.Parameter()\n gases = luigi.Parameter()\n variables = luigi.Parameter()\n thresholds = luigi.ListParameter(default=[1e-3])\n\n def output_directory(self):\n return 'error-estimation'\n\n def output_extension(self):\n return '.csv'\n\n def requires(self):\n parameter = {\n 'file': [self.file],\n 'dst': [self.dst],\n 'thresholds': [self.thresholds],\n 'gas': self.gases,\n 'variable': self.variables,\n 'log_file': [self.log_file]\n }\n parameter_grid = ParameterGrid(parameter)\n # exclude cross average kernel from atmospheric temperature.\n # atmospheric temperature has only avk and noise matrix\n parameter_grid = filter(lambda params: not(params['gas'] == 'Tatm') or not(\n params['variable'] == 'Tatmxavk'), parameter_grid)\n return [VariableErrorEstimation(**params) for params in parameter_grid]\n\n def run(self):\n report = pd.DataFrame()\n for task in self.input():\n with task.open() as file:\n task_report = pd.read_csv(file)\n report = report.append(task_report)\n with self.output().temporary_path() as target:\n report.to_csv(target, index=False)\n\n\nclass VariableErrorEstimation(FileTask):\n\n gas = luigi.Parameter()\n variable = luigi.Parameter()\n thresholds = luigi.ListParameter(default=[1e-3])\n\n def output_extension(self):\n return '.csv'\n\n def requires(self):\n compressed = [DecompressDataset(\n dst=self.dst,\n file=self.file,\n threshold=threshold,\n log_file=self.log_file,\n compress_upstream=True\n ) for threshold in self.thresholds]\n original = MoveVariables(\n dst=self.dst, file=self.file, log_file=self.log_file)\n return {\n 'compressed': compressed,\n 'original': original\n }\n\n def run(self):\n path = f'/state/{self.gas}/{self.variable}'\n logger.info('Starting error estimation for %s', path)\n tasks_and_input = list(zip(\n self.requires()['compressed'], self.input()['compressed']))\n original = Dataset(self.input()['original'].path)\n nol = original['atm_nol'][...]\n alt = original['atm_altitude'][...]\n avk = original['/state/WV/avk'][...]\n alt_trop = original['tropopause_altitude'][...]\n counter = 0\n message = f'Calculate original error for {path}: {counter}/{len(tasks_and_input)}'\n logger.info(message)\n self.set_status_message(message)\n self.set_progress_percentage(int(counter / len(tasks_and_input) * 100))\n error_estimation: ErrorEstimation = ErrorEstimation.factory(\n self.gas, nol, alt, avk, alt_trop=alt_trop)\n # calculation of original error\n variable_report = error_estimation.report_for(\n original[path], original[path][...], None, rc_error=False)\n variable_report['threshold'] = 0\n # calculation of reconstruction error\n for task, input in tasks_and_input:\n counter += 1\n nc = Dataset(input.path)\n message = f'Calculating error estimation {counter} of {len(tasks_and_input)} for {path} with threshold {task.threshold}'\n logger.info(message)\n self.set_status_message(message)\n self.set_progress_percentage(\n int(counter / len(tasks_and_input) * 100))\n reconstructed_values = nc[path][...]\n original_values = original[path][...]\n report = error_estimation.report_for(\n original[path], original_values, reconstructed_values, rc_error=True)\n report['threshold'] = task.threshold\n variable_report = variable_report.append(report, ignore_index=True)\n nc.close()\n variable_report['var'] = self.variable\n variable_report['gas'] = self.gas\n with self.output().temporary_path() as target:\n variable_report.to_csv(target, index=False)\n original.close()\n\n def output_directory(self):\n return os.path.join('error-estimation', self.gas, self.variable)\n\n\nclass ErrorEstimation:\n levels_of_interest = []\n # assume statosphere starting at 25 km\n alt_strat = 25000\n\n @staticmethod\n def factory(gas: str, nol, alt, avk, alt_trop=None):\n if gas == 'WV':\n return WaterVapour(gas, nol, alt, avk, alt_trop, type_two=True)\n if gas == 'GHG':\n return GreenhouseGas(gas, nol, alt, alt_trop)\n if gas == 'HNO3':\n return NitridAcid(gas, nol, alt, alt_trop)\n if gas == 'Tatm':\n return AtmosphericTemperature(gas, nol, alt, alt_trop)\n raise ValueError(f'No error estimation implementation for gas {gas}')\n\n def __init__(self, gas, nol, alt, alt_trop, type_two=False):\n # each gas may have multiple levels of interest\n self.type_two = type_two\n self.nol = nol\n self.alt = alt\n self.gas = gas\n self.alt_trop = alt_trop\n\n def matrix_ok(self, event, path, matrix):\n ok = True\n if np.ma.is_masked(matrix):\n logger.warning(\n 'event %d contains masked values in %s. skipping...', event, path)\n ok = False\n if np.isnan(matrix).any():\n logger.warning(\n 'event %d contains nan values in %s. skipping...', event, path)\n ok = False\n if np.isinf(matrix).any():\n logger.warning(\n 'event %d contains inf values in %s. skipping...', event, path)\n ok = False\n if np.allclose(matrix, 0, atol=1e-14):\n logger.warning(\n 'event %d contains zero or close to zero values in %s. skipping...', event, path)\n ok = False\n return ok\n\n def report_for(self, variable: Variable, original, reconstructed, rc_error) -> pd.DataFrame:\n # if not original.shape == reconstructed.shape:\n # message = f'Different shape for {type(self).__name__} {variable.name}: original {original.shape}, reconstructed {reconstructed.shape}'\n # logger.error(message)\n # raise ValueError(message)\n result = {\n 'event': [],\n 'level_of_interest': [],\n 'err': [],\n 'rc_error': [],\n 'type': []\n }\n error_estimation_methods = {\n 'avk': self.averaging_kernel,\n 'n': self.noise_matrix,\n 'Tatmxavk': self.cross_averaging_kernel\n }\n estimation_method = error_estimation_methods.get(variable.name)\n if estimation_method is None:\n raise ValueError(\n f'No error estimation method for variable {variable.name}')\n\n reshaper = Quadrant.for_assembly(self.gas, variable.name, variable)\n path = f'/state/{self.gas}/{variable.name}'\n for event in range(original.shape[0]):\n if np.ma.is_masked(self.nol[event]) or self.nol.data[event] > 29:\n continue\n nol_event = self.nol.data[event]\n if not self.matrix_ok(event, path, self.alt[event, :nol_event]):\n continue\n covariance = Covariance(nol_event, self.alt[event])\n original_event = reshaper.transform(original[event], nol_event)\n if not self.matrix_ok(event, path, original_event):\n continue\n # use reconstruced values iff rc_error flag is set\n if rc_error:\n rc_event = reshaper.transform(reconstructed[event], nol_event)\n if not self.matrix_ok(event, path, rc_event):\n continue\n rc_event = rc_event.data\n else:\n rc_event = None\n if isinstance(self, WaterVapour):\n avk_event = AssembleFourQuadrants(\n nol_event).transform(self.avk[event], nol_event)\n if not self.matrix_ok(event, 'wv_avk', avk_event):\n continue\n avk_event = avk_event.data\n else:\n avk_event = None\n # type two error only exists for water vapour\n # if gas does not require type 2 error estimation, break loop after first iteration\n calc_type_two = self.type_two\n while True:\n error = estimation_method(event,\n original_event.data, rc_event, covariance, type2=calc_type_two, avk=avk_event)\n for loi in self.levels_of_interest:\n # zero == surface (special value)\n if loi == 0:\n level = 0\n # for other levels substract from highest level\n else:\n level = nol_event + loi\n if level < 2:\n continue\n result['event'].append(event)\n result['level_of_interest'].append(loi)\n result['err'].append(error[level, level])\n result['rc_error'].append(rc_error)\n result['type'].append(2 if calc_type_two else 1)\n if self.gas == 'GHG':\n # for greenhouse gases export also CH4 (lower right quadrant)\n # nol as index offset for error level\n result['event'].append(event)\n result['level_of_interest'].append(loi - 29)\n result['err'].append(\n error[level + nol_event, level + nol_event])\n result['rc_error'].append(rc_error)\n result['type'].append(2 if calc_type_two else 1)\n # stop if type 1 is calculated\n if not calc_type_two:\n break\n # just finished type 2 in first iteration -> repeat with type 1\n calc_type_two = False\n return pd.DataFrame(result)\n\n def averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None):\n raise NotImplementedError\n\n def noise_matrix(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None):\n raise NotImplementedError\n\n def cross_averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None):\n raise NotImplementedError\n\n def smoothing_error(self, actual_matrix, to_compare, assumed_covariance) -> np.ndarray:\n \"\"\"Calulate smooting error with two matrices and assumed covariance\"\"\"\n return (actual_matrix - to_compare) @ assumed_covariance @ (actual_matrix - to_compare).T\n\n def assumed_covariance_temperature(self, event: int) -> np.ndarray:\n \"\"\"Return assumed covariance for temperature cross averaging kernel\"\"\"\n sig = self.sigma(event)\n amp = self.amplitude_temperature(event)\n return self.construct_covariance_matrix(event, amp, sig)\n\n def construct_covariance_matrix(self, event, amp: np.ndarray, sig: np.ndarray) -> np.ndarray:\n \"\"\"create a covariance matrix by amplitude and deviation\n\n :param amp: Amplitude for levels\n :param sig: Standard deviation for levels\n \"\"\"\n nol = self.nol.data[event]\n alt = self.alt.data[event]\n sa = np.ndarray((nol, nol))\n for i in range(nol):\n for j in range(nol):\n sa[i, j] = amp[i] * amp[j] * \\\n np.exp(-((alt[i] - alt[j])*(alt[i] - alt[j])) /\n (2 * sig[i] * sig[j]))\n return sa\n\n def sigma(self, event, f_sigma: float = 0.6) -> np.ndarray:\n \"\"\"Assumed correlation length for all gases and temperature.\n\n :param self.alt_strat: altitude of stratosphere in meters\n :param f_sigma: scaling factor\n\n :return: correlation length for each level\n \"\"\"\n nol = self.nol.data[event]\n alt = self.alt.data[event]\n alt_trop = self.alt_trop[event]\n sig = np.ndarray(nol)\n for i in range(nol):\n # below tropopause\n if alt[i] < alt_trop:\n sig[i] = 2500 + (alt[i] - alt[0]) * \\\n ((5000-2500)/(alt_trop-alt[0]))\n # inside statrophere\n if alt[i] >= alt_trop and alt[i] < self.alt_strat:\n sig[i] = 5000+(alt[i]-alt_trop) * \\\n ((10000-5000)/(self.alt_strat-alt_trop))\n # above stratosphere\n if alt[i] > self.alt_strat:\n sig[i] = 10000\n return sig * f_sigma\n\n def amplitude(self, event):\n raise NotImplementedError\n\n def amplitude_temperature(self, event) -> np.ndarray:\n \"\"\"Get amplitude and deviation for atmospheric temperature\n\n :return: amp\n \"\"\"\n nol = self.nol.data[event]\n alt = self.alt.data[event, :nol]\n alt_trop = self.alt_trop.data[event]\n amp = np.ndarray(nol)\n for i in range(nol):\n if alt[0]+4000 < alt_trop:\n # setting amp_T\n if alt[i] <= alt[0]+4000:\n amp[i] = 2.0 - 1.0 * (alt[i] - alt[0]) / 4000\n elif alt[i] >= alt[0]+4000 and alt[i] <= alt_trop:\n amp[i] = 1.\n elif alt[i] > alt_trop and alt[i] <= alt_trop+5000:\n amp[i] = 1.0 + 0.5 * (alt[i] - alt_trop) / 5000\n elif alt[i] > alt_trop+5000:\n amp[i] = 1.5\n else:\n # setting amp[i]\n if alt[i] < alt_trop:\n amp[i] = 2.0 - 1.0 * (alt[i] - alt[0]) / \\\n (alt_trop - alt[0])\n elif alt[i] == alt_trop:\n amp[i] = 1.\n elif alt[i] > alt_trop and alt[i] <= alt_trop+5000:\n amp[i] = 1.0 + 0.5 * (alt[i] - alt_trop) / 5000\n elif alt[i] > alt_trop+5000:\n amp[i] = 1.5\n return amp\n\n\nclass WaterVapour(ErrorEstimation):\n levels_of_interest = [-6, -16, -19]\n\n def __init__(self, gas, nol, alt, avk, alt_trop, type_two=True):\n super().__init__(gas, nol, alt, alt_trop, type_two=type_two)\n self.avk = avk\n\n # for each method type one and type two\n\n def averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n # in this method, avk should be same like original\n if not np.allclose(original, avk):\n logger.warn('There are differences in original parameter and avk')\n s_cov = self.assumed_covariance(event)\n nol = self.nol.data[event]\n if type2:\n # type 2 error\n original_type2 = covariance.type2_of(original)\n if reconstructed is None:\n # type 2 original error\n return self.smoothing_error(original_type2, np.identity(2 * nol), s_cov)\n else:\n # type 2 reconstruction error\n rc_type2 = covariance.type2_of(reconstructed)\n return self.smoothing_error(original_type2, rc_type2, s_cov)\n else:\n # type 1 error\n original_type1 = covariance.type1_of(original)\n if reconstructed is None:\n # type 1 original error\n return self.smoothing_error(\n original_type1, np.identity(2 * nol), s_cov)\n else:\n # type 1 reconstruction error\n rc_type1 = covariance.type1_of(reconstructed)\n return self.smoothing_error(original_type1, rc_type1, s_cov)\n\n def noise_matrix(self, event: int, original: np.ndarray, reconstruced: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n # original/approx event is already covariance matrix -> only type1/2 transformation\n assert avk is not None\n P = covariance.traf()\n if type2:\n # type 2 error\n C = covariance.c_by_avk(avk)\n original_type2 = C @ P @ original @ P.T @ C.T\n if reconstruced is None:\n # original error\n return original_type2\n else:\n # reconstruction error\n rc_type2 = C @ P @ reconstruced @ P.T @ C.T\n return np.absolute(original_type2 - rc_type2)\n else:\n # type 1 error\n original_type1 = P @ original @ P.T\n if reconstruced is None:\n return original_type1\n else:\n rc_type1 = P @ reconstruced @ P.T\n return np.absolute(original_type1 - rc_type1)\n\n def cross_averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n assert avk is not None\n P = covariance.traf()\n s_cov = self.assumed_covariance_temperature(event)\n if type2:\n # type 2 error\n C = covariance.c_by_avk(avk)\n original_type2 = C @ P @ original\n if reconstructed is None:\n # original error\n return original_type2 @ s_cov @ original_type2.T\n # reconstruction error\n rc_type2 = C @ P @ reconstructed\n return self.smoothing_error(original_type2, rc_type2, s_cov)\n else:\n # type 1 error\n original_type1 = P @ original\n if reconstructed is None:\n # original error\n return original_type1 @ s_cov @ original_type1.T\n else:\n # reconstruction error\n rc_type1 = P @ reconstructed\n return self.smoothing_error(original_type1, rc_type1, s_cov)\n\n def assumed_covariance(self, event: int) -> np.ndarray:\n \"\"\"Assumed covariance for both H2O and HDO\"\"\"\n nol = self.nol.data[event]\n amp_H2O, amp_dD = self.amplitude(event)\n sig = self.sigma(event)\n Sa_ = np.zeros([2*nol, 2*nol])\n # Sa H2O\n Sa_[:nol, :nol] = self.construct_covariance_matrix(event, amp_H2O, sig)\n # Sa delD\n Sa_[nol:, nol:] = self.construct_covariance_matrix(event, amp_dD, sig)\n return Sa_\n\n def amplitude(self, event):\n \"\"\"Calculate amplitude for H2O and HDO\n\n :return: (amp_H2O, amp_dD)\n \"\"\"\n nol = self.nol.data[event]\n alt = self.alt.data[event, :nol]\n alt_trop = self.alt_trop.data[event]\n amp_H2O = np.ndarray(nol)\n amp_dD = np.ndarray(nol)\n for i in range(nol):\n if alt[i] < 5000.:\n amp_H2O[i] = 0.75 * (1 + alt[i] / 5000)\n amp_dD[i] = 0.09 * (1 + alt[i] / 5000)\n elif 5000. <= alt[i] < alt_trop:\n amp_H2O[i] = 1.5\n amp_dD[i] = 0.18\n elif alt_trop <= alt[i] < self.alt_strat:\n amp_H2O[i] = 1.5 - 1.2 * \\\n (alt[i] - alt_trop) / (self.alt_strat - alt_trop)\n amp_dD[i] = 0.18 - 0.12 * \\\n (alt[i] - alt_trop) / (self.alt_strat - alt_trop)\n elif alt[i] >= self.alt_strat:\n amp_H2O[i] = 0.3\n amp_dD[i] = 0.06\n else:\n raise ValueError(f'Invalid altitude at {event}')\n return amp_H2O, amp_dD\n\n\nclass GreenhouseGas(ErrorEstimation):\n levels_of_interest = [-6, -10, -19]\n\n def averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n assert not type2\n if reconstructed is None:\n # original error\n reconstructed = np.identity(covariance.nol * 2)\n s_cov = self.assumed_covariance(event)\n return self.smoothing_error(original, reconstructed, s_cov)\n\n def cross_averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n assert not type2\n s_cov = self.assumed_covariance_temperature(event)\n if reconstructed is None:\n # original error\n return original @ s_cov @ original.T\n return self.smoothing_error(original, reconstructed, s_cov)\n\n def noise_matrix(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n if reconstructed is None:\n return original\n else:\n return np.absolute(original - reconstructed)\n\n def assumed_covariance(self, event) -> np.ndarray:\n amp = self.amplitude(event)\n sig = self.sigma(event)\n s_cov = self.construct_covariance_matrix(event, amp, sig)\n nol = self.nol.data[event]\n s_cov_ghg = np.zeros((2 * nol, 2 * nol))\n s_cov_ghg[:nol, :nol] = s_cov\n s_cov_ghg[nol:, nol:] = s_cov\n return s_cov_ghg\n\n def amplitude(self, event) -> np.ndarray:\n \"\"\"Amplitude for GHG\"\"\"\n nol = self.nol.data[event]\n alt = self.alt.data[event, :nol]\n alt_trop = self.alt_trop.data[event]\n amp = np.ndarray((nol))\n for i in range(nol):\n if alt[i] < alt_trop:\n amp[i] = 0.1\n elif alt_trop <= alt[i] < self.alt_strat:\n amp[i] = 0.1 + (alt[i] - alt_trop) * \\\n ((0.25 - 0.1)/(self.alt_strat - alt_trop))\n elif alt[i] >= self.alt_strat:\n amp[i] = 0.25\n else:\n raise ValueError('Invalid altitude')\n return amp\n\n\nclass NitridAcid(ErrorEstimation):\n levels_of_interest = [-6]\n\n def averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n assert not type2\n if reconstructed is None:\n # original error\n reconstructed = np.identity(covariance.nol)\n s_cov = self.assumed_covariance(event)\n return self.smoothing_error(original, reconstructed, s_cov)\n\n def cross_averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n s_cov = self.assumed_covariance_temperature(event)\n if reconstructed is None:\n # original error\n return original @ s_cov @ original.T\n return self.smoothing_error(original, reconstructed, s_cov)\n\n def noise_matrix(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None) -> np.ndarray:\n if reconstructed is None:\n return original\n else:\n return np.absolute(original - reconstructed)\n\n def assumed_covariance(self, event) -> np.ndarray:\n amp = self.amplitude(event)\n sig = self.sigma(event)\n return self.construct_covariance_matrix(event, amp, sig)\n\n def amplitude(self, event: int):\n \"\"\"Amplitude of HNO3\"\"\"\n nol = self.nol.data[event]\n alt = self.alt.data[event, :nol]\n alt_trop = self.alt_trop.data[event]\n amp = np.ndarray((nol))\n for i in range(nol):\n # surface is more than 4km below tropopause\n if alt[0] < alt_trop - 4000:\n # higher variances in valley's due to human made emmisions\n if alt[i] < alt_trop - 4000:\n amp[i] = 2.4 + (alt[i] - alt[0]) * \\\n ((1.2 - 2.4)/(alt_trop - 4000 - alt[0]))\n elif alt_trop - 4000 <= alt[i] < alt_trop + 8000:\n amp[i] = 1.2\n elif alt_trop + 8000 <= alt[i] < 50000:\n amp[i] = 1.2 + (alt[i] - (alt_trop + 8000)) * \\\n ((0.3-1.2) / (50000 - (alt_trop + 8000)))\n elif alt[i] >= 50000:\n amp[i] = 0.3\n else:\n raise ValueError('Invalid altitude')\n else:\n # at higher altitudes covariance is lower\n if alt_trop - 4000 <= alt[i] < alt_trop + 8000:\n amp[i] = 1.2\n elif alt_trop + 8000 < alt[i] < 50000:\n amp[i] = 1.2 + (alt[i] - (alt_trop + 8000)) * \\\n ((0.3 - 1.2)/(50000 - (alt_trop + 8000)))\n elif alt[i] >= 50000:\n amp[i] = 0.3\n else:\n raise ValueError('Invalid altitude')\n return amp\n\n\nclass AtmosphericTemperature(ErrorEstimation):\n # zero means surface\n levels_of_interest = [0, -10, -19]\n\n def averaging_kernel(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None):\n assert not type2\n if reconstructed is None:\n reconstructed = np.identity(covariance.nol)\n s_cov = self.assumed_covariance_temperature(event)\n return self.smoothing_error(original, reconstructed, s_cov)\n\n def noise_matrix(self, event: int, original: np.ndarray, reconstructed: np.ndarray, covariance: Covariance, type2=False, avk=None):\n assert not type2\n if reconstructed is None:\n return original\n else:\n return np.absolute(original - reconstructed)\n"
] |
[
[
"numpy.absolute",
"pandas.read_csv",
"numpy.allclose",
"numpy.isnan",
"numpy.ndarray",
"pandas.DataFrame",
"sklearn.model_selection.ParameterGrid",
"numpy.identity",
"numpy.exp",
"numpy.ma.is_masked",
"numpy.isinf",
"numpy.zeros"
]
] |
matias-seer/seer-py
|
[
"fbb018e683817d108f2e1ee3162680de06ce110c",
"fbb018e683817d108f2e1ee3162680de06ce110c"
] |
[
"tests/test_seerpy.py",
"seerpy/utils.py"
] |
[
"# Copyright 2017,2018 Seer Medical Pty Ltd, Inc. or its affiliates. All Rights Reserved.\n\nimport json\nimport pathlib\nfrom unittest import mock\n\nimport pytest\nimport pandas as pd\n\nfrom seerpy.seerpy import SeerConnect\n\n\n# having a class is useful to allow patches to be shared across mutliple test functions, but then\n# pylint complains that the methods could be a function. this disables that warning.\n# pylint:disable=no-self-use\n\n# not really a problem for these test classes\n# pylint:disable=too-few-public-methods\n\n\nTEST_DATA_DIR = pathlib.Path(__file__).parent / \"test_data\"\n\n\[email protected]('seerpy.seerpy.SeerAuth', autospec=True)\nclass TestSeerConnect:\n\n def test_success(self, seer_auth):\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n result = SeerConnect()\n\n assert result.graphql_client\n\n def test_login_unauthorized(self, seer_auth):\n seer_auth.return_value.cookie = None\n\n # not really desired behaviour, just documenting current behaviour\n with pytest.raises(AttributeError):\n SeerConnect()\n\n def test_login_error(self, seer_auth):\n seer_auth.side_effect = InterruptedError('Authentication Failed')\n\n with pytest.raises(InterruptedError):\n SeerConnect()\n\n\[email protected](SeerConnect, \"get_all_study_metadata_by_ids\", autospec=True)\[email protected](SeerConnect, \"__init__\", autospec=True, return_value=None)\nclass TestGetAllStudyMetaDataDataframeByIds:\n\n # as we don't rely on anything in __init() I have mocked it for simplicity\n\n def test_single_study(self, unused_seer_connect_init, get_all_metadata):\n # setup\n with open(TEST_DATA_DIR / \"study1_metadata.json\", \"r\") as f:\n test_input = json.load(f)\n get_all_metadata.return_value = {'studies': [test_input['study']]}\n\n expected_result = pd.read_csv(TEST_DATA_DIR / \"study1_metadata.csv\", index_col=0)\n\n # run test\n result = SeerConnect().get_all_study_metadata_dataframe_by_ids()\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result)\n\n def test_four_studies(self, unused_seer_connect_init, get_all_metadata):\n # setup\n studies = []\n for i in range(1, 5):\n filename = \"study\" + str(i) + \"_metadata.json\"\n with open(TEST_DATA_DIR / filename, \"r\") as f:\n studies.append(json.load(f)['study'])\n\n get_all_metadata.return_value = {'studies': studies}\n\n expected_result = pd.read_csv(TEST_DATA_DIR / \"studies1-4_metadata.csv\", index_col=0)\n\n # run test\n result = SeerConnect().get_all_study_metadata_dataframe_by_ids()\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result)\n\n\[email protected]('time.sleep', return_value=None)\[email protected]('seerpy.seerpy.GQLClient', autospec=True)\[email protected]('seerpy.seerpy.SeerAuth', autospec=True)\nclass TestGetAllStudyMetaDataByNames:\n\n def test_no_study_param(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n\n # this is the call in get_studies()\n with open(TEST_DATA_DIR / \"studies.json\", \"r\") as f:\n side_effects.append({'studies': json.load(f)})\n # this is the \"no more data\" response for get_studies()\n side_effects.append({'studies': []})\n\n # these are the calls from the loop in get_all_study_metadata_by_ids()\n expected_results = []\n for i in range(1, 5):\n filename = \"study\" + str(i) + \"_metadata.json\"\n with open(TEST_DATA_DIR / filename, \"r\") as f:\n study = json.load(f)\n side_effects.append(study)\n expected_results.append(study['study'])\n\n gql_client.return_value.execute.side_effect = side_effects\n\n # run test\n result = SeerConnect().get_all_study_metadata_by_names()\n\n # check result\n assert result == {'studies' : expected_results}\n\n def test_existing_study_param(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n\n # this is the call in get_studies()\n with open(TEST_DATA_DIR / \"studies.json\", \"r\") as f:\n side_effects.append({'studies': json.load(f)})\n # this is the \"no more data\" response for get_studies()\n side_effects.append({'studies': []})\n\n # these are the calls from the loop in get_all_study_metadata_by_ids()\n expected_results = []\n with open(TEST_DATA_DIR / \"study1_metadata.json\", \"r\") as f:\n study = json.load(f)\n side_effects.append(study)\n expected_results = [study['study']]\n\n gql_client.return_value.execute.side_effect = side_effects\n\n # run test\n result = SeerConnect().get_all_study_metadata_by_names(\"Study 1\")\n\n # check result\n assert result == {'studies' : expected_results}\n\n def test_nonexistent_study_param(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n\n # this is the call in get_studies()\n with open(TEST_DATA_DIR / \"studies.json\", \"r\") as f:\n side_effects.append({'studies': json.load(f)})\n # this is the \"no more data\" response for get_studies()\n side_effects.append({'studies': []})\n\n gql_client.return_value.execute.side_effect = side_effects\n\n # run test\n result = SeerConnect().get_all_study_metadata_by_names(\"Study 12\")\n\n # check result\n assert result == {'studies' : []}\n # the only call will be in getStudies()\n assert gql_client.return_value.execute.call_count == 2\n\n\[email protected]('time.sleep', return_value=None)\[email protected]('seerpy.seerpy.GQLClient', autospec=True)\[email protected]('seerpy.seerpy.SeerAuth', autospec=True)\nclass TestGetSegmentUrls:\n\n def test_success(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n with open(TEST_DATA_DIR / \"segment_urls_1.json\", \"r\") as f:\n gql_client.return_value.execute.return_value = json.load(f)\n\n expected_result = pd.read_csv(TEST_DATA_DIR / \"segment_urls_1.csv\", index_col=0)\n\n # run test\n result = SeerConnect().get_segment_urls([\"segment-1-id\", \"segment-2-id\"])\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result)\n\n def test_multiple_batches(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n for file_name in [\"segment_urls_1.json\", \"segment_urls_2.json\"]:\n with open(TEST_DATA_DIR / file_name, \"r\") as f:\n side_effects.append(json.load(f))\n gql_client.return_value.execute.side_effect = side_effects\n\n expected_result = pd.read_csv(TEST_DATA_DIR / \"segment_urls_2.csv\", index_col=0)\n\n # run test\n result = SeerConnect().get_segment_urls([\"segment-1-id\", \"segment-2-id\", \"segment-3-id\",\n \"segment-4-id\"], 2)\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result)\n\n def test_none_segment_ids(self, seer_auth, unused_gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n expected_result = pd.read_csv(TEST_DATA_DIR / \"segment_urls_empty.csv\", index_col=0)\n\n # run test\n result = SeerConnect().get_segment_urls(None)\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result)\n\n def test_empty_segment_ids(self, seer_auth, unused_gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n # gql_client is never called as we don't enter the loop\n\n # run test\n result = SeerConnect().get_segment_urls([])\n\n # check result\n assert result.empty\n\n def test_unmatched_segment_ids(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n with open(TEST_DATA_DIR / \"segment_urls_no_match.json\", \"r\") as f:\n gql_client.return_value.execute.return_value = json.load(f)\n\n # run test\n result = SeerConnect().get_segment_urls([\"blah\", \"blah1\"])\n\n # check result\n assert result.empty\n\n\[email protected]('time.sleep', return_value=None)\[email protected]('seerpy.seerpy.GQLClient', autospec=True)\[email protected]('seerpy.seerpy.SeerAuth', autospec=True)\nclass TestGetLabels:\n\n def test_success(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n\n with open(TEST_DATA_DIR / \"labels_1.json\", \"r\") as f:\n side_effects.append(json.load(f))\n with open(TEST_DATA_DIR / \"labels_2.json\", \"r\") as f:\n side_effects.append(json.load(f))\n # this is the \"no more data\" response for get_labels()\n with open(TEST_DATA_DIR / \"labels_1_empty.json\", \"r\") as f:\n side_effects.append(json.load(f))\n\n gql_client.return_value.execute.side_effect = side_effects\n\n with open(TEST_DATA_DIR / \"labels_result.json\", \"r\") as f:\n expected_result = json.load(f)\n\n # run test\n result = SeerConnect().get_labels(\"study-1-id\", \"label-group-1-id\")\n\n # check result\n assert result == expected_result\n\n\[email protected]('time.sleep', return_value=None)\[email protected]('seerpy.seerpy.GQLClient', autospec=True)\[email protected]('seerpy.seerpy.SeerAuth', autospec=True)\nclass TestGetLabelsDataframe:\n\n def test_success(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n\n with open(TEST_DATA_DIR / \"labels_1.json\", \"r\") as f:\n side_effects.append(json.load(f))\n with open(TEST_DATA_DIR / \"labels_2.json\", \"r\") as f:\n side_effects.append(json.load(f))\n # this is the \"no more data\" response for get_labels()\n with open(TEST_DATA_DIR / \"labels_1_empty.json\", \"r\") as f:\n side_effects.append(json.load(f))\n\n gql_client.return_value.execute.side_effect = side_effects\n\n expected_result = pd.read_csv(TEST_DATA_DIR / \"labels_1.csv\", index_col=0)\n\n # run test\n result = SeerConnect().get_labels_dataframe(\"study-1-id\", \"label-group-1-id\")\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result)\n\n\[email protected]('time.sleep', return_value=None)\[email protected]('seerpy.seerpy.GQLClient', autospec=True)\[email protected]('seerpy.seerpy.SeerAuth', autospec=True)\nclass TestGetViewedTimesDataframe:\n\n def test_success(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n\n with open(TEST_DATA_DIR / \"view_groups.json\", \"r\") as f:\n side_effects.append(json.load(f))\n # this is the \"no more data\" response for get_viewed_times_dataframe()\n with open(TEST_DATA_DIR / \"view_groups_empty.json\", \"r\") as f:\n side_effects.append(json.load(f))\n\n gql_client.return_value.execute.side_effect = side_effects\n\n # need to set parse_dates and float_precision='round_trip' to make the comparison work\n expected_result = pd.read_csv(TEST_DATA_DIR / \"views.csv\", index_col=0,\n parse_dates=['createdAt', 'updatedAt'],\n float_precision='round_trip')\n\n # run test\n result = SeerConnect().get_viewed_times_dataframe(\"study-1-id\")\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result)\n\n\[email protected]('time.sleep', return_value=None)\[email protected]('seerpy.seerpy.GQLClient', autospec=True)\[email protected]('seerpy.seerpy.SeerAuth', autospec=True)\nclass TestGetDocumentsForStudiesDataframe:\n\n def test_success(self, seer_auth, gql_client, unused_time_sleep):\n # setup\n seer_auth.return_value.cookie = {'seer.sid': \"cookie\"}\n\n side_effects = []\n\n with open(TEST_DATA_DIR / \"study_documents.json\", \"r\") as f:\n side_effects.append(json.load(f))\n # # this is the \"no more data\" response for get_documents_for_studies_dataframe()\n with open(TEST_DATA_DIR / \"study_documents_empty.json\", \"r\") as f:\n side_effects.append(json.load(f))\n side_effects.append({'studies': []}) # this is the \"no more data\" response for get_studies()\n\n gql_client.return_value.execute.side_effect = side_effects\n\n # need to set parse_dates and float_precision='round_trip' to make the comparison work\n expected_result = pd.read_csv(TEST_DATA_DIR / \"study_documents.csv\", index_col=0,\n parse_dates=['uploaded'],\n float_precision='round_trip')\n expected_result['uploaded'] = expected_result['uploaded'].astype(int)\n\n # run test\n result = SeerConnect().get_documents_for_studies_dataframe(\"study-1-id\")\n\n # check result\n pd.testing.assert_frame_equal(result, expected_result, check_like=True)",
"# Copyright 2017 Seer Medical Pty Ltd, Inc. or its affiliates. All Rights Reserved.\n\nimport functools\nimport gzip\nfrom multiprocessing import Pool\nimport os\n\nfrom matplotlib.collections import LineCollection\nfrom matplotlib import gridspec\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom scipy.signal import butter, sosfilt\n\n\n# pylint:disable=too-many-locals,too-many-statements\ndef download_channel_data(data_q, download_function):\n meta_data, study_id, channel_groups_id, segments_id, channel_names = data_q\n try:\n raw_data = download_function(meta_data['dataChunks.url'])\n data = raw_data.content\n\n try:\n if meta_data['channelGroups.compression'] == 'gzip':\n data = gzip.decompress(data)\n except OSError:\n pass\n\n data_type = meta_data['channelGroups.sampleEncoding']\n data = np.frombuffer(data, dtype=np.dtype(data_type))\n data = data.astype(np.float32)\n data = data.reshape(-1, len(channel_names),\n int(meta_data['channelGroups.samplesPerRecord']))\n data = np.transpose(data, (0, 2, 1))\n data = data.reshape(-1, data.shape[2])\n if 'int' in data_type:\n nan_mask = np.all(data == np.iinfo(np.dtype(data_type)).min, axis=1)\n if nan_mask[-1]:\n nan_mask_corrected = np.ones(nan_mask.shape, dtype=bool)\n for i in range(len(nan_mask) - 1, -1, -1):\n if nan_mask[i]:\n nan_mask_corrected[i] = False\n else:\n break\n data = data[nan_mask_corrected]\n\n # fill missing values with nans\n data[np.all(data == np.iinfo(np.dtype(data_type)).min, axis=1), :] = np.nan\n ## TODO: what happens for floats?\n chan_min = meta_data['channelGroups.signalMin'].astype(np.float64)\n chan_max = meta_data['channelGroups.signalMax'].astype(np.float64)\n exponent = meta_data['channelGroups.exponent'].astype(np.float64)\n if 'int' in data_type:\n chan_diff = chan_max - chan_min\n dig_min = np.iinfo(data_type).min\n dig_max = np.iinfo(data_type).max\n dig_diff = abs(dig_min) + abs(dig_max)\n\n with np.errstate(divide='ignore', invalid='ignore'):\n data = (data - dig_min) / dig_diff * chan_diff + chan_min\n\n data = data * 10.0 ** exponent\n data = pd.DataFrame(data=data, index=None, columns=channel_names)\n data = data.fillna(method='ffill', axis='columns')\n data = data.fillna(method='bfill', axis='columns')\n data = data.fillna(value=0., axis='columns')\n data['time'] = (np.arange(data.shape[0]) * (1000.0 / meta_data['channelGroups.sampleRate'])\n + meta_data['dataChunks.time'])\n data['id'] = study_id\n data['channelGroups.id'] = channel_groups_id\n data['segments.id'] = segments_id\n data = data[['time', 'id', 'channelGroups.id', 'segments.id'] + channel_names]\n return data\n except Exception as ex:\n print(ex)\n print(study_id)\n print(channel_names)\n print(meta_data['dataChunks.url'])\n print('{0:.2f}'.format(meta_data['dataChunks.time']))\n print(meta_data)\n try:\n print(raw_data.headers)\n except Exception as ex: # pylint: disable=broad-except\n pass\n raise\n\n\n# pylint:disable=too-many-locals\ndef create_data_chunk_urls(metadata, segment_urls, from_time=0, to_time=9e12):\n chunk_pattern = '00000000000.dat'\n\n data_chunks = []\n metadata = metadata.drop_duplicates('segments.id').reset_index(drop=True)\n for index in range(len(metadata.index)):\n row = metadata.iloc[index]\n\n seg_base_urls = segment_urls.loc[segment_urls['segments.id'] == row['segments.id'],\n 'baseDataChunkUrl']\n if seg_base_urls.empty:\n continue\n seg_base_url = seg_base_urls.iloc[0]\n\n chunk_period = row['channelGroups.chunkPeriod']\n num_chunks = int(np.ceil(row['segments.duration'] / chunk_period / 1000.))\n start_time = row['segments.startTime']\n\n for i in range(num_chunks):\n chunk_start_time = chunk_period * 1000 * i + start_time\n next_chunk_start_time = chunk_period * 1000 * (i + 1) + start_time\n if (chunk_start_time <= to_time and next_chunk_start_time >= from_time):\n data_chunk_name = str(i).zfill(len(chunk_pattern) - 4) + chunk_pattern[-4:]\n data_chunk_url = seg_base_url.replace(chunk_pattern, data_chunk_name)\n data_chunk = [row['segments.id'], data_chunk_url, chunk_start_time]\n data_chunks.append(data_chunk)\n\n return pd.DataFrame.from_records(data_chunks, columns=['segments.id', 'dataChunks.url',\n 'dataChunks.time'])\n\n\n# pylint:disable=too-many-locals\ndef get_channel_data(all_data, segment_urls, # pylint:disable=too-many-arguments\n download_function=requests.get, threads=None, from_time=0, to_time=9e12):\n \"\"\"Download data chunks and stich them together in one dataframe\n\n Parameters\n ----------\n all_data : pandas DataFrame\n metadata required for downloading and processing raw data\n segment_urls : pandas DataFrame\n columns=['segments.id', 'baseDataChunkUrl']\n download_function: function\n the function used to download the channel data. defaults to requests.get\n threads : int\n number of threads to use. If > 1 then will use multiprocessing\n if None (default), it will use 1 on Windows and 5 on Linux/MacOS\n\n Returns\n -------\n data : pandas DataFrame\n dataframe containing studyID, channelGroupIDs, semgmentIDs, time, and raw data\n\n Example\n -------\n data = get_channel_data(all_data, segment_urls)\n\n \"\"\"\n if threads is None:\n if os.name == 'nt':\n threads = 1\n else:\n threads = 5\n\n segment_ids = all_data['segments.id'].drop_duplicates().tolist()\n\n data_q = []\n data_list = []\n\n for segment_id in segment_ids:\n metadata = all_data[all_data['segments.id'].values == segment_id]\n actual_channel_names = get_channel_names_or_ids(metadata)\n metadata = metadata.drop_duplicates('segments.id')\n\n study_id = metadata['id'].iloc[0]\n channel_groups_id = metadata['channelGroups.id'].iloc[0]\n\n data_chunks = create_data_chunk_urls(metadata, segment_urls, from_time=from_time,\n to_time=to_time)\n metadata = metadata.merge(data_chunks, how='left', left_on='segments.id',\n right_on='segments.id', suffixes=('', '_y'))\n\n metadata = metadata[['dataChunks.url', 'dataChunks.time', 'channelGroups.sampleEncoding',\n 'channelGroups.sampleRate', 'channelGroups.samplesPerRecord',\n 'channelGroups.recordsPerChunk', 'channelGroups.compression',\n 'channelGroups.signalMin', 'channelGroups.signalMax',\n 'channelGroups.exponent']]\n metadata = metadata.drop_duplicates()\n metadata = metadata.dropna(axis=0, how='any', subset=['dataChunks.url'])\n for i in range(len(metadata.index)):\n data_q.append([metadata.iloc[i], study_id, channel_groups_id, segment_id,\n actual_channel_names])\n\n download_function = functools.partial(download_channel_data,\n download_function=download_function)\n if data_q:\n if threads > 1:\n pool = Pool(processes=min(threads, len(data_q) + 1))\n data_list = list(pool.map(download_function, data_q))\n pool.close()\n pool.join()\n else:\n data_list = [download_function(data_q_item) for data_q_item in data_q]\n\n if data_list:\n # sort=False to silence deprecation warning. This comes into play when we are processing\n # segments across multiple channel groups which have different channels.\n data = pd.concat(data_list, sort=False)\n data = data.loc[(data['time'] >= from_time) & (data['time'] < to_time)]\n data = data.sort_values(['id', 'channelGroups.id', 'time'], axis=0,\n ascending=True, na_position='last')\n data = data.reset_index(drop=True)\n else:\n data = None\n\n return data\n\n\ndef get_channel_names_or_ids(metadata):\n \"\"\"Get a list of unique channel names, or ids where name is null or duplicated.\n\n Parameters\n ----------\n metadata : pandas DataFrame\n a dataframe containing a 'channels.name' and 'channels.id' column\n\n Returns\n -------\n actual_channel_names : list\n a list of unique channels names or ids.\n \"\"\"\n actual_channel_names = []\n unique_ids = metadata.drop_duplicates(subset='channels.id')\n name_value_counts = unique_ids['channels.name'].value_counts()\n for index in range(len(unique_ids.index)):\n row = unique_ids.iloc[index]\n channel_name = row['channels.name']\n if not channel_name or name_value_counts[channel_name] > 1:\n actual_channel_names.append(row['channels.id'])\n else:\n actual_channel_names.append(channel_name)\n return actual_channel_names\n\n\n# pylint:disable=too-many-locals\ndef plot_eeg(x, y=None, pred=None, squeeze=5.0, scaling_factor=None):\n if not isinstance(x, np.ndarray):\n x = np.asarray(x)\n\n if len(x.shape) < 2:\n x = x.reshape(-1, 1)\n\n channels = x.shape[1]\n x = np.flip(x, axis=1)\n has_pred = 1 if pred is not None else 0\n grid_spec = gridspec.GridSpec(2, 1, height_ratios=[channels, 1])\n ticks = np.arange(x.shape[0]).astype(np.float32)\n fig = plt.figure(figsize=(14, (channels + has_pred) * 2))\n fig.tight_layout()\n ticklocs = []\n ax2 = fig.add_subplot(grid_spec[0])\n if scaling_factor is None:\n scaling_factor = np.nanmedian(np.abs(x)) * squeeze # Crowd them a bit.\n y_bottom = -scaling_factor # pylint: disable=invalid-unary-operand-type\n y_top = (channels) * scaling_factor\n ax2.set_ylim(y_bottom, y_top)\n ax2.set_xlim(ticks.min(), ticks.max())\n\n segs = []\n for i in range(channels):\n segs.append(np.hstack((ticks[:, np.newaxis], x[:, i, np.newaxis])))\n ticklocs.append(i * scaling_factor)\n\n offsets = np.zeros((channels, 2), dtype=float)\n offsets[:, 1] = ticklocs\n\n lines = LineCollection(segs, offsets=offsets, transOffset=None, linewidths=(0.5))\n ax2.add_collection(lines)\n\n if y is not None:\n if len(y.shape) > 1:\n for i in range(y.shape[-1]):\n y_ticks = ticks.copy()\n y_ticks[y[:, i].reshape(-1) == 0] = np.nan\n ax2.fill_between(y_ticks, -1000, 1000, alpha=0.1)\n else:\n ticks[y == 0] = np.nan\n ax2.fill_between(ticks, -1000, 1000, alpha=0.1)\n\n if pred is not None:\n ax3 = fig.add_subplot(grid_spec[1])\n ax3.set_ylim(0, 1)\n ax3.fill_between(np.arange(len(pred)) * 10, 0, pred, alpha=0.6)\n\n plt.tight_layout()\n return plt\n\n\ndef butter_bandstop(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n sos = butter(order, [low, high], analog=False, btype='bandstop', output='sos')\n return sos\n\n\ndef butter_bandstop_filter(data, lowcut, highcut, fs, order=5):\n sos = butter_bandstop(lowcut, highcut, fs, order=order)\n y = sosfilt(sos, data)\n return y\n\n\ndef butter_bandpass(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n sos = butter(order, [low, high], analog=False, btype='bandpass', output='sos')\n return sos\n\n\ndef butter_bandpass_filter(data, lowcut, highcut, fs, order=5):\n sos = butter_bandpass(lowcut, highcut, fs, order=order)\n y = sosfilt(sos, data)\n return y\n"
] |
[
[
"pandas.read_csv",
"pandas.testing.assert_frame_equal"
],
[
"scipy.signal.sosfilt",
"numpy.asarray",
"pandas.DataFrame",
"numpy.dtype",
"numpy.iinfo",
"pandas.DataFrame.from_records",
"numpy.hstack",
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"numpy.ceil",
"scipy.signal.butter",
"matplotlib.gridspec.GridSpec",
"numpy.zeros",
"matplotlib.pyplot.figure",
"pandas.concat",
"matplotlib.collections.LineCollection",
"numpy.transpose",
"numpy.errstate",
"numpy.flip",
"numpy.abs",
"numpy.ones"
]
] |
liespace/pyRRTs
|
[
"11bfefad99218bc9eccd97040355c61d34a1181d"
] |
[
"test/test_planner.py"
] |
[
"#!/usr/bin/env python\nfrom copy import deepcopy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nfrom matplotlib.patches import Polygon\nfrom rrts import BiRRTStar, RRTStar\nfrom rrts.debugger import Debugger\n\n\ndef center2rear(node, wheelbase=2.96):\n \"\"\"calculate the coordinate of rear track center according to mass center\"\"\"\n if not isinstance(node, RRTStar.StateNode):\n theta, r = node[2] + np.pi, wheelbase / 2.\n node[0] += r * np.cos(theta)\n node[1] += r * np.sin(theta)\n return node\n theta, r = node.state[2] + np.pi, wheelbase / 2.\n node.state[0] += r * np.cos(theta)\n node.state[1] += r * np.sin(theta)\n return node\n\n\ndef contour(wheelbase=2.96, width=2.0, length=5.0): # 2.96, 2.2, 5.0\n return np.array([\n [-(length/2. - wheelbase / 2.), width/2. - 1.0], [-(length/2. - wheelbase / 2. - 0.4), width/2.],\n [length/2. + wheelbase / 2. - 0.6, width/2.], [length/2. + wheelbase / 2., width/2. - 0.8],\n [length/2. + wheelbase / 2., -(width/2. - 0.8)], [length/2. + wheelbase / 2. - 0.6, -width/2.],\n [-(length/2. - wheelbase / 2. - 0.4), -width/2.], [-(length/2. - wheelbase / 2.), -(width/2. - 1.0)]])\n\n\ndef read_task(filepath, seq=0):\n \"\"\"\n read source(start) and target(goal), and transform to right-hand and local coordinate system centered in source\n LCS: local coordinate system, or said vehicle-frame.\n GCS: global coordinate system\n \"\"\"\n # read task and transform coordinate system to right-hand\n task = np.loadtxt('{}/{}_task.txt'.format(filepath, seq), delimiter=',')\n org, aim = task[0], task[1]\n # coordinate of the center of mass on source(start) state, in GCS\n source = RRTStar.StateNode(state=(org[0], -org[1], -np.radians(org[3])))\n # coordinate of center of mass on target(goal) state, in GCS\n target = RRTStar.StateNode(state=(aim[0], -aim[1], -np.radians(aim[3])))\n return source, target\n\n\ndef read_grid(filepath, seq):\n # type: (str, int) -> np.ndarray\n \"\"\"read occupancy grid map\"\"\"\n return cv2.imread(filename='{}/{}_gridmap.png'.format(filepath, seq), flags=-1)\n\n\ndef read_ose(filepath, seq):\n \"\"\"read heuristic ose\"\"\"\n oseh = np.loadtxt('{}/{}_ose.txt'.format(filepath, seq), delimiter=',')\n oseh = [((x[0], x[1], x[2]), ((0., x[3]/3.), (0., x[3]/3.), (0., x[3]/3. * np.pi/3./3.))) for x in oseh]\n return oseh\n\n\ndef read_yips(filepath, seq, discrimination=0.7):\n yips = np.loadtxt('{}/{}_pred.txt'.format(filepath, seq), delimiter=',')\n yips = filter(lambda x: x[-1] > discrimination, yips)\n yips = map(center2rear, yips)\n yips = [((yip[0], yip[1], yip[2]), ((0.621, 2.146), (0.015, 1.951 * 1.0), (0.005, 0.401 * 1.0))) for yip in yips]\n return yips\n\n\ndef set_plot(switch=True):\n if switch:\n plt.ion()\n plt.figure()\n plt.gca().set_xticks([])\n plt.gca().set_yticks([])\n plt.gca().set_aspect('equal')\n plt.gca().set_facecolor((0.2, 0.2, 0.2))\n plt.gca().set_xlim((-30, 30))\n plt.gca().set_ylim((-30, 30))\n plt.draw()\n\n\ndef transform(pts, pto):\n xyo = np.array([[pto[0]], [pto[1]]])\n rot = np.array([[np.cos(pto[2]), -np.sin(pto[2])], [np.sin(pto[2]), np.cos(pto[2])]])\n return np.dot(rot, pts) + xyo\n\n\ndef main():\n filepath, seq, debug = './test_scenes', 2062, True\n rrt_star = BiRRTStar().set_vehicle(contour(), 0.3, 0.25)\n # heuristic = read_ose(filepath, seq)\n # heuristic = read_yips(filepath, seq)\n heuristic = None\n source, target = read_task(filepath, seq)\n start = center2rear(deepcopy(source)).gcs2lcs(source.state)\n goal = center2rear(deepcopy(target)).gcs2lcs(source.state)\n grid_ori = deepcopy(source).gcs2lcs(source.state)\n grid_map = read_grid(filepath, seq)\n grid_res = 0.1\n\n if debug:\n set_plot(debug)\n Debugger.plot_grid(grid_map, grid_res)\n Debugger().plot_nodes([start, goal])\n plt.gca().add_patch(Polygon(\n transform(contour().transpose(), start.state).transpose(), True, color='b', fill=False, lw=2.0))\n plt.gca().add_patch(Polygon(\n transform(contour().transpose(), goal.state).transpose(), True, color='g', fill=False, lw=2.0))\n if heuristic:\n Debugger.plot_heuristic(heuristic)\n plt.draw()\n rrt_star.debug = debug\n rrt_star.preset(start, goal, grid_map, grid_res, grid_ori, 255, heuristic).planning(100, debug=debug)\n\n Debugger.breaker('Plotting', switch=debug)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.dot",
"matplotlib.pyplot.gca",
"numpy.radians",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.draw",
"numpy.array",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.figure"
]
] |
LouisFaure/simpleppt
|
[
"466c73fc64b9c4e3bf14b2c46c11d69de31c8a9b"
] |
[
"simpleppt/SimplePPT.py"
] |
[
"from typing import Any, Union, Optional, Mapping, Iterable # Meta\nfrom typing import Mapping\nimport numpy as np\nimport igraph\nfrom sklearn.metrics import pairwise_distances\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse.csgraph import shortest_path\nimport pandas as pd\nimport itertools\n\n\nclass SimplePPT:\n \"\"\"A python object containing the data used for dynamical tracks analysis.\n\n Parameters\n ----------\n\n F\n coordinates of principal points in the learned space.\n R\n soft assignment of datapoints to principal points.\n B\n adjacency matrix of the principal points.\n L\n Laplacian matrix.\n d\n Pairwise distance matrix of principal points.\n score\n Score minimized during the tree learning.\n tips\n Node IDs of the tree that have degree 1.\n forks\n Node IDs of the tree that have a degree of more than 1.\n root\n Selected node ID as the root of the tree for distance calculations.\n pp_info\n Per node ID info of distance from the root, and segment assigment.\n pp_seg\n Per segment info with node ID extremities and distance.\"\"\"\n\n def __init__(\n self,\n F: np.array,\n R: np.array,\n B: np.array,\n L: np.array,\n d: np.array,\n score: float,\n lam: float,\n sigma: float,\n nsteps: int,\n metric: str,\n tips: Optional[Union[Iterable, None]] = None,\n forks: Optional[Union[Iterable, None]] = None,\n root: Optional[Union[int, None]] = None,\n pp_info: Optional[Union[pd.DataFrame]] = None,\n pp_seg: Optional[Union[pd.DataFrame]] = None,\n ):\n\n self.F = F\n self.R = R\n self.B = B\n self.L = L\n self.d = d\n self.score = score\n self.lam = lam\n self.sigma = sigma\n self.nsteps = nsteps\n self.metric = metric\n self.tips = tips\n self.forks = forks\n\n def __repr__(self):\n dt, nd = self.R.shape\n descr = f\"SimplePPT object of {nd} nodes approximating {dt} datapoints\"\n return descr\n\n def set_tips_forks(self):\n \"\"\"Obtains the tips and forks of the tree.\n\n Returns\n -------\n adds to SimplePPT object the following fields: :class:`simpleppt.SimplePPT`\n\n `.tips`\n Node IDs of the tree that have degree 1..\n `.forks`\n Node IDs of the tree that have a degree of more than 1.\n\n \"\"\"\n g = igraph.Graph.Adjacency((self.B > 0).tolist(), mode=\"undirected\")\n self.tips = np.argwhere(np.array(g.degree()) == 1).flatten()\n self.forks = np.argwhere(np.array(g.degree()) > 2).flatten()\n\n def set_branches(self, root=None):\n \"\"\"Assign branches/segments to nodes.\n\n Returns\n -------\n adds to SimplePPT object the following fields: :class:`simpleppt.SimplePPT`\n\n `.pp_info`\n Per node ID info of distance from the root, and segment assigment.\n `.pp_seg`\n Per segment info with node ID extremities and distance.\n \"\"\"\n root = self.tips[0] if root is None else root\n d = 1e-6 + pairwise_distances(self.F.T, self.F.T, metric=self.metric)\n\n to_g = self.B * d\n\n csr = csr_matrix(to_g)\n\n g = igraph.Graph.Adjacency((to_g > 0).tolist(), mode=\"undirected\")\n g.es[\"weight\"] = to_g[to_g.nonzero()]\n\n root_dist_matrix = shortest_path(csr, directed=False, indices=root)\n pp_info = pd.DataFrame(\n {\n \"PP\": g.vs.indices,\n \"dist\": root_dist_matrix,\n \"seg\": np.zeros(csr.shape[0]),\n }\n )\n\n nodes = np.argwhere(\n np.apply_along_axis(arr=(csr > 0).todense(), axis=0, func1d=np.sum) != 2\n ).flatten()\n nodes = np.unique(np.append(nodes, root))\n\n pp_seg = pd.DataFrame(columns=[\"n\", \"from\", \"to\", \"d\"])\n for node1, node2 in itertools.combinations(nodes, 2):\n paths12 = g.get_shortest_paths(node1, node2)\n paths12 = np.array([val for sublist in paths12 for val in sublist])\n\n if np.sum(np.isin(nodes, paths12)) == 2:\n fromto = np.array([node1, node2])\n path_root = root_dist_matrix[[node1, node2]]\n fro = fromto[np.argmin(path_root)]\n to = fromto[np.argmax(path_root)]\n pp_info.loc[paths12, \"seg\"] = pp_seg.shape[0] + 1\n pp_seg = pp_seg.append(\n pd.DataFrame(\n {\n \"n\": pp_seg.shape[0] + 1,\n \"from\": fro,\n \"to\": to,\n \"d\": shortest_path(csr, directed=False, indices=fro)[to],\n },\n index=[pp_seg.shape[0] + 1],\n )\n )\n\n pp_seg[\"n\"] = pp_seg[\"n\"].astype(int).astype(str)\n pp_seg[\"n\"] = pp_seg[\"n\"].astype(int).astype(str)\n\n pp_seg[\"from\"] = pp_seg[\"from\"].astype(int)\n pp_seg[\"to\"] = pp_seg[\"to\"].astype(int)\n\n pp_info[\"seg\"] = pp_info[\"seg\"].astype(int).astype(str)\n pp_info[\"seg\"] = pp_info[\"seg\"].astype(int).astype(str)\n\n self.pp_info = pp_info\n self.pp_seg = pp_seg\n self.root = root\n"
] |
[
[
"sklearn.metrics.pairwise_distances",
"scipy.sparse.csgraph.shortest_path",
"scipy.sparse.csr_matrix",
"pandas.DataFrame",
"numpy.append",
"numpy.argmax",
"numpy.argmin",
"numpy.array",
"numpy.zeros",
"numpy.isin"
]
] |
onl1ner/django-image-classifier
|
[
"6bb0726fbd61bb60bd245356ca85d7030ced131e"
] |
[
"imageclassifierapp/services/classifier.py"
] |
[
"import os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom PIL import Image\n\nfrom django.conf import settings\n\nfrom keras.preprocessing import image\nfrom keras.models import load_model\n\nclass Classifier:\n IMG_SIZE = (32, 32)\n\n LABELS = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n\n def __init__(self, image):\n self.image = image\n\n def classify(self):\n resized_img = self.image.resize(self.IMG_SIZE, Image.ANTIALIAS)\n img_array = image.img_to_array(resized_img)\n\n data = np.expand_dims(img_array, axis = 0)\n\n file = os.path.join(settings.BASE_DIR, 'model/model.h5')\n model = load_model(file)\n \n prediction = model.predict(data)\n label_index = np.argmax(prediction, axis = 1)[0]\n\n return self.LABELS[label_index]\n\n pass"
] |
[
[
"numpy.expand_dims",
"numpy.argmax"
]
] |
shenyuanv/powerAnalysis
|
[
"8ebd4c9ad79c1bfe7ac13008fe39a74b00d64805"
] |
[
"analyseUsage.py"
] |
[
"import sys\nimport sqlite3\nfrom datetime import datetime\nfrom datetime import timedelta\nimport numpy as np\nimport argparse\nfrom collections import namedtuple\n\ndef contiguous_regions(condition):\n d = np.diff(condition)\n idx, = d.nonzero() \n\n idx += 1\n\n if condition[0]:\n idx = np.r_[0, idx]\n\n if condition[-1]:\n idx = np.r_[idx, condition.size]\n\n idx.shape = (-1,2)\n return idx\n\n\ndef valid_date(s):\n try:\n return datetime.strptime(s, \"%Y-%m-%d %H:%M\")\n except ValueError:\n msg = \"Not a valid date: '{0}'.\".format(s)\n raise argparse.ArgumentTypeError(msg)\n\n\ndef extractSecondsActiveFromResultSet(rows, activeState):\n\tx = [datetime.fromtimestamp(row[0]) for row in rows]\n\ty = [row[1] for row in rows]\n\tcondition = np.abs(y) == activeState\n\n\tregions = contiguous_regions(condition)\n\tcount = timedelta(0)\n\n\tfor reg in regions:\n\t\ttimeOfRow = x[reg[0]];\n\t\n\t\tif (reg[1] < len(x)):\n\t\t\tcount += (x[reg[1]] - x[reg[0]])\n\treturn count.total_seconds()\n\ndef formatTimeDelta(timedelta):\n\thours, remainder = divmod(timedelta.total_seconds, 3600)\n\tminutes, seconds = divmod(remainder, 60) \n\treturn '%d:%02d:%02d' % (hours, minutes, seconds)\n\ndef main(argv):\n\tparser=argparse.ArgumentParser()\n\tparser.add_argument('inputFile')\n\tparser.add_argument('-s', \"--startDate\", help=\"The Start Date - format YYYY-MM-DD HH:MM\", required=False, type=valid_date)\n\tparser.add_argument('-e', \"--endDate\", help=\"The End Date - format YYYY-MM-DD HH:MM\", required=False, type=valid_date)\n\targs=parser.parse_args()\n\n\twhereClause = ''\n\n\tif args.startDate:\n\t\twhereClause = 'timestamp > {startDate} '.format(startDate = args.startDate.strftime('%s'))\n\n\tif args.endDate:\n\t\tif args.startDate:\n\t\t\twhereClause += ' AND '\n\t\twhereClause += ' timestamp < {endDate} '.format(endDate = args.endDate.strftime('%s')) \n\n\tdb = sqlite3.connect(argv[0])\n\tdb.row_factory = sqlite3.Row\n\tcursor = db.cursor()\n\n\tcursor.execute('''SELECT timestamp, Active \n\t\t\t\t\t\tFROM PLDisplayAgent_EventPoint_Display {whereClause} \n\t\t\t\t\t\tORDER BY timestamp'''.format(whereClause=('', 'WHERE {0}'.format(whereClause))[len(whereClause) > 0]))\n\n\tall_rows = cursor.fetchall()\n\tif len(all_rows):\n\t\tdisplayOnLength =extractSecondsActiveFromResultSet(all_rows, 1)\n\telse:\n\t\tdisplayOnLength = 0\n\n\tcursor.execute('''SELECT timestamp, state \n\t\t\t\t\t\t FROM PLSleepWakeAgent_EventForward_PowerState {whereClause} \n\t\t\t\t\t\t ORDER BY timestamp'''.format(whereClause=('', 'WHERE {0}'.format(whereClause))[len(whereClause) > 0]))\n\n\tall_rows = cursor.fetchall()\n\tif len(all_rows):\n\t\tdeviceOnLength =extractSecondsActiveFromResultSet(all_rows, 0)\n\telse:\n\t\tdeviceOnLength = 0\n\n\t(startTimeInData, endTimeInData) = (all_rows[0][0], all_rows[-1][0])\n\n\toverallBreakdown = '''<table class=\"table table-striped table-bordered display responsive\">\n\t\t\t\t\t\t\t\t\t<tbody>\n\t\t\t\t\t\t\t\t\t\t<tr><td>Display active for {0}</td></tr>\n\t\t\t\t\t\t\t\t\t\t<tr><td>Device active for {1}</td></tr>\n\t\t\t\t\t\t\t\t\t</tbody>\n\t\t\t\t\t\t\t\t</table>\n\t\t\t\t\t\t'''.format(str(timedelta(seconds=displayOnLength)),str(timedelta(seconds=deviceOnLength)))\n\n\t# App list\n\n\tcursor.execute('''SELECT AppName, AppBundleId, AppBundleVersion, AppIs3rdParty\n\t\t\t\t\t\tFROM PLApplicationAgent_EventNone_AllApps''')\n\n\tall_rows = cursor.fetchall()\n\t\n\tappListBody = ''\n\tfor row in all_rows:\n\t\tappListBody += '<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>\\n'.format(row[0], row[1], row[2])\n\t\n\tapplistBreakdown = '''<table id=\"applistBreakDown\" class=\"table table-striped table-condensed\">\n\t\t\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class=\"col-md-3\">App Name</td>\n\t\t\t\t\t\t\t\t\t<td>AppBundleId</td>\n\t\t\t\t\t\t\t\t\t<td>AppBundleVersion</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t\t\t<tbody>{appListBody}</tbody>\n\t\t\t\t\t\t\t</table>'''.format(appListBody = appListBody)\n\n\t# Per Process Timing\n\n\tcursor.execute('''SELECT processname, SUM(value) AS TotalTime \n\t\t\t\t\t\tFROM PLProcessMonitorAgent_EventInterval_ProcessMonitorInterval_Dynamic, PLProcessMonitorAgent_EventInterval_ProcessMonitorInterval \n\t\t\t\t\t\tWHERE PLProcessMonitorAgent_EventInterval_ProcessMonitorInterval.ID = PLProcessMonitorAgent_EventInterval_ProcessMonitorInterval_Dynamic.FK_ID\n\t\t\t\t\t\t\t {whereClause}\n\t\t\t\t\t \tGROUP BY processname \n\t\t\t\t\t \tORDER BY TotalTime DESC'''.format(whereClause=('', 'AND {0}'.format(whereClause))[len(whereClause) > 0]))\n\n\tall_rows = cursor.fetchall()\n\t\n\tperProcessBreakdownBody = ''\n\tfor row in all_rows:\n\t\tperProcessBreakdownBody += '<tr><td>{0}</td><td>{1}</td></tr>\\n'.format(row[0], row[1])\n\t\n\tperProcesssBreakdown = '''<table id=\"processBreakdown\" class=\"table table-striped table-condensed\">\n\t\t\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class=\"col-md-3\">Process Name</td>\n\t\t\t\t\t\t\t\t\t<td>Time (s)</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t\t\t<tbody>{perProcessBreakdownBody}</tbody>\n\t\t\t\t\t\t\t</table>'''.format(perProcessBreakdownBody = perProcessBreakdownBody)\n\n\n\t# Signal Bars\n\tcursor.execute('''SELECT signalBars, ROUND(CAST(COUNT(*) AS REAL)/total, 2) * 100 AS percent \n\t\t\t\tFROM PLBBAgent_EventPoint_TelephonyActivity \n \t\t\t\tCROSS JOIN\n\t\t\t\t ( SELECT COUNT(*) AS total \n\t\t\t\t FROM PLBBAgent_EventPoint_TelephonyActivity \n\t\t\t\t\t WHERE airplaneMode=\"off\" \n\t\t\t\t\t {whereClause}\n\t\t\t\t )\n\t\t\t\tWHERE airplaneMode=\"off\" {whereClause}\n\t\t\t\tGROUP BY signalBars'''.format(whereClause=('', 'AND {0}'.format(whereClause))[len(whereClause) > 0]))\n\n\tall_rows = cursor.fetchall()\n\n\tsignalBody = ''\n\tfor row in all_rows:\n\t\tsignalBody += '<tr><td>{0}</td><td>{1}</td></tr>\\n'.format(row[0], row[1])\n\t\n\tsignalBreakdown = '''<table id=\"signalBreakdown\" class=\"table table-striped table-condensed\">\n\t\t\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class=\"col-md-3\">Number of Bars</td>\n\t\t\t\t\t\t\t\t\t<td>%</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t\t\t<tbody>{signalBody}</tbody>\n\t\t\t\t\t\t\t</table>'''.format(signalBody = signalBody)\n\n\n\t#locations\n\tcursor.execute('''SELECT Client, Type, COUNT(Client) AS Count \n\t\t\t\t\t\t FROM PLLocationAgent_EventForward_ClientStatus\n\t\t\t\t\t\t {whereClause}\n\t\t\t\t\t\t GROUP BY Client ORDER BY Count DESC'''.format(whereClause=('', 'WHERE {0}'.format(whereClause))[len(whereClause) > 0]))\n\n\tall_rows = cursor.fetchall()\n\n\tlocationBody = ''\n\tfor row in all_rows:\n\t\tlocationBody += '<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>\\n'.format(row[0], row[1], row[2])\n\t\n\tlocationBreakdown = '''<table id=\"locationBreakdown\" class=\"table table-striped table-condensed\">\n\t\t\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class=\"col-md-3\">Client</td>\n\t\t\t\t\t\t\t\t\t<td>Type</td>\n\t\t\t\t\t\t\t\t\t<td>Number of Requests</td>\n\t\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t\t\t<tbody>{locationBody}</tbody>\n\t\t\t\t\t\t\t</table>'''.format(locationBody = locationBody)\n\n\t#power consumption\n\tcursor.execute('''SELECT Name, SUM(Energy) AS TotalEnergy \n\t\t\t\t\t\tFROM PLAccountingOperator_Aggregate_RootNodeEnergy, PLAccountingOperator_EventNone_Nodes \n\t\t\t\t\t\tWHERE PLAccountingOperator_Aggregate_RootNodeEnergy.NodeID = PLAccountingOperator_EventNone_Nodes.ID\n\t\t\t\t\t\t\t {whereClause}\n\t\t\t\t\t \tGROUP BY Name \n\t\t\t\t\t \tORDER BY TotalEnergy DESC'''.format(whereClause=('', 'AND {0}'.format(whereClause))[len(whereClause) > 0]))\n\tall_rows = cursor.fetchall()\n\t\n\tperProcessPowerConsumption = ''\n\tfor row in all_rows:\n\t\tperProcessPowerConsumption += '<tr><td>{0}</td><td>{1}</td></tr>\\n'.format(row[0], row[1])\n\t\n\tpowerBreakDown = '''<table id=\"powerBreakDown\" class=\"table table-striped table-condensed\">\n\t\t\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class=\"col-md-3\">Node Name</td>\n\t\t\t\t\t\t\t\t\t<td>Power Usage</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t\t\t<tbody>{perProcessPowerConsumption}</tbody>\n\t\t\t\t\t\t\t</table>'''.format(perProcessPowerConsumption = perProcessPowerConsumption)\n\n\t#memory usage\n\tcursor.execute('''SELECT PLApplicationAgent_EventNone_AllApps.AppName, PLApplicationAgent_EventBackward_ApplicationMemory.AppBundleId, avg(PeakMemory) AS avgpeak \n\t\t\t\t\t\tFROM PLApplicationAgent_EventBackward_ApplicationMemory \n\t\t\t\t\t\tLEFT JOIN PLApplicationAgent_EventNone_AllApps \n\t\t\t\t\t\tON PLApplicationAgent_EventBackward_ApplicationMemory.AppBundleId = PLApplicationAgent_EventNone_AllApps.AppBundleId \n\t\t\t\t\t\t{whereClause} \n\t\t\t\t\t \tGROUP BY PLApplicationAgent_EventBackward_ApplicationMemory.AppBundleId \n\t\t\t\t\t \tORDER BY avgpeak DESC'''.format(whereClause=('', '{0}'.format(whereClause))[len(whereClause) > 0]))\n\tall_rows = cursor.fetchall()\n\t\n\tperProcessMemPeaks = ''\n\tfor row in all_rows:\n\t\tAppName = row[0] if row[0] else ''\n\t\tperProcessMemPeaks += '<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>\\n'.format(row[1], AppName.encode('utf-8'), row[2])\n\t\n\tmemoryBreakDown = '''<table id=\"memoryBreakDown\" class=\"table table-striped table-condensed\">\n\t\t\t\t\t\t\t\t<thead>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td class=\"col-md-3\">AppBundleId</td>\n\t\t\t\t\t\t\t\t\t<td>AppName</td>\n\t\t\t\t\t\t\t\t\t<td>Peak Memory</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t</thead>\n\t\t\t\t\t\t\t\t<tbody>{perProcessMemPeaks}</tbody>\n\t\t\t\t\t\t\t</table>'''.format(perProcessMemPeaks = perProcessMemPeaks)\n\n\n\tf = open('report.html', 'w')\n\treport = '''<html>\n\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css\">\n\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.css\">\n\n\t\t<script type=\"text/javascript\" language=\"javascript\" src=\"https://code.jquery.com/jquery-1.10.2.min.js\"></script>\n\t\t<script type=\"text/javascript\" language=\"javascript\" src=\"https://cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js\"></script>\n\t\t<script type=\"text/javascript\" language=\"javascript\" src=\"https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.js\"></script>\n\n\t\t<script type=\"text/javascript\" charset=\"utf-8\">\n\t\t\t$(document).ready(function() {{\n\t\t\t\t$('#processBreakdown').DataTable( {{\n \t\t\t\"responsive\": true,\n \t\t\t\"order\": [[ 1, \"desc\" ]]\n \t\t\t}});\n\t\t\t\t$('#notificationBreakdown').DataTable( {{\n \t\t\t\"responsive\": true,\n \t\t\t\"order\": [[ 1, \"desc\" ]]\n \t\t\t}});\n\t\t\t\t$('#locationBreakdown').DataTable( {{\n \t\t\t\"responsive\": true,\n \t\t\t\"order\": [[ 1, \"desc\" ]]\n \t\t\t}});\n\t\t\t\t$('#powerBreakDown').DataTable( {{\n \t\t\t\"responsive\": true,\n \t\t\t\"order\": [[ 1, \"desc\" ]]\n \t\t\t}});\n\t\t\t\t$('#memoryBreakDown').DataTable( {{\n \t\t\t\"responsive\": true,\n \t\t\t\"order\": [[ 1, \"desc\" ]]\n \t\t\t}});\n\t\t\t\t$('#applistBreakdown').DataTable( {{\n \t\t\t\"responsive\": true,\n \t\t\t\"order\": [[ 1, \"desc\" ]]\n \t\t\t}});\n\t\t\t}});\n\t\t</script>\n\n\t\t<body>\n\t\t\t<div class=\"container\">\n\t\t\t<h1>Energy Report - {startDate} to {endDate}<h1>\n\n\t\t\t<h2>Overall Metrics</h2>\n\t\t\t{overallBreakdown}\n\n\t\t\t<h2>App list breakdown</h2>\n\t\t\t{applistBreakdown}\n\n\t\t\t<h2>Process time breakdown</h2>\n\t\t\t{perProcesssBreakdown}\n\n\t\t\t<h2>Core Location</h2>\n\t\t\t{locationBreakdown}\n\n\t\t\t<h2>Signal Breakdown</h2>\n\t\t\t{signalBreakdown}\n\n\t\t\t<h2>Power Breakdown</h2>\n\t\t\t{powerBreakDown}\n\n\t\t\t<h2>Memory Breakdown</h2>\n\t\t\t{memoryBreakDown}\n\t\t\t</div>\n\t\t<body>\n\t</html>'''.format(startDate = datetime.fromtimestamp(startTimeInData).strftime(\"%Y-%m-%d %H:%M\"), \n\t\t\t\t\t\tendDate = datetime.fromtimestamp(endTimeInData).strftime(\"%Y-%m-%d %H:%M\"), \n\t\t\t\t\t\toverallBreakdown = overallBreakdown,\n\t\t\t\t\t\tperProcesssBreakdown = perProcesssBreakdown,\n\t\t\t\t\t\tsignalBreakdown=signalBreakdown,\n\t\t\t\t\t\tlocationBreakdown = locationBreakdown,\n\t\t\t\t\t\tpowerBreakDown = powerBreakDown,\n\t\t\t\t\t\tmemoryBreakDown = memoryBreakDown,\n\t\t\t\t\t\tapplistBreakdown = applistBreakdown)\n\tf.write(report)\n\tf.close()\n\n\tdb.close()\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n"
] |
[
[
"numpy.diff",
"numpy.abs"
]
] |
timcera/tstoolbox
|
[
"a32fa399d96082f01b7eedfd6c8893bdb881845c",
"a32fa399d96082f01b7eedfd6c8893bdb881845c"
] |
[
"tests/test_convert_units.py",
"src/tstoolbox/functions/expanding_window.py"
] |
[
"# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\n\nimport pint_pandas\nimport pytest\nfrom pandas.testing import assert_frame_equal\n\nfrom tstoolbox import tstoolbox\n\n\nclass TestConvertUnits(TestCase):\n @staticmethod\n def test_convert_units():\n a = tstoolbox.read(\"tests/data_gainesville_daily_precip.csv\", target_units=\"in\")\n b = tstoolbox.equation(\n \"x1/25.4\", input_ts=\"tests/data_gainesville_daily_precip.csv\"\n )\n b.columns = [\"ADaymet-prcp:in\"]\n assert_frame_equal(a, b, check_dtype=False)\n\n a = tstoolbox.read(\"tests/data_gainesville_daily_precip.csv\", target_units=\"km\")\n b = tstoolbox.equation(\n \"x1/(1000*1000)\", input_ts=\"tests/data_gainesville_daily_precip.csv\"\n )\n b.columns = [\"ADaymet-prcp:km\"]\n assert_frame_equal(a, b, check_dtype=False)\n\n with pytest.raises(ValueError) as e_info:\n _ = tstoolbox.read(\n \"tests/data_gainesville_daily_precip.csv\", source_units=\"ft3/s\"\n )\n assert r'The units specified by the \"source_units\" keyword and in the' in str(\n e_info.value\n )\n\n with pytest.raises(ValueError) as e_info:\n _ = tstoolbox.read(\n \"tests/data_gainesville_daily_precip.csv\", target_units=\"ft3/s\"\n )\n",
"# -*- coding: utf-8 -*-\n\"\"\"Collection of functions for the manipulation of time series.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom typing import List, Optional\n\nimport mando\nimport pandas as pd\nimport typic\nfrom mando.rst_text_formatter import RSTHelpFormatter\n\nfrom .. import tsutils\n\ntry:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal\n\n\[email protected](\"expanding_window\", formatter_class=RSTHelpFormatter, doctype=\"numpy\")\[email protected](tsutils.docstrings)\ndef expanding_window_cli(\n input_ts=\"-\",\n columns=None,\n start_date=None,\n end_date=None,\n dropna=\"no\",\n skiprows=None,\n index_type=\"datetime\",\n names=None,\n clean=False,\n statistic=\"\",\n min_periods=1,\n center=False,\n source_units=None,\n target_units=None,\n print_input=False,\n tablefmt=\"csv\",\n):\n \"\"\"Calculate an expanding window statistic.\n\n Parameters\n ----------\n statistic : str\n [optional, default is '']\n\n +-----------+----------------------+\n | statistic | Meaning |\n +===========+======================+\n | corr | correlation |\n +-----------+----------------------+\n | count | count of real values |\n +-----------+----------------------+\n | cov | covariance |\n +-----------+----------------------+\n | kurt | kurtosis |\n +-----------+----------------------+\n | max | maximum |\n +-----------+----------------------+\n | mean | mean |\n +-----------+----------------------+\n | median | median |\n +-----------+----------------------+\n | min | minimum |\n +-----------+----------------------+\n | skew | skew |\n +-----------+----------------------+\n | std | standard deviation |\n +-----------+----------------------+\n | sum | sum |\n +-----------+----------------------+\n | var | variance |\n +-----------+----------------------+\n\n min_periods : int\n [optional, default is 1]\n\n Minimum number of observations in window required to have a value\n\n center : boolean\n [optional, default is False]\n\n Set the labels at the center of the window.\n\n {input_ts}\n\n {columns}\n\n {start_date}\n\n {end_date}\n\n {dropna}\n\n {skiprows}\n\n {index_type}\n\n {names}\n\n {clean}\n\n {source_units}\n\n {target_units}\n\n {print_input}\n\n {tablefmt}\n\n \"\"\"\n tsutils.printiso(\n expanding_window(\n input_ts=input_ts,\n columns=columns,\n start_date=start_date,\n end_date=end_date,\n dropna=dropna,\n skiprows=skiprows,\n index_type=index_type,\n names=names,\n clean=clean,\n statistic=statistic,\n min_periods=min_periods,\n center=center,\n source_units=source_units,\n target_units=target_units,\n print_input=print_input,\n ),\n tablefmt=tablefmt,\n )\n\n\[email protected]_args(statistic=tsutils.make_list)\[email protected]\ndef expanding_window(\n input_ts=\"-\",\n columns=None,\n start_date=None,\n end_date=None,\n dropna=\"no\",\n skiprows=None,\n index_type=\"datetime\",\n names=None,\n clean=False,\n statistic: Optional[\n List[\n Literal[\n \"corr\",\n \"count\",\n \"cov\",\n \"kurt\",\n \"max\",\n \"mean\",\n \"median\",\n \"min\",\n \"skew\",\n \"std\",\n \"sum\",\n \"var\",\n ]\n ]\n ] = None,\n min_periods: tsutils.IntGreaterEqualToZero = 1,\n center: bool = False,\n source_units=None,\n target_units=None,\n print_input=False,\n):\n \"\"\"Calculate an expanding window statistic.\"\"\"\n tsd = tsutils.common_kwds(\n input_ts,\n skiprows=skiprows,\n names=names,\n index_type=index_type,\n start_date=start_date,\n end_date=end_date,\n pick=columns,\n dropna=dropna,\n source_units=source_units,\n target_units=target_units,\n clean=clean,\n )\n\n ntsd = tsd.expanding(min_periods=min_periods, center=center)\n\n if statistic:\n nntsd = pd.DataFrame()\n for stat in statistic:\n ntsd = eval(\"ntsd.{}()\".format(stat))\n ntsd.columns = [\n tsutils.renamer(i, \"expanding.{}\".format(stat)) for i in ntsd.columns\n ]\n nntsd = nntsd.join(ntsd, how=\"outer\")\n else:\n nntsd = ntsd\n\n return tsutils.return_input(print_input, tsd, nntsd)\n\n\nexpanding_window.__doc__ = expanding_window_cli.__doc__\n"
] |
[
[
"pandas.testing.assert_frame_equal"
],
[
"pandas.DataFrame"
]
] |
BillyCheung10botics/donkeycar
|
[
"a3278818367e65250a381e59458b5be13b7d2b7c"
] |
[
"donkeycar/parts/lidar.py"
] |
[
"\"\"\"\nLidar\n\"\"\"\n\n# requies glob to be installed: \"pip3 install glob2\"\n# requires rplidar to be installed: \"pip3 install rplidar\"\n\nimport time\nimport math\nimport pickle\nimport serial\nimport numpy as np\nfrom donkeycar.utils import norm_deg, dist, deg2rad, arr_to_img\nfrom PIL import Image, ImageDraw\n\nclass RPLidar(object):\n '''\n https://github.com/SkoltechRobotics/rplidar\n '''\n def __init__(self, lower_limit = 0, upper_limit = 360, debug=False):\n from rplidar import RPLidar\n import glob\n port_found = False\n self.lower_limit = lower_limit\n self.upper_limit = upper_limit\n temp_list = glob.glob ('/dev/ttyUSB*')\n result = []\n for a_port in temp_list:\n try:\n s = serial.Serial(a_port)\n s.close()\n result.append(a_port)\n port_found = True\n except serial.SerialException:\n pass\n if port_found:\n self.port = result[0]\n self.distances = [] #a list of distance measurements \n self.angles = [] # a list of angles corresponding to dist meas above\n self.lidar = RPLidar(self.port, baudrate=115200)\n self.lidar.clear_input()\n time.sleep(1)\n self.on = True\n #print(self.lidar.get_info())\n #print(self.lidar.get_health())\n else:\n print(\"No Lidar found\")\n\n\n\n def update(self):\n scans = self.lidar.iter_scans(550)\n while self.on:\n try:\n for scan in scans:\n self.distances = [item[2] for item in scan]\n self.angles = [item[1] for item in scan]\n except serial.serialutil.SerialException:\n print('serial.serialutil.SerialException from Lidar. common when shutting down.')\n\n def run_threaded(self):\n sorted_distances = []\n if (self.angles != []) and (self.distances != []):\n angs = np.copy(self.angles)\n dists = np.copy(self.distances)\n\n filter_angs = angs[(angs > self.lower_limit) & (angs < self.upper_limit)]\n filter_dist = dists[(angs > self.lower_limit) & (angs < self.upper_limit)] #sorts distances based on angle values\n\n angles_ind = np.argsort(filter_angs) # returns the indexes that sorts filter_angs\n if angles_ind != []:\n sorted_distances = np.argsort(filter_dist) # sorts distances based on angle indexes\n return sorted_distances\n\n\n def shutdown(self):\n self.on = False\n time.sleep(2)\n self.lidar.stop()\n self.lidar.stop_motor()\n self.lidar.disconnect()\n\nclass YDLidar(object):\n '''\n https://pypi.org/project/PyLidar3/\n '''\n def __init__(self, port='/dev/ttyUSB0'):\n import PyLidar3\n self.port = port\n self.distances = [] #a list of distance measurements \n self.angles = [] # a list of angles corresponding to dist meas above\n self.lidar = PyLidar3.YdLidarX4(port)\n if(self.lidar.Connect()):\n print(self.lidar.GetDeviceInfo())\n self.gen = self.lidar.StartScanning()\n else:\n print(\"Error connecting to lidar\")\n self.on = True\n\n\n def init(self, port='/dev/ttyUSB0'):\n import PyLidar3\n print(\"Starting lidar...\")\n self.port = port\n self.distances = [] #a list of distance measurements \n self.angles = [] # a list of angles corresponding to dist meas above\n self.lidar = PyLidar3.YdLidarX4(port)\n if(self.lidar.Connect()):\n print(self.lidar.GetDeviceInfo())\n gen = self.lidar.StartScanning()\n return gen\n else:\n print(\"Error connecting to lidar\")\n self.on = True\n #print(self.lidar.get_info())\n #print(self.lidar.get_health())\n\n def update(self, lidar, debug = False):\n while self.on:\n try:\n self.data = next(lidar)\n for angle in range(0,360):\n if(self.data[angle]>1000):\n self.angles = [angle] \n self.distances = [self.data[angle]]\n if debug:\n return self.distances, self.angles\n except serial.serialutil.SerialException:\n print('serial.serialutil.SerialException from Lidar. common when shutting down.')\n\n def run_threaded(self):\n return self.distances, self.angles\n\n def shutdown(self):\n self.on = False\n time.sleep(2)\n self.lidar.StopScanning()\n self.lidar.Disconnect()\n\nclass LidarPlot(object):\n '''\n takes the raw lidar measurements and plots it to an image\n '''\n PLOT_TYPE_LINE = 0\n PLOT_TYPE_CIRC = 1\n def __init__(self, resolution=(500,500),\n max_dist=1000, #mm\n radius_plot=3,\n plot_type=PLOT_TYPE_CIRC):\n self.frame = Image.new('RGB', resolution)\n self.max_dist = max_dist\n self.rad = radius_plot\n self.resolution = resolution\n if plot_type == self.PLOT_TYPE_CIRC:\n self.plot_fn = self.plot_circ\n else:\n self.plot_fn = self.plot_line\n \n\n def plot_line(self, img, dist, theta, max_dist, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the line using the draw ImageDraw object\n '''\n center = (img.width / 2, img.height / 2)\n max_pixel = min(center[0], center[1])\n dist = dist / max_dist * max_pixel\n if dist < 0 :\n dist = 0\n elif dist > max_pixel:\n dist = max_pixel\n theta = np.radians(theta)\n sx = math.cos(theta) * dist + center[0]\n sy = math.sin(theta) * dist + center[1]\n ex = math.cos(theta) * (dist + self.rad) + center[0]\n ey = math.sin(theta) * (dist + self.rad) + center[1]\n fill = 128\n draw.line((sx,sy, ex, ey), fill=(fill, fill, fill), width=1)\n \n def plot_circ(self, img, dist, theta, max_dist, draw):\n '''\n scale dist so that max_dist is edge of img (mm)\n and img is PIL Image, draw the circle using the draw ImageDraw object\n '''\n center = (img.width / 2, img.height / 2)\n max_pixel = min(center[0], center[1])\n dist = dist / max_dist * max_pixel\n if dist < 0 :\n dist = 0\n elif dist > max_pixel:\n dist = max_pixel\n theta = np.radians(theta)\n sx = int(math.cos(theta) * dist + center[0])\n sy = int(math.sin(theta) * dist + center[1])\n ex = int(math.cos(theta) * (dist + 2 * self.rad) + center[0])\n ey = int(math.sin(theta) * (dist + 2 * self.rad) + center[1])\n fill = 128\n\n draw.ellipse((min(sx, ex), min(sy, ey), max(sx, ex), max(sy, ey)), fill=(fill, fill, fill))\n\n def plot_scan(self, img, distances, angles, max_dist, draw):\n for dist, angle in zip(distances, angles):\n self.plot_fn(img, dist, angle, max_dist, draw)\n \n def run(self, distances, angles):\n '''\n takes two lists of equal length, one of distance values, the other of angles corresponding to the dist meas \n '''\n self.frame = Image.new('RGB', self.resolution, (255, 255, 255))\n draw = ImageDraw.Draw(self.frame)\n self.plot_scan(self.frame, distances, angles, self.max_dist, draw)\n return self.frame\n\n def shutdown(self):\n pass\n\n\nclass BreezySLAM(object):\n '''\n https://github.com/simondlevy/BreezySLAM\n '''\n def __init__(self, MAP_SIZE_PIXELS=500, MAP_SIZE_METERS=10):\n from breezyslam.algorithms import RMHC_SLAM\n from breezyslam.sensors import Laser\n\n laser_model = Laser(scan_size=360, scan_rate_hz=10., detection_angle_degrees=360, distance_no_detection_mm=12000)\n MAP_QUALITY=5\n self.slam = RMHC_SLAM(laser_model, MAP_SIZE_PIXELS, MAP_SIZE_METERS, MAP_QUALITY)\n \n def run(self, distances, angles, map_bytes):\n \n self.slam.update(distances, scan_angles_degrees=angles)\n x, y, theta = self.slam.getpos()\n\n if map_bytes is not None:\n self.slam.getmap(map_bytes)\n\n #print('x', x, 'y', y, 'theta', norm_deg(theta))\n return x, y, deg2rad(norm_deg(theta))\n\n def shutdown(self):\n pass\n\n\n\nclass BreezyMap(object):\n '''\n bitmap that may optionally be constructed by BreezySLAM\n '''\n def __init__(self, MAP_SIZE_PIXELS=500):\n self.mapbytes = bytearray(MAP_SIZE_PIXELS * MAP_SIZE_PIXELS)\n\n def run(self):\n return self.mapbytes\n\n def shutdown(self):\n pass\n\nclass MapToImage(object):\n\n def __init__(self, resolution=(500, 500)):\n self.resolution = resolution\n\n def run(self, map_bytes):\n np_arr = np.array(map_bytes).reshape(self.resolution)\n return arr_to_img(np_arr)\n\n def shutdown(self):\n pass\n"
] |
[
[
"numpy.array",
"numpy.argsort",
"numpy.copy",
"numpy.radians"
]
] |
zixia/python-facenet
|
[
"d86e0c49a9ce413bef6e58a19a9f723aadcef968"
] |
[
"src/models/inception_resnet_v1.py"
] |
[
"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Contains the definition of the Inception Resnet V1 architecture.\nAs described in http://arxiv.org/abs/1602.07261.\n Inception-v4, Inception-ResNet and the Impact of Residual Connections\n on Learning\n Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\n# Inception-Resnet-A\ndef block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):\n \"\"\"Builds the 35x35 resnet block.\"\"\"\n with tf.variable_scope(scope, 'Block35', [net], reuse=reuse):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope='Conv2d_0b_3x3')\n with tf.variable_scope('Branch_2'):\n tower_conv2_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1')\n tower_conv2_1 = slim.conv2d(tower_conv2_0, 32, 3, scope='Conv2d_0b_3x3')\n tower_conv2_2 = slim.conv2d(tower_conv2_1, 32, 3, scope='Conv2d_0c_3x3')\n mixed = tf.concat([tower_conv, tower_conv1_1, tower_conv2_2], 3)\n up35 = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,\n activation_fn=None, scope='Conv2d_1x1')\n net += scale * up35\n if activation_fn:\n net = activation_fn(net)\n return net\n\n# Inception-Resnet-B\ndef block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):\n \"\"\"Builds the 17x17 resnet block.\"\"\"\n with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 128, 1, scope='Conv2d_1x1')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, 128, [1, 7],\n scope='Conv2d_0b_1x7')\n tower_conv1_2 = slim.conv2d(tower_conv1_1, 128, [7, 1],\n scope='Conv2d_0c_7x1')\n mixed = tf.concat([tower_conv, tower_conv1_2], 3)\n up17 = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,\n activation_fn=None, scope='Conv2d_1x1')\n net += scale * up17\n if activation_fn:\n net = activation_fn(net)\n return net\n\n\n# Inception-Resnet-C\ndef block8(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):\n \"\"\"Builds the 8x8 resnet block.\"\"\"\n with tf.variable_scope(scope, 'Block8', [net], reuse=reuse):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, 192, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, 192, [1, 3],\n scope='Conv2d_0b_1x3')\n tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [3, 1],\n scope='Conv2d_0c_3x1')\n mixed = tf.concat([tower_conv, tower_conv1_2], 3)\n up8 = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,\n activation_fn=None, scope='Conv2d_1x1')\n net += scale * up8\n if activation_fn:\n net = activation_fn(net)\n return net\n\n# pylint: disable=C0103\ndef reduction_a(net, k, l, m, n):\n \"\"\"reduction\n \"\"\"\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, n, 3, stride=2, padding='VALID',\n scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, k, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, l, 3,\n scope='Conv2d_0b_3x3')\n tower_conv1_2 = slim.conv2d(tower_conv1_1, m, 3,\n stride=2, padding='VALID',\n scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_2'):\n tower_pool = slim.max_pool2d(net, 3, stride=2, padding='VALID',\n scope='MaxPool_1a_3x3')\n net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3)\n return net\n\ndef reduction_b(net):\n \"\"\"reduction b\"\"\"\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')\n tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2,\n padding='VALID', scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_1'):\n tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1, 256, 3, stride=2,\n padding='VALID', scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_2'):\n tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')\n tower_conv2_1 = slim.conv2d(tower_conv2, 256, 3,\n scope='Conv2d_0b_3x3')\n tower_conv2_2 = slim.conv2d(tower_conv2_1, 256, 3, stride=2,\n padding='VALID', scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_3'):\n tower_pool = slim.max_pool2d(net, 3, stride=2, padding='VALID',\n scope='MaxPool_1a_3x3')\n net = tf.concat([tower_conv_1, tower_conv1_1,\n tower_conv2_2, tower_pool], 3)\n return net\n\ndef inference(images, keep_probability, phase_train=True,\n bottleneck_layer_size=128, weight_decay=0.0, reuse=None):\n \"\"\"inference\"\"\"\n batch_norm_params = {\n # Decay for the moving averages.\n 'decay': 0.995,\n # epsilon to prevent 0s in variance.\n 'epsilon': 0.001,\n # force in-place updates of mean and variance estimates\n 'updates_collections': None,\n # Moving averages ends up in the trainable variables collection\n 'variables_collections': [tf.GraphKeys.TRAINABLE_VARIABLES],\n }\n\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n weights_initializer=slim.initializers.xavier_initializer(), \n weights_regularizer=slim.l2_regularizer(weight_decay),\n normalizer_fn=slim.batch_norm,\n normalizer_params=batch_norm_params):\n return inception_resnet_v1(images, is_training=phase_train,\n dropout_keep_prob=keep_probability,\n bottleneck_layer_size=bottleneck_layer_size,\n reuse=reuse)\n\n\ndef inception_resnet_v1(inputs, is_training=True,\n dropout_keep_prob=0.8,\n bottleneck_layer_size=128,\n reuse=None,\n scope='InceptionResnetV1'):\n \"\"\"Creates the Inception Resnet V1 model.\n Args:\n inputs: a 4-D tensor of size [batch_size, height, width, 3].\n num_classes: number of predicted classes.\n is_training: whether is training or not.\n dropout_keep_prob: float, the fraction to keep before final layer.\n reuse: whether or not the network and its variables should be reused. To be\n able to reuse 'scope' must be given.\n scope: Optional variable_scope.\n Returns:\n logits: the logits outputs of the model.\n end_points: the set of end_points from the inception model.\n \"\"\"\n end_points = {}\n\n with tf.variable_scope(scope, 'InceptionResnetV1', [inputs], reuse=reuse):\n with slim.arg_scope([slim.batch_norm, slim.dropout],\n is_training=is_training):\n with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],\n stride=1, padding='SAME'):\n\n # 149 x 149 x 32\n net = slim.conv2d(inputs, 32, 3, stride=2, padding='VALID',\n scope='Conv2d_1a_3x3')\n end_points['Conv2d_1a_3x3'] = net\n # 147 x 147 x 32\n net = slim.conv2d(net, 32, 3, padding='VALID',\n scope='Conv2d_2a_3x3')\n end_points['Conv2d_2a_3x3'] = net\n # 147 x 147 x 64\n net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3')\n end_points['Conv2d_2b_3x3'] = net\n # 73 x 73 x 64\n net = slim.max_pool2d(net, 3, stride=2, padding='VALID',\n scope='MaxPool_3a_3x3')\n end_points['MaxPool_3a_3x3'] = net\n # 73 x 73 x 80\n net = slim.conv2d(net, 80, 1, padding='VALID',\n scope='Conv2d_3b_1x1')\n end_points['Conv2d_3b_1x1'] = net\n # 71 x 71 x 192\n net = slim.conv2d(net, 192, 3, padding='VALID',\n scope='Conv2d_4a_3x3')\n end_points['Conv2d_4a_3x3'] = net\n # 35 x 35 x 256\n net = slim.conv2d(net, 256, 3, stride=2, padding='VALID',\n scope='Conv2d_4b_3x3')\n end_points['Conv2d_4b_3x3'] = net\n\n # 5 x Inception-resnet-A\n net = slim.repeat(net, 5, block35, scale=0.17)\n end_points['Mixed_5a'] = net\n\n # Reduction-A\n with tf.variable_scope('Mixed_6a'):\n net = reduction_a(net, 192, 192, 256, 384)\n end_points['Mixed_6a'] = net\n\n # 10 x Inception-Resnet-B\n net = slim.repeat(net, 10, block17, scale=0.10)\n end_points['Mixed_6b'] = net\n\n # Reduction-B\n with tf.variable_scope('Mixed_7a'):\n net = reduction_b(net)\n end_points['Mixed_7a'] = net\n\n # 5 x Inception-Resnet-C\n net = slim.repeat(net, 5, block8, scale=0.20)\n end_points['Mixed_8a'] = net\n\n net = block8(net, activation_fn=None)\n end_points['Mixed_8b'] = net\n\n with tf.variable_scope('Logits'):\n end_points['PrePool'] = net\n #pylint: disable=no-member\n net = slim.avg_pool2d(net, net.get_shape()[1:3], padding='VALID',\n scope='AvgPool_1a_8x8')\n net = slim.flatten(net)\n\n net = slim.dropout(net, dropout_keep_prob, is_training=is_training,\n scope='Dropout')\n\n end_points['PreLogitsFlatten'] = net\n\n net = slim.fully_connected(net, bottleneck_layer_size, activation_fn=None,\n scope='Bottleneck', reuse=False)\n\n return net, end_points\n"
] |
[
[
"tensorflow.concat",
"tensorflow.contrib.slim.dropout",
"tensorflow.contrib.slim.arg_scope",
"tensorflow.contrib.slim.max_pool2d",
"tensorflow.contrib.slim.l2_regularizer",
"tensorflow.contrib.slim.repeat",
"tensorflow.contrib.slim.initializers.xavier_initializer",
"tensorflow.contrib.slim.fully_connected",
"tensorflow.contrib.slim.flatten",
"tensorflow.contrib.slim.conv2d",
"tensorflow.variable_scope"
]
] |
xfli376/Lecture
|
[
"4ee193769df089053726ec6e7792718e30f633a4"
] |
[
"EM-beamer/image/bessel.py"
] |
[
"from scipy import optimize, special\nfrom numpy import *\nfrom matplotlib import pyplot as pb \n \nx = arange(0,20,0.01)\n \nfor k in arange(0.5,5.5):\n y = special.jv(k,x)\n pb.plot(x,y)\n f = lambda x: -special.jv(k,x)\n x_max = optimize.fminbound(f,0,6)\n pb.plot([x_max], [special.jv(k,x_max)],'ro')\n pb.title('Different Bessel functions and their local maxima')\n pb.savefig('myplot.png')\npb.show()"
] |
[
[
"matplotlib.pyplot.title",
"scipy.special.jv",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"scipy.optimize.fminbound",
"matplotlib.pyplot.show"
]
] |
Sliverk/hybridAveragePrecision
|
[
"e0417ef71e7419a770b3c106624b5f4336ff5a8d"
] |
[
"utils/kitti.py"
] |
[
"import pathlib\nimport numpy as np\n\ndef get_image_index_str(img_idx):\n return \"{:06d}\".format(img_idx)\n\n\ndef get_label_anno(label_path):\n annotations = {}\n annotations.update({\n 'name': [],\n 'truncated': [],\n 'occluded': [],\n 'alpha': [],\n 'bbox': [],\n 'dimensions': [],\n 'location': [],\n 'rotation_y': []\n })\n with open(label_path, 'r') as f:\n lines = f.readlines()\n # if len(lines) == 0 or len(lines[0]) < 15:\n # content = []\n # else:\n content = [line.strip().split(' ') for line in lines]\n annotations['name'] = np.array([x[0] for x in content])\n annotations['truncated'] = np.array([float(x[1]) for x in content])\n annotations['occluded'] = np.array([int(x[2]) for x in content])\n annotations['alpha'] = np.array([float(x[3]) for x in content])\n annotations['bbox'] = np.array(\n [[float(info) for info in x[4:8]] for x in content]).reshape(-1, 4)\n # dimensions will convert hwl format to standard lhw(camera) format.\n annotations['dimensions'] = np.array(\n [[float(info) for info in x[8:11]] for x in content]).reshape(\n -1, 3)[:, [2, 0, 1]]\n annotations['location'] = np.array(\n [[float(info) for info in x[11:14]] for x in content]).reshape(-1, 3)\n annotations['rotation_y'] = np.array(\n [float(x[14]) for x in content]).reshape(-1)\n if len(content) != 0 and len(content[0]) == 16: # have score\n annotations['score'] = np.array([float(x[15]) for x in content])\n else:\n annotations['score'] = np.zeros([len(annotations['bbox'])])\n return annotations\n\ndef get_label_annos(label_folder, image_ids=None):\n if image_ids is None:\n filepaths = pathlib.Path(label_folder).glob('*.txt')\n prog = re.compile(r'^\\d{6}.txt$')\n filepaths = filter(lambda f: prog.match(f.name), filepaths)\n image_ids = [int(p.stem) for p in filepaths]\n image_ids = sorted(image_ids)\n if not isinstance(image_ids, list):\n image_ids = list(range(image_ids))\n annos = []\n label_folder = pathlib.Path(label_folder)\n for idx in image_ids:\n image_idx = get_image_index_str(idx)\n label_filename = label_folder / (image_idx + '.txt')\n annos.append(get_label_anno(label_filename))\n return annos\n\ndef load_dt_annos(root_path, filelist):\n dt_annos = get_label_annos(root_path, filelist)\n return dt_annos\n\ndef load_gt_annos(root_path, filelist):\n gt_annos = get_label_annos(root_path, filelist)\n return gt_annos\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"numpy.array"
]
] |
uv10000/P4
|
[
"e9e7f0c06dd9fb32e0febae016857b113eee747a"
] |
[
"model.py"
] |
[
"import os\nimport csv\nimport cv2\nimport numpy as np\nimport keras\nfrom scipy import ndimage\nfrom random import shuffle\n\n\n# read in udacity data from file\nlines=[]\nwith open('../data_provided_by_udacity/driving_log.csv') as csvfile:\n reader=csv.reader(csvfile)\n i_have_seen_firstline=False\n for line in reader:\n if i_have_seen_firstline:\n lines.append(line)\n else:\n i_have_seen_firstline = True\n\nimport sklearn\n\n# split them into a training and a validation set\nfrom sklearn.model_selection import train_test_split\ntrain_samples, validation_samples = train_test_split(lines, test_size=0.2) \n\n#define generator\n\ndef generator(samples, batch_size=32):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n #name = './IMG/'+batch_sample[0].split('/')[-1]\n current_path = '../data_provided_by_udacity/IMG/' + batch_sample[0].split('/')[-1] \n current_left_path = '../data_provided_by_udacity/IMG/' + batch_sample[1].split('/')[-1] \n current_right_path = '../data_provided_by_udacity/IMG/' + batch_sample[2].split('/')[-1] \n #center_image = cv2.imread(current_path)\n center_image = ndimage.imread(current_path)\n left_image = ndimage.imread(current_left_path) \n right_image = ndimage.imread(current_right_path)\n #center_image = cv2.cvtColor(ndimage.imread(current_path), cv2.COLOR_RBG2YUV)\n #left_image = cv2.cvtColor(ndimage.imread(current_left_path) , cv2.COLOR_RBG2YUV)\n #right_image = cv2.cvtColor(ndimage.imread(current_right_path), cv2.COLOR_RBG2YUV)\n center_angle = float(batch_sample[3])\n correction = 0.003 # this is a parameter to tune 0.03 was not bad\n left_angle = center_angle + correction\n right_angle = center_angle - correction\n #left_angle = center_angle *1.15\n #ight_angle = center_angle - 1.15\n #optionally use left and right cameras\n use_all_cameras = True\n if use_all_cameras:\n images.extend([center_image, left_image,right_image])\n angles.extend([center_angle,left_angle,right_angle])\n else:\n images.append(center_image)\n angles.extend(center_angle)\n #optionally augment by flipping all images right curves <> left curves \n augment_by_flipping=True\n if augment_by_flipping:\n augmented_images, augmented_angles = [],[]\n for image,angle in zip(images, angles):\n augmented_images.append(image)\n augmented_angles.append(angle)\n #augmented_images.append(cv2.flip(image,1))\n augmented_images.append(np.fliplr(image))\n augmented_angles.append(angle*-1.0)\n else:\n augmented_images, augmented_angles =images,angles\n\n X_train = np.array(augmented_images)\n y_train = np.array(augmented_angles)\n yield sklearn.utils.shuffle(X_train, y_train)\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten,Dense,Lambda,Dense, Activation, Dropout\nfrom keras.layers.convolutional import Conv2D, Cropping2D\nfrom keras.layers.pooling import MaxPooling2D\nimport matplotlib.pyplot as plt\n\n# compile and train the model using the generator function\nmy_batch_size= 16 #128\ntrain_generator = generator(train_samples, batch_size=my_batch_size)\nvalidation_generator = generator(validation_samples, batch_size=my_batch_size)\n\nch, row, col = 3, 160, 320 # Trimmed image format\n\n# optionally perform dropout in some layers, see below\ndropout_prob=0.0#0.8\n\nmodel=Sequential()\n#model.add(Lambda(lambda x: x/255.0 -0.5, input_shape=(160,320,3)))\n#normalize data\nmodel.add(Lambda(lambda x: x/127.5 - 1., #\n input_shape=(row, col,ch))) #,\n #output_shape=(row, col, ch)))\n\n#optionally apply cropping\ncropping= True\nif cropping:\n model.add(Cropping2D(cropping=((50,20), (0,0)), input_shape=(160,320,3)))\n\nmodel.add(Dropout(dropout_prob))\n \n##### 1st convolutional layer:\nmodel.add(Conv2D(24, kernel_size=(5, 5),\n strides = (2,2),\n activation='relu',\n padding='valid'))\n#model.add(MaxPooling2D(pool_size=(2, 2)))\n#model.add(Dropout(dropout_prob))\n\n##### 2nd convolutional layer:\nmodel.add(Conv2D(36, kernel_size=(5, 5),\n strides = (2,2),\n activation='relu',\n padding='valid'))\n#model.add(MaxPooling2D(pool_size=(2, 2)))\n#model.add(Dropout(dropout_prob))\n\n##### 3rd convolutional layer:\nmodel.add(Conv2D(48, kernel_size=(5, 5),\n strides = (2,2),\n activation='relu',\n padding='valid'))\n#model.add(MaxPooling2D(pool_size=(2, 2)))\n#model.add(Dropout(dropout_prob))\n\n##### 4th convolutional layer:\nmodel.add(Conv2D(64, kernel_size=(3, 3),\n strides = (1,1),\n activation='relu',\n padding='valid'))\n#model.add(MaxPooling2D(pool_size=(2, 2)))\n#model.add(Dropout(dropout_prob))\n\n##### 5th convolutional layer:\nmodel.add(Conv2D(64, kernel_size=(3, 3),\n strides = (1,1),\n activation='relu',\n padding='valid'))\n#model.add(MaxPooling2D(pool_size=(2, 2)))\n#model.add(Dropout(dropout_prob))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(100))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(dropout_prob))\n\nmodel.add(Dense(50))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(dropout_prob))\n\nmodel.add(Dense(10))\nmodel.add(Activation('relu'))\n#model.add(Dropout(dropout_prob))\n\nmodel.add(Dense(1))\n\n\n#model.summary()\n\nmodel.compile(loss='mse',optimizer='adam')\n\nhistory_object = model.fit_generator(train_generator, steps_per_epoch= len(train_samples)/my_batch_size, \n epochs=4, verbose=1,\n validation_data=validation_generator, validation_steps= len(validation_samples)/my_batch_size, use_multiprocessing=True\n )\n\n# save the model\nmodel.save('model.h5')\n\n\n#plot validation and training losses over time\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='upper right')\nplt.show()\n\n\n##############\n"
] |
[
[
"matplotlib.pyplot.legend",
"scipy.ndimage.imread",
"matplotlib.pyplot.title",
"numpy.fliplr",
"sklearn.utils.shuffle",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
chariothy/proxy-mon
|
[
"aa51220874d8a08553d4a2a26783533feb4a4949"
] |
[
"rank.py"
] |
[
"from pandas import DataFrame\nfrom utils import ut, tmp_env\nfrom pybeans import utils as pu\n\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\n#from model import Proxy, Delay, Rank, query_delay, query_proxy\n\nfrom premailer import transform\nfrom pybeans import today\nfrom notify import notify_by_ding_talk\n\nimport arrow\nimport os\nimport re\nREG_DATE = re.compile(r'(\\d{8})_\\d{6}.json')\n\nRANK_CONDITIONS = dict(\n avg = dict(asc=True, weight=3),\n std = dict(asc=True, weight=1),\n lost = dict(asc=True, weight=3)\n)\n\ndef clear_old_data(days:int=3):\n ut.D(f'############ 清除{days}天前的CURL数据 ############')\n ut.session.query(Delay).where(Delay.when < (datetime.now()-timedelta(days = days))).delete()\n ut.D(f'############ 清除{days*10}天前的排名数据 ############')\n ut.session.query(Rank).where(Rank.when < (datetime.now()-timedelta(days = days*10))).delete()\n ut.session.commit()\n \n\ndef report(data):\n template = tmp_env.get_template('rank.html')\n html = template.render(dict(\n rank_conditions = RANK_CONDITIONS,\n data = data\n ))\n #su.D(html)\n html = transform(html)\n #print(html)\n result = ut.send_email(f'代理服务器统计报告', html_body=html)\n ut.D('发送邮件:', f'失败:{result}' if result else '成功')\n \n notify_by_ding_talk(data)\n \n \ndef rank_v1():\n import re\n reg_proxy_multi = re.compile(r'\\|(\\d\\.?\\d?)x(?:\\||$)')\n\n id_proxy = {}\n multi_proxies = {}\n proxies = query_proxy(ut.session).all()\n for p in proxies:\n #ut.D(p)\n id_proxy[p.id] = p\n match = reg_proxy_multi.search(p.remark)\n if match:\n multi = float(match.groups()[0])\n else:\n multi = 1.0\n \n q = query_delay(ut.session, p.id)\n df = pd.read_sql(q.statement, q.session.bind, parse_dates=[\"when\"])\n p01 = df.value.quantile(0.01)\n p99 = df.value.quantile(0.95)\n vdf = df[(df.value >= p01) & (df.value <= p99)]\n if vdf.proxy_id.count() < 100:\n continue\n if multi not in multi_proxies:\n multi_proxies[multi] = {}\n #ut.D(f'{p.remark},倍率{multi}')\n multi_proxies[multi][p.id] = [\n p.id,\n vdf.value.mean(),\n vdf.value.median(),\n df[df.value.isnull()].proxy_id.count() / df.value.count() * 100,\n vdf.value.std(),\n p.remark,\n p.type,\n vdf.value.count(),\n df.value.count(),\n 0,\n 0 if p.avg_rank is None else round(p.avg_rank),\n 0,\n 0 # 必须放在最后一个\n ]\n #ut.D(multi_proxies)\n columns = {\n 'id': None,\n 'vmean': True, # valid mean\n 'vmed': True, # valid med\n 'outper': True, # timeout percentage\n 'std': True,\n 'remark': None,\n 'type': None,\n 'vcount': None,\n 'count': None,\n 'drank': None, # delta rank\n 'arank': None, # avg rank\n 'nrank': None, # new rank\n 'score': None\n }\n column_name = {k:v for k,v in enumerate(columns)}\n \n for multi in multi_proxies:\n dfm = DataFrame(multi_proxies[multi]).T\n dfm.rename(columns=column_name,inplace=True)\n #ut.D(f'倍率{multi}组排序\\n', dfm)\n for col in columns:\n if columns[col] is not None:\n sorted_dfm = dfm.sort_values(by=[col], ignore_index=True, ascending=columns[col])\n for i, p in sorted_dfm.iterrows():\n # 排序成绩相加\n multi_proxies[multi][p.id][-1] += i\n \n data = {}\n top = 2\n today_str = today()\n for multi in multi_proxies:\n ut.D(f'倍率{multi}组TOP3')\n dfr = DataFrame(multi_proxies[multi]).T\n dfr.rename(columns=column_name,inplace=True)\n #print(dfr)\n sorted_dfr = dfr.sort_values(by=['score'], ignore_index=True)\n print(sorted_dfr.head(5))\n for i, sp in sorted_dfr.iterrows():\n new_rank = i + 1\n sp.nrank = new_rank\n old_rank = multi_proxies[multi][sp.id][-3]\n if old_rank is not None:\n sp.drank = new_rank - old_rank\n \n rank_mod = ut.session \\\n .query(Rank) \\\n .where(Rank.proxy_id == sp.id) \\\n .where(Rank.when == today_str) \\\n .one_or_none()\n if not rank_mod:\n rank_mod = Rank()\n rank_mod.proxy_id = sp.id\n rank_mod.when = today_str\n rank_mod.rank = new_rank\n ut.session.add(rank_mod)\n data[multi] = sorted_dfr.T.to_dict().values()\n \n if data:\n #TODO: Report all NONE proxy\n ut.session.commit()\n report(data)\n\n\ndef df_from_json(data_path:str):\n result = pu.load_json(data_path)\n df = pd.json_normalize(\n result,\n record_path=['raw'],\n meta=['alias', 'id']\n ).rename(columns={0: 'curl'})\n #print(df)\n return df\n\n\ndef history(df_agg):\n today_int = int(pu.today('%Y%m%d'))\n df_agg['date'] = today_int\n df_agg['pos'] = df_agg.index\n today_cnt = 0\n history_path = ut['history_path']\n if os.path.exists(history_path):\n dfh = pd.read_csv(history_path, index_col=0, parse_dates=['date'])\n # 去除更新订阅后消失的节点,!记得换机场时要备份history,否则会被全部自动删除\n dfh = dfh[dfh.alias.isin(df_agg.alias)]\n if dfh.pos.count() == 0:\n raise RuntimeError('History中不存在任何新节点,请先备份history.csv')\n # 只保留最近一个月的记录\n dfh = dfh[dfh.date>arrow.now().shift(months=-1).format('YYYY-MM-DD')]\n today_cnt = dfh[dfh.date==today_int].pos.count()\n if today_cnt == 0:\n all_frame = pd.concat([df_agg, dfh])\n all_frame.to_csv(history_path)\n else:\n df_agg.to_csv(history_path)\n ut.run(f'scp {history_path} {ut[\"scp_data_dir\"]}') # 复制到网站服务器\n ut.run(ut['after_scp_data'])\n\n\ndef rank(df:DataFrame):\n df_agg=df.groupby(['alias', 'id']).agg(avg=('curl','mean'),std=('curl','std'),valid=('curl','count'),total=('curl','size'))\n df_agg['lost'] = df_agg['total'] - df_agg['valid']\n df_agg.reset_index(inplace=True)\n df_agg['curl_rank'] = 0\n #print(df_agg)\n \n for col in RANK_CONDITIONS:\n condition = RANK_CONDITIONS[col]\n percentile = f'{col}_pct'\n df_agg[percentile] = df_agg[col].rank(method='min', ascending=condition['asc'])\n df_agg['curl_rank'] += df_agg[percentile] * condition['weight']\n\n return df_agg.sort_values(by=['curl_rank']).reset_index()\n \n\nif __name__ == '__main__':\n df_agg = rank(df_from_json('./data/20211111_092739.json'))\n history(df_agg)\n #report(df_agg.head(4))\n \n "
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.json_normalize",
"pandas.DataFrame",
"pandas.read_sql"
]
] |
nairobi222/chainhammer
|
[
"94ab5269a9a9c751d355b41f90ac244026ccf46b"
] |
[
"reader/blocksDB_diagramming.py"
] |
[
"#!/usr/bin/env python3\n\"\"\"\n@summary: for the jupyter notebooks: tools, column creators, diagramming routines, etc. \n\n@version: v40 (29/November/2018)\n@since: 26/June/2018\n@organization: \n@author: https://github.com/drandreaskrueger\n@see: https://github.com/drandreaskrueger/chainhammer for updates\n\n@TODO: this needs usage comments; not every function has a docstring yet \n\"\"\"\n\n#global DBFILE, NAME_PREFIX\n#DBFILE = \"temp.db\"\n#NAME_PREFIX = \"TEMP\"\n\n################\n## Dependencies:\n\n# standard library\nimport sys, os, json, time\nimport sqlite3\nfrom pprint import pprint\n\n# pypi:\nimport pandas\nimport numpy\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# chainhammer\n# extend sys.path for imports:\nif __name__ == '__main__' and __package__ is None:\n from os import sys, path\n sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\nfrom hammer.config import RPCaddress, EMPTY_BLOCKS_AT_END\n\n################\n\n\ndef DB_query(SQL, conn):\n \"\"\"\n any SQL query, with many answers \n \"\"\"\n cur = conn.cursor()\n cur.execute(SQL)\n result = cur.fetchall()\n return result\n\n\ndef DB_tableSize(tablename, conn):\n \"\"\"\n prints number of rows\n \"\"\"\n count = DB_query(\"SELECT COUNT(*) FROM %s\" % tablename, conn)\n print (\"TABLE %s has %d rows\" % (tablename, count[0][0]))\n return count[0][0]\n\n\ndef maxBlockNumber(conn):\n \"\"\"\n what is the first & last block we have?\n \"\"\"\n result = DB_query(\"SELECT MIN(blocknumber), MAX(blocknumber) FROM blocks\", conn)\n print (\"MIN(blocknumber), MAX(blocknumber) = %s \" % (result) )\n return result\n\n\ndef check_whether_complete(blocknumbers):\n \"\"\"\n do we have consecutive blocks, none missing?\n \"\"\"\n start = min(blocknumbers)[0]\n last = max(blocknumbers)[0]\n old = start-1\n total=0\n for bn in blocknumbers:\n bn = bn[0]\n missing=bn-old-1\n if missing>0:\n print (\"from \", old+1, \"to\", bn - 1, \"there are \", missing, \" missing\")\n total+=missing\n old = bn\n print()\n complete = (not total)\n print (\"complete\" if complete else \"some %d blocks missing\" % total, end=\" \")\n print (\"between blocks %d and %d.\" %(min(blocknumbers)[0], max(blocknumbers)[0]))\n\n return complete\n\n##################\n## add columns\n\n\ndef add_blocktime(df):\n \"\"\"\n blocktime = timestamp[n] - timestamp[n-1]\n \"\"\"\n df['blocktime'] = df['timestamp'] - df['timestamp'].shift()\n df.loc[1, \"blocktime\"] = numpy.nan\n\n\ndef add_TPS(df, numBlocks):\n \"\"\"\n transactions per second\n with differently sized (rectangular) windows\n \"\"\"\n name = 'TPS_%dblks'%numBlocks if numBlocks>1 else 'TPS_%dblk'%numBlocks\n df[name]=df['txcount'].rolling(numBlocks).sum() / df['blocktime'].rolling(numBlocks).sum()\n \n\ndef add_GUPS(df, numBlocks):\n \"\"\"\n gasUsed per second\n \"\"\"\n name = 'GUPS_%dblks'%numBlocks if numBlocks>1 else 'GUPS_%dblk'%numBlocks\n df[name]=df['gasUsed'].rolling(numBlocks).sum() / df['blocktime'].rolling(numBlocks).sum()\n\ndef add_GLPS(df, numBlocks):\n \"\"\"\n gasLimit per second\n \"\"\"\n name = 'GLPS_%dblks'%numBlocks if numBlocks>1 else 'GLPS_%dblk'%numBlocks\n df[name]=df['gasLimit'].rolling(numBlocks).sum() / df['blocktime'].rolling(numBlocks).sum()\n\n\n##################################################\n## diagramming stand-alone\n## does the same as the jupyter notebook\n## but more convenient for cloud server \n## ... on the command line\n##\n##################################################\n## TODOs: \n## * also get the simpler single diagrams ? \n## from the original blocksDB_analyze.ipynb\n## * doc strings for the following routines:\n##################################################\n\ndef load_dependencies():\n \n import sqlite3; print(\"sqlite3 version\", sqlite3.version)\n import pandas; print(\"pandas version\", pandas.__version__)\n import numpy; print(\"numpy version\", numpy.__version__)\n import matplotlib; print(\"matplotlib version\", matplotlib.__version__)\n from matplotlib import pyplot as plt\n \n backend=matplotlib.get_backend()\n print(\"matplotlib backend\", backend)\n \n # get_ipython().run_line_magic('matplotlib', 'inline')\n \n # https://github.com/matplotlib/matplotlib/issues/5907#issuecomment-179001811\n matplotlib.rcParams['agg.path.chunksize'] = 10000\n \n # my own routines are now all in separate .py file:\n # from blocksDB_diagramming import DB_query, DB_tableSize, maxBlockNumber, check_whether_complete\n # from blocksDB_diagramming import add_blocktime, add_TPS, add_GUPS, add_GLPS\n\n\ndef load_db_and_check_complete(DBFILE):\n print (\"\\nReading blocks table from\", DBFILE)\n \n # open database connection\n conn = sqlite3.connect(DBFILE)\n \n print (\"DB table names: \", \n DB_query(\"SELECT name FROM sqlite_master WHERE type='table';\", conn)[0])\n \n # number of rows?\n _=DB_tableSize(\"blocks\", conn)\n \n # what is the first & last block we have?\n minblock, maxblock = maxBlockNumber(conn)[0]\n \n blocknumbers = DB_query(\"SELECT blocknumber FROM blocks ORDER BY blocknumber\", conn) \n print (\"len(blocknumbers)=\", len(blocknumbers))\n \n # do we have consecutive blocks, none missing?\n check_whether_complete(blocknumbers)\n print ()\n\n return conn, blocknumbers\n\n\ndef simple_stats(conn):\n \n # simple statistics\n\n txcount_sum = DB_query(\"SELECT SUM(txcount) FROM blocks\", conn); print (\"txcount_sum\", txcount_sum[0][0]) \n size_max = DB_query(\"SELECT MAX(size) FROM blocks\", conn); print (\"blocksize_max\", size_max[0][0])\n txcount_max = DB_query(\"SELECT MAX(txcount) FROM blocks\", conn); print (\"txcount_max\", txcount_max[0][0])\n txcount_av = DB_query(\"SELECT AVG(txcount) FROM blocks\", conn); print (\"txcount average per block\", txcount_av[0][0])\n blocks_nonempty_count = DB_query(\"SELECT COUNT(blocknumber) FROM blocks WHERE txcount != 0\", conn); print (\"blocks_nonempty_count\", blocks_nonempty_count[0][0])\n print (\"txcount average per NONEMPTY blocks = \", txcount_sum[0][0] / blocks_nonempty_count[0][0] )\n print ()\n \n \ndef read_whole_table_into_dataframe(conn):\n \n # SQL=\"SELECT * FROM blocks WHERE 48500<blocknumber and blocknumber<49000 ORDER BY blocknumber\"\n SQL=\"SELECT * FROM blocks ORDER BY blocknumber\"\n df = pandas.read_sql(SQL, conn)\n\n return df\n \n\ndef check_timestamp_format(df):\n \"\"\"\n some clients report absolute blocktime as epochtime in seconds, \n some in nanoseconds\n that should have been handled already, in the timestampToSeconds() function\n but if it hasn't, the problem would show up here.\n \"\"\"\n # print (\"example- first 4 rows:\")\n # print (df[0:4])\n # better come up with an automated test, not just visual inspection: \n # print (\" is timestamp in seconds?\")\n # ### `geth` based clients have a nanosecond timestamp\n # not anymore?\n # transform nanoseconds to seconds\n # df[\"timestamp\"]=df[\"timestamp\"]/1000000000\n\n problematic = []\n for ts in df[\"timestamp\"]:\n # year 2001 year 2255 testrpc-py issue https://github.com/pipermerriam/eth-testrpc/issues/117\n if not ((1000000000 < ts < 9000000000) or (6000000 < ts < 8000000)): \n problematic.append(ts)\n \n if problematic:\n print (\"%d problematic timestamps = probably not in unit of seconds\" % len(problematic))\n try:# try, for the case that the list is short\n problematic = problematic[:3] + problematic[-3:]\n problematic = sorted(list(set(problematic))) # remove duplicates\n except:\n pass\n print (\"examples:\", problematic)\n \n # hello year 2255, you might have a Y2286 problem \n # when epochtime goes from 9999999999 to 10000000000\n # someone warned you 30 years earlier. Hahaha :-)\n return not problematic\n\n\ndef add_columns(df):\n\n # blocktime = timestamp[n] - timestamp[n-1]\n add_blocktime(df)\n \n \n #df[\"TPS_1\"]=df['txcount']/df['blocktime']\n #df\n \n \n # transactions per second\n # with differently sized (rectangular) windows\n add_TPS(df, numBlocks=1)\n add_TPS(df, numBlocks=3)\n add_TPS(df, numBlocks=5)\n add_TPS(df, numBlocks=10)\n \n \n # gasUsed and gasLimit per second\n add_GUPS(df, numBlocks=1)\n add_GUPS(df, numBlocks=3)\n add_GUPS(df, numBlocks=5)\n \n add_GLPS(df, numBlocks=1)\n add_GLPS(df, numBlocks=3)\n add_GLPS(df, numBlocks=5)\n\n print (\"\\nColumns added. Now: \", df.columns.tolist() )\n print ()\n \n \ndef show_peak_TPS(df):\n \n columns = ['blocknumber', \n 'TPS_1blk', 'TPS_3blks', 'TPS_5blks', 'TPS_10blks',\n 'txcount', 'size', 'gasUsed', 'gasLimit', 'timestamp', 'blocktime'] \n\n print (\"peak TPS single block:\")\n df1 = df.sort_values(by=['TPS_1blk'], ascending=False)[0:10]\n max1 = max(df1['TPS_1blk'])\n pprint (df1[columns])\n \n \n print (\"\\npeak TPS over ten blocks:\")\n df10 = df.sort_values(by=['TPS_10blks'], ascending=False)[0:10]\n max10 = max(df10['TPS_10blks'])\n pprint (df10[columns])\n\n print (\"\\nSingle block, vs averaged over 10 blocks:\")\n print (\"peak( TPS_1blk) = %.2f \\npeak(TPS_10blk) = %.2f\" % (max1,max10))\n return max1, max10\n \n\ndef diagrams_oldversion(df, blockFrom, blockTo, prefix=\"\", gas_logy=True, bt_logy=True, imgpath=\"img\"):\n \"\"\"\n OBSOLETE NOW!\n \"\"\"\n \n from matplotlib import pyplot as plt\n \n # https://github.com/matplotlib/matplotlib/issues/5907#issuecomment-179001811\n matplotlib.rcParams['agg.path.chunksize'] = 10000\n \n ###################################################\n # prepare 2x2 subplots\n # plt = matplotlib.pyplot\n fig, axes = plt.subplots(nrows=2, ncols=2,figsize=(15,10))\n plt.tight_layout(pad=6.0, w_pad=6.0, h_pad=7.5)\n title = prefix + \" blocks %d to %d\" % (blockFrom, blockTo)\n plt.suptitle(title, fontsize=16)\n \n ####################################\n # TPS\n \n # TPS averages --> legend\n cols=['TPS_1blk', 'TPS_3blks', 'TPS_5blks', 'TPS_10blks']\n averages=df[cols][blockFrom:blockTo].mean()\n legend = [col + \" (av %.1f)\" % averages[col] for col in cols]\n # print (legend)\n \n # TPS diagram\n cols = ['blocknumber'] + cols\n ax=df[cols][blockFrom:blockTo].plot(x='blocknumber', rot=90, ax=axes[0,0])\n ax.set_title(\"transactions per second\")\n ax.get_xaxis().get_major_formatter().set_useOffset(False)\n ax.legend(legend);\n \n ###########################################\n # bar charts or line charts\n \n # bar charts are too expensive when too many blocks\n numBlocks = blockTo - blockFrom\n kind = 'bar' if numBlocks<2000 else 'line'\n \n #############################################\n # BT\n ax=df[['blocknumber', 'blocktime']][blockFrom:blockTo].plot(x='blocknumber', kind=kind, ax=axes[0,1],\n logy=bt_logy)\n ax.set_title(\"blocktime since last block\")\n ax.locator_params(nbins=1, axis='x') # TODO: matplotlib's ticks - how to autoselect few? Any idea welcome\n \n #############################################\n # blocksize\n ax=df[['blocknumber', 'size']][blockFrom:blockTo].plot(x='blocknumber', rot=90, kind=kind, ax=axes[1,0])\n # ax.get_xaxis().get_major_formatter().set_useOffset(False)\n ax.get_yaxis().get_major_formatter().set_scientific(False)\n ax.set_title(\"blocksize in bytes\")\n ax.locator_params(nbins=1, axis='x') # TODO: matplotlib's ticks - how to autoselect few? Any idea welcome\n \n ####################################\n # gas\n ax=df[['blocknumber', 'GLPS_1blk', 'GUPS_1blk']][blockFrom:blockTo].plot(x='blocknumber', \n rot=90, ax=axes[1,1], \n logy=gas_logy)\n ax.get_xaxis().get_major_formatter().set_useOffset(False)\n if not gas_logy:\n ax.get_yaxis().get_major_formatter().set_scientific(False)\n ax.set_title(\"gasUsed and gasLimit per second\")\n \n ##############################################\n # save diagram to PNG file\n filename = \"%s_tps-bt-bs-gas_blks%d-%d.png\" % (prefix,blockFrom,blockTo)\n filepath = os.path.join(imgpath, filename)\n fig.savefig(filepath)\n \n return filepath\n\n\n\n################################################################################\n# new diagrams\n# completely overhauled, mostly written new actually\n################################################################################\n\n\n\n\ndef experiment_slice(df, FROM_BLOCK, TO_BLOCK, emptyBlocks):\n \"\"\"\n cut out the dataframe from FROM_BLOCK to TO_BLOCK+emptyBlocks (incl that last one)\n can handle that df starts not at block 0\n can handle that limits are smaller or larger than available blocknumbers\n \n \"\"\"\n assert FROM_BLOCK <= TO_BLOCK\n \n index_from = min( df[df['blocknumber'] >= FROM_BLOCK].index.tolist() )\n # print (slice_from)\n \n index_to = max( df[df['blocknumber'] <= TO_BLOCK+emptyBlocks].index.tolist() )\n # print(slice_to)\n \n dfs = df[index_from:index_to + 1]\n \n return dfs, index_from, index_to\n\n\ndef averageTps_wholeExperiment(dfs, FROM_BLOCK, TO_BLOCK):\n \"\"\"\n works on already sliced dataframe, \n where first experiment block is index 0\n and last experiment(!) block is index [TO_BLOCK - FROM_BLOCK],\n (so the 10 empty blocks at the end are NOT part of this!)\n N.B.:\n we cannot rely on the blocktime of very first block\n so we simply leave the transactions out of the summation, and \n the duration is from when that first block WAS MINED = its timestamp.\n \"\"\"\n \n blocks = TO_BLOCK - FROM_BLOCK + 1\n ts1 = dfs.iloc[0]['timestamp'] # stop clock starts WHEN block 0 is in already!\n bn1 = dfs.iloc[0]['blocknumber']\n ts2 = dfs.iloc[blocks-1]['timestamp'] # and clock ends at last filled block\n bn2 = dfs.iloc[blocks-1]['blocknumber']\n duration = ts2-ts1\n txs=sum(dfs['txcount'][1:blocks]) # N.B.: start summing at block 1 not 0 !\n tps=(txs/duration)\n\n print (\"second to last experiment block, averaging:\")\n txt=\"blocks %d-%d, timestamps %d-%d, duration %d seconds, txcount %d, tps %.1f\"\n print (txt % (bn1, bn2, ts1, ts2, duration, txs, tps))\n print()\n\n return tps, \"%.1f\" % tps\n\n\ndef averager(dfs, col, emptyBlocks, fmt=\"%.1f\"):\n \"\"\"\n We want the real average of that 'col', taken only over the non-empty blocks.\n \n N.B.: this assumes that there are actually enough emptyBlocks at the end!\n \"\"\"\n filledSlice = dfs[col] [:len(dfs)-emptyBlocks-1]\n av = avCopy = filledSlice .mean()\n if fmt==\"%d\": \n avCopy = int(round(av))\n avTxt = fmt % avCopy\n return av, avTxt\n\n\ndef avgLine(ax, dfs, emptyBlocks, avg, avgTxt):\n \"\"\"\n horizontal line plus text on white background\n \"\"\"\n lastFilledBlock_index = len(dfs)-emptyBlocks-1\n blMin, blMax = min(dfs[\"blocknumber\"])+1, max(dfs[\"blocknumber\"][:lastFilledBlock_index])\n ax.plot([blMin, blMax], [avg, avg], \"k-\")\n \n ax.text(blMin + (blMax-blMin + emptyBlocks)*0.95, avg, avgTxt, \n bbox=dict(facecolor='white', edgecolor='white'))\n \n\ndef axes_simplifier(ax, logYscale=False):\n \"\"\"\n otherwise matplotlib automatically switches on notations on the ticks \n that might be confusing to non-technical people\n \"\"\"\n ax.get_xaxis().get_major_formatter().set_useOffset(False)\n ax.get_xaxis().get_major_formatter().set_scientific(False)\n if not logYscale:\n ax.get_yaxis().get_major_formatter().set_useOffset(False)\n ax.get_yaxis().get_major_formatter().set_scientific(False)\n\n\ndef tps_plotter(ax, dfs, FROM_BLOCK, TO_BLOCK, emptyBlocks):\n \"\"\"\n TPS average calculated only over non-empty blocks!\n average calculated for TPS (not for smoothed 3, 5, 10 blocks averages)\n \n N.B.: this assumes that in dfs there are actually enough emptyBlocks at the end!\n \"\"\"\n cols=['TPS_1blk', 'TPS_3blks', 'TPS_5blks', 'TPS_10blks']\n for col in cols:\n ax.plot(dfs['blocknumber'], dfs[col])\n\n axes_simplifier(ax)\n \n #avg1, avg1Txt = averager(dfs, cols[0], emptyBlocks, \"%.1f\")\n #legend = [cols[0] + \" (avg1 %s)\"%avg1Txt ] + cols[1:]\n ax.legend(cols); \n \n avg, avgTxt = averageTps_wholeExperiment(dfs, FROM_BLOCK, TO_BLOCK)\n avgLine(ax, dfs, emptyBlocks, avg, avgTxt)\n print (\"averaged over whole experiment: %s TPS\" %avgTxt)\n \n ax.set_title(\"avg TPS %s = #TX whole experiment / blocktimes diff\" % avgTxt)\n \n return avg\n \n \ndef blocktimes_plotter(ax, dfs):\n \"plot the blocktimes\"\n\n ax.set_title(\"blocktime seconds since last block\")\n \n ax.scatter(x=dfs['blocknumber'], y=dfs['blocktime'], c=\"b\", marker=\"x\")\n \n axes_simplifier(ax)\n\n\ndef blocksizes_plotter(ax, dfs, emptyBlocks):\n \"\"\"\n blocksizes\n plus average line\n \"\"\"\n \n ax.scatter(dfs['blocknumber'], dfs['size'], c=\"g\", marker=\"o\")\n ax.plot( dfs['blocknumber'], dfs['size'], \"g-\")\n \n avg, avgTxt = averager(dfs, 'size', emptyBlocks, \"%d\")\n avgLine(ax, dfs, emptyBlocks, avg, avgTxt)\n print ('averaged ( \" ) blocksize: %s bytes' % avgTxt)\n \n ax.set_title(\"blocksizes in bytes\")\n \n axes_simplifier(ax)\n\n\ndef gas_plotter(ax, dfs):\n \"\"\"\n plot gasUsed and gasLimit per second\n \"\"\"\n ax.set_title(\"gasUsed and gasLimit per second\") \n \n ax.plot( dfs['blocknumber'], dfs['GLPS_1blk']) # , \"g-\")\n ax.plot( dfs['blocknumber'], dfs['GUPS_1blk']) # \n \n ax.set_yscale('log')\n \n axes_simplifier(ax, logYscale=True)\n ax.legend ([\"gasLimit/sec\", \"gasUsed/sec\"] )\n\n\ndef diagrams(prefix, df, blockFrom, blockTo, emptyBlocks):\n \"\"\"\n new version \n more precise & consistent\n * slice of whole experiment (from/to), plus some emptyBlocks at the end\n * averages are calc'ed over the experiment blocks only! \n * average lines & number for tps & block size\n * title shows more infos about experiment\n * x-axis ticks issues solved\n \"\"\"\n \n # offset=min(df[\"blocknumber\"])\n # just the slice of the experiment + 10 extra blocks:\n # dfs = df[FROM_BLOCK-offset:TO_BLOCK-offset+emptyBlocks+1] \n dfs, index_from, index_to = experiment_slice(df, blockFrom, blockTo, emptyBlocks)\n \n # https://github.com/matplotlib/matplotlib/issues/5907#issuecomment-179001811\n import matplotlib\n matplotlib.rcParams['agg.path.chunksize'] = 10000\n \n fig, axes = plt.subplots(2, 2, figsize=(16,9)) #, sharex=True)\n fig.subplots_adjust(hspace=0.25, wspace=0.20)\n \n tpsAv = tps_plotter(axes[0,0], dfs, blockFrom, blockTo, emptyBlocks)\n blocktimes_plotter(axes[0,1], dfs)\n blocksizes_plotter(axes[1,0], dfs, emptyBlocks) \n gas_plotter(axes[1,1], dfs)\n \n txs=sum(dfs['txcount'][0:-emptyBlocks+1])\n title = prefix + \" blocks %d-%d with %d txs ~ %d txs/block\" \n title = title % (blockFrom, blockTo, txs, round(txs/(blockTo-blockFrom+1)))\n fig.suptitle(title, fontsize=16)\n \n return fig, axes, dfs, txs, tpsAv\n\n\ndef read_experiment_infofile(fn):\n \"\"\"\n now the experiments are all writing out basic information.\n read this in here, to know the range of blocks.\n \"\"\"\n with open(fn, \"r\") as f:\n info = json.load(f)\n return info\n\n\ndef timestamp_humanreadable(epoch):\n return time.strftime(\"%Y%m%d-%H%M\", time.localtime(epoch))\n\n\ndef savePlot(fig, prefix, blockFrom, blockTo, imgpath, INFOFILE=None):\n if INFOFILE:\n info = read_experiment_infofile(INFOFILE)\n ts = timestamp_humanreadable(info['tps']['start_epochtime'])\n prefix = prefix + \"-\" +ts\n filename = \"%s_blks%d-%d.png\" % (prefix,blockFrom,blockTo)\n filepath = os.path.join(imgpath, filename)\n fig.savefig(filepath)\n return filepath\n\n\ndef add_to_infofile(INFOFILE, img_fn, tpsAv, prefix):\n info = read_experiment_infofile(fn=INFOFILE)\n info['diagrams']={}\n info['diagrams']['filename'] = img_fn\n info['diagrams']['blocktimestampsTpsAv'] = tpsAv\n info['diagrams']['prefix'] = prefix\n with open(INFOFILE, \"w\") as f:\n json.dump(info, f)\n \n \n\n################################################################################\n\ndef load_prepare_plot_save(DBFILE, NAME_PREFIX, \n FROM_BLOCK, TO_BLOCK, EMPTY_BLOCKS, \n INFOFILE, imgpath=\"img\"):\n \n load_dependencies()\n conn, blocknumbers = load_db_and_check_complete(DBFILE)\n simple_stats(conn)\n df = read_whole_table_into_dataframe(conn)\n conn.close()\n assert check_timestamp_format(df)\n add_columns(df)\n show_peak_TPS(df)\n \n if FROM_BLOCK==-1: FROM_BLOCK = min(blocknumbers)[0]\n if TO_BLOCK==-1: TO_BLOCK = max(blocknumbers)[0]\n # print (FROM_BLOCK, TO_BLOCK); exit()\n \n print()\n # fn = diagrams_oldversion(df, FROM_BLOCK, TO_BLOCK, NAME_PREFIX, gas_logy=True, bt_logy=True, imgpath=imgpath)\n fig, axes, dfs, txs, tpsAv = diagrams(NAME_PREFIX, df, FROM_BLOCK, TO_BLOCK,\n emptyBlocks=EMPTY_BLOCKS)\n fn = savePlot(fig, NAME_PREFIX, FROM_BLOCK, TO_BLOCK, imgpath, INFOFILE)\n \n print (\"\\ndiagrams saved to: \", fn)\n \n if INFOFILE:\n add_to_infofile(INFOFILE, fn, tpsAv, NAME_PREFIX) \n \n return fn\n\n###############################################################################\n\ndef sanify(mystring):\n \"\"\"\n from given string, make something that can be used as filename\n \"\"\"\n keepcharacters = ('-','.','_')\n sane = \"\".join(c for c in mystring if c.isalnum() or c in keepcharacters)\n sane = sane.rstrip()\n return sane\n \n\ndef CLI_params():\n\n if len(sys.argv) not in (3, 4, 5):\n print (\"Please give\\n\"\n \"THREE arguments DBFILE PREFIX INFOFILE\\n\\n\"\n \"Or give FOUR arguments, \\n\"\n \"the filename DBFILE ___.db, \\n\"\n \"a PREFIX for characterising the diagram output files; \\n\"\n \"and FROM_BLOCK and TO_BLOCK for where to zoom,\\n\"\n \"or\\n\"\n \"give only the first TWO arguments, for the whole chain\\n\\n\"\n \"examples:\\n\"\n \"%s temp.db TEMP ../hammer/last-experiment.json\\n\"\n \"%s temp.db TEMP 115 230\\n\"\n \"%s temp.db TEMP\\n\" % (sys.argv[0], sys.argv[0], sys.argv[0]))\n exit(1)\n \n DBFILE=sys.argv[1]\n NAME_PREFIX = sanify( sys.argv[2] )\n print (\"using DBFILE=%s NAME_PREFIX=%s\" % (DBFILE, NAME_PREFIX))\n \n if len(sys.argv)==3:\n FROM_BLOCK=-1\n TO_BLOCK=-1\n print (\"for the whole chain, first to last block\")\n\n INFOFILE=None\n EMPTY_BLOCKS = EMPTY_BLOCKS_AT_END\n \n if len(sys.argv) == 4:\n INFOFILE=sys.argv[3]\n print (\"reading blocks range from\", INFOFILE)\n info = read_experiment_infofile(fn=INFOFILE)\n # pprint(info); exit()\n FROM_BLOCK = info['send']['block_first']\n TO_BLOCK = info['send']['block_last']\n EMPTY_BLOCKS = info['send']['empty_blocks']\n txt = \"from block %d to block %d, with %d empty blocks afterwards\"\n print (txt % (FROM_BLOCK, TO_BLOCK, EMPTY_BLOCKS) )\n\n if len(sys.argv)==5:\n FROM_BLOCK=int(sys.argv[3])\n TO_BLOCK =int(sys.argv[4])\n print (\"from block %d to block %d\" % (FROM_BLOCK, TO_BLOCK) ) \n\n print ()\n return DBFILE, NAME_PREFIX, FROM_BLOCK, TO_BLOCK, EMPTY_BLOCKS, INFOFILE\n\n\nif __name__ == '__main__':\n \n # ./blocksDB_diagramming.py temp1.db TEMP 54 124\n params = CLI_params();\n \n # params = (\"temp1.db\", \"TEMP\", 54, 124) \n # params = (\"temp1.db\", \"TEMP\", 0, 233)\n # params = (\"temp2.db\", \"TEMP\", 0, 5000) \n\n load_prepare_plot_save(*params)\n\n print (\"Done.\")\n \n "
] |
[
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"matplotlib.get_backend",
"matplotlib.pyplot.suptitle",
"pandas.read_sql"
]
] |
kongyanye/paper_search
|
[
"a5e8ab6210dd73988a5b0912bcbfc814b8a09f5e"
] |
[
"analyze.py"
] |
[
"\"\"\"\nReads txt files of all papers and computes tfidf vectors for all papers.\nDumps results to file tfidf.p\n\"\"\"\n\nfrom random import shuffle, seed\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom utils import Config, safe_pickle_dump, load_db\n\nseed(1337)\n# max number of tfidf training documents (chosen randomly), for memory efficiency\nmax_train = 50000\nmax_features = 50000\n\n# reading papers\ndb = load_db()\n\n# compute tfidf vectors with scikits\nv = TfidfVectorizer(input='content',\n encoding='utf-8', decode_error='replace', strip_accents='unicode',\n lowercase=True, analyzer='word', stop_words='english',\n token_pattern=r'(?u)\\b[a-zA-Z_][a-zA-Z0-9_]+\\b',\n ngram_range=(1, 2), max_features=max_features,\n norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=True,\n max_df=1.0, min_df=1)\n\n# create an iterator object to conserve memory\n\n\ndef make_corpus(paths):\n for p in paths:\n yield db[p].get('summary', '')\n\n\ntxt_paths = list(db.keys())\npids = []\nfor pid, j in db.items():\n if '_rawid' in j:\n idvv = '%sv%d' % (j['_rawid'], j['_version'])\n else:\n idvv = pid\n pids.append(idvv)\n\n# train\ntrain_txt_paths = list(txt_paths) # duplicate\nshuffle(train_txt_paths) # shuffle\ntrain_txt_paths = train_txt_paths[:min(\n len(train_txt_paths), max_train)] # crop\nprint(\"training on %d documents...\" % (len(train_txt_paths), ))\ntrain_corpus = make_corpus(train_txt_paths)\nv.fit(train_corpus)\n\n# transform\nprint(\"transforming %d documents...\" % (len(txt_paths), ))\ncorpus = make_corpus(txt_paths)\nX = v.transform(corpus)\n# print(v.vocabulary_)\nprint(X.shape)\n\n# write full matrix out\nout = {}\nout['X'] = X # this one is heavy!\nprint(\"writing\", Config.tfidf_path)\nsafe_pickle_dump(out, Config.tfidf_path)\n\n# writing lighter metadata information into a separate (smaller) file\nout = {}\nout['vocab'] = v.vocabulary_\nout['idf'] = v._tfidf.idf_\nout['pids'] = pids # a full idvv string (id and version number)\nout['ptoi'] = {x: i for i, x in enumerate(pids)} # pid to ix in X mapping\nprint(\"writing\", Config.meta_path)\nsafe_pickle_dump(out, Config.meta_path)\n\n'''\nprint(\"precomputing nearest neighbor queries in batches...\")\nX = X.todense() # originally it's a sparse matrix\nsim_dict = {}\nbatch_size = 1000\nfor i in range(0, len(pids), batch_size):\n i1 = min(len(pids), i+batch_size)\n xquery = X[i:i1] # BxD\n ds = -np.asarray(np.dot(X, xquery.T)) # NxD * DxB => NxB\n IX = np.argsort(ds, axis=0) # NxB\n for j in range(i1-i):\n sim_dict[pids[i+j]] = [pids[q] for q in list(IX[:50, j])]\n print('%d/%d...' % (i, len(pids)))\n\nprint(\"writing\", Config.sim_path)\nsafe_pickle_dump(sim_dict, Config.sim_path)\n'''"
] |
[
[
"sklearn.feature_extraction.text.TfidfVectorizer"
]
] |
MISC-FORKS-cqc/onnx
|
[
"c50f329dcde038aa364082e0942764d36fcd1448"
] |
[
"onnx/backend/test/case/node/sub.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np # type: ignore\n\nimport onnx\nfrom ..base import Base\nfrom . import expect\n\n\nclass Sub(Base):\n\n @staticmethod\n def export(): # type: () -> None\n node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n )\n\n x = np.array([1, 2, 3]).astype(np.float32)\n y = np.array([3, 2, 1]).astype(np.float32)\n z = x - y # expected output [-2., 0., 2.]\n expect(node, inputs=[x, y], outputs=[z],\n name='test_sub_example')\n\n x = np.random.randn(3, 4, 5).astype(np.float32)\n y = np.random.randn(3, 4, 5).astype(np.float32)\n z = x - y\n expect(node, inputs=[x, y], outputs=[z],\n name='test_sub')\n\n @staticmethod\n def export_sub_broadcast(): # type: () -> None\n node = onnx.helper.make_node(\n 'Sub',\n inputs=['x', 'y'],\n outputs=['z'],\n broadcast=1,\n )\n\n x = np.random.randn(3, 4, 5).astype(np.float32)\n y = np.random.randn(5).astype(np.float32)\n z = x - y\n expect(node, inputs=[x, y], outputs=[z],\n name='test_sub_bcast')\n"
] |
[
[
"numpy.array",
"numpy.random.randn"
]
] |
FMsunyh/SiamDW
|
[
"ef7a97ee6bdf732edbb7dc2943daf15b92535019"
] |
[
"siamese_tracking/test_siamrpn.py"
] |
[
"# ------------------------------------------------------------------------------\r\n# Copyright (c) Microsoft\r\n# Licensed under the MIT License.\r\n# Written by Houwen Peng and Zhipeng Zhang\r\n# Email: [email protected]\r\n# Clean testing scripts for SiamRPN\r\n# New: support GENE and TPE tuning\r\n# ------------------------------------------------------------------------------\r\n\r\nimport _init_paths\r\nimport os\r\nimport cv2\r\nimport random\r\nimport argparse\r\nimport numpy as np\r\n# import matlab.engine\r\nfrom os.path import exists, join\r\nimport models.models as models\r\nfrom tracker.siamrpn import SiamRPN\r\nfrom torch.autograd import Variable\r\nfrom easydict import EasyDict as edict\r\nfrom utils.utils import load_pretrain, cxy_wh_2_rect, get_axis_aligned_bbox, load_dataset, poly_iou\r\n\r\n# eng = matlab.engine.start_matlab()\r\n\r\ndef parse_args():\r\n \"\"\"\r\n args for rpn testing.\r\n \"\"\"\r\n parser = argparse.ArgumentParser(description='PyTorch SiamRPN Tracking Test')\r\n parser.add_argument('--arch', dest='arch', default='SiamRPNIncep22', help='backbone architecture')\r\n parser.add_argument('--resume', required=True, type=str, help='pretrained model')\r\n parser.add_argument('--dataset', default='VOT2017', help='dataset test')\r\n parser.add_argument('--anchor_nums', default=5, type=int, help='anchor numbers')\r\n parser.add_argument('--cls_type', default=\"thinner\", type=str, help='cls/loss type, thicker or thinner or else you defined')\r\n parser.add_argument('--epoch_test', default=False, type=bool, help='multi-gpu epoch test flag')\r\n args = parser.parse_args()\r\n\r\n return args\r\n\r\n\r\ndef track(tracker, net, video, args):\r\n start_frame, lost_times, toc = 0, 0, 0\r\n\r\n # save result to evaluate\r\n if args.epoch_test:\r\n suffix = args.resume.split('/')[-1]\r\n suffix = suffix.split('.')[0]\r\n tracker_path = os.path.join('result', args.dataset, args.arch + suffix)\r\n else:\r\n tracker_path = os.path.join('result', args.dataset, args.arch)\r\n\r\n if not os.path.exists(tracker_path):\r\n os.makedirs(tracker_path)\r\n\r\n if 'VOT' in args.dataset:\r\n baseline_path = join(tracker_path, 'baseline')\r\n video_path = join(baseline_path, video['name'])\r\n if not os.path.exists(video_path):\r\n os.makedirs(video_path)\r\n result_path = join(video_path, video['name'] + '_001.txt')\r\n else:\r\n result_path = join(tracker_path, '{:s}.txt'.format(video['name']))\r\n\r\n if os.path.exists(result_path):\r\n return 0 # for mult-gputesting\r\n\r\n regions = [] # result and states[1 init / 2 lost / 0 skip]\r\n image_files, gt = video['image_files'], video['gt']\r\n for f, image_file in enumerate(image_files):\r\n im = cv2.imread(image_file)\r\n if len(im.shape) == 2:\r\n im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)\r\n\r\n tic = cv2.getTickCount()\r\n\r\n if f == start_frame: # init\r\n cx, cy, w, h = get_axis_aligned_bbox(gt[f])\r\n target_pos = np.array([cx, cy])\r\n target_sz = np.array([w, h])\r\n state = tracker.init(im, target_pos, target_sz, net) # init tracker\r\n regions.append(1 if 'VOT' in args.dataset else gt[f])\r\n elif f > start_frame: # tracking\r\n state = tracker.track(state, im) # track\r\n location = cxy_wh_2_rect(state['target_pos'], state['target_sz'])\r\n b_overlap = poly_iou(gt[f], location) if 'VOT' in args.dataset else 1\r\n if b_overlap > 0:\r\n regions.append(location)\r\n else:\r\n regions.append(2)\r\n lost_times += 1\r\n start_frame = f + 5 # skip 5 frames\r\n else: # skip\r\n regions.append(0)\r\n toc += cv2.getTickCount() - tic\r\n toc /= cv2.getTickFrequency()\r\n\r\n with open(result_path, \"w\") as fin:\r\n if 'VOT' in args.dataset:\r\n for x in regions:\r\n if isinstance(x, int):\r\n fin.write(\"{:d}\\n\".format(x))\r\n else:\r\n p_bbox = x.copy()\r\n fin.write(','.join([str(i) for i in p_bbox]) + '\\n')\r\n else:\r\n for x in regions:\r\n p_bbox = x.copy()\r\n fin.write(','.join([str(i + 1) if idx == 0 or idx == 1 else str(i) for idx, i in enumerate(p_bbox)]) + '\\n')\r\n\r\n print('Video: {:12s} Time: {:2.1f}s Speed: {:3.1f}fps Lost: {:d}'.format(video['name'], toc, f / toc, lost_times))\r\n\r\n return lost_times\r\n\r\n\r\ndef main():\r\n args = parse_args()\r\n total_lost = 0\r\n\r\n # prepare model\r\n net = models.__dict__[args.arch](anchors_nums=args.anchor_nums, cls_type=args.cls_type)\r\n net = load_pretrain(net, args.resume)\r\n net.eval()\r\n net = net.cuda()\r\n\r\n # prepare video\r\n dataset = load_dataset(args.dataset)\r\n video_keys = list(dataset.keys()).copy()\r\n\r\n # prepare tracker\r\n info = edict()\r\n info.arch = args.arch\r\n info.cls_type = args.cls_type\r\n info.dataset = args.dataset\r\n info.epoch_test = args.epoch_test\r\n tracker = SiamRPN(info)\r\n\r\n for video in video_keys:\r\n total_lost += track(tracker, net, dataset[video], args)\r\n print('Total Lost: {:d}'.format(total_lost))\r\n\r\n\r\n# ------------------------------------------------------------\r\n# The next few functions are utilized for tuning\r\n# Only VOT is supported\r\n# About 1000 - 3000 group is needed\r\n# ------------------------------------------------------------\r\ndef track_tune(tracker, net, video, config):\r\n arch = config['arch']\r\n benchmark_name = config['benchmark']\r\n resume = config['resume']\r\n hp = config['hp'] # penalty_k, scale_lr, window_influence, adaptive size (for vot2017 or later)\r\n\r\n tracker_path = join('test', (benchmark_name + resume.split('/')[-1].split('.')[0] +\r\n '_small_size_{:.4f}'.format(hp['small_sz']) +\r\n '_big_size_{:.4f}'.format(hp['big_sz']) +\r\n '_penalty_k_{:.4f}'.format(hp['penalty_k']) +\r\n '_w_influence_{:.4f}'.format(hp['window_influence']) +\r\n '_scale_lr_{:.4f}'.format(hp['lr'])).replace('.', '_')) # no .\r\n\r\n if not os.path.exists(tracker_path):\r\n os.makedirs(tracker_path)\r\n\r\n if 'VOT' in benchmark_name:\r\n baseline_path = join(tracker_path, 'baseline')\r\n video_path = join(baseline_path, video['name'])\r\n if not os.path.exists(video_path):\r\n os.makedirs(video_path)\r\n result_path = join(video_path, video['name'] + '_001.txt')\r\n else:\r\n raise ValueError('Only VOT is supported')\r\n\r\n # occ for parallel running\r\n if not os.path.exists(result_path):\r\n fin = open(result_path, 'w')\r\n fin.close()\r\n else:\r\n if benchmark_name.startswith('VOT'):\r\n return 0\r\n else:\r\n raise ValueError('Only VOT is supported')\r\n\r\n\r\n start_frame, lost_times, toc = 0, 0, 0\r\n regions = [] # result and states[1 init / 2 lost / 0 skip]\r\n image_files, gt = video['image_files'], video['gt']\r\n for f, image_file in enumerate(image_files):\r\n im = cv2.imread(image_file)\r\n if len(im.shape) == 2:\r\n im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)\r\n if f == start_frame: # init\r\n cx, cy, w, h = get_axis_aligned_bbox(gt[f])\r\n target_pos = np.array([cx, cy])\r\n target_sz = np.array([w, h])\r\n state = tracker.init(im, target_pos, target_sz, net, hp=hp) # init tracker\r\n regions.append([float(1)] if 'VOT' in benchmark_name else gt[f])\r\n elif f > start_frame: # tracking\r\n state = tracker.track(state, im) # track\r\n location = cxy_wh_2_rect(state['target_pos'], state['target_sz'])\r\n b_overlap = poly_iou(gt[f], location) if 'VOT' in benchmark_name else 1\r\n if b_overlap > 0:\r\n regions.append(location)\r\n else:\r\n regions.append([float(2)])\r\n lost_times += 1\r\n start_frame = f + 5 # skip 5 frames\r\n else: # skip\r\n regions.append([float(0)])\r\n\r\n # save results for OTB\r\n if benchmark_name.startswith('VOT'):\r\n return regions\r\n else:\r\n raise ValueError('Only VOT is supported')\r\n\r\n\r\n\r\ndef eao_vot_rpn(tracker, net, config):\r\n dataset = load_dataset(config['benchmark'])\r\n video_keys = sorted(list(dataset.keys()).copy())\r\n results = []\r\n for video in video_keys:\r\n video_result = track_tune(tracker, net, dataset[video], config)\r\n results.append(video_result)\r\n\r\n year = config['benchmark'][-4:] # need a str, instead of a int\r\n eng.cd('./lib/core')\r\n eao = eng.get_eao(results, year)\r\n\r\n return eao\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n"
] |
[
[
"numpy.array"
]
] |
gnomonsis/nncf_pytorch
|
[
"9fc4a92b5cb1b2c240e633c4ffa69b4fae1917fb"
] |
[
"tests/test_backward_compat.py"
] |
[
"\"\"\"\n Copyright (c) 2019-2020 Intel Corporation\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 http://www.apache.org/licenses/LICENSE-2.0\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 os\nimport pytest\nimport torch\n\nfrom examples.common.distributed import configure_distributed\nfrom examples.common.execution import ExecutionMode, prepare_model_for_execution, get_device\nfrom examples.common.model_loader import load_model\nfrom examples.common.sample_config import SampleConfig\nfrom nncf.checkpoint_loading import load_state\nfrom nncf.config import NNCFConfig\nfrom tests.conftest import TEST_ROOT\nfrom tests.test_compression_training import get_cli_dict_args, parse_best_acc1\nfrom tests.test_helpers import create_compressed_model_and_algo_for_test\nfrom tests.test_sanity_sample import Command, create_command_line\n\nGLOBAL_CONFIG = {\n TEST_ROOT.joinpath(\"data\", \"configs\", \"squeezenet1_1_cifar10_rb_sparsity_int8.json\"): [\n {\n 'checkpoint_name': 'squeezenet1_1_custom_cifar10_rb_sparsity_int8_dp.pth',\n 'dataset': \"cifar10\",\n 'execution_mode': ExecutionMode.GPU_DATAPARALLEL,\n },\n {\n 'checkpoint_name': 'squeezenet1_1_custom_cifar10_rb_sparsity_int8_ddp.pth',\n 'dataset': \"cifar10\",\n 'execution_mode': ExecutionMode.MULTIPROCESSING_DISTRIBUTED,\n },\n ],\n}\n\nCONFIG_PARAMS = []\nfor config_path_, cases_list_ in GLOBAL_CONFIG.items():\n for case_params_ in cases_list_:\n CONFIG_PARAMS.append((config_path_, case_params_,))\n\n\[email protected](scope='module', params=CONFIG_PARAMS,\n ids=['-'.join([str(p[0]), p[1]['execution_mode']]) for p in CONFIG_PARAMS])\ndef _params(request, backward_compat_models_path):\n if backward_compat_models_path is None:\n pytest.skip('Path to models weights for backward compatibility testing is not set,'\n ' use --backward-compat-models option.')\n config_path, case_params = request.param\n checkpoint_path = str(os.path.join(backward_compat_models_path, case_params['checkpoint_name']))\n return {\n 'sample_config_path': config_path,\n 'checkpoint_path': checkpoint_path,\n 'execution_mode': case_params['execution_mode'],\n 'dataset': case_params['dataset']\n }\n\n\ndef test_model_can_be_loaded_with_resume(_params):\n p = _params\n sample_config_path = p['sample_config_path']\n checkpoint_path = p['checkpoint_path']\n\n config = SampleConfig.from_json(str(sample_config_path))\n nncf_config = NNCFConfig.from_json(str(sample_config_path))\n\n config.execution_mode = p['execution_mode']\n\n config.current_gpu = 0\n config.device = get_device(config)\n config.distributed = config.execution_mode in (ExecutionMode.DISTRIBUTED, ExecutionMode.MULTIPROCESSING_DISTRIBUTED)\n if config.distributed:\n config.dist_url = \"tcp://127.0.0.1:9898\"\n config.dist_backend = \"nccl\"\n config.rank = 0\n config.world_size = 1\n configure_distributed(config)\n\n model_name = config['model']\n model = load_model(model_name,\n pretrained=False,\n num_classes=config.get('num_classes', 1000),\n model_params=config.get('model_params'))\n\n model.to(config.device)\n model, compression_ctrl = create_compressed_model_and_algo_for_test(model, nncf_config)\n model, _ = prepare_model_for_execution(model, config)\n\n if config.distributed:\n compression_ctrl.distributed()\n\n checkpoint = torch.load(checkpoint_path, map_location='cpu')\n load_state(model, checkpoint['state_dict'], is_resume=True)\n\n\ndef test_loaded_model_evals_according_to_saved_acc(_params, tmp_path):\n p = _params\n config_path = p['sample_config_path']\n checkpoint_path = p['checkpoint_path']\n\n tmp_path = str(tmp_path)\n args = {}\n args['data'] = tmp_path + '/' + p['dataset']\n args['dataset'] = p['dataset']\n args['config'] = str(config_path)\n args['mode'] = 'test'\n args['log-dir'] = tmp_path\n args['workers'] = 4\n args['seed'] = 1\n args['resume'] = checkpoint_path\n\n if p['execution_mode'] == ExecutionMode.MULTIPROCESSING_DISTRIBUTED:\n args['multiprocessing-distributed'] = ''\n else:\n pytest.skip(\"DataParallel eval takes too long for this test to be run during pre-commit\")\n\n runner = Command(create_command_line(get_cli_dict_args(args), \"classification\"))\n res = runner.run()\n assert res == 0\n\n acc1 = parse_best_acc1(tmp_path)\n assert torch.load(checkpoint_path)['best_acc1'] == pytest.approx(acc1)\n"
] |
[
[
"torch.load"
]
] |
UnnamedMoose/LearningMLandRL
|
[
"a3a47998c32078a069ea82ce0032c30bb8b387f2"
] |
[
"_old_basic_tensorflow/tutorial2_simpleRegressionLowLevel/simpleRegressionLowLevel.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n# correlation variable x and ground truth values\nx = tf.constant([[1], [2], [3], [4]], dtype=tf.float32, name=\"inputData\")\ny_true = tf.constant([[0], [-1], [-2], [-3]], dtype=tf.float32, name=\"groundTruth\")\n\n# linear model\nlinear_model = tf.layers.Dense(units=1, name=\"regressionModel\")\n\n# prediciton of y from x using the linear model is what we're after\ny_pred = linear_model(x)\n\n# loss model that computes mean square error between the ground truth and predictions\nloss = tf.losses.mean_squared_error(labels=y_true, predictions=y_pred)\n\n# create an optimiser instance that will tune the coefficients of the graph\n# in order to minimise the loss function\noptimizer = tf.train.GradientDescentOptimizer(0.01, name=\"gradientOpt\")\ntrain = optimizer.minimize(loss)\n\n# initialiser\ninit = tf.global_variables_initializer()\n\n# create a writer for graph visualisation; produces an \"event\" file\nwriter = tf.summary.FileWriter(\"./modelData\")\nwriter.add_graph(tf.get_default_graph())\n\nlossTrace = []\nwith tf.Session() as sess:\n # initialise\n sess.run(init)\n\n # run the training\n for i in range(1000):\n _, loss_value = sess.run((train, loss))\n lossTrace = np.append(lossTrace, loss_value)\n if i%100 == 0:\n print(\"Iter {:2d}, loss ={:7.4f}\".format(i, loss_value))\n\n # come up with the final prediciton and convert to numpy arrays for further processing\n independentVariable = sess.run(x)\n finalPred = sess.run(y_pred)\n groundTruth = sess.run(y_true)\n print(\"\\nFinal prediction: {}\".format(finalPred))\n print(\"\\nGround truth: {}\".format(groundTruth))\n\nplt.figure()\nplt.plot(lossTrace, \"kp--\", ms=5, lw=2)\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"Loss [-]\")\n\nplt.figure()\nplt.plot(independentVariable, groundTruth, \"kp--\", ms=9, lw=2, label=\"Ground truth\")\nplt.plot(independentVariable, finalPred, \"rx--\", ms=9, lw=2,\n markeredgewidth=2, label=\"Predicted value\")\nplt.legend(prop={\"size\":14})\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"tensorflow.losses.mean_squared_error",
"tensorflow.get_default_graph",
"tensorflow.constant",
"tensorflow.summary.FileWriter",
"tensorflow.layers.Dense",
"matplotlib.pyplot.plot",
"tensorflow.global_variables_initializer",
"matplotlib.pyplot.ylabel",
"tensorflow.train.GradientDescentOptimizer",
"numpy.append",
"tensorflow.Session",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
leosampaio/scene-designer
|
[
"8a7276067acfde1997d386942aabc44d92436a1a"
] |
[
"metrics/visualisation.py"
] |
[
"import os\n\nimport numpy as np\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nimport skimage.transform as sk_transform\nfrom sklearn.cluster import KMeans\nfrom PIL import Image\n\nfrom core.metrics import ProjectionMetric, ImageMetric\n\n\nclass TSNEProjection(ProjectionMetric):\n name = 'tsne'\n input_type = 'predictions_on_validation_set'\n\n def compute(self, input_data):\n x, y, pred_x, pred_y, pred_z, tokenizer, plot_filepath, tmp_filepath = input_data\n\n np.random.seed(14)\n idx = np.random.permutation(len(y))\n np.random.seed()\n\n # [194, 103, 317, 100, 112, 221, 223, 293, 239, 8],\n feats, labels, sel_labels, counter, label_counter = [], [], [], 0, 0\n y, pred_z = y[idx], pred_z[idx]\n for label, feature in zip(y, pred_z):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n feats.append(feature)\n labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n tsne = TSNE(n_components=2,\n verbose=0, perplexity=30,\n n_iter=1000,\n random_state=14)\n tsne_results = tsne.fit_transform(feats)\n return np.concatenate((tsne_results, labels),\n axis=1)\n\n\nclass TSNEImagesProjection(ImageMetric):\n name = 'tsne-images'\n input_type = 'features_and_images'\n\n def compute(self, input_data):\n feats, images = input_data\n\n tsne = TSNE(n_components=2,\n verbose=0, perplexity=30,\n n_iter=1000,\n random_state=14)\n tsne_results = tsne.fit_transform(feats)\n tx, ty = tsne_results[:, 0], tsne_results[:, 1]\n tx = (tx - np.min(tx)) / (np.max(tx) - np.min(tx))\n ty = (ty - np.min(ty)) / (np.max(ty) - np.min(ty))\n tsne_results[:, 0], tsne_results[:, 1] = tx, ty\n\n width = 4000\n height = 4000\n max_dim = 100\n\n full_image = Image.new('RGBA', (width, height))\n for img, x, y in zip(images, tx, ty):\n tile = img\n rs = max(1, tile.shape[0] / max_dim, tile.shape[1] / max_dim)\n tile = sk_transform.resize(tile, (int(tile.shape[0] / rs), int(tile.shape[1] / rs)), anti_aliasing=True)\n tile = Image.fromarray(np.uint8(tile * 255))\n full_image.paste(tile, (int((width - max_dim) * x), int((height - max_dim) * y)), mask=tile.convert('RGBA'))\n\n image_plot_file = '/tmp/tsne-image-plot.png'\n full_image.save(image_plot_file)\n\n return image_plot_file\n\n\nclass EmbeddingTSNEProjection(ProjectionMetric):\n name = 'embedding-tsne'\n input_type = 'embedding_from_appearence_net_on_validation'\n\n def compute(self, input_data):\n emb, y = input_data\n\n np.random.seed(14)\n idx = np.random.permutation(len(y))\n np.random.seed()\n\n sel_x, labels, sel_labels, counter, label_counter = [], [], [], 0, 0\n y = y[idx]\n emb = emb[idx]\n for feat, label in zip(emb, y):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n sel_x.append(feat)\n labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n tsne = TSNE(n_components=2,\n verbose=0, perplexity=30,\n n_iter=5000,\n random_state=14)\n tsne_results = tsne.fit_transform(sel_x)\n return np.concatenate((tsne_results, labels),\n axis=1)\n\nclass EmbeddingPCAProjection(ProjectionMetric):\n name = 'embedding-pca'\n input_type = 'embedding_from_appearence_net_on_validation'\n\n def compute(self, input_data):\n emb, y = input_data\n\n np.random.seed(14)\n idx = np.random.permutation(len(y))\n np.random.seed()\n\n sel_x, labels, sel_labels, counter, label_counter = [], [], [], 0, 0\n y = y[idx]\n emb = emb[idx]\n for feat, label in zip(emb, y):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n sel_x.append(feat)\n labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n pca = PCA(n_components=2)\n pca.fit(sel_x)\n pca_result = pca.transform(sel_x)\n return np.concatenate((pca_result, labels),\n axis=1)\n\n\nclass EmbeddingsFromAppearenceNetTSNEProjection(ProjectionMetric):\n name = 'common-embedding-tsne'\n input_type = 'common_embedding_from_appearence_net_on_validation'\n plot_type = 'scatter-with-shapes'\n\n def compute(self, input_data):\n obj_emb, sketch_emb, y, skt_y = input_data\n\n np.random.seed(14)\n idx = np.random.permutation(len(y))\n skt_idx = np.random.permutation(len(skt_y))\n np.random.seed()\n\n sel_objs, sel_skts, labels, skt_labels, sel_labels, counter, label_counter = [], [], [], [], [], 0, 0\n y = y[idx]\n obj_emb = obj_emb[idx]\n skt_y = skt_y[skt_idx]\n sketch_emb = sketch_emb[skt_idx]\n for skt, label in zip(sketch_emb, skt_y):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n sel_skts.append(skt)\n skt_labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n counter = 0\n for obj, label in zip(obj_emb, y):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n sel_objs.append(obj)\n labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n tsne = TSNE(n_components=2,\n verbose=0, perplexity=30,\n n_iter=1000,\n random_state=14)\n combined_embs = np.concatenate((sel_objs, sel_skts), axis=0)\n print(np.array(obj_emb).shape, np.array(sketch_emb).shape, np.array(sel_objs).shape, np.array(sel_skts).shape, np.array(combined_embs).shape, np.array(labels).shape)\n tsne_results = tsne.fit_transform(combined_embs)\n objs_tsne, skt_tsne = tsne_results[:len(sel_objs)], tsne_results[len(sel_objs):]\n return np.array([np.concatenate((objs_tsne, np.expand_dims(labels, -1)),\n axis=1),\n np.concatenate((skt_tsne, np.expand_dims(skt_labels, -1)),\n axis=1)])\n\n\nclass EmbeddingsFromTripletTSNEProjection(ProjectionMetric):\n name = 'common-obj-rep-tsne'\n input_type = 'rep_SBIR_on_validation_set'\n plot_type = 'scatter-with-shapes'\n\n def compute(self, input_data):\n _, _, _, _, _, R_ave, mAP, obj_emb, sketch_emb, y = input_data\n skt_y = y\n\n np.random.seed(14)\n idx = np.random.permutation(len(y))\n skt_idx = np.random.permutation(len(skt_y))\n np.random.seed()\n\n sel_objs, sel_skts, labels, skt_labels, sel_labels, counter, label_counter = [], [], [], [], [], 0, 0\n y = y[idx]\n obj_emb = obj_emb[idx]\n skt_y = skt_y[skt_idx]\n sketch_emb = sketch_emb[skt_idx]\n for skt, label in zip(sketch_emb, skt_y):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n sel_skts.append(skt)\n skt_labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n counter = 0\n for obj, label in zip(obj_emb, y):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n sel_objs.append(obj)\n labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n tsne = TSNE(n_components=2,\n verbose=0, perplexity=30,\n n_iter=1000,\n random_state=14)\n combined_embs = np.concatenate((sel_objs, sel_skts), axis=0)\n print(np.array(obj_emb).shape, np.array(sketch_emb).shape, np.array(sel_objs).shape, np.array(sel_skts).shape, np.array(combined_embs).shape, np.array(labels).shape)\n tsne_results = tsne.fit_transform(combined_embs)\n objs_tsne, skt_tsne = tsne_results[:len(sel_objs)], tsne_results[len(sel_objs):]\n return np.array([np.concatenate((objs_tsne, labels),\n axis=1),\n np.concatenate((skt_tsne, skt_labels),\n axis=1)])\n\n\nclass ClusterTSNEProjection(ProjectionMetric):\n name = 'tsne-cluster'\n input_type = 'predictions_on_validation_set'\n\n def compute(self, input_data):\n x, y, pred_x, pred_y, pred_z, tokenizer, plot_filepath, tmp_filepath = input_data\n\n np.random.seed(14)\n idx = np.random.permutation(len(x))\n np.random.seed()\n\n feats, labels, sel_labels, counter, label_counter = [], [], [], 0, 0\n x, y, pred_z = x[idx], y[idx], pred_z[idx]\n for sketch, label, feature in zip(x, y, pred_z):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n feats.append(feature)\n labels.append(label)\n counter += 1\n if counter >= 1000:\n break\n\n tsne = TSNE(n_components=2,\n verbose=0, perplexity=30,\n n_iter=1000,\n random_state=14)\n tsne_results = tsne.fit_transform(feats)\n\n kmeans = KMeans(n_clusters=30, random_state=14).fit(feats)\n cluster_labels = kmeans.labels_\n sel_feats, feats_labels = None, None\n for i in range(30):\n clustered_feats = np.array(tsne_results)[np.where(cluster_labels == i)[0]]\n sel_feats = np.concatenate((sel_feats, clustered_feats)) if sel_feats is not None else clustered_feats\n feat_label = np.ones(len(clustered_feats,)) * i\n feats_labels = np.concatenate((feats_labels, feat_label)) if feats_labels is not None else feat_label\n\n np.random.seed()\n return np.concatenate((sel_feats, np.expand_dims(feats_labels, axis=1)),\n axis=1)\n\n\nclass PredictedLabelsTSNEProjection(ProjectionMetric):\n name = 'tsne-predicted'\n input_type = 'predictions_on_validation_set'\n\n def compute(self, input_data):\n x, y, pred_x, pred_y, pred_z, tokenizer, plot_filepath, tmp_filepath = input_data\n\n np.random.seed(14)\n idx = np.random.permutation(len(y))\n np.random.seed()\n\n feats, labels, sel_labels, counter, label_counter = [], [], [], 0, 0\n y, pred_z, pred_y = y[idx], pred_z[idx], pred_y[idx]\n for label, feature, pred_label in zip(y, pred_z, pred_y):\n if label not in sel_labels and label_counter < 10:\n sel_labels.append(label)\n label_counter += 1\n if label in sel_labels:\n feats.append(feature)\n labels.append(pred_label)\n counter += 1\n if counter >= 1000:\n break\n\n tsne = TSNE(n_components=2,\n verbose=0, perplexity=30,\n n_iter=1000,\n random_state=14)\n tsne_results = tsne.fit_transform(feats)\n return np.concatenate((tsne_results, np.expand_dims(labels, axis=1)),\n axis=1)\n\n\nclass PCAProjection(ProjectionMetric):\n name = 'pca'\n input_type = 'predictions_on_validation_set'\n\n def compute(self, input_data):\n entries, _, plot_filepath, tmp_filepath = input_data\n\n np.random.seed(14)\n idx = np.random.permutation(len(entries))\n np.random.seed()\n\n feats, labels, sel_labels, counter, label_counter = [], [], [], 0, 0\n for i in idx:\n skt = entries[i]\n if skt['label'] not in sel_labels and label_counter < 10:\n sel_labels.append(skt['label'])\n label_counter += 1\n if skt['label'] in sel_labels:\n feats.append(skt['features'])\n labels.append(skt['label'])\n counter += 1\n if counter >= 1000:\n break\n\n pca = PCA(n_components=2)\n pca.fit(feats)\n pca_result = pca.transform(feats)\n return np.concatenate((pca_result, np.expand_dims(labels, axis=1)),\n axis=1)\n"
] |
[
[
"numpy.expand_dims",
"numpy.random.seed",
"numpy.min",
"sklearn.cluster.KMeans",
"numpy.uint8",
"numpy.concatenate",
"sklearn.manifold.TSNE",
"numpy.max",
"numpy.array",
"numpy.where",
"sklearn.decomposition.PCA"
]
] |
iamdebanjangoswami/Image-Caption-IR--Im2txt
|
[
"e871cdd03c80fd70695ae5a46f32351e35956684"
] |
[
"im2txt/train.py"
] |
[
"\n\"\"\"Train the model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nimport tensorflow as tf\n\nfrom im2txt import configuration\nfrom im2txt import show_and_tell_model\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.flags.DEFINE_string(\"input_file_pattern\", \"\",\n \"File pattern of sharded TFRecord input files.\")\ntf.flags.DEFINE_string(\"inception_checkpoint_file\", \"\",\n \"Path to a pretrained inception_v3 model.\")\ntf.flags.DEFINE_string(\"train_dir\", \"\",\n \"Directory for saving and loading model checkpoints.\")\ntf.flags.DEFINE_boolean(\"train_inception\", False,\n \"Whether to train inception submodel variables.\")\ntf.flags.DEFINE_integer(\"number_of_steps\", 1000000, \"Number of training steps.\")\ntf.flags.DEFINE_integer(\"log_every_n_steps\", 1,\n \"Frequency at which loss and global step are logged.\")\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\ndef main(unused_argv):\n assert FLAGS.input_file_pattern, \"--input_file_pattern is required\"\n assert FLAGS.train_dir, \"--train_dir is required\"\n\n model_config = configuration.ModelConfig()\n model_config.input_file_pattern = FLAGS.input_file_pattern\n model_config.inception_checkpoint_file = FLAGS.inception_checkpoint_file\n training_config = configuration.TrainingConfig()\n\n # Create training directory.\n train_dir = FLAGS.train_dir\n if not tf.gfile.IsDirectory(train_dir):\n tf.logging.info(\"Creating training directory: %s\", train_dir)\n tf.gfile.MakeDirs(train_dir)\n\n # Build the TensorFlow graph.\n g = tf.Graph()\n with g.as_default():\n # Build the model.\n model = show_and_tell_model.ShowAndTellModel(\n model_config, mode=\"train\", train_inception=FLAGS.train_inception)\n model.build()\n\n # Set up the learning rate.\n learning_rate_decay_fn = None\n if FLAGS.train_inception:\n learning_rate = tf.constant(training_config.train_inception_learning_rate)\n else:\n learning_rate = tf.constant(training_config.initial_learning_rate)\n if training_config.learning_rate_decay_factor > 0:\n num_batches_per_epoch = (training_config.num_examples_per_epoch /\n model_config.batch_size)\n decay_steps = int(num_batches_per_epoch *\n training_config.num_epochs_per_decay)\n\n def _learning_rate_decay_fn(learning_rate, global_step):\n return tf.train.exponential_decay(\n learning_rate,\n global_step,\n decay_steps=decay_steps,\n decay_rate=training_config.learning_rate_decay_factor,\n staircase=True)\n\n learning_rate_decay_fn = _learning_rate_decay_fn\n\n # Set up the training ops.\n train_op = tf.contrib.layers.optimize_loss(\n loss=model.total_loss,\n global_step=model.global_step,\n learning_rate=learning_rate,\n optimizer=training_config.optimizer,\n clip_gradients=training_config.clip_gradients,\n learning_rate_decay_fn=learning_rate_decay_fn)\n\n # Set up the Saver for saving and restoring model checkpoints.\n saver = tf.train.Saver(max_to_keep=training_config.max_checkpoints_to_keep)\n\n # Run training.\n tf.contrib.slim.learning.train(\n train_op,\n train_dir,\n log_every_n_steps=FLAGS.log_every_n_steps,\n graph=g,\n global_step=model.global_step,\n number_of_steps=FLAGS.number_of_steps,\n init_fn=model.init_fn,\n saver=saver)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n"
] |
[
[
"tensorflow.flags.DEFINE_boolean",
"tensorflow.Graph",
"tensorflow.contrib.slim.learning.train",
"tensorflow.constant",
"tensorflow.flags.DEFINE_string",
"tensorflow.train.exponential_decay",
"tensorflow.contrib.layers.optimize_loss",
"tensorflow.gfile.MakeDirs",
"tensorflow.logging.info",
"tensorflow.logging.set_verbosity",
"tensorflow.train.Saver",
"tensorflow.gfile.IsDirectory",
"tensorflow.flags.DEFINE_integer",
"tensorflow.app.run"
]
] |
samholt/NeuralSymbolicRegressionThatScales
|
[
"da023e5a3fdf157ab60e56a966eeea0129366bfc"
] |
[
"scripts/csv_handling/dataload_format_to_csv.py"
] |
[
"import pandas as pd \nimport numpy as np\nimport multiprocessing\nfrom multiprocessing import Manager\nimport click\nimport warnings\nfrom tqdm import tqdm\nimport json\nimport os\nfrom nesymres.dataset import generator\nimport time\nimport signal\nfrom pathlib import Path\nimport pickle\nfrom sympy import lambdify\nfrom nesymres.utils import create_env, load_metadata_hdf5, load_eq\nfrom nesymres.dataset import data_utils \nimport copyreg\nimport types\nfrom itertools import chain\nimport traceback\nimport sympy as sp\nfrom nesymres.dataset.sympy_utils import add_multiplicative_constants, add_additive_constants\nimport random\nimport hydra\nfrom tqdm import tqdm\n\ndef create_df(path,metadata,cfg, constats_on = False):\n rows = {\"eq\": [], \"support\": [], \"num_points\": []}\n for idx in tqdm(range(metadata.total_number_of_eqs)):\n eq = load_eq(path, idx, metadata.eqs_per_hdf)\n w_const, wout_consts = data_utils.sample_symbolic_constants(eq,cfg.dataset_test.constants)\n if constats_on:\n dict_const = w_const\n else:\n dict_const = wout_consts\n eq_string = eq.expr.format(**dict_const)\n eq_string = str(sp.simplify(eq_string))\n d = {}\n if not eq.support:\n for var in eq.variables:\n d[var] = cfg.dataset_test.fun_support\n rows[\"eq\"].append(str(eq_string))\n rows[\"support\"].append(str(d))\n rows[\"num_points\"].append(cfg.dataset_test.max_number_of_points)\n dataset = pd.DataFrame(rows)\n return dataset\n\n\[email protected](config_name=\"../config\")\ndef converter(cfg):\n df = pd.DataFrame()\n path = hydra.utils.to_absolute_path(cfg.raw_test_path)\n metadata = load_metadata_hdf5(path)\n df = create_df(path,metadata,cfg,constats_on = False)\n df.to_csv(hydra.utils.to_absolute_path(\"test_set/test_nc.csv\"))\n df = create_df(path,metadata,cfg,constats_on = True)\n df.to_csv(hydra.utils.to_absolute_path(\"test_set/test_wc.csv\"))\n\n \n \n # dataset.to_csv(hydra.utils.to_absolute_path(\"test_set/test.csv\"))\n # with open(hydra.utils.to_absolute_path(\"data/benchmark/test_csv\"), \"wb\") as file:\n # pickle.dump(dataset, file)\n\nif __name__ == \"__main__\":\n converter()"
] |
[
[
"pandas.DataFrame"
]
] |
hkvision/analytics-zoo
|
[
"aee693a0604db5b5d01540d5d414b644313d5d22"
] |
[
"pyzoo/test/zoo/serving/test_serialization.py"
] |
[
"#\n# Copyright 2018 Analytics Zoo 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\n\nimport numpy as np\nimport base64\nfrom zoo.serving.client import InputQueue, OutputQueue, http_response_to_ndarray\nimport os\n\n\nresource_path = os.path.join(os.path.split(__file__)[0], \"../resources\")\n\n\nclass TestSerialization:\n\n def test_encode(self):\n input_api = InputQueue()\n b64 = input_api.data_to_b64(t1=np.array([1, 2]), t2=np.array([3, 4]))\n byte = base64.b64decode(b64)\n\n def test_http_response_to_ndarray(self):\n with open(os.path.join(resource_path, \"serving/http_response\")) as f:\n data = f.read()\n arr = http_response_to_ndarray(data)\n assert isinstance(arr, np.ndarray)\n assert len(arr.shape) == 1\n assert arr.shape[0] == 128\n"
] |
[
[
"numpy.array"
]
] |
AndrewJBean/Stocks
|
[
"1a082856983936e77c45d5b47274ac5f2a344348"
] |
[
"Processing/play_model.py"
] |
[
"#!/usr/bin/env python3\n\n# MIT License\n\n# Copyright (c) 2018 Andrew J. Bean\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import load_model\n\ndef main():\n Gain = '0.5'\n Loss = '0.5'\n MSE_Loss = False\n LinearActivation = False\n DropFrac = '0.0'\n NEpochs = '200'\n NameRoot = 'my_model_'\n\n whichplot = 1\n\n extension = Gain+','+Loss +'_open'\n ExamplesFile = h5py.File(\"2min_examples_\"+extension+\".hdf5\", \"r\")\n # ExamplesFile = h5py.File(\"2min_aggregated_examples_\"+extension+\".hdf5\", \"r\")\n\n SaveName = NameRoot+extension\n if MSE_Loss:\n SaveName = SaveName + '_MSE'\n if LinearActivation:\n SaveName = SaveName + '_Lin'\n if DropFrac!='0.7':\n SaveName = SaveName + '_' + DropFrac\n # SaveName = 'Trained/' + SaveName + \"_\"+NEpochs+\"_\"+val_loss+\".h5\"\n SaveName = 'Trained/' + SaveName + \"_\"+NEpochs+\".h5\"\n print(SaveName)\n model = load_model(SaveName)\n\n print(extension)\n if MSE_Loss:\n print('using mean_squared_error loss')\n else:\n print('using binary_crossentropy loss')\n print(ExamplesFile['Features'].shape)\n print(ExamplesFile['Outcomes'].shape)\n print(ExamplesFile['Timestamps'].shape)\n\n NumExamples = ExamplesFile['Features'].shape[0]\n FeatureSize = ExamplesFile['Features'].shape[1]\n\n SampleShift = 0.0\n StartTest = int((0.9 - SampleShift )*NumExamples)\n EndTest = int((1.0 - SampleShift )*NumExamples)\n\n print('reading data from HDF5...')\n # x_train = ExamplesFile['Features'][:StartTest]\n # y_train = ExamplesFile['Outcomes'][:StartTest]\n\n x_test = ExamplesFile['Features'][StartTest:EndTest]\n y_test = ExamplesFile['Outcomes'][StartTest:EndTest]\n t_test = ExamplesFile['Timestamps'][StartTest:EndTest]\n\n y_predict = model.predict_on_batch(x_test)\n y_predict = np.array([y_predict[i][0] for i in range(len(y_predict))])\n Rearrange = y_predict.argsort()\n # flip so losses are at right of plot\n # don't flip to keep losses at the left\n # Rearrange = np.flip(Rearrange,0)\n y_predict = y_predict[Rearrange]\n y_test = y_test[Rearrange]\n t_test = t_test[Rearrange]\n y_test = y_test*(float(Gain)+float(Loss))/100.0 - float(Loss)/100.0 + 1.0\n\n if whichplot==0:\n y_test = np.log(y_test)\n y_test = np.cumsum(y_test)\n for i in range(len(y_test)):\n y_test[i] = y_test[i]/(i+1.0)\n plt.plot(np.exp(y_test)*100-100)\n plt.plot((t_test-min(t_test))/(max(t_test)-min(t_test)),'.')\n plt.show()\n elif whichplot==1:\n NWindow = 100\n plt.plot((t_test-min(t_test))/(max(t_test)-min(t_test)),'.')\n plt.plot(np.convolve(y_test*100-100,np.ones(NWindow)/NWindow,mode='same'))\n plt.plot(y_predict)\n plt.show()\n\n\n\n\nif __name__ == '__main__':\n main()\n\n"
] |
[
[
"numpy.log",
"numpy.cumsum",
"numpy.ones",
"matplotlib.pyplot.plot",
"numpy.exp",
"matplotlib.pyplot.show"
]
] |
YHKIM71/openpilot0813Volt
|
[
"9f8b401d2b544d54e3b5e8c019f6ca20926a61f0"
] |
[
"selfdrive/controls/lib/lane_planner.py"
] |
[
"import numpy as np\nfrom cereal import log\nfrom common.filter_simple import FirstOrderFilter\nfrom common.numpy_fast import interp, clip, mean\nfrom common.realtime import DT_MDL\nfrom selfdrive.hardware import EON, TICI\nfrom selfdrive.swaglog import cloudlog\nfrom selfdrive.ntune import ntune_common_get\n\nENABLE_ZORROBYTE = True\nENABLE_INC_LANE_PROB = True\n\nTRAJECTORY_SIZE = 33\n# camera offset is meters from center car to camera\nif EON:\n CAMERA_OFFSET = ntune_common_get(\"cameraOffset\")\n PATH_OFFSET = 0.0\nelif TICI:\n CAMERA_OFFSET = -0.04\n PATH_OFFSET = -0.04\nelse:\n CAMERA_OFFSET = 0.0\n PATH_OFFSET = 0.0\n\n\nclass LanePlanner:\n def __init__(self, wide_camera=False):\n self.ll_t = np.zeros((TRAJECTORY_SIZE,))\n self.ll_x = np.zeros((TRAJECTORY_SIZE,))\n self.lll_y = np.zeros((TRAJECTORY_SIZE,))\n self.rll_y = np.zeros((TRAJECTORY_SIZE,))\n self.lane_width_estimate = FirstOrderFilter(3.7, 9.95, DT_MDL)\n self.lane_width_certainty = FirstOrderFilter(1.0, 0.95, DT_MDL)\n self.lane_width = 3.7\n\n self.lll_prob = 0.\n self.rll_prob = 0.\n self.d_prob = 0.\n\n self.lll_std = 0.\n self.rll_std = 0.\n\n self.l_lane_change_prob = 0.\n self.r_lane_change_prob = 0.\n\n self.camera_offset = -CAMERA_OFFSET if wide_camera else CAMERA_OFFSET\n self.path_offset = -PATH_OFFSET if wide_camera else PATH_OFFSET\n\n self.readings = []\n self.frame = 0\n\n self.wide_camera = wide_camera\n\n def parse_model(self, md):\n lane_lines = md.laneLines\n if len(lane_lines) == 4 and len(lane_lines[0].t) == TRAJECTORY_SIZE:\n self.ll_t = (np.array(lane_lines[1].t) + np.array(lane_lines[2].t))/2\n # left and right ll x is the same\n self.ll_x = lane_lines[1].x\n # only offset left and right lane lines; offsetting path does not make sense\n\n cameraOffset = ntune_common_get(\"cameraOffset\") + 0.08 if self.wide_camera else ntune_common_get(\"cameraOffset\")\n\n self.lll_y = np.array(lane_lines[1].y) - cameraOffset\n self.rll_y = np.array(lane_lines[2].y) - cameraOffset\n self.lll_prob = md.laneLineProbs[1]\n self.rll_prob = md.laneLineProbs[2]\n self.lll_std = md.laneLineStds[1]\n self.rll_std = md.laneLineStds[2]\n\n desire_state = md.meta.desireState\n if len(desire_state):\n self.l_lane_change_prob = desire_state[log.LateralPlan.Desire.laneChangeLeft]\n self.r_lane_change_prob = desire_state[log.LateralPlan.Desire.laneChangeRight]\n\n def get_d_path(self, v_ego, path_t, path_xyz):\n # Reduce reliance on lanelines that are too far apart or\n # will be in a few seconds\n path_xyz[:, 1] -= self.path_offset\n l_prob, r_prob = self.lll_prob, self.rll_prob\n width_pts = self.rll_y - self.lll_y\n prob_mods = []\n for t_check in [0.0, 1.5, 3.0]:\n width_at_t = interp(t_check * (v_ego + 7), self.ll_x, width_pts)\n prob_mods.append(interp(width_at_t, [4.0, 5.0], [1.0, 0.0]))\n mod = min(prob_mods)\n l_prob *= mod\n r_prob *= mod\n\n # Reduce reliance on uncertain lanelines\n l_std_mod = interp(self.lll_std, [.15, .3], [1.0, 0.0])\n r_std_mod = interp(self.rll_std, [.15, .3], [1.0, 0.0])\n l_prob *= l_std_mod\n r_prob *= r_std_mod\n\n if ENABLE_ZORROBYTE:\n # zorrobyte code\n if l_prob > 0.5 and r_prob > 0.5:\n self.frame += 1\n if self.frame > 20:\n self.frame = 0\n current_lane_width = clip(abs(self.rll_y[0] - self.lll_y[0]), 2.5, 3.5)\n self.readings.append(current_lane_width)\n self.lane_width = mean(self.readings)\n if len(self.readings) >= 30:\n self.readings.pop(0)\n\n # zorrobyte\n # Don't exit dive\n if abs(self.rll_y[0] - self.lll_y[0]) > self.lane_width:\n r_prob = r_prob / interp(l_prob, [0, 1], [1, 3])\n\n else:\n # Find current lanewidth\n self.lane_width_certainty.update(l_prob * r_prob)\n current_lane_width = abs(self.rll_y[0] - self.lll_y[0])\n self.lane_width_estimate.update(current_lane_width)\n speed_lane_width = interp(v_ego, [0., 31.], [2.8, 3.5])\n self.lane_width = self.lane_width_certainty.x * self.lane_width_estimate.x + \\\n (1 - self.lane_width_certainty.x) * speed_lane_width\n\n clipped_lane_width = min(4.0, self.lane_width)\n path_from_left_lane = self.lll_y + clipped_lane_width / 2.0\n path_from_right_lane = self.rll_y - clipped_lane_width / 2.0\n\n self.d_prob = l_prob + r_prob - l_prob * r_prob\n\n # neokii\n if ENABLE_INC_LANE_PROB and self.d_prob > 0.65:\n self.d_prob = min(self.d_prob * 1.3, 1.0)\n\n lane_path_y = (l_prob * path_from_left_lane + r_prob * path_from_right_lane) / (l_prob + r_prob + 0.0001)\n safe_idxs = np.isfinite(self.ll_t)\n if safe_idxs[0]:\n lane_path_y_interp = np.interp(path_t, self.ll_t[safe_idxs], lane_path_y[safe_idxs])\n path_xyz[:,1] = self.d_prob * lane_path_y_interp + (1.0 - self.d_prob) * path_xyz[:,1]\n else:\n cloudlog.warning(\"Lateral mpc - NaNs in laneline times, ignoring\")\n return path_xyz\n"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.interp",
"numpy.isfinite"
]
] |
AlexsLemonade/refinebio
|
[
"52f44947f902adedaccf270d5f9dbd56ab47e40a"
] |
[
"workers/data_refinery_workers/processors/test_compendia.py"
] |
[
"import copy\nimport itertools\nimport json\nimport math\nimport os\nimport random\nimport zipfile\nfrom typing import Dict\n\nfrom django.test import TransactionTestCase, tag\n\nimport numpy as np\nimport pandas as pd\n\nfrom data_refinery_common.enums import PipelineEnum, ProcessorPipeline\nfrom data_refinery_common.models import (\n ComputationalResult,\n ComputationalResultAnnotation,\n ComputedFile,\n Dataset,\n Experiment,\n ExperimentSampleAssociation,\n Organism,\n Pipeline,\n ProcessorJob,\n ProcessorJobDatasetAssociation,\n Sample,\n SampleComputedFileAssociation,\n SampleResultAssociation,\n)\nfrom data_refinery_workers.processors import create_compendia, utils\nfrom data_refinery_workers.processors.testing_utils import ProcessorJobTestCaseMixin\n\n\ndef create_sample_for_experiment(sample_info: Dict, experiment: Experiment) -> Sample:\n result = ComputationalResult()\n result.save()\n\n sample = Sample()\n sample.accession_code = sample_info[\"accession_code\"]\n sample.title = sample_info.get(\"title\", None) or sample_info[\"accession_code\"]\n sample.organism = sample_info[\"organism\"]\n sample.technology = sample_info[\"technology\"]\n sample.save()\n\n sra = SampleResultAssociation()\n sra.sample = sample\n sra.result = result\n sra.save()\n\n esa = ExperimentSampleAssociation()\n esa.experiment = experiment\n esa.sample = sample\n esa.save()\n\n if sample_info.get(\"filename\") is not None:\n computed_file = ComputedFile()\n computed_file.filename = sample_info[\"filename\"]\n computed_file.absolute_file_path = sample_info[\"data_dir\"] + sample_info[\"filename\"]\n computed_file.result = result\n computed_file.size_in_bytes = 123\n computed_file.is_smashable = True\n computed_file.save()\n\n assoc = SampleComputedFileAssociation()\n assoc.sample = sample\n assoc.computed_file = computed_file\n assoc.save()\n\n return sample\n\n\nclass CompendiaTestCase(TransactionTestCase, ProcessorJobTestCaseMixin):\n @tag(\"compendia\")\n def test_create_compendia(self):\n DATA_DIR = \"/home/user/data_store/PCL/\"\n\n job = ProcessorJob()\n job.pipeline_applied = ProcessorPipeline.CREATE_COMPENDIA.value\n job.save()\n\n gallus_gallus = Organism.get_object_for_name(\"GALLUS_GALLUS\", taxonomy_id=1001)\n\n # MICROARRAY TECH\n (experiment, _) = Experiment.objects.get_or_create(accession_code=\"GSE1487313\")\n experiment.accession_code = \"GSE1487313\"\n experiment.save()\n\n create_sample_for_experiment(\n {\n \"organism\": gallus_gallus,\n \"accession_code\": \"GSM1487313\",\n \"technology\": \"MICROARRAY\",\n \"filename\": \"GSM1487313_liver.PCL\",\n \"data_dir\": DATA_DIR,\n },\n experiment,\n )\n\n # Missing sample that will be filtered\n create_sample_for_experiment(\n {\n \"organism\": gallus_gallus,\n \"accession_code\": \"GSM1487222\",\n \"title\": \"this sample will be filtered\",\n \"technology\": \"MICROARRAY\",\n \"filename\": \"GSM1487222_empty.PCL\",\n \"data_dir\": DATA_DIR,\n },\n experiment,\n )\n\n # RNASEQ TECH\n experiment2 = Experiment()\n experiment2.accession_code = \"SRP149598\"\n experiment2.save()\n\n create_sample_for_experiment(\n {\n \"organism\": gallus_gallus,\n \"accession_code\": \"SRR7250867\",\n \"technology\": \"RNA-SEQ\",\n \"filename\": \"SRP149598_gene_lengthScaledTPM.tsv\",\n \"data_dir\": DATA_DIR,\n },\n experiment,\n )\n\n dset = Dataset()\n dset.data = {\n \"GSE1487313\": [\"GSM1487313\", \"GSM1487222\"],\n \"SRP149598\": [\"SRR7250867\"],\n }\n dset.scale_by = \"NONE\"\n dset.aggregate_by = \"SPECIES\"\n dset.svd_algorithm = \"ARPACK\"\n dset.quantile_normalize = True\n dset.save()\n\n pjda = ProcessorJobDatasetAssociation()\n pjda.processor_job = job\n pjda.dataset = dset\n pjda.save()\n\n final_context = create_compendia.create_compendia(job.id)\n\n # Because one of the samples is filtered out, there will be too few\n # remaining samples to smash together, so we expect this job to fail.\n self.assertFailed(job, \"k must be between 1 and min(A.shape)\")\n\n # check that sample with no computed file was skipped\n self.assertTrue(\"GSM1487222\" in final_context[\"filtered_samples\"])\n self.assertEqual(\n final_context[\"filtered_samples\"][\"GSM1487222\"][\"experiment_accession_code\"],\n \"GSE1487313\",\n )\n\n @tag(\"compendia\")\n def test_create_compendia_danio(self):\n job = ProcessorJob()\n job.pipeline_applied = ProcessorPipeline.CREATE_COMPENDIA.value\n job.save()\n\n # MICROARRAY TECH\n experiment = Experiment()\n experiment.accession_code = \"GSE1234\"\n experiment.save()\n\n result = ComputationalResult()\n result.save()\n\n qn_target = ComputedFile()\n qn_target.filename = \"danio_target.tsv\"\n qn_target.absolute_file_path = \"/home/user/data_store/QN/danio_target.tsv\"\n qn_target.is_qn_target = True\n qn_target.size_in_bytes = \"12345\"\n qn_target.sha1 = \"aabbccddeeff\"\n qn_target.result = result\n qn_target.save()\n\n danio_rerio = Organism(name=\"DANIO_RERIO\", taxonomy_id=1, qn_target=result)\n danio_rerio.save()\n\n cra = ComputationalResultAnnotation()\n cra.data = {}\n cra.data[\"organism_id\"] = danio_rerio.id\n cra.data[\"is_qn\"] = True\n cra.result = result\n cra.save()\n\n result = ComputationalResult()\n result.save()\n\n micros = []\n for file in os.listdir(\"/home/user/data_store/raw/TEST/MICROARRAY/\"):\n\n if \"microarray.txt\" in file:\n continue\n\n create_sample_for_experiment(\n {\n \"organism\": danio_rerio,\n \"accession_code\": file,\n \"technology\": \"MICROARRAY\",\n \"filename\": file,\n \"data_dir\": \"/home/user/data_store/raw/TEST/MICROARRAY/\",\n },\n experiment,\n )\n\n micros.append(file)\n\n experiment = Experiment()\n experiment.accession_code = \"GSE5678\"\n experiment.save()\n\n result = ComputationalResult()\n result.save()\n rnas = []\n for file in os.listdir(\"/home/user/data_store/raw/TEST/RNASEQ/\"):\n\n if \"rnaseq.txt\" in file:\n continue\n\n create_sample_for_experiment(\n {\n \"organism\": danio_rerio,\n \"accession_code\": file,\n \"technology\": \"RNA-SEQ\",\n \"filename\": file,\n \"data_dir\": \"/home/user/data_store/raw/TEST/RNASEQ/\",\n },\n experiment,\n )\n\n rnas.append(file)\n\n # Missing sample that will be filtered\n sample = create_sample_for_experiment(\n {\n \"organism\": danio_rerio,\n \"accession_code\": \"GSM1487222\",\n \"title\": \"this sample will be filtered\",\n \"technology\": \"RNA-SEQ\",\n \"filename\": None,\n },\n experiment,\n )\n rnas.append(sample.accession_code)\n\n dset = Dataset()\n dset.data = {\"GSE1234\": micros, \"GSE5678\": rnas}\n dset.scale_by = \"NONE\"\n dset.aggregate_by = \"SPECIES\"\n dset.svd_algorithm = \"ARPACK\"\n dset.quantile_normalize = True\n dset.save()\n\n pjda = ProcessorJobDatasetAssociation()\n pjda.processor_job = job\n pjda.dataset = dset\n pjda.save()\n\n final_context = create_compendia.create_compendia(job.id)\n\n self.assertSucceeded(job)\n\n # Verify result\n self.assertEqual(final_context[\"compendium_result\"].result.computedfile_set.count(), 1)\n for file in final_context[\"compendium_result\"].result.computedfile_set.all():\n self.assertTrue(os.path.exists(file.absolute_file_path))\n\n # test compendium_result\n self.assertEqual(final_context[\"compendium_result\"].svd_algorithm, \"ARPACK\")\n self.assertEqual(\n final_context[\"compendium_result\"].primary_organism.name,\n final_context[\"organism_name\"],\n )\n self.assertEqual(final_context[\"compendium_result\"].primary_organism.name, \"DANIO_RERIO\")\n self.assertEqual(final_context[\"compendium_result\"].organisms.count(), 1)\n\n self.assertEqual(len(final_context[\"filtered_samples\"]), 10)\n\n # check that sample with no computed file was skipped\n self.assertTrue(\"GSM1487222\" in final_context[\"filtered_samples\"])\n self.assertEqual(\n final_context[\"filtered_samples\"][\"GSM1487222\"][\"experiment_accession_code\"], \"GSE5678\"\n )\n self.assertIn(\n \"This sample did not have a processed file\",\n final_context[\"filtered_samples\"][\"GSM1487222\"][\"reason\"],\n )\n\n # check that the 9 files with lots of missing measurements were filtered\n self.assertEqual(\n len(\n list(\n filter(\n lambda x: \"less than 50% present values\" in x[\"reason\"],\n final_context[\"filtered_samples\"].values(),\n )\n )\n ),\n 9,\n )\n\n zf = zipfile.ZipFile(\n final_context[\"compendium_result\"].result.computedfile_set.first().absolute_file_path\n )\n with zf.open(\"aggregated_metadata.json\") as f:\n metadata = json.load(f)\n\n self.assertFalse(metadata.get(\"quant_sf_only\"))\n self.assertEqual(metadata.get(\"compendium_version\"), 1)\n\n # 420 microarray + 420 RNA seq\n # -1 that is filtered for a missing file\n # -9 that are filtered for having less than 50% present values\n self.assertEqual(metadata.get(\"num_samples\"), 830)\n\n self.assertEqual(metadata.get(\"num_experiments\"), 2)\n\n # Make sure the data were quantile normalized\n self.assertTrue(metadata.get(\"quantile_normalized\"))\n\n self.assertIn(\"ks_statistic\", final_context)\n self.assertIn(\"ks_pvalue\", final_context)\n self.assertEqual(final_context[\"ks_pvalue\"], 1.0)\n\n @tag(\"compendia\")\n def test_create_compendia_microarray_only(self):\n \"\"\"\n Make sure that we can actually create a compendium with just microarray samples.\n \"\"\"\n job = ProcessorJob()\n job.pipeline_applied = ProcessorPipeline.CREATE_COMPENDIA.value\n job.save()\n\n # MICROARRAY TECH\n experiment = Experiment()\n experiment.accession_code = \"GSE1234\"\n experiment.save()\n\n result = ComputationalResult()\n result.save()\n\n qn_target = ComputedFile()\n qn_target.filename = \"danio_target.tsv\"\n qn_target.absolute_file_path = \"/home/user/data_store/QN/danio_target.tsv\"\n qn_target.is_qn_target = True\n qn_target.size_in_bytes = \"12345\"\n qn_target.sha1 = \"aabbccddeeff\"\n qn_target.result = result\n qn_target.save()\n\n danio_rerio = Organism(name=\"DANIO_RERIO\", taxonomy_id=1, qn_target=result)\n danio_rerio.save()\n\n cra = ComputationalResultAnnotation()\n cra.data = {}\n cra.data[\"organism_id\"] = danio_rerio.id\n cra.data[\"is_qn\"] = True\n cra.result = result\n cra.save()\n\n result = ComputationalResult()\n result.save()\n\n micros = []\n for file in os.listdir(\"/home/user/data_store/raw/TEST/MICROARRAY/\"):\n\n if \"microarray.txt\" in file:\n continue\n\n create_sample_for_experiment(\n {\n \"organism\": danio_rerio,\n \"accession_code\": file,\n \"technology\": \"MICROARRAY\",\n \"filename\": file,\n \"data_dir\": \"/home/user/data_store/raw/TEST/MICROARRAY/\",\n },\n experiment,\n )\n\n micros.append(file)\n\n dset = Dataset()\n dset.data = {\"GSE1234\": micros}\n dset.scale_by = \"NONE\"\n dset.aggregate_by = \"SPECIES\"\n dset.svd_algorithm = \"ARPACK\"\n dset.quantile_normalize = True\n dset.save()\n\n pjda = ProcessorJobDatasetAssociation()\n pjda.processor_job = job\n pjda.dataset = dset\n pjda.save()\n\n final_context = create_compendia.create_compendia(job.id)\n\n self.assertSucceeded(job)\n\n # Verify result\n self.assertEqual(final_context[\"compendium_result\"].result.computedfile_set.count(), 1)\n for file in final_context[\"compendium_result\"].result.computedfile_set.all():\n self.assertTrue(os.path.exists(file.absolute_file_path))\n\n # test compendium_result\n self.assertEqual(final_context[\"compendium_result\"].svd_algorithm, \"ARPACK\")\n self.assertEqual(\n final_context[\"compendium_result\"].primary_organism.name,\n final_context[\"organism_name\"],\n )\n self.assertEqual(final_context[\"compendium_result\"].primary_organism.name, \"DANIO_RERIO\")\n self.assertEqual(final_context[\"compendium_result\"].organisms.count(), 1)\n\n zf = zipfile.ZipFile(\n final_context[\"compendium_result\"].result.computedfile_set.first().absolute_file_path\n )\n with zf.open(\"aggregated_metadata.json\") as f:\n metadata = json.load(f)\n\n self.assertFalse(metadata.get(\"quant_sf_only\"))\n # 420 microarray\n self.assertEqual(metadata.get(\"num_samples\"), 420)\n self.assertEqual(metadata.get(\"num_experiments\"), 1)\n\n # Make sure the data were quantile normalized\n self.assertTrue(metadata.get(\"quantile_normalized\"))\n\n self.assertIn(\"ks_statistic\", final_context)\n self.assertIn(\"ks_pvalue\", final_context)\n self.assertEqual(final_context[\"ks_pvalue\"], 1.0)\n\n @tag(\"compendia\")\n def test_filter_rnaseq_matrix_drop_row_sums(self):\n job = ProcessorJob()\n job.pipeline_applied = ProcessorPipeline.CREATE_COMPENDIA.value\n job.save()\n\n samples = list(str(i) for i in range(0, 10))\n df = pd.DataFrame(columns=samples)\n for i in range(1, 101):\n df.loc[str(i)] = {idx: i for idx in samples}\n\n job_context = {\"rnaseq_matrix\": df, \"job\": job}\n\n final_job_context = create_compendia._filter_rnaseq_matrix(job_context)\n\n filtered_matrix = final_job_context[\"filtered_rnaseq_matrix\"]\n\n # Make sure that we are getting rid of intermediate results\n # appropriately. Because these matrices can be pretty heavy, the input\n # should not stick around in the job context like this.\n self.assertNotIn(\"rnaseq_matrix\", final_job_context.keys())\n\n # We drop all rows below the 10th percentile in row sum, so we would\n # expect to drop rows 1 through 10 that we created above\n self.assertEqual(set(filtered_matrix.index), set(str(i) for i in range(11, 101)))\n\n @tag(\"compendia\")\n def test_drop_samples(self):\n \"\"\"Make sure that we drop samples with >50% missing values\"\"\"\n job = ProcessorJob()\n job.pipeline_applied = ProcessorPipeline.CREATE_COMPENDIA.value\n job.save()\n\n danio_rerio = Organism(name=\"DANIO_RERIO\", taxonomy_id=1)\n danio_rerio.save()\n\n experiment = Experiment()\n experiment.accession_code = \"GSE1234\"\n experiment.save()\n\n samples = list(str(i) for i in range(0, 10))\n for i in samples:\n create_sample_for_experiment(\n {\"organism\": danio_rerio, \"accession_code\": i, \"technology\": \"MICROARRAY\"},\n experiment,\n )\n\n dset = Dataset()\n dset.data = {\"GSE1234\": \"ALL\"}\n dset.scale_by = \"NONE\"\n dset.aggregate_by = \"SPECIES\"\n dset.svd_algorithm = \"ARPACK\"\n dset.quantile_normalize = True\n dset.save()\n\n df = pd.DataFrame(columns=samples)\n for i in range(1, 101):\n row_i = {idx: i for idx in samples}\n\n if i % 3 != 0 and i % 3 != 1:\n del row_i[\"0\"]\n\n if i % 2 != 0:\n del row_i[\"1\"]\n\n if i % 3 != 0:\n del row_i[\"2\"]\n\n if i % 4 != 0:\n del row_i[\"3\"]\n\n df.loc[str(i)] = row_i\n\n job_context = {\n \"microarray_matrix\": df,\n \"job\": job,\n \"dataset\": dset,\n # This key is added in the setup code, so we need to add it ourselves here\n \"filtered_samples\": {},\n }\n\n job_context = create_compendia._full_outer_join_gene_matrices(job_context)\n final_job_context = create_compendia._filter_rows_and_columns(job_context)\n\n filtered_matrix = final_job_context[\"row_col_filtered_matrix\"]\n\n # Columns 0 and 1 have missing data, but they should still have >= 50%.\n # Columns 2 and 3 are both missing >50% though, so they should be filtered.\n self.assertEqual(set(filtered_matrix.columns), {\"0\", \"1\"} | {str(i) for i in range(4, 10)})\n self.assertEqual(set(final_job_context[\"filtered_samples\"].keys()), {\"2\", \"3\"})\n for v in final_job_context[\"filtered_samples\"].values():\n self.assertIn(\"less than 50% present\", v[\"reason\"])\n\n @tag(\"compendia\")\n def test_imputation(self):\n job = ProcessorJob()\n job.pipeline_applied = ProcessorPipeline.CREATE_COMPENDIA.value\n job.save()\n\n # MICROARRAY TECH\n experiment = Experiment()\n experiment.accession_code = \"GSE1234\"\n experiment.save()\n\n result = ComputationalResult()\n result.save()\n\n qn_target = ComputedFile()\n qn_target.filename = \"danio_target.tsv\"\n qn_target.absolute_file_path = \"/home/user/data_store/QN/danio_target.tsv\"\n qn_target.is_qn_target = True\n qn_target.size_in_bytes = \"12345\"\n qn_target.sha1 = \"aabbccddeeff\"\n qn_target.result = result\n qn_target.save()\n\n danio_rerio = Organism(name=\"DANIO_RERIO\", taxonomy_id=1, qn_target=result)\n danio_rerio.save()\n\n cra = ComputationalResultAnnotation()\n cra.data = {}\n cra.data[\"organism_id\"] = danio_rerio.id\n cra.data[\"is_qn\"] = True\n cra.result = result\n cra.save()\n\n result = ComputationalResult()\n result.save()\n\n micros = []\n for file in os.listdir(\"/home/user/data_store/raw/TEST/MICROARRAY/\"):\n\n if \"microarray.txt\" in file:\n continue\n\n create_sample_for_experiment(\n {\n \"organism\": danio_rerio,\n \"accession_code\": file,\n \"technology\": \"MICROARRAY\",\n \"filename\": file,\n \"data_dir\": \"/home/user/data_store/raw/TEST/MICROARRAY/\",\n },\n experiment,\n )\n\n micros.append(file)\n\n experiment = Experiment()\n experiment.accession_code = \"GSE5678\"\n experiment.save()\n\n result = ComputationalResult()\n result.save()\n rnas = []\n for file in os.listdir(\"/home/user/data_store/raw/TEST/RNASEQ/\"):\n\n if \"rnaseq.txt\" in file:\n continue\n\n create_sample_for_experiment(\n {\n \"organism\": danio_rerio,\n \"accession_code\": file,\n \"technology\": \"RNA-SEQ\",\n \"filename\": file,\n \"data_dir\": \"/home/user/data_store/raw/TEST/RNASEQ/\",\n },\n experiment,\n )\n\n rnas.append(file)\n\n # Missing sample that will be filtered\n sample = create_sample_for_experiment(\n {\n \"organism\": danio_rerio,\n \"accession_code\": \"GSM1487222\",\n \"title\": \"this sample will be filtered\",\n \"technology\": \"RNA-SEQ\",\n \"filename\": None,\n },\n experiment,\n )\n rnas.append(sample.accession_code)\n\n dset = Dataset()\n dset.data = {\"GSE1234\": micros, \"GSE5678\": rnas}\n dset.scale_by = \"NONE\"\n dset.aggregate_by = \"SPECIES\"\n dset.svd_algorithm = \"ARPACK\"\n dset.quantile_normalize = True\n dset.save()\n\n pjda = ProcessorJobDatasetAssociation()\n pjda.processor_job = job\n pjda.dataset = dset\n pjda.save()\n\n imputation_index = create_compendia.COMPENDIA_PIPELINE.index(\n create_compendia._perform_imputation\n )\n\n pipeline = Pipeline(name=PipelineEnum.CREATE_COMPENDIA.value)\n job_context = utils.run_pipeline(\n {\"job_id\": job.id, \"pipeline\": pipeline},\n create_compendia.COMPENDIA_PIPELINE[:imputation_index],\n )\n\n # First, run the imputation step without removing anything to get a baseline\n expected_context = utils.run_pipeline(\n job_context.copy(), [create_compendia.COMPENDIA_PIPELINE[imputation_index]]\n )\n\n # Now pick some rows to remove according to the instructions from\n # https://github.com/AlexsLemonade/refinebio/pull/2879#issuecomment-895143336\n\n random.seed(42)\n\n # Select some rows randomly and mask a little bit less than 30% of the values\n rare_rows = random.sample(list(job_context[\"microarray_matrix\"].index), k=25)\n rare_genes = {}\n for row in rare_rows:\n cols = random.sample(\n list(job_context[\"microarray_matrix\"].columns),\n # There are around 840 samples, and we want to pick a little bit\n # less than 30% of them\n k=int(0.28 * 840),\n )\n rare_genes[row] = cols\n for col in cols:\n job_context[\"microarray_matrix\"].loc[row, col] = np.nan\n\n # Now randomly select some entries from the other rows to mask\n individual_indices = random.sample(\n list(\n itertools.product(\n set(job_context[\"microarray_matrix\"].index) - set(rare_rows),\n job_context[\"microarray_matrix\"].columns,\n )\n ),\n k=1000,\n )\n for row, col in individual_indices:\n job_context[\"microarray_matrix\"].loc[row, col] = np.nan\n\n final_context = utils.run_pipeline(\n job_context, [create_compendia.COMPENDIA_PIPELINE[imputation_index]]\n )\n self.assertDidNotFail(job)\n\n index = set(final_context[\"merged_no_qn\"].index) & set(\n expected_context[\"merged_no_qn\"].index\n )\n columns = set(final_context[\"merged_no_qn\"].columns) & set(\n expected_context[\"merged_no_qn\"].columns\n )\n\n # Calculate the Root-Mean-Square Error (RMSE) of the imputed values.\n # See https://en.wikipedia.org/wiki/Root-mean-square_deviation\n # for a description of the formula.\n\n N = 0\n squared_error = 0\n affected_entries = {\n *individual_indices,\n *((row, col) for row, cols in rare_genes.items() for col in cols),\n }\n for row, col in affected_entries:\n if row in index and col in columns:\n actual = final_context[\"merged_no_qn\"].loc[row, col]\n expected = expected_context[\"merged_no_qn\"].loc[row, col]\n\n N += 1\n squared_error += (actual - expected) ** 2\n\n rmse = math.sqrt(squared_error / N)\n\n # The results of a previous run plus a little bit of leeway\n self.assertLess(abs(rmse - 0.2868600293662542), 0.05)\n"
] |
[
[
"pandas.DataFrame"
]
] |
myatthukyaw/res_efficient_gcns
|
[
"89280d10f1d4864dfa0a5c3813db11e074dcb2f2"
] |
[
"EfficientGCNv1/utils/tracking/deepsort/deep/model.py"
] |
[
"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\n\r\nclass BasicBlock(nn.Module):\r\n def __init__(self, c_in, c_out, is_downsample=False):\r\n super(BasicBlock, self).__init__()\r\n self.is_downsample = is_downsample\r\n if is_downsample:\r\n self.conv1 = nn.Conv2d(\r\n c_in, c_out, 3, stride=2, padding=1, bias=False)\r\n else:\r\n self.conv1 = nn.Conv2d(\r\n c_in, c_out, 3, stride=1, padding=1, bias=False)\r\n self.bn1 = nn.BatchNorm2d(c_out)\r\n self.relu = nn.ReLU(True)\r\n self.conv2 = nn.Conv2d(c_out, c_out, 3, stride=1,\r\n padding=1, bias=False)\r\n self.bn2 = nn.BatchNorm2d(c_out)\r\n if is_downsample:\r\n self.downsample = nn.Sequential(\r\n nn.Conv2d(c_in, c_out, 1, stride=2, bias=False),\r\n nn.BatchNorm2d(c_out)\r\n )\r\n elif c_in != c_out:\r\n self.downsample = nn.Sequential(\r\n nn.Conv2d(c_in, c_out, 1, stride=1, bias=False),\r\n nn.BatchNorm2d(c_out)\r\n )\r\n self.is_downsample = True\r\n\r\n def forward(self, x):\r\n y = self.conv1(x)\r\n y = self.bn1(y)\r\n y = self.relu(y)\r\n y = self.conv2(y)\r\n y = self.bn2(y)\r\n if self.is_downsample:\r\n x = self.downsample(x)\r\n return F.relu(x.add(y), True)\r\n\r\n\r\ndef make_layers(c_in, c_out, repeat_times, is_downsample=False):\r\n blocks = []\r\n for i in range(repeat_times):\r\n if i == 0:\r\n blocks += [BasicBlock(c_in, c_out, is_downsample=is_downsample)]\r\n else:\r\n blocks += [BasicBlock(c_out, c_out)]\r\n return nn.Sequential(*blocks)\r\n\r\n\r\nclass Net(nn.Module):\r\n def __init__(self, num_classes=751, reid=False):\r\n super(Net, self).__init__()\r\n # 3 128 64\r\n self.conv = nn.Sequential(\r\n nn.Conv2d(3, 64, 3, stride=1, padding=1),\r\n nn.BatchNorm2d(64),\r\n nn.ReLU(inplace=True),\r\n # nn.Conv2d(32,32,3,stride=1,padding=1),\r\n # nn.BatchNorm2d(32),\r\n # nn.ReLU(inplace=True),\r\n nn.MaxPool2d(3, 2, padding=1),\r\n )\r\n # 32 64 32\r\n self.layer1 = make_layers(64, 64, 2, False)\r\n # 32 64 32\r\n self.layer2 = make_layers(64, 128, 2, True)\r\n # 64 32 16\r\n self.layer3 = make_layers(128, 256, 2, True)\r\n # 128 16 8\r\n self.layer4 = make_layers(256, 512, 2, True)\r\n # 256 8 4\r\n self.avgpool = nn.AvgPool2d((8, 4), 1)\r\n # 256 1 1\r\n self.reid = reid\r\n self.classifier = nn.Sequential(\r\n nn.Linear(512, 256),\r\n nn.BatchNorm1d(256),\r\n nn.ReLU(inplace=True),\r\n nn.Dropout(),\r\n nn.Linear(256, num_classes),\r\n )\r\n\r\n def forward(self, x):\r\n x = self.conv(x)\r\n x = self.layer1(x)\r\n x = self.layer2(x)\r\n x = self.layer3(x)\r\n x = self.layer4(x)\r\n x = self.avgpool(x)\r\n x = x.view(x.size(0), -1)\r\n # B x 128\r\n if self.reid:\r\n x = x.div(x.norm(p=2, dim=1, keepdim=True))\r\n return x\r\n # classifier\r\n x = self.classifier(x)\r\n return x\r\n\r\n\r\nif __name__ == '__main__':\r\n net = Net()\r\n x = torch.randn(4, 3, 128, 64)\r\n y = net(x)\r\n import ipdb\r\n ipdb.set_trace()\r\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"torch.nn.Dropout",
"torch.randn",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.Linear",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
Eclipse-Dominator/machine_learning_ANN_python
|
[
"cb65b1ed6d62544ee8eaa749fb64fa5d3e792f76"
] |
[
"Python_3.6/ANN_class/ANN.py"
] |
[
"import numpy as np\n# Artificial Neural Network\nclass ANN:\n\tdef __init__(self, layer_size_list):\n\t\tself.input_size = layer_size_list[0]\n\t\tself.hidden_output_layer = []\n\t\tself.cost_result = []\n\t\tself.accuracy_result = []\n\t\tfor layer_index in range(1, len(layer_size_list)):\n\t\t\tself.hidden_output_layer.append( NNlayer( layer_size_list[layer_index - 1], layer_size_list[layer_index], self.sigmoid, self.de_sigmoid ) )\n\n\tdef propagate_result(self, network_input, save_result = False):\n\t\tprevious_output = [network_input]\n\t\tfor layer in self.hidden_output_layer:\n\t\t\tprevious_output = layer.CalculateOutput(previous_output,save_data = save_result)\n\t\treturn previous_output\n\n\tdef mini_batch_training(self, training_data, batch_size, learning_rate = 0.3, total_epoch = 500): # batch_size should be in integer \n\t\ttotal_num_training_data = len(training_data)\n\t\ttotal_iterations = total_num_training_data // batch_size\n\t\tnp.random.shuffle(training_data)\n\t\tfor z in range(total_epoch):\n\t\t\tsuccess_total = 0\n\t\t\tcost_total = 0\n\t\t\ttemp_batch = 0\n\t\t\tfor i in range(total_iterations):\n\t\t\t\tindex = batch_size * i\n\t\t\t\tsuccess, cost = self.batch_SGD(training_data[index:index+batch_size],learning_rate)\n\t\t\t\ttemp_batch = len(training_data[index:index+batch_size])\n\t\t\t\tsuccess_total += success\n\t\t\t\tcost_total += cost\n\t\t\tself.cost_result.append( cost_total/(temp_batch*total_iterations) )\n\t\t\tself.accuracy_result.append( success_total/(temp_batch*total_iterations) )\t\n\t\t\tprint(\"epoch:\", z+1, \"out of\", total_epoch,\"| Accuracy:\", success_total/(temp_batch*total_iterations))\n\n\n\tdef batch_SGD(self,training_data,learning_rate):\n\t\tbatch_size = len(training_data)\n\t\tcorrect = 0.0\n\t\tcostTot = 0.0\n\t\tfor data in training_data:\n\t\t\tnetwork_result = self.propagate_result(data[0],save_result = True)\n\t\t\tif np.argmax(network_result) == np.argmax(data[1]):\n\t\t\t\tcorrect += 1.0\n\t\t\td_cost = network_result - [data[1]]\n\t\t\tcostTot+=0.5 * np.sum( (d_cost)**2 )\n\t\t\tself.backpropagate_result(d_cost)\n\t\tself.update_layers(batch_size, learning_rate)\n\t\treturn correct, costTot\n\n\tdef update_layers(self, batch_size, learning_rate):\n\t\tfor layer in self.hidden_output_layer:\n\t\t\tlayer.update_constants(learning_rate, batch_size)\n\n\tdef backpropagate_result(self, d_cost):\n\t\tfinal_derivative = d_cost\n\t\tfor layer in reversed(self.hidden_output_layer):\n\t\t\tfinal_derivative = layer.backpropagate_layer(final_derivative)\n\n\tdef sigmoid(self, x): return 1/(1+np.exp(-x))\n\tdef de_sigmoid(self, x): return self.sigmoid(x) * ( 1 - self.sigmoid(x) )\n\nclass NNlayer:\n\tdef __init__(self, previous_nodes, current_nodes, activating_function, derivative_function):\n\t\tself.weightArr = np.random.random((previous_nodes,current_nodes))*2-1\n\t\tself.biasArr = np.random.random((1,current_nodes))*2-1\n\t\tself.activating_function = activating_function # must be iterative\n\t\tself.derivative_function = derivative_function # must be iterative\n\t\tself.bias_G_sum = np.copy(self.biasArr) * 0\n\t\tself.weight_G_sum = np.copy(self.weightArr) * 0\n\n\tdef CalculateOutput(self, previous_layer_output, save_data = False):\n\t\tpre_activating = np.dot(previous_layer_output, self.weightArr) + self.biasArr\n\t\tif save_data: \n\t\t\tself.derivative_activation = self.derivative_function( pre_activating )\n\t\t\tself.previous_layer_output = np.array(previous_layer_output)\n\t\treturn self.activating_function( pre_activating )\n\n\tdef backpropagate_layer(self, next_layer):\n\t\tbias_G = next_layer * self.derivative_activation\n\t\tweight_G = np.dot( self.previous_layer_output.T, bias_G )\n\t\tweight_G = self.previous_layer_output.T.dot( bias_G )\n\t\tself.bias_G_sum += bias_G\n\t\tself.weight_G_sum += weight_G\n\n\t\treturn np.dot( bias_G, self.weightArr.T )\n\n\tdef update_constants(self, learning_rate, batch_size):\n\t\tself.weightArr -= learning_rate * self.weight_G_sum / batch_size\n\t\tself.biasArr -= learning_rate * self.bias_G_sum / batch_size\n\t\tgradient_magnitude = np.linalg.norm(self.bias_G_sum / batch_size) + np.linalg.norm(self.weight_G_sum / batch_size)\n\t\tself.bias_G_sum *= 0\n\t\tself.weight_G_sum *= 0\n\t\treturn gradient_magnitude\n"
] |
[
[
"numpy.dot",
"numpy.random.random",
"numpy.linalg.norm",
"numpy.random.shuffle",
"numpy.copy",
"numpy.argmax",
"numpy.exp",
"numpy.array",
"numpy.sum"
]
] |
mataney/encoder-agnostic-adaptation
|
[
"59d7c2d4fe69f794c7449f0459f00350fcfbbf70"
] |
[
"onmt/model_builder.py"
] |
[
"\"\"\"\nThis file is for models creation, which consults options\nand creates each encoder and decoder accordingly.\n\"\"\"\nimport re\nimport math\nimport copy\nimport torch\nimport torch.nn as nn\nfrom torch.nn.init import xavier_uniform_\n\nimport onmt.inputters as inputters\nimport onmt.modules\nfrom onmt.encoders import str2enc\n\nfrom onmt.decoders import str2dec\n\nfrom onmt.modules import Embeddings, CopyGenerator, SimpleFusionGenerator\nfrom onmt.modules.util_class import Cast\nfrom onmt.utils.misc import use_gpu\nfrom onmt.utils.logging import logger\nfrom onmt.utils.parse import ArgumentParser\n\n\ndef build_embeddings(opt, text_field, for_encoder=True):\n \"\"\"\n Args:\n opt: the option in current environment.\n text_field(TextMultiField): word and feats field.\n for_encoder(bool): build Embeddings for encoder or decoder?\n \"\"\"\n emb_dim = opt.src_word_vec_size if for_encoder else opt.tgt_word_vec_size\n\n pad_indices = [f.vocab.stoi[f.pad_token] for _, f in text_field]\n\n word_padding_idx, feat_pad_indices = pad_indices[0], pad_indices[1:]\n\n num_embs = [len(f.vocab) for _, f in text_field]\n num_word_embeddings, num_feat_embeddings = num_embs[0], num_embs[1:]\n\n fix_word_vecs = opt.fix_word_vecs_enc if for_encoder \\\n else opt.fix_word_vecs_dec\n\n pos_enc_learned = opt.position_encoding_learned_enc if for_encoder else opt.position_encoding_learned_dec\n GPT_representation_mode = opt.GPT_representation_mode if opt.GPT_representation_loc == 'both' or (opt.GPT_representation_loc == 'src' and for_encoder) or (opt.GPT_representation_loc == 'tgt' and not for_encoder) else 'none'\n\n emb = Embeddings(\n word_vec_size=emb_dim,\n position_encoding=opt.position_encoding,\n position_encoding_learned=pos_enc_learned,\n position_encoding_ctxsize=opt.position_encoding_ctxsize,\n feat_merge=opt.feat_merge,\n feat_vec_exponent=opt.feat_vec_exponent,\n feat_vec_size=opt.feat_vec_size,\n dropout=opt.dropout,\n word_padding_idx=word_padding_idx,\n feat_padding_idx=feat_pad_indices,\n word_vocab_size=num_word_embeddings,\n feat_vocab_sizes=num_feat_embeddings,\n sparse=opt.optim == \"sparseadam\",\n fix_word_vecs=fix_word_vecs,\n GPT_representation_mode=GPT_representation_mode,\n GPT_representation_tgt=not for_encoder\n )\n return emb\n\n\ndef build_encoder(opt, embeddings):\n \"\"\"\n Various encoder dispatcher function.\n Args:\n opt: the option in current environment.\n embeddings (Embeddings): vocab embeddings for this encoder.\n \"\"\"\n enc_type = opt.encoder_type if opt.model_type == \"text\" else opt.model_type\n return str2enc[enc_type].from_opt(opt, embeddings)\n\n\ndef build_decoder(opt, embeddings):\n \"\"\"\n Various decoder dispatcher function.\n Args:\n opt: the option in current environment.\n embeddings (Embeddings): vocab embeddings for this decoder.\n \"\"\"\n dec_type = \"ifrnn\" if opt.decoder_type == \"rnn\" and opt.input_feed \\\n else opt.decoder_type\n return str2dec[dec_type].from_opt(opt, embeddings)\n\n\ndef load_test_model(opt, model_path=None):\n if model_path is None:\n model_path = opt.models[0]\n checkpoint = torch.load(model_path,\n map_location=lambda storage, loc: storage)\n\n model_opt = ArgumentParser.ckpt_model_opts(checkpoint['opt'])\n ArgumentParser.update_model_opts(model_opt)\n ArgumentParser.validate_model_opts(model_opt)\n vocab = checkpoint['vocab']\n if inputters.old_style_vocab(vocab):\n fields = inputters.load_old_vocab(\n vocab, opt.data_type, dynamic_dict=model_opt.copy_attn\n )\n else:\n fields = vocab\n\n model = build_base_model(model_opt, fields, use_gpu(opt), checkpoint,\n opt.gpu)\n if opt.fp32:\n model.float()\n\n model.eval()\n model.generator.eval()\n return fields, model, model_opt\n\nclass PadGen(nn.Module):\n def __init__(self):\n super(PadGen, self).__init__()\n\n def forward(self, vals):\n # Need to make this more general\n vals[..., 50257:] = -1e10\n return vals\n \n\ndef build_base_model(model_opt, fields, gpu, checkpoint=None, gpu_id=None):\n \"\"\"Build a model from opts.\n\n Args:\n model_opt: the option loaded from checkpoint. It's important that\n the opts have been updated and validated. See\n :class:`onmt.utils.parse.ArgumentParser`.\n fields (dict[str, torchtext.data.Field]):\n `Field` objects for the model.\n gpu (bool): whether to use gpu.\n checkpoint: the model gnerated by train phase, or a resumed snapshot\n model from a stopped training.\n gpu_id (int or NoneType): Which GPU to use.\n\n Returns:\n the NMTModel.\n \"\"\"\n\n # Build embeddings.\n if model_opt.model_type == \"text\":\n src_field = fields[\"src\"]\n src_emb = build_embeddings(model_opt, src_field)\n else:\n src_emb = None\n\n # Build encoder.\n encoder = build_encoder(model_opt, src_emb)\n\n # Build decoder.\n tgt_field = fields[\"tgt\"]\n tgt_emb = build_embeddings(model_opt, tgt_field, for_encoder=False)\n\n # Share the embedding matrix - preprocess with share_vocab required.\n if model_opt.share_embeddings:\n # src/tgt vocab should be the same if `-share_vocab` is specified.\n assert src_field.base_field.vocab == tgt_field.base_field.vocab, \\\n \"preprocess with -share_vocab if you use share_embeddings\"\n\n tgt_emb.word_lut.weight = src_emb.word_lut.weight\n\n if model_opt.share_position_embeddings:\n tgt_emb.make_embedding.pe.pe.weight = src_emb.make_embedding.pe.pe.weight\n\n decoder = build_decoder(model_opt, tgt_emb)\n\n # Build NMTModel(= encoder + decoder).\n if gpu and gpu_id is not None:\n device = torch.device(\"cuda\", gpu_id)\n elif gpu and not gpu_id:\n device = torch.device(\"cuda\")\n elif not gpu:\n device = torch.device(\"cpu\")\n\n # Build separate LM if doing simple fusion\n if model_opt.simple_fusion:\n layers = 12\n size = 768\n heads = 12\n\n lm_decoder_opt = copy.deepcopy(model_opt)\n lm_decoder_opt.dec_layers = layers\n lm_decoder_opt.use_GPT_version_ctxattn = False\n lm_decoder_opt.use_GPT_version_psa = False\n lm_decoder_opt.use_GPT_version_unconditional = True\n lm_decoder_opt.tgt_word_vec_size = size\n lm_decoder_opt.rnn_size = size\n lm_decoder_opt.dec_rnn_size = size\n lm_decoder_opt.transformer_ff = size*4\n lm_decoder_opt.dec_heads = heads\n lm_decoder_opt.position_encoding_learned_dec = True\n lm_decoder_opt.share_decoder_embeddings = True\n lm_decoder_opt.dropout = 0\n\n lm_decoder_emb = build_embeddings(lm_decoder_opt, tgt_field, for_encoder=False)\n logger.info(lm_decoder_emb)\n\n lm_decoder = build_decoder(lm_decoder_opt, lm_decoder_emb)\n load_decoder = lm_decoder\n\n model = onmt.models.SimpleFusionModel(encoder, decoder, lm_decoder)\n\n generator = SimpleFusionGenerator(model_opt.dec_rnn_size,\n lm_decoder_opt.dec_rnn_size,\n len(fields[\"tgt\"].base_field.vocab))\n generator.lm_linear.weight = lm_decoder.embeddings.word_lut.weight\n\n if model_opt.share_decoder_embeddings:\n generator.decoder_linear.weight = decoder.embeddings.word_lut.weight\n gen_linear = generator.lm_linear\n else:\n load_decoder = decoder\n if model_opt.unconditional:\n model = onmt.models.UncondModel(decoder)\n elif model_opt.num_src > 1:\n from argparse import Namespace\n agenda_field = fields[\"agenda\"]\n agenda_opt = Namespace(**model_opt.__dict__)\n\n for k in agenda_opt.__dict__.keys():\n if hasattr(model_opt, f\"agenda_{k}\"):\n setattr(agenda_opt, k, getattr(model_opt, f\"agenda_{k}\"))\n\n agenda_emb = build_embeddings(agenda_opt, agenda_field)\n\n agenda_encoder = build_encoder(model_opt, agenda_emb)\n encoders = nn.ModuleList([encoder, agenda_encoder])\n model = onmt.neural_checklist.MultiSrcNMTModel(encoders, decoder)\n else:\n model = onmt.models.NMTModel(encoder, decoder)\n\n # Build Generator.\n if not model_opt.copy_attn:\n if model_opt.generator_function == \"sparsemax\":\n gen_func = onmt.modules.sparse_activations.LogSparsemax(dim=-1)\n else:\n gen_func = nn.LogSoftmax(dim=-1)\n\n if model_opt.padded_vocab_fix_me_later:\n gen_func = nn.Sequential(PadGen(), gen_func)\n\n generator = nn.Sequential(\n nn.Linear(model_opt.dec_rnn_size,\n len(fields[\"tgt\"].base_field.vocab)),\n Cast(torch.float32),\n gen_func\n )\n if model_opt.share_decoder_embeddings:\n generator[0].weight = decoder.embeddings.word_lut.weight\n gen_linear = generator[0]\n else:\n tgt_base_field = fields[\"tgt\"].base_field\n vocab_size = len(tgt_base_field.vocab)\n pad_idx = tgt_base_field.vocab.stoi[tgt_base_field.pad_token]\n generator = CopyGenerator(model_opt.dec_rnn_size, vocab_size, pad_idx)\n if model_opt.share_decoder_embeddings:\n generator.linear.weight = decoder.embeddings.word_lut.weight\n gen_linear = generator.linear\n\n if model_opt.encdec_share_params:\n for name, p in decoder.named_parameters():\n if 'ctx' in name or 'context' in name:\n continue\n pointer = encoder\n attrs = name.split('.')\n for attr_name in attrs[:-1]:\n pointer = getattr(pointer, attr_name)\n\n # pointer now has the encoder version of the parameter parent\n setattr(pointer, attrs[-1], p)\n\n\n # Load the model states from checkpoint or initialize them.\n if checkpoint is not None:\n # Normally, just load the model parameters from checkpoint\n if 'gpt2_params' not in checkpoint and 'enc_model' not in checkpoint:\n # This preserves backward-compat for models using customed layernorm\n def fix_key(s):\n s = re.sub(r'(.*)\\.layer_norm((_\\d+)?)\\.b_2',\n r'\\1.layer_norm\\2.bias', s)\n s = re.sub(r'(.*)\\.layer_norm((_\\d+)?)\\.a_2',\n r'\\1.layer_norm\\2.weight', s)\n return s\n \n checkpoint['model'] = {fix_key(k): v\n for k, v in checkpoint['model'].items()}\n # end of patch for backward compatibility\n\n # Initialize rest of parameters normally\n if hasattr(model_opt, 'load_uncond_from') and model_opt.load_uncond_from:\n for p in decoder.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n \n # Always initialize encoder parameters normally\n for p in encoder.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n\n if model_opt.ctx_weight_param:\n for name, p in decoder.named_parameters():\n if 'ctx_weight' in name:\n p.data.zero_()\n if 'ctx_bias' in name:\n p.data.fill_(-10)\n\n\n model.load_state_dict(checkpoint['model'], strict=False)\n generator.load_state_dict(checkpoint['generator'], strict=False)\n else:\n # load the gpt parameters\n if 'gpt2_params' in checkpoint:\n init_something = model_opt.gpt2_init_embanddec or model_opt.simple_fusion or model_opt.gpt2_init_embandenc or model_opt.GPT_representation_mode != 'none'\n \n if init_something:\n # Initialize all the weights first\n if model_opt.gpt2_init_zero:\n for p in decoder.parameters():\n p.data.zero_()\n if model_opt.simple_fusion:\n generator.decoder_linear.weight.data.zero_()\n generator.decoder_linear.bias.data.zero_()\n else:\n for p in decoder.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n \n # Always initialize encoder parameters normally\n if encoder is not None:\n for p in encoder.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n for p in generator.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n if model_opt.zero_bias_init:\n gen_linear.bias.data.zero_()\n\n if model_opt.ctx_weight_param:\n for name, p in decoder.named_parameters():\n if 'ctx_weight' in name:\n p.data.zero_()\n if 'ctx_bias' in name:\n p.data.fill_(-10)\n gen_linear.bias.data.zero_()\n\n load_models = []\n if model_opt.GPT_representation_mode != 'none':\n load_embs = []\n if model_opt.GPT_representation_loc in ['both', 'src']:\n load_models.append(src_emb.gpt_model)\n load_embs.append(src_emb)\n if model_opt.GPT_representation_loc in ['both', 'tgt']:\n load_models.append(tgt_emb.gpt_model)\n load_embs.append(tgt_emb)\n \n else:\n if model_opt.gpt2_init_embanddec or model_opt.simple_fusion:\n load_models = [load_decoder]\n elif model_opt.gpt2_init_embandenc:\n load_models = [encoder]\n \n it_list = list(checkpoint['gpt2_params'])\n for lm_idx, load_model in enumerate(load_models):\n #print(lm_idx, load_model)\n for name, array in it_list:\n name = name[6:] # skip \"model/\"\n name = name.split('/')\n\n assigned = False\n if name[0] == 'wpe':\n if model_opt.GPT_representation_mode != 'none':\n pointer = load_embs[lm_idx].make_embedding.pe.pe.weight\n else:\n pointer = load_model.embeddings.make_embedding.pe.pe.weight\n\n elif name[0] == 'wte':\n if model_opt.GPT_representation_mode != 'none':\n pointer = [load_embs[lm_idx].make_embedding.emb_luts[0].weight, gen_linear.weight]\n else:\n pointer = [load_model.embeddings.make_embedding.emb_luts[0].weight]\n if not model_opt.nopretrain_decemb:\n pointer.append(gen_linear.weight)\n if model_opt.simple_fusion and model_opt.sf_pretrain_dec_emb:\n pointer.append(decoder.embeddings.make_embedding.emb_luts[0].weight)\n\n elif name[0] == 'ln_f':\n if name[1] == 'g':\n pointer = load_model.layer_norm.weight\n elif name[1] == 'b':\n pointer = load_model.layer_norm.bias\n else:\n raise ValueError('I am missing something here!')\n\n elif name[0][0] == 'h':\n layer_num = name[0][1:]\n pointer = getattr(load_model.transformer_layers, layer_num)\n if name[1] == 'attn':\n assigned = True\n pointer = pointer.self_attn\n full_data = torch.from_numpy(array)\n if name[2] == 'c_attn':\n end_size = full_data.shape[-1]//3\n assert full_data.shape[-1] % 3 == 0\n if name[3] == 'b':\n if init_something:\n pointer.linear_query.bias.data = full_data[:end_size]\n pointer.linear_keys.bias.data = full_data[end_size:end_size*2]\n pointer.linear_values.bias.data = full_data[end_size*2:]\n if model_opt.gpt2_params_std > 0:\n pointer.linear_query.bias.orig = full_data[:end_size].clone()\n pointer.linear_keys.bias.orig = full_data[end_size:end_size*2].clone()\n pointer.linear_values.bias.orig = full_data[end_size*2:].clone()\n elif name[3] == 'w':\n if init_something:\n pointer.linear_query.weight.data = full_data[:, :end_size].t().contiguous()\n pointer.linear_keys.weight.data = full_data[:, end_size:end_size*2].t().contiguous()\n pointer.linear_values.weight.data = full_data[:, end_size*2:].t().contiguous()\n if model_opt.gpt2_params_std > 0:\n pointer.linear_query.weight.orig = full_data[:, :end_size].t().contiguous().clone()\n pointer.linear_keys.weight.orig = full_data[:, end_size:end_size*2].t().contiguous().clone()\n pointer.linear_values.weight.orig = full_data[:, end_size*2:].t().contiguous().clone()\n else:\n raise ValueError('I am missing something here!')\n elif name[2] == 'c_proj':\n if name[3] == 'b':\n if init_something:\n pointer.final_linear.bias.data = full_data\n if model_opt.gpt2_params_std > 0:\n pointer.final_linear.bias.orig = full_data.clone()\n elif name[3] == 'w':\n if init_something:\n pointer.final_linear.weight.data = full_data.t().contiguous()\n if model_opt.gpt2_params_std > 0:\n pointer.final_linear.weight.orig = full_data.t().contiguous().clone()\n\n else:\n raise ValueError('I am missing something here!')\n\n elif name[1] == 'ln_1' or name[1] == 'ln_2':\n num = name[1][3]\n pointer = getattr(pointer, 'layer_norm_'+num)\n if name[2] == 'b':\n pointer = pointer.bias\n elif name[2] == 'g':\n pointer = pointer.weight\n else:\n raise ValueError('I am missing something here!')\n elif name[1] == 'mlp':\n pointer = pointer.feed_forward\n pointer = getattr(pointer, name[2])\n if name[3] == 'b':\n pointer = pointer.bias\n elif name[3] == 'w':\n pointer = pointer.weight\n else:\n raise ValueError('I am missing something here!')\n else:\n raise ValueError('I am missing something here!')\n else:\n raise ValueError('I am missing something here!')\n \n if not assigned:\n if name[-1] == 'w' or name[-1] == 'g':\n array = array.T\n\n if not isinstance(pointer, list):\n pointer = [pointer]\n for pointer_i in pointer:\n target_size = int(math.ceil(array.shape[0]/8))*8\n padded_vocab = name[0] == 'wte' and pointer_i.shape[0] == target_size\n padded_vocab = padded_vocab and pointer_i.shape[1:] == array.shape[1:]\n try:\n assert pointer_i.shape == array.shape or padded_vocab\n except AssertionError as e:\n e.args += (pointer_i.shape, array.shape)\n raise\n if init_something:\n print(\"Initialize PyTorch weight {}\".format(name))\n if padded_vocab:\n pointer_i.data[:array.shape[0]] = torch.from_numpy(array)\n else:\n pointer_i.data = torch.from_numpy(array)\n if model_opt.gpt2_params_std > 0:\n if padded_vocab:\n raise NotImplementedError\n else:\n pointer_i.orig = torch.from_numpy(array).clone()\n if 'enc_model' in checkpoint:\n load_dict = {k[8:]: v for k, v in checkpoint['enc_model'] if 'encoder' in k}\n encoder.load_state_dict(load_dict, strict=True)\n else:\n if model_opt.param_init != 0.0:\n for p in model.parameters():\n p.data.uniform_(-model_opt.param_init, model_opt.param_init)\n for p in generator.parameters():\n p.data.uniform_(-model_opt.param_init, model_opt.param_init)\n if model_opt.param_init_glorot:\n for p in model.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n for p in generator.parameters():\n if p.dim() > 1:\n xavier_uniform_(p)\n\n if not model_opt.unconditional and hasattr(model.encoder, 'embeddings') \\\n and model.encoder.embeddings is not None:\n model.encoder.embeddings.load_pretrained_vectors(\n model_opt.pre_word_vecs_enc)\n if hasattr(model.decoder, 'embeddings'):\n model.decoder.embeddings.load_pretrained_vectors(\n model_opt.pre_word_vecs_dec)\n\n # remove requires_grad from params that are not trained:\n if model_opt.notrain_emb or model_opt.notrain_embanddec:\n if model_opt.position_encoding_learned_enc and model_opt.share_position_embeddings:\n model.encoder.embeddings.make_embedding.pe.pe.weight.requires_grad = False\n if model_opt.share_embeddings:\n model.encoder.embeddings.make_embedding.emb_luts[0].weight.requires_grad = False\n model.decoder.embeddings.make_embedding.pe.pe.weight.requires_grad = False\n model.decoder.embeddings.make_embedding.emb_luts[0].weight.requires_grad = False\n generator[0].weight.requires_grad = False\n\n if model_opt.notrain_genbias:\n generator[0].bias.requires_grad = False\n\n if model_opt.notrain_embanddec:\n for name, p in load_decoder.layer_norm.named_parameters():\n p.requires_grad = False\n for name, p in load_decoder.transformer_layers.named_parameters():\n if 'context' not in name and 'ctx' not in name: # Takes care of normal and psa versions\n p.requires_grad = False\n \n if model_opt.onlytrainln:\n for name, p in model.decoder.named_parameters():\n if 'layer_norm' not in name:\n p.requires_grad = False\n for p in generator.parameters():\n p.requires_grad = False\n\n if model_opt.onlytrainoutp:\n if model_opt.share_decoder_embeddings:\n raise ValueError\n\n for p in model.decoder.parameters():\n p.requires_grad = False\n\n if model_opt.simple_fusion:\n for p in lm_decoder.parameters():\n p.requires_grad = False\n for p in generator.lm_linear.parameters():\n p.requires_grad = False\n\n model.generator = generator\n model.to(device)\n if model_opt.model_dtype == 'fp16':\n model.half()\n\n for p in model.parameters():\n if hasattr(p, 'orig'):\n p.orig = p.orig.to(device)\n if model_opt.model_dtype == 'fp16':\n p.orig = p.orig.half()\n\n return model\n\n\ndef linear_repr_patch(self):\n return 'in_features={}, out_features={}, bias={}, wgrad={}, bgrad={}'.format(\n self.in_features, self.out_features, self.bias is not None,\n self.weight.requires_grad, self.bias.requires_grad if self.bias is not None else 'N/A'\n )\n\ndef ln_repr_patch(self):\n string = '{normalized_shape}, eps={eps}, ' \\\n 'elementwise_affine={elementwise_affine}'.format(**self.__dict__)\n string += ', wgrad={}, bgrad={}'.format(self.weight.requires_grad if self.weight is not None else 'N/A', \n self.bias.requires_grad if self.bias is not None else 'N/A')\n return string\n\ndef emb_repr_patch(self):\n s = '{num_embeddings}, {embedding_dim}'\n if self.padding_idx is not None:\n s += ', padding_idx={padding_idx}'\n if self.max_norm is not None:\n s += ', max_norm={max_norm}'\n if self.norm_type != 2:\n s += ', norm_type={norm_type}'\n if self.scale_grad_by_freq is not False:\n s += ', scale_grad_by_freq={scale_grad_by_freq}'\n if self.sparse is not False:\n s += ', sparse=True'\n s = s.format(**self.__dict__)\n s += ', grad={}'.format(self.weight.requires_grad)\n return s\n\ndef build_model(model_opt, opt, fields, checkpoint):\n logger.info('Building model...')\n model = build_base_model(model_opt, fields, use_gpu(opt), checkpoint)\n\n # Show which params will be updated\n nn.Linear.extra_repr = linear_repr_patch\n nn.LayerNorm.extra_repr = ln_repr_patch\n nn.Embedding.extra_repr = emb_repr_patch\n\n logger.info(model)\n return model\n"
] |
[
[
"torch.nn.LogSoftmax",
"torch.load",
"torch.nn.ModuleList",
"torch.from_numpy",
"torch.nn.init.xavier_uniform_",
"torch.device"
]
] |
alvicler/python-nmr
|
[
"7b68275f0e1e8dd85622a6b796dc618eb5ac3e62"
] |
[
"py-code/nmrvar.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport nmrglue as ng\nimport sys\nimport numpy as np\nimport pandas as pd\nget_ipython().run_line_magic('matplotlib', 'qt5')\nimport matplotlib.pyplot as plt\n\n#import matplotlib\n#print('Python version ' + sys.version)\n#print('Pandas version ' + pd.__version__)\n#print('Matplotlib version ' + matplotlib.__version__)\nimport os\nsamples = len(os.listdir('urine'))\n\n\nthis = sys.modules[__name__] # this is now your current namespace\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx # or array[idx]\n\n\ni = 1\ndf = pd.DataFrame([])\nyarr=[]\nxarr=[]\n## set the number of 1r files to open, always open first processed spectra ##\nwhile i < samples+1:\n name=\"urine/Calvin_Gab_ATU\"+str(i)+\"/1/pdata/1\"\n dic, data= ng.bruker.read_pdata(name)\n \n sf=float(dic[\"procs\"][\"SF\"]) \n sfo1=float(dic[\"acqus\"][\"SFO1\"]) \n o1=float(dic[\"acqus\"][\"O1\"])\n hzppt=float(dic[\"acqus\"][\"SW_h\"])/len(data)\n swh=float(dic[\"acqus\"][\"SW_h\"])\n sr=o1+(sf-sfo1)*1000000.\n \n pts=int(sr//hzppt) # Calc pts to Calibrate 0ppm to Xscale\n data = ng.proc_base.rev(data) # reverse the data\n \n #setattr(this, 'data%s' % i, data)\n \n #### scale x from pts to ppm ###\n ## Bin size for PCA##\n \n si=len(data) \n xs=[]\n \n for j in range(0-pts,si-pts):\n hz=float(((o1-swh/2)+(hzppt*(j)))/sf)\n xs+=[hz]\n xs = np.asarray(xs)\n \n #setattr(this, 'xs%s' % i, xs)\n\n \n #xmin=xs.min()\n xmin=-.25\n #xmax=xs.max()\n xmax=1.4\n ## Bin size for PCA##\n xbin=(xmax-xmin)/5\n #xbin=.25\n k=1\n f=0\n a={}\n for j in np.arange(xmin,xmax, xbin): \n f=j+xbin\n fpos=find_nearest(xs, f)\n jpos=find_nearest(xs, j)\n #print(jpos,fpos)\n \n peak = data[jpos:fpos]\n #peak_scale=xs[j:f]\n #if peak.sum()<0:\n # a['slice.'+str(k)]=0 \n #else:\n #a[k]=peak.max().cumsum()\n a[k]=peak.sum()\n k+=1\n #setattr(this, 'databin%s' % i, a)\n b=pd.Series(a, name=i)\n df = df.append(b)\n yarr.append(data)\n xarr.append(xs)\n i += 1 ## index for number of spectra\n \ndf\n\n"
] |
[
[
"pandas.Series",
"numpy.abs",
"numpy.asarray",
"numpy.arange",
"pandas.DataFrame"
]
] |
goel96vibhor/AdvSentEval
|
[
"c23684c5f9da905517071361fdb40acf194cd608"
] |
[
"examples/gensen_util.py"
] |
[
"# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\n\"\"\"\nClone GenSen repo here: https://github.com/Maluuba/gensen.git\nAnd follow instructions for loading the model used in batcher\n\"\"\"\n\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport sys\nimport logging\n# import GenSen package\nfrom gensen import GenSen, GenSenSingle\nimport gensen\nimport numpy as np\n\n\n\n\n# Set PATHs\nPATH_TO_SENTEVAL = '../'\nPATH_TO_DATA = '../data'\nPATH_TO_VEC = 'fasttext/crawl-300d-2M.vec'\n\n# import SentEval\nsys.path.insert(0, PATH_TO_SENTEVAL)\nimport senteval\nsys.path.insert(1,PATH_TO_SENTEVAL)\nfrom AdversarialModels import WordNetSynonym\nimport io\n\ndef get_sentence(sentence):\n sent = \"\"\n for word in sentence:\n sent+=word+\" \"\n return sent\n\n\ndef create_dictionary(sentences, threshold=0):\n words = {}\n for s in sentences:\n for word in s:\n words[word] = words.get(word, 0) + 1\n\n if threshold > 0:\n newwords = {}\n for word in words:\n if words[word] >= threshold:\n newwords[word] = words[word]\n words = newwords\n words['<s>'] = 1e9 + 4\n words['</s>'] = 1e9 + 3\n words['<p>'] = 1e9 + 2\n\n sorted_words = sorted(words.items(), key=lambda x: -x[1]) # inverse sort\n id2word = []\n word2id = {}\n for i, (w, _) in enumerate(sorted_words):\n id2word.append(w)\n word2id[w] = i\n\n return id2word, word2id\n\n# SentEval prepare and batcher\ndef prepare(params, samples):\n _, params.word2id = create_dictionary(samples)\n params.word_vec = get_wordvec(PATH_TO_VEC, params.word2id)\n params.wvec_dim = 300\n return\n\ndef get_wordvec(path_to_vec, word2id):\n word_vec = {}\n\n with io.open(path_to_vec, 'r', encoding='utf-8') as f:\n # if word2vec or fasttext file : skip first line \"next(f)\"\n for line in f:\n word, vec = line.split(' ', 1)\n if word in word2id:\n word_vec[word] = np.fromstring(vec, sep=' ')\n\n logging.info('Found {0} words with word vectors, out of \\\n {1} words'.format(len(word_vec), len(word2id)))\n return word_vec\n\ndef batcher(params, batch):\n batch = [' '.join(sent) if sent != [] else '.' for sent in batch]\n _, reps_h_t = gensen_encoder.get_representation(\n batch, pool='last', return_numpy=True, tokenize=True\n )\n embeddings = reps_h_t\n return embeddings\n\n\ndef prepare_adversarial_samples(params, sentences, y_labels):\n\n new_sentences = []\n new_labels = []\n\n for sent, label in zip(sentences, y_labels):\n sent_adversaries = []\n sent_adv_labels = []\n new_sent = list(sent)\n sent_adversaries.append(new_sent)\n sent_adv_labels.append(label)\n\n new_sent = list(sent)\n sent_adversaries.append(new_sent)\n sent_adv_labels.append(label)\n\n # if sent == sentences[43]:\n # print(\"orig sent vec\", get_sentence(sent), \" ,label:\", label)\n # print(\"mod sent vec\", get_sentence(new_sent))\n\n\n for word, word_pos in zip(sent, range(len(sent))):\n # print \"new word \", word, \"-\" *80\n if word in params.word_vec:\n # print word, \"-\" * 30\n # print params.word_vec[word][:20]\n new_sent = list(sent)\n # print \"new sent vec \", \"-\" * 30\n # print new_sentvec[:20]\n word_syns = WordNetSynonym.get_word_synonym(word)\n\n # print word_syns\n for syn in word_syns:\n if syn in params.word_vec:\n\n if syn == word:\n continue\n\n # print syn, \"-\"*30\n # print params.word_vec[syn][:20]\n new_sent = list(sent)\n new_sent[word_pos] = syn\n sent_adversaries.append(new_sent)\n sent_adv_labels.append(label)\n\n # if sent == sentences[43]:\n # print(\"mod sent vec\", get_sentence(new_sent))\n\n # print \"mod sent vec\", \"-\" * 30\n # print modified_vecs[len(modified_vecs)-1][:20], \"\\n\"\n new_sentences.append(sent_adversaries)\n new_labels.append(sent_adv_labels)\n\n\n return new_sentences, new_labels\n\n\n\ndef adversarialFunc(params, batch_sentences, batch_labels, embeddings = None):\n # sentvec = np.multiply(sentvec, params.wvec_dim)\n\n\n adv_batch_sentences, adv_labels = prepare_adversarial_samples(params, batch_sentences, batch_labels)\n\n print(\"adv samples size %d\",len(adv_batch_sentences))\n\n total_count = sum(len(x) for x in adv_batch_sentences)\n print(\"sum of sentences called %d, batch_size %d\" %(total_count, params.batch_size))\n\n adv_embeddings = []\n\n for sent_adversaries, i in zip(adv_batch_sentences, range(len(adv_batch_sentences))):\n\n sentences = [' '.join(sent) if sent != [] else '.' for sent in sent_adversaries]\n _, reps_h_t = gensen_encoder.get_representation(\n sentences, pool='last', return_numpy=True, tokenize=True\n )\n sent_adv_embeddings = reps_h_t\n\n # sent_adv_embeddings = params.infersent.encode_without_shuffle(sentences, bsize=params.batch_size, tokenize=False)\n adv_embeddings.append(sent_adv_embeddings)\n\n if i%10 == 0:\n print(\"%d sentences done\"%(i))\n # print(\"Adv embeddings shape: %s, adv_labels shape\", len(sent_adv_embeddings), dim(adv_labels[i]))\n\n print(\"Adv embeddings shape: %s, adv_labels shape %s\" %(len(adv_embeddings), len(adv_labels)))\n\n for i in range(0,len(adv_embeddings),10):\n print(\"Adv embeddings shape: %s, adv_labels shape\", len(adv_embeddings[i]), len(adv_labels[i]))\n return adv_embeddings, adv_labels, adv_batch_sentences\n\n\n\n\n# Load GenSen model\ngensen_1 = GenSenSingle(\n model_folder='../data/models',\n filename_prefix='nli_large_bothskip',\n pretrained_emb='fasttext/glove.840B.300d.h5'\n)\ngensen_2 = GenSenSingle(\n model_folder='../data/models',\n filename_prefix='nli_large_bothskip_parse',\n pretrained_emb='fasttext/glove.840B.300d.h5'\n)\ngensen_encoder = GenSen(gensen_1, gensen_2)\n\n\n\n# reps_h, reps_h_t = gensen_encoder.get_representation(\n# sentences, pool='last', return_numpy=True, tokenize=True\n# )\n\n# Set params for SentEval\nparams_senteval = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'kfold': 5, 'model_name': 'gensen','batch_size': 128}\nparams_senteval['classifier'] = {'nhid': 0, 'optim': 'rmsprop', 'batch_size': 128,\n 'tenacity': 3, 'epoch_size': 2, 'cudaEfficient' : True}\nparams_senteval['gensen'] = gensen_encoder\n\n\n# Set up logger\nlogging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG, adversarialFunc=adversarialFunc)\n\nif __name__ == \"__main__\":\n se = senteval.engine.SE(params_senteval, batcher, prepare, adversarialFunc=adversarialFunc)\n # transfer_tasks = ['STS12', 'STS13', 'STS14', 'STS15', 'STS16',\n # 'MR', 'CR', 'MPQA', 'SUBJ', 'SST2', 'SST5', 'TREC', 'MRPC',\n # 'SICKEntailment', 'SICKRelatedness', 'STSBenchmark',\n # 'Length', 'WordContent', 'Depth', 'TopConstituents',\n # 'BigramShift', 'Tense', 'SubjNumber', 'ObjNumber',\n # 'OddManOut', 'CoordinationInversion']\n transfer_tasks = ['STSBenchmark']\n results = se.eval(transfer_tasks)\n # print(results)\n"
] |
[
[
"numpy.fromstring"
]
] |
PingjunChen/pycontour
|
[
"13f64b685740368605db314b0f547f9f8dd4e737"
] |
[
"pycontour/fea/setup.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport os\n\nBASE_PATH = os.path.abspath(os.path.dirname(__file__))\nMODULE_NAME = os.path.basename(BASE_PATH)\n\ndef configuration(parent_package='', top_path=None):\n from numpy.distutils.misc_util import Configuration\n\n config = Configuration(MODULE_NAME, parent_package, top_path)\n\n return config\n\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(maintainer='Pingjun Chen',\n maintainer_email='[email protected]',\n description='Contour feature calculation.',\n url='https://github.com/PingjunChen/pycontour',\n license='MIT',\n **(configuration(top_path='').todict())\n )\n"
] |
[
[
"numpy.distutils.misc_util.Configuration"
]
] |
RiccardoRuggiero/micronet
|
[
"bfdac2a50a5f0f8484a253b356c06a166bf7e6a0"
] |
[
"micronet/compression/quantization/wqaq/iao/main.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nsys.path.append(\"../../../..\")\nimport math\nimport os\nimport argparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nfrom torch.nn import init\nfrom models import nin_gc, nin\n\nimport quantize\n\n\ndef setup_seed(seed):\n torch.manual_seed(seed)\n # torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n torch.backends.cudnn.deterministic = True\n\n\ndef save_state(model, best_acc):\n print('==> Saving model ...')\n state = {\n 'best_acc': best_acc,\n 'state_dict': model.state_dict(),\n }\n state_copy = state['state_dict'].copy()\n for key in state_copy.keys():\n if 'module' in key:\n state['state_dict'][key.replace('module.', '')] = \\\n state['state_dict'].pop(key)\n if args.model_type == 0:\n if args.bn_fuse == 1:\n if args.prune_qat or args.qaft:\n torch.save({'cfg': cfg, 'best_acc': best_acc,\n 'state_dict': state['state_dict']}, 'models_save/nin_bn_fused.pth')\n else:\n torch.save(state, 'models_save/nin_bn_fused.pth')\n else:\n if args.prune_qat or args.qaft:\n torch.save({'cfg': cfg, 'best_acc': best_acc,\n 'state_dict': state['state_dict']}, 'models_save/nin.pth')\n else:\n torch.save(state, 'models_save/nin.pth')\n else:\n if args.bn_fuse == 1:\n if args.prune_qat or args.qaft:\n torch.save({'cfg': cfg, 'best_acc': best_acc,\n 'state_dict': state['state_dict']}, 'models_save/nin_gc_bn_fused.pth')\n else:\n torch.save(state, 'models_save/nin_gc_bn_fused.pth')\n else:\n if args.prune_qat or args.qaft:\n torch.save({'cfg': cfg, 'best_acc': best_acc,\n 'state_dict': state['state_dict']}, 'models_save/nin_gc.pth')\n else:\n torch.save(state, 'models_save/nin_gc.pth')\n\n\ndef adjust_learning_rate(optimizer, epoch):\n update_list = [80, 130, 180, 230, 280]\n if epoch in update_list:\n for param_group in optimizer.param_groups:\n param_group['lr'] = param_group['lr'] * 0.1\n return\n\n\ndef train(epoch):\n model.train()\n\n for batch_idx, (data, target) in enumerate(trainloader):\n if not args.cpu:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n output = model(data)\n loss = criterion(output, target)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if batch_idx % 100 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}\\tLR: {}'.format(\n epoch, batch_idx * len(data), len(trainloader.dataset),\n 100. * batch_idx / len(trainloader), loss.data.item(),\n optimizer.param_groups[0]['lr']))\n return\n\n\ndef test():\n global best_acc\n model.eval()\n test_loss = 0\n correct = 0\n\n for data, target in testloader:\n if not args.cpu:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n output = model(data)\n test_loss += criterion(output, target).data.item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n acc = 100. * float(correct) / len(testloader.dataset)\n\n if acc > best_acc:\n best_acc = acc\n save_state(model, best_acc)\n average_test_loss = test_loss / (len(testloader.dataset) / args.eval_batch_size)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)'.format(\n average_test_loss, correct, len(testloader.dataset),\n 100. * float(correct) / len(testloader.dataset)))\n\n print('Best Accuracy: {:.2f}%\\n'.format(best_acc))\n return\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--cpu', action='store_true',\n help='set if only CPU is available')\n parser.add_argument('--gpu_id', action='store', default='',\n help='gpu_id')\n parser.add_argument('--data', action='store', default='../../../../data',\n help='dataset path')\n parser.add_argument('--lr', action='store', default=0.01,\n help='the intial learning rate')\n parser.add_argument('--wd', action='store', default=1e-5,\n help='the intial learning rate')\n # prune_qat\n parser.add_argument('--prune_qat', default='', type=str, metavar='PATH',\n help='the path to the prune_qat model')\n # refine\n parser.add_argument('--refine', default='', type=str, metavar='PATH',\n help='the path to the float_refine model')\n # resume\n parser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='the path to the resume model')\n parser.add_argument('--train_batch_size', type=int, default=64)\n parser.add_argument('--eval_batch_size', type=int, default=64)\n parser.add_argument('--num_workers', type=int, default=2)\n parser.add_argument('--start_epochs', type=int, default=1, metavar='N',\n help='number of epochs to train_start')\n parser.add_argument('--end_epochs', type=int, default=300, metavar='N',\n help='number of epochs to train_end')\n # W/A — bits\n parser.add_argument('--w_bits', type=int, default=8)\n parser.add_argument('--a_bits', type=int, default=8)\n # bn融合标志位\n parser.add_argument('--bn_fuse', type=int, default=0,\n help='bn_fuse:1')\n # 量化方法选择\n parser.add_argument('--q_type', type=int, default=0,\n help='quant_type:0-symmetric, 1-asymmetric')\n # 量化级别选择\n parser.add_argument('--q_level', type=int, default=0,\n help='quant_level:0-per_channel, 1-per_layer')\n # weight_observer选择\n parser.add_argument('--weight_observer', type=int, default=0,\n help='quant_weight_observer:0-MinMaxObserver, 1-MovingAverageMinMaxObserver')\n # pretrained_model标志位\n parser.add_argument('--pretrained_model', action='store_true',\n help='pretrained_model')\n # qaft标志位\n parser.add_argument('--qaft', action='store_true',\n help='quantization-aware-finetune') \n # prune_qaft\n parser.add_argument('--prune_qaft', default='', type=str, metavar='PATH',\n help='the path to the prune_qaft model') \n parser.add_argument('--model_type', type=int, default=1,\n help='model type:0-nin,1-nin_gc')\n args = parser.parse_args()\n print('==> Options:', args)\n\n if args.gpu_id:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id\n if not args.cpu:\n device = 'cuda'\n else:\n device = 'cpu'\n\n setup_seed(1)\n\n print('==> Preparing data..')\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])\n\n trainset = torchvision.datasets.CIFAR10(root=args.data, train=True, download=True,\n transform=transform_train)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.train_batch_size,\n shuffle=True, num_workers=args.num_workers)\n\n testset = torchvision.datasets.CIFAR10(root=args.data, train=False, download=True,\n transform=transform_test)\n testloader = torch.utils.data.DataLoader(testset, batch_size=args.eval_batch_size,\n shuffle=False, num_workers=args.num_workers)\n\n classes = ('plane', 'car', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck')\n\n if args.prune_qat:\n print('******Prune QAT model******')\n #checkpoint = torch.load('../prune/models_save/nin_refine.pth')\n checkpoint = torch.load(args.prune_qat)\n cfg = checkpoint['cfg']\n if args.model_type == 0:\n model = nin.Net(cfg=checkpoint['cfg'])\n else:\n model = nin_gc.Net(cfg=checkpoint['cfg'])\n model.load_state_dict(checkpoint['state_dict'])\n best_acc = 0\n print('***ori_model***\\n', model)\n quantize.prepare(model, inplace=True, a_bits=args.a_bits,\n w_bits=args.w_bits, q_type=args.q_type,\n q_level=args.q_level, device=device,\n weight_observer=args.weight_observer,\n bn_fuse=args.bn_fuse,\n pretrained_model=args.pretrained_model,\n qaft=args.qaft)\n print('\\n***quant_model***\\n', model)\n elif args.prune_qaft:\n print('******Prune QAFT model******')\n #checkpoint = torch.load('models_save/nin_bn_fused.pth')\n checkpoint = torch.load(args.prune_qaft)\n cfg = checkpoint['cfg']\n if args.model_type == 0:\n model = nin.Net(cfg=checkpoint['cfg'])\n else:\n model = nin_gc.Net(cfg=checkpoint['cfg'])\n print('***ori_model***\\n', model)\n quantize.prepare(model, inplace=True, a_bits=args.a_bits,\n w_bits=args.w_bits, q_type=args.q_type,\n q_level=args.q_level, device=device,\n weight_observer=args.weight_observer,\n bn_fuse=args.bn_fuse,\n pretrained_model=args.pretrained_model,\n qaft=args.qaft)\n print('\\n***quant_model***\\n', model)\n model.load_state_dict(checkpoint['state_dict'])\n best_acc = checkpoint['best_acc']\n elif args.refine:\n print('******Float Refine model******')\n #checkpoint = torch.load('models_save/nin.pth')\n state_dict = torch.load(args.refine)\n if args.model_type == 0:\n model = nin.Net()\n else:\n model = nin_gc.Net()\n model.load_state_dict(state_dict)\n best_acc = 0\n print('***ori_model***\\n', model)\n quantize.prepare(model, inplace=True, a_bits=args.a_bits,\n w_bits=args.w_bits, q_type=args.q_type,\n q_level=args.q_level, device=device,\n weight_observer=args.weight_observer,\n bn_fuse=args.bn_fuse,\n pretrained_model=args.pretrained_model,\n qaft=args.qaft)\n print('\\n***quant_model***\\n', model)\n elif args.resume:\n print('******Reume model******')\n #checkpoint = torch.load('models_save/nin.pth')\n checkpoint = torch.load(args.resume)\n if args.model_type == 0:\n model = nin.Net()\n else:\n model = nin_gc.Net()\n print('***ori_model***\\n', model)\n quantize.prepare(model, inplace=True, a_bits=args.a_bits,\n w_bits=args.w_bits, q_type=args.q_type,\n q_level=args.q_level, device=device,\n weight_observer=args.weight_observer,\n bn_fuse=args.bn_fuse,\n pretrained_model=args.pretrained_model,\n qaft=args.qaft)\n print('\\n***quant_model***\\n', model)\n model.load_state_dict(checkpoint['state_dict'])\n best_acc = checkpoint['best_acc']\n else:\n print('******Initializing model******')\n if args.model_type == 0:\n model = nin.Net()\n else:\n model = nin_gc.Net()\n best_acc = 0\n for m in model.modules():\n if isinstance(m, nn.Conv2d):\n init.xavier_uniform_(m.weight)\n if m.bias is not None:\n init.zeros_(m.bias)\n elif isinstance(m, nn.Linear):\n init.normal_(m.weight, 0, 0.01)\n if m.bias is not None:\n init.zeros_(m.bias)\n print('***ori_model***\\n', model)\n quantize.prepare(model, inplace=True, a_bits=args.a_bits,\n w_bits=args.w_bits, q_type=args.q_type,\n q_level=args.q_level, device=device,\n weight_observer=args.weight_observer,\n bn_fuse=args.bn_fuse,\n pretrained_model=args.pretrained_model,\n qaft=args.qaft)\n print('\\n***quant_model***\\n', model)\n\n if not args.cpu:\n model.cuda()\n model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))\n\n base_lr = float(args.lr)\n param_dict = dict(model.named_parameters())\n params = []\n for key, value in param_dict.items():\n params += [{'params': [value], 'lr': base_lr, 'weight_decay':args.wd}]\n\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.Adam(params, lr=base_lr, weight_decay=args.wd)\n\n for epoch in range(args.start_epochs, args.end_epochs):\n adjust_learning_rate(optimizer, epoch)\n train(epoch)\n test()\n"
] |
[
[
"torch.optim.Adam",
"torch.nn.CrossEntropyLoss",
"numpy.random.seed",
"torch.load",
"torch.nn.init.zeros_",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.save",
"torch.nn.init.normal_",
"torch.cuda.manual_seed_all",
"torch.nn.init.xavier_uniform_",
"torch.cuda.device_count",
"torch.autograd.Variable"
]
] |
asnt/vispy
|
[
"e515b00de7086527070b3e51e1133f8c1c5ca165"
] |
[
"vispy/visuals/image.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\"\"\"Primitive 2D image visual class.\"\"\"\n\nfrom __future__ import division\n\nimport numpy as np\n\nfrom ..gloo import Texture2D, VertexBuffer\nfrom ..gloo.texture import should_cast_to_f32\nfrom ..color import get_colormap\nfrom .shaders import Function, FunctionChain\nfrom .transforms import NullTransform\nfrom .visual import Visual\nfrom ..io import load_spatial_filters\nfrom ._scalable_textures import CPUScaledTexture2D, GPUScaledTexture2D\n\n\nVERT_SHADER = \"\"\"\nuniform int method; // 0=subdivide, 1=impostor\nattribute vec2 a_position;\nattribute vec2 a_texcoord;\nvarying vec2 v_texcoord;\n\nvoid main() {\n v_texcoord = a_texcoord;\n gl_Position = $transform(vec4(a_position, 0., 1.));\n}\n\"\"\"\n\nFRAG_SHADER = \"\"\"\nuniform vec2 image_size;\nuniform int method; // 0=subdivide, 1=impostor\nuniform sampler2D u_texture;\nvarying vec2 v_texcoord;\n\nvec4 map_local_to_tex(vec4 x) {\n // Cast ray from 3D viewport to surface of image\n // (if $transform does not affect z values, then this\n // can be optimized as simply $transform.map(x) )\n vec4 p1 = $transform(x);\n vec4 p2 = $transform(x + vec4(0, 0, 0.5, 0));\n p1 /= p1.w;\n p2 /= p2.w;\n vec4 d = p2 - p1;\n float f = p2.z / d.z;\n vec4 p3 = p2 - d * f;\n\n // finally map local to texture coords\n return vec4(p3.xy / image_size, 0, 1);\n}\n\n\nvoid main()\n{\n vec2 texcoord;\n if( method == 0 ) {\n texcoord = v_texcoord;\n }\n else {\n // vertex shader outputs clip coordinates;\n // fragment shader maps to texture coordinates\n texcoord = map_local_to_tex(vec4(v_texcoord, 0, 1)).xy;\n }\n\n gl_FragColor = $color_transform($get_data(texcoord));\n}\n\"\"\" # noqa\n\n_interpolation_template = \"\"\"\n #include \"misc/spatial-filters.frag\"\n vec4 texture_lookup_filtered(vec2 texcoord) {\n if(texcoord.x < 0.0 || texcoord.x > 1.0 ||\n texcoord.y < 0.0 || texcoord.y > 1.0) {\n discard;\n }\n return %s($texture, $shape, texcoord);\n }\"\"\"\n\n_texture_lookup = \"\"\"\n vec4 texture_lookup(vec2 texcoord) {\n if(texcoord.x < 0.0 || texcoord.x > 1.0 ||\n texcoord.y < 0.0 || texcoord.y > 1.0) {\n discard;\n }\n return texture2D($texture, texcoord);\n }\"\"\"\n\n_apply_clim_float = \"\"\"\n float apply_clim(float data) {\n data = clamp(data, min($clim.x, $clim.y), max($clim.x, $clim.y));\n data = (data - $clim.x) / ($clim.y - $clim.x);\n return data;\n }\"\"\"\n_apply_clim = \"\"\"\n vec4 apply_clim(vec4 color) {\n if ($clim.x < $clim.y) {{\n color.rgb = clamp(color.rgb, $clim.x, $clim.y);\n }} else if ($clim.x > $clim.y) {{\n color.rgb = clamp(color.rgb, $clim.y, $clim.x);\n }} else {{\n // clims are the same, show minimum colormap value\n return vec4(0.0, 0.0, 0.0, 1.0);\n }}\n color.rgb = color.rgb - $clim.x;\n color.rgb = color.rgb / ($clim.y - $clim.x);\n return max(color, 0);\n }\n\"\"\"\n\n_apply_gamma_float = \"\"\"\n float apply_gamma(float data) {\n return pow(data, $gamma);\n }\"\"\"\n_apply_gamma = \"\"\"\n vec4 apply_gamma(vec4 color) {\n color.rgb = pow(color.rgb, vec3($gamma));\n return color;\n }\n\"\"\"\n\n_null_color_transform = 'vec4 pass(vec4 color) { return color; }'\n_c2l_red = 'float cmap(vec4 color) { return color.r; }'\n\n\nclass ImageVisual(Visual):\n \"\"\"Visual subclass displaying an image.\n\n Parameters\n ----------\n data : ndarray\n ImageVisual data. Can be shape (M, N), (M, N, 3), or (M, N, 4).\n method : str\n Selects method of rendering image in case of non-linear transforms.\n Each method produces similar results, but may trade efficiency\n and accuracy. If the transform is linear, this parameter is ignored\n and a single quad is drawn around the area of the image.\n\n * 'auto': Automatically select 'impostor' if the image is drawn\n with a nonlinear transform; otherwise select 'subdivide'.\n * 'subdivide': ImageVisual is represented as a grid of triangles\n with texture coordinates linearly mapped.\n * 'impostor': ImageVisual is represented as a quad covering the\n entire view, with texture coordinates determined by the\n transform. This produces the best transformation results, but may\n be slow.\n\n grid: tuple (rows, cols)\n If method='subdivide', this tuple determines the number of rows and\n columns in the image grid.\n cmap : str | ColorMap\n Colormap to use for luminance images.\n clim : str | tuple\n Limits to use for the colormap. I.e. the values that map to black and white\n in a gray colormap. Can be 'auto' to auto-set bounds to\n the min and max of the data. If not given or None, 'auto' is used.\n gamma : float\n Gamma to use during colormap lookup. Final color will be cmap(val**gamma).\n by default: 1.\n interpolation : str\n Selects method of image interpolation. Makes use of the two Texture2D\n interpolation methods and the available interpolation methods defined\n in vispy/gloo/glsl/misc/spatial_filters.frag\n\n * 'nearest': Default, uses 'nearest' with Texture2D interpolation.\n * 'bilinear': uses 'linear' with Texture2D interpolation.\n * 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'bicubic',\n 'catrom', 'mitchell', 'spline16', 'spline36', 'gaussian',\n 'bessel', 'sinc', 'lanczos', 'blackman'\n texture_format: numpy.dtype | str | None\n How to store data on the GPU. OpenGL allows for many different storage\n formats and schemes for the low-level texture data stored in the GPU.\n Most common is unsigned integers or floating point numbers.\n Unsigned integers are the most widely supported while other formats\n may not be supported on older versions of OpenGL, WebGL\n (without enabling some extensions), or with older GPUs.\n Default value is ``None`` which means data will be scaled on the\n CPU and the result stored in the GPU as an unsigned integer. If a\n numpy dtype object, an internal texture format will be chosen to\n support that dtype and data will *not* be scaled on the CPU. Not all\n dtypes are supported. If a string, then\n it must be one of the OpenGL internalformat strings described in the\n table on this page: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml\n The name should have `GL_` removed and be lowercase (ex.\n `GL_R32F` becomes ``'r32f'``). Lastly, this can also be the string\n ``'auto'`` which will use the data type of the provided image data\n to determine the internalformat of the texture.\n When this is specified (not ``None``) data is scaled on the\n GPU which allows for faster color limit changes. Additionally, when\n 32-bit float data is provided it won't be copied before being\n transferred to the GPU.\n **kwargs : dict\n Keyword arguments to pass to `Visual`.\n\n Notes\n -----\n The colormap functionality through ``cmap`` and ``clim`` are only used\n if the data are 2D.\n \"\"\"\n\n VERTEX_SHADER = VERT_SHADER\n FRAGMENT_SHADER = FRAG_SHADER\n\n def __init__(self, data=None, method='auto', grid=(1, 1),\n cmap='viridis', clim='auto', gamma=1.0,\n interpolation='nearest', texture_format=None, **kwargs):\n \"\"\"Initialize image properties, texture storage, and interpolation methods.\"\"\"\n self._data = None\n self._gamma = gamma\n\n # load 'float packed rgba8' interpolation kernel\n # to load float interpolation kernel use\n # `load_spatial_filters(packed=False)`\n kernel, interpolation_names = load_spatial_filters()\n\n self._kerneltex = Texture2D(kernel, interpolation='nearest')\n # The unpacking can be debugged by changing \"spatial-filters.frag\"\n # to have the \"unpack\" function just return the .r component. That\n # combined with using the below as the _kerneltex allows debugging\n # of the pipeline\n # self._kerneltex = Texture2D(kernel, interpolation='linear',\n # internalformat='r32f')\n\n interpolation_names, interpolation_fun = self._init_interpolation(\n interpolation_names)\n self._interpolation_names = interpolation_names\n self._interpolation_fun = interpolation_fun\n self._interpolation = interpolation\n if self._interpolation not in self._interpolation_names:\n raise ValueError(\"interpolation must be one of %s\" %\n ', '.join(self._interpolation_names))\n\n # check texture interpolation\n if self._interpolation == 'bilinear':\n texture_interpolation = 'linear'\n else:\n texture_interpolation = 'nearest'\n\n self._method = method\n self._grid = grid\n self._need_texture_upload = True\n self._need_vertex_update = True\n self._need_colortransform_update = True\n self._need_interpolation_update = True\n if texture_format is None:\n self._texture = CPUScaledTexture2D(\n data, interpolation=texture_interpolation)\n else:\n self._texture = GPUScaledTexture2D(\n data, internalformat=texture_format,\n interpolation=texture_interpolation)\n self._subdiv_position = VertexBuffer()\n self._subdiv_texcoord = VertexBuffer()\n\n # impostor quad covers entire viewport\n vertices = np.array([[-1, -1], [1, -1], [1, 1],\n [-1, -1], [1, 1], [-1, 1]],\n dtype=np.float32)\n self._impostor_coords = VertexBuffer(vertices)\n self._null_tr = NullTransform()\n\n self._init_view(self)\n super(ImageVisual, self).__init__(vcode=self.VERTEX_SHADER, fcode=self.FRAGMENT_SHADER)\n self.set_gl_state('translucent', cull_face=False)\n self._draw_mode = 'triangles'\n\n # define _data_lookup_fn as None, will be setup in\n # self._build_interpolation()\n self._data_lookup_fn = None\n\n self.clim = clim or \"auto\" # None -> \"auto\"\n self.cmap = cmap\n if data is not None:\n self.set_data(data)\n self.freeze()\n\n @staticmethod\n def _init_interpolation(interpolation_names):\n # create interpolation shader functions for available\n # interpolations\n fun = [Function(_interpolation_template % n)\n for n in interpolation_names]\n interpolation_names = [n.lower() for n in interpolation_names]\n\n interpolation_fun = dict(zip(interpolation_names, fun))\n interpolation_names = tuple(sorted(interpolation_names))\n\n # overwrite \"nearest\" and \"bilinear\" spatial-filters\n # with \"hardware\" interpolation _data_lookup_fn\n interpolation_fun['nearest'] = Function(_texture_lookup)\n interpolation_fun['bilinear'] = Function(_texture_lookup)\n return interpolation_names, interpolation_fun\n\n def set_data(self, image):\n \"\"\"Set the image data.\n\n Parameters\n ----------\n image : array-like\n The image data.\n texture_format : str or None\n\n \"\"\"\n data = np.asarray(image)\n if should_cast_to_f32(data.dtype):\n data = data.astype(np.float32)\n # can the texture handle this data?\n self._texture.check_data_format(data)\n if self._data is None or self._data.shape[:2] != data.shape[:2]:\n # Only rebuild if the size of the image changed\n self._need_vertex_update = True\n self._data = data\n self._need_texture_upload = True\n\n def view(self):\n \"\"\"Get the :class:`vispy.visuals.visual.VisualView` for this visual.\"\"\"\n v = Visual.view(self)\n self._init_view(v)\n return v\n\n def _init_view(self, view):\n # Store some extra variables per-view\n view._need_method_update = True\n view._method_used = None\n\n @property\n def clim(self):\n \"\"\"Get color limits used when rendering the image (cmin, cmax).\"\"\"\n return self._texture.clim\n\n @clim.setter\n def clim(self, clim):\n if self._texture.set_clim(clim):\n self._need_texture_upload = True\n # shortcut so we don't have to rebuild the whole color transform\n if not self._need_colortransform_update:\n self.shared_program.frag['color_transform'][1]['clim'] = self._texture.clim_normalized\n self.update()\n\n @property\n def cmap(self):\n \"\"\"Get the colormap object applied to luminance (single band) data.\"\"\"\n return self._cmap\n\n @cmap.setter\n def cmap(self, cmap):\n self._cmap = get_colormap(cmap)\n self._need_colortransform_update = True\n self.update()\n\n @property\n def gamma(self):\n \"\"\"Get the gamma used when rendering the image.\"\"\"\n return self._gamma\n\n @gamma.setter\n def gamma(self, value):\n \"\"\"Set gamma used when rendering the image.\"\"\"\n if value <= 0:\n raise ValueError(\"gamma must be > 0\")\n self._gamma = float(value)\n # shortcut so we don't have to rebuild the color transform\n if not self._need_colortransform_update:\n self.shared_program.frag['color_transform'][2]['gamma'] = self._gamma\n self.update()\n\n @property\n def method(self):\n \"\"\"Get rendering method name.\"\"\"\n return self._method\n\n @method.setter\n def method(self, m):\n if self._method != m:\n self._method = m\n self._need_vertex_update = True\n self.update()\n\n @property\n def size(self):\n \"\"\"Get size of the image (width, height).\"\"\"\n return self._data.shape[:2][::-1]\n\n @property\n def interpolation(self):\n \"\"\"Get interpolation algorithm name.\"\"\"\n return self._interpolation\n\n @interpolation.setter\n def interpolation(self, i):\n if i not in self._interpolation_names:\n raise ValueError(\"interpolation must be one of %s\" %\n ', '.join(self._interpolation_names))\n if self._interpolation != i:\n self._interpolation = i\n self._need_interpolation_update = True\n self.update()\n\n @property\n def interpolation_functions(self):\n \"\"\"Get names of possible interpolation methods.\"\"\"\n return self._interpolation_names\n\n # The interpolation code could be transferred to a dedicated filter\n # function in visuals/filters as discussed in #1051\n def _build_interpolation(self):\n \"\"\"Rebuild the _data_lookup_fn for different interpolations.\"\"\"\n interpolation = self._interpolation\n self._data_lookup_fn = self._interpolation_fun[interpolation]\n self.shared_program.frag['get_data'] = self._data_lookup_fn\n\n # only 'bilinear' uses 'linear' texture interpolation\n if interpolation == 'bilinear':\n texture_interpolation = 'linear'\n else:\n # 'nearest' (and also 'bilinear') doesn't use spatial_filters.frag\n # so u_kernel and shape setting is skipped\n texture_interpolation = 'nearest'\n if interpolation != 'nearest':\n self.shared_program['u_kernel'] = self._kerneltex\n self._data_lookup_fn['shape'] = self._data.shape[:2][::-1]\n\n if self._texture.interpolation != texture_interpolation:\n self._texture.interpolation = texture_interpolation\n\n self._data_lookup_fn['texture'] = self._texture\n\n self._need_interpolation_update = False\n\n def _build_vertex_data(self):\n \"\"\"Rebuild the vertex buffers for the subdivide method.\"\"\"\n grid = self._grid\n w = 1.0 / grid[1]\n h = 1.0 / grid[0]\n\n quad = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0],\n [0, 0, 0], [w, h, 0], [0, h, 0]],\n dtype=np.float32)\n quads = np.empty((grid[1], grid[0], 6, 3), dtype=np.float32)\n quads[:] = quad\n\n mgrid = np.mgrid[0.:grid[1], 0.:grid[0]].transpose(1, 2, 0)\n mgrid = mgrid[:, :, np.newaxis, :]\n mgrid[..., 0] *= w\n mgrid[..., 1] *= h\n\n quads[..., :2] += mgrid\n tex_coords = quads.reshape(grid[1]*grid[0]*6, 3)\n tex_coords = np.ascontiguousarray(tex_coords[:, :2])\n vertices = tex_coords * self.size\n\n self._subdiv_position.set_data(vertices.astype('float32'))\n self._subdiv_texcoord.set_data(tex_coords.astype('float32'))\n self._need_vertex_update = False\n\n def _update_method(self, view):\n \"\"\"Decide which method to use for *view* and configure it accordingly.\"\"\"\n method = self._method\n if method == 'auto':\n if view.transforms.get_transform().Linear:\n method = 'subdivide'\n else:\n method = 'impostor'\n view._method_used = method\n\n if method == 'subdivide':\n view.view_program['method'] = 0\n view.view_program['a_position'] = self._subdiv_position\n view.view_program['a_texcoord'] = self._subdiv_texcoord\n elif method == 'impostor':\n view.view_program['method'] = 1\n view.view_program['a_position'] = self._impostor_coords\n view.view_program['a_texcoord'] = self._impostor_coords\n else:\n raise ValueError(\"Unknown image draw method '%s'\" % method)\n\n self.shared_program['image_size'] = self.size\n view._need_method_update = False\n self._prepare_transforms(view)\n\n def _build_texture(self):\n pre_clims = self._texture.clim\n pre_internalformat = self._texture.internalformat\n self._texture.scale_and_set_data(self._data)\n post_clims = self._texture.clim\n post_internalformat = self._texture.internalformat\n # color transform needs rebuilding if the internalformat was changed\n # new color limits need to be assigned if the normalized clims changed\n # otherwise, the original color transform should be fine\n # Note that this assumes that if clim changed, clim_normalized changed\n new_if = post_internalformat != pre_internalformat\n new_cl = post_clims != pre_clims\n if not new_if and new_cl and not self._need_colortransform_update:\n # shortcut so we don't have to rebuild the whole color transform\n self.shared_program.frag['color_transform'][1]['clim'] = self._texture.clim_normalized\n elif new_if:\n self._need_colortransform_update = True\n self._need_texture_upload = False\n\n def _compute_bounds(self, axis, view):\n if axis > 1:\n return 0, 0\n else:\n return 0, self.size[axis]\n\n def _build_color_transform(self):\n if self._data.ndim == 2 or self._data.shape[2] == 1:\n # luminance data\n fclim = Function(_apply_clim_float)\n fgamma = Function(_apply_gamma_float)\n # NOTE: _c2l_red only uses the red component, fancy internalformats\n # may need to use the other components or a different function chain\n fun = FunctionChain(\n None, [Function(_c2l_red), fclim, fgamma, Function(self.cmap.glsl_map)]\n )\n else:\n # RGB/A image data (no colormap)\n fclim = Function(_apply_clim)\n fgamma = Function(_apply_gamma)\n fun = FunctionChain(None, [Function(_null_color_transform), fclim, fgamma])\n fclim['clim'] = self._texture.clim_normalized\n fgamma['gamma'] = self.gamma\n return fun\n\n def _prepare_transforms(self, view):\n trs = view.transforms\n prg = view.view_program\n method = view._method_used\n if method == 'subdivide':\n prg.vert['transform'] = trs.get_transform()\n prg.frag['transform'] = self._null_tr\n else:\n prg.vert['transform'] = self._null_tr\n prg.frag['transform'] = trs.get_transform().inverse\n\n def _prepare_draw(self, view):\n if self._data is None:\n return False\n\n if self._need_interpolation_update:\n self._build_interpolation()\n\n if self._need_texture_upload:\n self._build_texture()\n\n if self._need_colortransform_update:\n prg = view.view_program\n self.shared_program.frag['color_transform'] = self._build_color_transform()\n self._need_colortransform_update = False\n prg['texture2D_LUT'] = self.cmap.texture_lut() \\\n if (hasattr(self.cmap, 'texture_lut')) else None\n\n if self._need_vertex_update:\n self._build_vertex_data()\n\n if view._need_method_update:\n self._update_method(view)\n"
] |
[
[
"numpy.asarray",
"numpy.array",
"numpy.empty",
"numpy.ascontiguousarray"
]
] |
hoondy/pegasus
|
[
"ca6e8dc3b39402deab21d6db80ad4ce8d41631e9"
] |
[
"pegasus/tools/visualization.py"
] |
[
"import time\nimport numpy as np\nimport scipy\nimport umap as umap_module\nimport forceatlas2 as fa2\nimport uuid\n\nfrom threadpoolctl import threadpool_limits\nfrom pegasusio import MultimodalData\n\nfrom pegasus.tools import (\n eff_n_jobs,\n update_rep,\n X_from_rep,\n W_from_rep,\n get_neighbors,\n neighbors,\n net_train_and_predict,\n calculate_nearest_neighbors,\n calculate_affinity_matrix,\n construct_graph,\n)\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom pegasusio import timer\n\n\n\ndef calc_tsne(\n X,\n nthreads,\n no_dims,\n perplexity,\n early_exag_coeff,\n learning_rate,\n rand_seed,\n initialization=None,\n max_iter=750,\n stop_early_exag_iter=250,\n mom_switch_iter=250,\n):\n \"\"\"\n TODO: Calculate t-SNE embeddings using the FIt-SNE package\n \"\"\"\n # FItSNE will change X content\n\n # Check if fftw3 is installed.\n import ctypes.util\n\n fftw3_loc = ctypes.util.find_library(\"fftw3\")\n if fftw3_loc is None:\n raise Exception(\"Please install 'fftw3' first to use the FIt-SNE feature!\")\n\n from fitsne import FItSNE\n\n return FItSNE(\n X,\n nthreads=nthreads,\n no_dims=no_dims,\n perplexity=perplexity,\n early_exag_coeff=early_exag_coeff,\n learning_rate=learning_rate,\n rand_seed=rand_seed,\n initialization=initialization,\n max_iter=max_iter,\n stop_early_exag_iter=stop_early_exag_iter,\n mom_switch_iter=mom_switch_iter,\n )\n\n\n# Running umap using our own kNN indices\ndef calc_umap(\n X,\n n_components,\n n_neighbors,\n min_dist,\n spread,\n random_state,\n init=\"spectral\",\n n_epochs=None,\n learning_rate=1.0,\n knn_indices=None,\n knn_dists=None,\n):\n \"\"\"\n TODO: Typing\n \"\"\"\n umap_obj = umap_module.UMAP(\n n_components=n_components,\n n_neighbors=n_neighbors,\n min_dist=min_dist,\n spread=spread,\n random_state=random_state,\n init=init,\n n_epochs=n_epochs,\n learning_rate=learning_rate,\n verbose=True,\n )\n\n embedding = None\n if X.shape[0] < 4096 or knn_indices is None:\n embedding = umap_obj.fit_transform(X)\n logger.info(f\"Using umap kNN graph because number of cells {X.shape[0]} is smaller than 4096 or knn_indices is not provided.\")\n else:\n assert knn_dists is not None\n # preprocessing codes adopted from UMAP's umap_.py fit function in order to use our own kNN graphs\n from sklearn.utils import check_random_state, check_array\n\n X = check_array(X, dtype=np.float32, accept_sparse=\"csr\")\n umap_obj._raw_data = X\n if umap_obj.a is None or umap_obj.b is None:\n umap_obj._a, umap_obj._b = umap_module.umap_.find_ab_params(\n umap_obj.spread, umap_obj.min_dist\n )\n else:\n umap_obj._a = umap_obj.a\n umap_obj._b = umap_obj.b\n umap_obj._metric_kwds = (\n umap_obj.metric_kwds if umap_obj.metric_kwds is not None else {}\n )\n umap_obj._target_metric_kwds = {}\n _init = (\n check_array(umap_obj.init, dtype=np.float32, accept_sparse=False)\n if isinstance(umap_obj.init, np.ndarray)\n else umap_obj.init\n )\n umap_obj._initial_alpha = umap_obj.learning_rate\n umap_obj._validate_parameters()\n\n if umap_obj.verbose:\n logger.info(str(umap_obj))\n\n if scipy.sparse.isspmatrix_csr(X):\n if not X.has_sorted_indices:\n X.sort_indices()\n umap_obj._sparse_data = True\n else:\n umap_obj._sparse_data = False\n\n _random_state = check_random_state(umap_obj.random_state)\n\n if umap_obj.verbose:\n logger.info(\"Construct fuzzy simplicial set\")\n\n umap_obj._small_data = False\n umap_obj.graph_, umap_obj._sigmas, umap_obj._rhos = umap_module.umap_.fuzzy_simplicial_set(\n X=X,\n n_neighbors=umap_obj.n_neighbors,\n random_state=_random_state,\n metric=umap_obj.metric,\n metric_kwds=umap_obj._metric_kwds,\n knn_indices=knn_indices,\n knn_dists=knn_dists,\n angular=umap_obj.angular_rp_forest,\n set_op_mix_ratio=umap_obj.set_op_mix_ratio,\n local_connectivity=umap_obj.local_connectivity,\n verbose=umap_obj.verbose,\n )\n\n _n_epochs = umap_obj.n_epochs if umap_obj.n_epochs is not None else 0\n if umap_obj.verbose:\n logger.info(\"Construct embedding\")\n\n def simplicial_set_embedding(*args, **kwargs):\n from packaging import version\n if version.parse(umap_module.__version__) >= version.parse('0.5.0'): # For umap-learn v0.5+\n kwargs.update({'densmap': False, 'densmap_kwds': {}, 'output_dens': False})\n embedding = umap_module.umap_.simplicial_set_embedding(*args, **kwargs)\n return (embedding[0] if isinstance(embedding, tuple) else embedding)\n\n embedding = simplicial_set_embedding(\n data=X,\n graph=umap_obj.graph_,\n n_components=umap_obj.n_components,\n initial_alpha=umap_obj._initial_alpha,\n a=umap_obj._a,\n b=umap_obj._b,\n gamma=umap_obj.repulsion_strength,\n negative_sample_rate=umap_obj.negative_sample_rate,\n n_epochs=_n_epochs,\n init=_init,\n random_state=_random_state,\n metric=umap_obj.metric,\n metric_kwds=umap_obj._metric_kwds,\n verbose=umap_obj.verbose,\n )\n\n return embedding\n\n\ndef calc_force_directed_layout(\n W,\n file_name,\n n_jobs,\n target_change_per_node,\n target_steps,\n is3d,\n memory,\n random_state,\n init=None,\n):\n \"\"\"\n TODO: Typing\n \"\"\"\n G = construct_graph(W)\n return fa2.forceatlas2(\n file_name,\n graph=G,\n n_jobs=n_jobs,\n target_change_per_node=target_change_per_node,\n target_steps=target_steps,\n is3d=is3d,\n memory=memory,\n random_state=random_state,\n init=init,\n )\n\n\n@timer(logger=logger)\ndef tsne(\n data: MultimodalData,\n rep: str = \"pca\",\n n_jobs: int = -1,\n n_components: int = 2,\n perplexity: float = 30,\n early_exaggeration: int = 12,\n learning_rate: float = \"auto\",\n initialization: str = \"pca\",\n random_state: int = 0,\n out_basis: str = \"tsne\",\n) -> None:\n \"\"\"Calculate t-SNE embedding of cells using the FIt-SNE package.\n\n This function uses fitsne_ package. See [Linderman19]_ for details on FIt-SNE algorithm.\n\n .. _fitsne: https://github.com/KlugerLab/FIt-SNE\n\n Parameters\n ----------\n data: ``pegasusio.MultimodalData``\n Annotated data matrix with rows for cells and columns for genes.\n\n rep: ``str``, optional, default: ``\"pca\"``\n Representation of data used for the calculation. By default, use PCA coordinates. If ``None``, use the count matrix ``data.X``.\n\n n_jobs: ``int``, optional, default: ``-1``\n Number of threads to use. If ``-1``, use all physical CPU cores.\n\n n_components: ``int``, optional, default: ``2``\n Dimension of calculated FI-tSNE coordinates. By default, generate 2-dimensional data for 2D visualization.\n\n perplexity: ``float``, optional, default: ``30``\n The perplexity is related to the number of nearest neighbors used in other manifold learning algorithms. Larger datasets usually require a larger perplexity.\n\n early_exaggeration: ``int``, optional, default: ``12``\n Controls how tight natural clusters in the original space are in the embedded space, and how much space will be between them.\n\n learning_rate: ``float``, optional, default: ``auto``\n By default, the learning rate is determined automatically as max(data.shape[0] / early_exaggeration, 200). See [Belkina19]_ and [Kobak19]_ for details.\n\n initialization: ``str``, optional, default: ``pca``\n Initialization can be either ``pca`` or ``random`` or np.ndarray. By default, we use ``pca`` initialization according to [Kobak19]_.\n\n random_state: ``int``, optional, default: ``0``\n Random seed set for reproducing results.\n\n out_basis: ``str``, optional, default: ``\"fitsne\"``\n Key name for calculated FI-tSNE coordinates to store.\n\n Returns\n -------\n ``None``\n\n Update ``data.obsm``:\n * ``data.obsm['X_' + out_basis]``: FI-tSNE coordinates of the data.\n\n Examples\n --------\n >>> pg.tsne(data)\n \"\"\"\n\n rep = update_rep(rep)\n n_jobs = eff_n_jobs(n_jobs)\n X = X_from_rep(data, rep).astype(np.float64)\n\n if learning_rate == \"auto\":\n learning_rate = max(X.shape[0] / early_exaggeration, 200.0)\n\n if initialization == \"random\":\n initialization = None\n elif initialization == \"pca\":\n if rep == \"pca\":\n initialization = X[:, 0:n_components].copy()\n else:\n from sklearn.decomposition import PCA\n pca = PCA(n_components=n_components, random_state=random_state)\n with threadpool_limits(limits = n_jobs):\n initialization = np.ascontiguousarray(pca.fit_transform(X))\n initialization = initialization / np.std(initialization[:, 0]) * 0.0001\n else:\n assert isinstance(initialization, np.ndarray) and initialization.ndim == 2 and initialization.shape[0] == X.shape[0] and initialization.shape[1] == n_components\n if initialization.dtype != np.float64:\n initialization = initialization.astype(np.float64)\n\n data.obsm[\"X_\" + out_basis] = calc_tsne(\n X,\n n_jobs,\n n_components,\n perplexity,\n early_exaggeration,\n learning_rate,\n random_state,\n initialization,\n )\n\n\n@timer(logger=logger)\ndef umap(\n data: MultimodalData,\n rep: str = \"pca\",\n n_components: int = 2,\n n_neighbors: int = 15,\n min_dist: float = 0.5,\n spread: float = 1.0,\n n_jobs: int = -1,\n full_speed: bool = False,\n random_state: int = 0,\n out_basis: str = \"umap\",\n) -> None:\n \"\"\"Calculate UMAP embedding of cells.\n\n This function uses umap-learn_ package. See [McInnes18]_ for details on UMAP.\n\n .. _umap-learn: https://github.com/lmcinnes/umap\n\n Parameters\n ----------\n data: ``pegasusio.MultimodalData``\n Annotated data matrix with rows for cells and columns for genes.\n\n rep: ``str``, optional, default: ``\"pca\"``\n Representation of data used for the calculation. By default, use PCA coordinates. If ``None``, use the count matrix ``data.X``.\n\n n_components: ``int``, optional, default: ``2``\n Dimension of calculated UMAP coordinates. By default, generate 2-dimensional data for 2D visualization.\n\n n_neighbors: ``int``, optional, default: ``15``\n Number of nearest neighbors considered during the computation.\n\n min_dist: ``float``, optional, default: ``0.5``\n The effective minimum distance between embedded data points.\n\n spread: ``float``, optional, default: ``1.0``\n The effective scale of embedded data points.\n\n n_jobs: ``int``, optional, default: ``-1``\n Number of threads to use for computing kNN graphs. If ``-1``, use all physical CPU cores.\n\n full_speed: ``bool``, optional, default: ``False``\n * If ``True``, use multiple threads in constructing ``hnsw`` index. However, the kNN results are not reproducible.\n * Otherwise, use only one thread to make sure results are reproducible.\n\n random_state: ``int``, optional, default: ``0``\n Random seed set for reproducing results.\n\n out_basis: ``str``, optional, default: ``\"umap\"``\n Key name for calculated UMAP coordinates to store.\n\n Returns\n -------\n ``None``\n\n Update ``data.obsm``:\n * ``data.obsm['X_' + out_basis]``: UMAP coordinates of the data.\n\n Examples\n --------\n >>> pg.umap(data)\n \"\"\"\n rep = update_rep(rep)\n X = X_from_rep(data, rep)\n\n if data.shape[0] < n_neighbors:\n logger.warning(f\"Warning: Number of samples = {data.shape[0]} < K = {n_neighbors}!\\n Set K to {data.shape[0]}.\")\n n_neighbors = data.shape[0]\n\n knn_indices, knn_dists = get_neighbors(data, K = n_neighbors, rep = rep, n_jobs = n_jobs, random_state = random_state, full_speed = full_speed)\n knn_indices = np.insert(knn_indices[:, 0 : n_neighbors - 1], 0, range(data.shape[0]), axis=1)\n knn_dists = np.insert(knn_dists[:, 0 : n_neighbors - 1], 0, 0.0, axis=1)\n\n data.obsm[\"X_\" + out_basis] = calc_umap(\n X,\n n_components,\n n_neighbors,\n min_dist,\n spread,\n random_state,\n knn_indices=knn_indices,\n knn_dists=knn_dists,\n )\n\n\n@timer(logger=logger)\ndef fle(\n data: MultimodalData,\n file_name: str = None,\n n_jobs: int = -1,\n rep: str = \"diffmap\",\n K: int = 50,\n full_speed: bool = False,\n target_change_per_node: float = 2.0,\n target_steps: int = 5000,\n is3d: bool = False,\n memory: int = 8,\n random_state: int = 0,\n out_basis: str = \"fle\",\n) -> None:\n \"\"\"Construct the Force-directed (FLE) graph.\n\n This implementation uses forceatlas2-python_ package, which is a Python wrapper of ForceAtlas2_.\n\n See [Jacomy14]_ for details on FLE.\n\n .. _forceatlas2-python: https://github.com/klarman-cell-observatory/forceatlas2-python\n .. _ForceAtlas2: https://github.com/klarman-cell-observatory/forceatlas2\n\n Parameters\n ----------\n data: ``pegasusio.MultimodalData``\n Annotated data matrix with rows for cells and columns for genes.\n\n file_name: ``str``, optional, default: ``None``\n Temporary file to store the coordinates as the input to forceatlas2. If ``None``, use ``tempfile.mkstemp`` to generate file name.\n\n n_jobs: ``int``, optional, default: ``-1``\n Number of threads to use. If ``-1``, use all physical CPU cores.\n\n rep: ``str``, optional, default: ``\"diffmap\"``\n Representation of data used for the calculation. By default, use Diffusion Map coordinates. If ``None``, use the count matrix ``data.X``.\n\n K: ``int``, optional, default: ``50``\n Number of nearest neighbors to be considered during the computation.\n\n full_speed: ``bool``, optional, default: ``False``\n * If ``True``, use multiple threads in constructing ``hnsw`` index. However, the kNN results are not reproducible.\n * Otherwise, use only one thread to make sure results are reproducible.\n\n target_change_per_node: ``float``, optional, default: ``2.0``\n Target change per node to stop ForceAtlas2.\n\n target_steps: ``int``, optional, default: ``5000``\n Maximum number of iterations before stopping the ForceAtlas2 algorithm.\n\n is3d: ``bool``, optional, default: ``False``\n If ``True``, calculate 3D force-directed layout.\n\n memory: ``int``, optional, default: ``8``\n Memory size in GB for the Java FA2 component. By default, use 8GB memory.\n\n random_state: ``int``, optional, default: ``0``\n Random seed set for reproducing results.\n\n out_basis: ``str``, optional, default: ``\"fle\"``\n Key name for calculated FLE coordinates to store.\n\n Returns\n -------\n ``None``\n\n Update ``data.obsm``:\n * ``data.obsm['X_' + out_basis]``: FLE coordinates of the data.\n\n Examples\n --------\n >>> pg.fle(data)\n \"\"\"\n\n if file_name is None:\n import tempfile\n\n _, file_name = tempfile.mkstemp()\n\n rep = update_rep(rep)\n n_jobs = eff_n_jobs(n_jobs)\n\n if (\"W_\" + rep) not in data.uns:\n neighbors(\n data,\n K=K,\n rep=rep,\n n_jobs=n_jobs,\n random_state=random_state,\n full_speed=full_speed,\n )\n\n data.obsm[\"X_\" + out_basis] = calc_force_directed_layout(\n W_from_rep(data, rep),\n file_name,\n n_jobs,\n target_change_per_node,\n target_steps,\n is3d,\n memory,\n random_state,\n )\n\n\n@timer(logger=logger)\ndef select_cells(distances, frac, K=25, alpha=1.0, random_state=0):\n \"\"\"\n TODO: documentation (not user API)\n \"\"\"\n nsample = distances.shape[0]\n assert K >= 2\n if K > distances.shape[1] + 1:\n logger.info(f\"Warning: in select_cells, K = {K} > the number of calculated nearest neighbors {distances.shape[1] + 1}!\\nSet K to {distances.shape[1] + 1}\")\n K = distances.shape[1] + 1\n\n probs = np.zeros(nsample)\n if alpha == 0.0:\n probs[:] = 1.0 # uniform\n elif alpha == 1.0:\n probs[:] = distances[:, K - 2]\n else:\n probs[:] = distances[:, K - 2] ** alpha\n probs /= probs.sum()\n\n np.random.seed(random_state)\n selected = np.zeros(nsample, dtype=bool)\n selected[\n np.random.choice(nsample, size=int(nsample * frac), replace=False, p=probs)\n ] = True\n\n return selected\n\n\n@timer(logger=logger)\ndef net_umap(\n data: MultimodalData,\n rep: str = \"pca\",\n n_jobs: int = -1,\n n_components: int = 2,\n n_neighbors: int = 15,\n min_dist: float = 0.5,\n spread: float = 1.0,\n random_state: int = 0,\n select_frac: float = 0.1,\n select_K: int = 25,\n select_alpha: float = 1.0,\n full_speed: bool = False,\n net_alpha: float = 0.1,\n polish_learning_rate: float = 10.0,\n polish_n_epochs: int = 30,\n out_basis: str = \"net_umap\",\n) -> None:\n \"\"\"Calculate Net-UMAP embedding of cells.\n\n Net-UMAP is an approximated UMAP embedding using Deep Learning model to improve the speed.\n\n In specific, the deep model used is MLPRegressor_, the *scikit-learn* implementation of Multi-layer Perceptron regressor.\n\n See [Li20]_ for details.\n\n .. _MLPRegressor: https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html\n\n Parameters\n ----------\n data: ``pegasusio.MultimodalData``\n Annotated data matrix with rows for cells and columns for genes.\n\n rep: ``str``, optional, default: ``\"pca\"``\n Representation of data used for the calculation. By default, use PCA coordinates. If ``None``, use the count matrix ``data.X``.\n\n n_jobs: ``int``, optional, default: ``-1``\n Number of threads to use. If ``-1``, use all physical CPU cores.\n\n n_components: ``int``, optional, default: ``2``\n Dimension of calculated UMAP coordinates. By default, generate 2-dimensional data for 2D visualization.\n\n n_neighbors: ``int``, optional, default: ``15``\n Number of nearest neighbors considered during the computation.\n\n min_dist: ``float``, optional, default: ``0.5``\n The effective minimum distance between embedded data points.\n\n spread: ``float``, optional, default: ``1.0``\n The effective scale of embedded data points.\n\n random_state: ``int``, optional, default: ``0``\n Random seed set for reproducing results.\n\n select_frac: ``float``, optional, default: ``0.1``\n Down sampling fraction on the cells.\n\n select_K: ``int``, optional, default: ``25``\n Number of neighbors to be used to estimate local density for each data point for down sampling.\n\n select_alpha: ``float``, optional, default: ``1.0``\n Weight the down sample to be proportional to ``radius ** select_alpha``.\n\n full_speed: ``bool``, optional, default: ``False``\n * If ``True``, use multiple threads in constructing ``hnsw`` index. However, the kNN results are not reproducible.\n * Otherwise, use only one thread to make sure results are reproducible.\n\n net_alpha: ``float``, optional, default: ``0.1``\n L2 penalty (regularization term) parameter of the deep regressor.\n\n polish_learning_frac: ``float``, optional, default: ``10.0``\n After running the deep regressor to predict new coordinates, use ``polish_learning_frac`` * ``n_obs`` as the learning rate to polish the coordinates.\n\n polish_n_iter: ``int``, optional, default: ``30``\n Number of iterations for polishing UMAP run.\n\n out_basis: ``str``, optional, default: ``\"net_umap\"``\n Key name for calculated UMAP coordinates to store.\n\n Returns\n -------\n ``None``\n\n Update ``data.obsm``:\n * ``data.obsm['X_' + out_basis]``: Net UMAP coordinates of the data.\n\n Update ``data.obs``:\n * ``data.obs['ds_selected']``: Boolean array to indicate which cells are selected during the down sampling phase.\n\n Examples\n --------\n >>> pg.net_umap(data)\n \"\"\"\n\n rep = update_rep(rep)\n n_jobs = eff_n_jobs(n_jobs)\n knn_indices, knn_dists = get_neighbors(data, K = select_K, rep = rep, n_jobs = n_jobs, random_state = random_state, full_speed = full_speed)\n\n selected = select_cells(\n knn_dists,\n select_frac,\n K=select_K,\n alpha=select_alpha,\n random_state=random_state,\n )\n X_full = X_from_rep(data, rep)\n X = X_full[selected, :]\n\n if data.shape[0] < n_neighbors:\n logger.warning(f\"Warning: Number of samples = {data.shape[0]} < K = {n_neighbors}!\\n Set K to {data.shape[0]}.\")\n n_neighbors = data.shape[0]\n\n ds_indices_key = \"ds_\" + rep + \"_knn_indices\" # ds refers to down-sampling\n ds_distances_key = \"ds_\" + rep + \"_knn_distances\"\n indices, distances = calculate_nearest_neighbors(\n X,\n K=n_neighbors,\n n_jobs=n_jobs,\n random_state=random_state,\n full_speed=full_speed,\n )\n data.uns[ds_indices_key] = indices\n data.uns[ds_distances_key] = distances\n\n knn_indices = np.insert(\n data.uns[ds_indices_key][:, 0 : n_neighbors - 1], 0, range(X.shape[0]), axis=1\n )\n knn_dists = np.insert(\n data.uns[ds_distances_key][:, 0 : n_neighbors - 1], 0, 0.0, axis=1\n )\n\n X_umap = calc_umap(\n X,\n n_components,\n n_neighbors,\n min_dist,\n spread,\n random_state,\n knn_indices=knn_indices,\n knn_dists=knn_dists,\n )\n\n data.uns[\"X_\" + out_basis + \"_small\"] = X_umap\n data.obs[\"ds_selected\"] = selected\n\n Y_init = np.zeros((data.shape[0], n_components), dtype=np.float64)\n Y_init[selected, :] = X_umap\n Y_init[~selected, :] = net_train_and_predict(\n X, X_umap, X_full[~selected, :], net_alpha, n_jobs, random_state, verbose=True\n )\n\n data.obsm[\"X_\" + out_basis + \"_pred\"] = Y_init\n\n knn_indices, knn_dists = get_neighbors(data, K = n_neighbors, rep = rep, n_jobs = n_jobs, random_state = random_state, full_speed = full_speed)\n knn_indices = np.insert(knn_indices[:, 0 : n_neighbors - 1], 0, range(data.shape[0]), axis=1)\n knn_dists = np.insert(knn_dists[:, 0 : n_neighbors - 1], 0, 0.0, axis=1)\n\n data.obsm[\"X_\" + out_basis] = calc_umap(\n X_full,\n n_components,\n n_neighbors,\n min_dist,\n spread,\n random_state,\n init=Y_init,\n n_epochs=polish_n_epochs,\n learning_rate=polish_learning_rate,\n knn_indices=knn_indices,\n knn_dists=knn_dists,\n )\n\n\n@timer(logger=logger)\ndef net_fle(\n data: MultimodalData,\n file_name: str = None,\n n_jobs: int = -1,\n rep: str = \"diffmap\",\n K: int = 50,\n full_speed: bool = False,\n target_change_per_node: float = 2.0,\n target_steps: int = 5000,\n is3d: bool = False,\n memory: int = 8,\n random_state: int = 0,\n select_frac: float = 0.1,\n select_K: int = 25,\n select_alpha: float = 1.0,\n net_alpha: float = 0.1,\n polish_target_steps: int = 1500,\n out_basis: str = \"net_fle\",\n) -> None:\n \"\"\"Construct Net-Force-directed (FLE) graph.\n\n Net-FLE is an approximated FLE graph using Deep Learning model to improve the speed.\n\n In specific, the deep model used is MLPRegressor_, the *scikit-learn* implementation of Multi-layer Perceptron regressor.\n\n See [Li20]_ for details.\n\n .. _MLPRegressor: https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html\n\n Parameters\n ----------\n data: ``pegasusio.MultimodalData``\n Annotated data matrix with rows for cells and columns for genes.\n\n file_name: ``str``, optional, default: ``None``\n Temporary file to store the coordinates as the input to forceatlas2. If ``None``, use ``tempfile.mkstemp`` to generate file name.\n\n n_jobs: ``int``, optional, default: ``-1``\n Number of threads to use. If ``-1``, use all physical CPU cores.\n\n rep: ``str``, optional, default: ``\"diffmap\"``\n Representation of data used for the calculation. By default, use Diffusion Map coordinates. If ``None``, use the count matrix ``data.X``.\n\n K: ``int``, optional, default: ``50``\n Number of nearest neighbors to be considered during the computation.\n\n full_speed: ``bool``, optional, default: ``False``\n * If ``True``, use multiple threads in constructing ``hnsw`` index. However, the kNN results are not reproducible.\n * Otherwise, use only one thread to make sure results are reproducible.\n\n target_change_per_node: ``float``, optional, default: ``2.0``\n Target change per node to stop ForceAtlas2.\n\n target_steps: ``int``, optional, default: ``5000``\n Maximum number of iterations before stopping the ForceAtlas2 algorithm.\n\n is3d: ``bool``, optional, default: ``False``\n If ``True``, calculate 3D force-directed layout.\n\n memory: ``int``, optional, default: ``8``\n Memory size in GB for the Java FA2 component. By default, use 8GB memory.\n\n random_state: ``int``, optional, default: ``0``\n Random seed set for reproducing results.\n\n select_frac: ``float``, optional, default: ``0.1``\n Down sampling fraction on the cells.\n\n select_K: ``int``, optional, default: ``25``\n Number of neighbors to be used to estimate local density for each data point for down sampling.\n\n select_alpha: ``float``, optional, default: ``1.0``\n Weight the down sample to be proportional to ``radius ** select_alpha``.\n\n net_alpha: ``float``, optional, default: ``0.1``\n L2 penalty (regularization term) parameter of the deep regressor.\n\n polish_target_steps: ``int``, optional, default: ``1500``\n After running the deep regressor to predict new coordinate, Number of ForceAtlas2 iterations.\n\n out_basis: ``str``, optional, default: ``\"net_fle\"``\n Key name for calculated FLE coordinates to store.\n\n Returns\n -------\n ``None``\n\n Update ``data.obsm``:\n * ``data.obsm['X_' + out_basis]``: Net FLE coordinates of the data.\n\n Update ``data.obs``:\n * ``data.obs['ds_selected']``: Boolean array to indicate which cells are selected during the down sampling phase.\n\n Examples\n --------\n >>> pg.net_fle(data)\n \"\"\"\n\n if file_name is None:\n if file_name is None:\n import tempfile\n\n _, file_name = tempfile.mkstemp()\n\n rep = update_rep(rep)\n n_jobs = eff_n_jobs(n_jobs)\n\n if (\"W_\" + rep) not in data.uns:\n neighbors(\n data,\n K=K,\n rep=rep,\n n_jobs=n_jobs,\n random_state=random_state,\n full_speed=full_speed,\n )\n\n knn_indices, knn_dists = get_neighbors(data, K = select_K, rep = rep, n_jobs = n_jobs, random_state = random_state, full_speed = full_speed)\n\n selected = select_cells(\n knn_dists,\n select_frac,\n K=select_K,\n alpha=select_alpha,\n random_state=random_state,\n )\n\n X_full = X_from_rep(data, rep)\n X = X_full[selected, :]\n\n ds_indices_key = \"ds_\" + rep + \"_knn_indices\"\n ds_distances_key = \"ds_\" + rep + \"_knn_distances\"\n indices, distances = calculate_nearest_neighbors(\n X, K=K, n_jobs=n_jobs, random_state=random_state, full_speed=full_speed\n )\n data.uns[ds_indices_key] = indices\n data.uns[ds_distances_key] = distances\n\n W = calculate_affinity_matrix(indices, distances)\n\n X_fle = calc_force_directed_layout(\n W,\n file_name + \".small\",\n n_jobs,\n target_change_per_node,\n target_steps,\n is3d,\n memory,\n random_state,\n )\n\n data.uns[\"X_\" + out_basis + \"_small\"] = X_fle\n data.obs[\"ds_diffmap_selected\"] = selected\n\n n_components = 2 if not is3d else 3\n Y_init = np.zeros((data.shape[0], n_components), dtype=np.float64)\n Y_init[selected, :] = X_fle\n Y_init[~selected, :] = net_train_and_predict(\n X, X_fle, X_full[~selected, :], net_alpha, n_jobs, random_state, verbose=True\n )\n\n data.obsm[\"X_\" + out_basis + \"_pred\"] = Y_init\n\n data.obsm[\"X_\" + out_basis] = calc_force_directed_layout(\n W_from_rep(data, rep),\n file_name,\n n_jobs,\n target_change_per_node,\n polish_target_steps,\n is3d,\n memory,\n random_state,\n init=Y_init,\n )\n"
] |
[
[
"numpy.random.seed",
"sklearn.utils.check_array",
"numpy.std",
"numpy.insert",
"sklearn.decomposition.PCA",
"scipy.sparse.isspmatrix_csr",
"numpy.zeros",
"sklearn.utils.check_random_state"
]
] |
greenmonn/distanceMatrixGPU
|
[
"b06d9309ff6bf5e950a1f9384e58b47665a9b22e"
] |
[
"cudaDistanceMatrix/cudaDistanceMatrix.py"
] |
[
"import h5py\nimport numpy as np\nfrom skcuda import linalg, misc\nimport pycuda.autoinit\nfrom pycuda.compiler import SourceModule\nimport pycuda.gpuarray as gpuarray\nlinalg.init()\nfrom numpy.linalg import norm\nimport os.path\n\ncuda_driver = pycuda.driver.init()\npycuda.driver.Device(0).retain_primary_context()\n\nfrom .fillArrayNumbaFloat32 import cudaFillFlattenArray32, cudaFillFullArray32\n\nclass DistanceMatrix:\n \"\"\"GPU accelerated Distannce matrix caluclations.\n Parameters\n ----------\n file_name: string\n Name of h5py file to save the distance matrix (don't need to have whole array in working memory).\n dtype_out: string\n What precision is needed? 32 or 64?\n gpu: bool\n Use gpu accelerations\n numba: bool\n Use additional gpu acceleration\n\n \"\"\"\n def __init__(self,\n file_name=\"cuda_dist\",\n gpu=True,\n numba=True,\n dictinoray=None):\n if os.path.isfile(str(file_name)):\n os.remove(str(file_name))\n \n self.filename_dist = file_name\n self.file_dist = h5py.File(file_name, 'w')\n self.out_type = np.float32\n self.float = \"float32\"\n self.load_full = False\n self.gpu = gpu\n self.numba = numba\n\n if dictinoray:\n self.dictinoray = dictinoray\n else:\n self.dictinoray = None\n def _cuda_norm(self, X):\n \"\"\"Caluclate L2-norm on gpu.\n\n Parameters\n ----------\n X: array\n Array to normalize\n Returns\n -------\n normX: array\n Normalized array\n\n \"\"\"\n return misc.divide(X, misc.sum(X ** 2, axis=1, keepdims=True) ** 0.5) \n def _norm(self, X):\n \"\"\"Caluclate L2-norm on cpu.\n\n Parameters\n ----------\n X: array\n Array to normalize\n Returns\n -------\n normX: array\n Normalized array\n \n \"\"\"\n return X / norm(X,axis=1, keepdims=True)\n\n \n def _get_XTX_cuda(self, X, x_1, x_2, y_1, y_2):\n \"\"\"Caluclate dot product between two array on gpu.\n\n Parameters\n ----------\n X: array\n Array to normalize\n x_1: int\n Lower bound on slice on x-axis\n x_2: int\n Upper bound on slice x-axis\n y_1: int\n Lower bound on slice y-axis\n y_2: int\n Upper bound on slice y-axis\n Returns\n -------\n XX.T: array\n X X.T array\n \n \"\"\"\n X_f, X_b = gpuarray.to_gpu(X[x_1:x_2, :]), gpuarray.to_gpu(X[y_1:y_2, :])\n X_f_norm, X_b_norm = self._cuda_norm(X_f), self._cuda_norm(X_b)\n return linalg.dot(X_f_norm, X_b_norm, transb=\"T\").get()\n \n def _get_XTX(self, X, x_1, x_2, y_1, y_2):\n \"\"\"Caluclate dot product between two array on cpu.\n\n Parameters\n ----------\n X: array\n Array to normalize\n x_1: int\n Lower bound on slice on x-axis\n x_2: int\n Upper bound on slice x-axis\n y_1: int\n Lower bound on slice y-axis\n y_2: int\n Upper bound on slice y-axis\n Returns\n -------\n XX.T: array\n X X.T array\n \n \"\"\"\n Xnorm1, Xnorm2 = self._norm(X[x_1:x_2,:]), self._norm(X[y_1:y_2,:])\n return np.dot(Xnorm1, Xnorm2.T)\n\n def _get_array_extensions(self, i, j):\n \"\"\"Get how much sub-array have to be exteneded to completely fill the whole array.\n\n Parameters\n ----------\n i: int\n Index to keep track on size of and position on sub-array\n \n j: int\n Index to keep track on size of and position on sub-array\n \n Returns\n -------\n extendX: int\n How much to extend sub-array on x-axis\n extendY: int\n How much to extend sub-array on y-axis\n \"\"\"\n extendX, extendY = 0, 0\n if i == self.nr_square - 1 and j == self.nr_square - 1:\n extendX = self.N % self.nr_square\n extendY = self.N % self.nr_square\n elif i == self.nr_square - 1:\n extendX = self.N % self.nr_square \n elif j == self.nr_square - 1:\n extendY = self.N % self.nr_square \n return extendX, extendY\n \n def _get_extensions_coef(self, i, j, dx, dy):\n \"\"\"Get position of where sub-array will be spliced from the complete array.\n\n Parameters\n ----------\n i: int\n Index to keep track on size of and position on sub-array\n \n j: int\n Index to keep track on size of and position on sub-array\n dx: int\n How much to extend on x-axis\n dy: int\n How much to extend on y-axis\n \n Returns\n -------\n x_1: int\n Lower bound on slice on x-axis\n x_2: int\n Upper bound on slice on x-axis\n y_1: int\n Lower bound on slice on y-axis\n y_2: int\n Upper bound on slice on y-axis\n \"\"\"\n x_1, x_2 = self.l * i, self.l * (i + 1) + dx\n y_1, y_2 = self.l * j, self.l * (j + 1) + dy\n return x_1, x_2, y_1, y_2\n \n def _get_flatten_distance_matrix(self, f_dist):\n \"\"\"Get the complete flatten distance matrix.\n\n Parameters\n ----------\n f_dist: array\n Contrains all sub-arrays with all distance data.\n \n \n Returns\n -------\n flattenDistancematrix: array\n The whole distance matrix\n \"\"\"\n entries = int(self.N * (self.N - 1) / 2)\n distance_matrix = np.zeros([entries],dtype=self.out_type)\n start_splice = 0\n for k in list(f_dist.keys()):\n data = np.asarray(f_dist[k])\n end_splice = start_splice + data.shape[0]\n distance_matrix[start_splice:end_splice] = data\n start_splice = end_splice\n return distance_matrix\n\n def _fill_fullDistanceMatrix(self, i, j, dist_data):\n \"\"\"Fill the complete full distance matrix (Void, fill array in-place)\n\n Parameters\n ----------\n i: int\n Index to keep track on size of and position on sub-array\n \n j: int\n Index to keep track on size of and position on sub-array\n dist_data: array\n Flatten sub-array with the distance data.\n \n Returns\n -------\n Void\n \n \"\"\"\n extendX, extendY = self._get_array_extensions(i, j)\n x_1, x_2, y_1, y_2 = self._get_extensions_coef(i, j, extendX, extendY) \n if i == j:\n subArr = np.ones([self.l + extendX, self.l + extendX], dtype=self.out_type)\n if self.float == \"float32\":\n A = cudaFillFullArray32(dist_data, subArr, self.l + extendX)\n elif self.float == \"float64\":\n A = cudaFillFullArray64(dist_data, subArr, self.l + extendX)\n self.fullDistMatrix[x_1: x_2, y_1 : y_2] = A \n else:\n self.fullDistMatrix[x_1: x_2, y_1 : y_2] = dist_data.reshape(self.l + extendX, self.l+ extendY)\n self.fullDistMatrix[y_1 : y_2, x_1: x_2] = dist_data.reshape(self.l + extendX, self.l+ extendY).T\n\n \n def _get_full_distance_matrix(self, f_dist):\n \"\"\"Get the complete full distance matrix\n\n Parameters\n ----------\n f_dist: array\n Array with all sub-arrays with distance data.\n Returns\n -------\n fullDistanceMatrix: array\n Array with the full complete distance array\n \"\"\"\n self.fullDistMatrix = np.zeros([self.N, self.N])\n sorted_filenames = self._sort_files(f_dist)\n for fileArr in sorted_filenames:\n dist_data = np.asarray(f_dist[fileArr])\n i, j = int(fileArr.split(\":\")[1].split(\"_\")[1]), int(fileArr.split(\":\")[1].split(\"_\")[2])\n self._fill_fullDistanceMatrix(i, j, dist_data)\n return self.fullDistMatrix\n\n def _sort_files(self, f_dist):\n file_names = list(f_dist.keys())\n arr_number = [int(ss.split(\":\")[1].split(\"_\")[3]) for ss in file_names]\n _, sorted_filenames = zip(*sorted(zip(arr_number, file_names)))\n return sorted_filenames\n\n \n def get_distance_matrix(self, fullMatrix=False):\n \"\"\"Get either the complete flatten or full distance matrix.\n\n Parameters\n ----------\n fullMatrix: bool\n Get full (True) take N**2 memory, else flatten (False) take N(N-1)/2 memory. Both O(N**2)\n Returns\n -------\n DistanceMatrix: array\n Matrix with all the distance.\n \"\"\"\n f_dist = h5py.File(self.filename_dist, 'r')\n if fullMatrix:\n self.load_full = fullMatrix\n return self._get_full_distance_matrix(f_dist)\n else:\n return self._get_flatten_distance_matrix(f_dist)\n \n def _get_flatten_entries(self, i, j, X_shape):\n \"\"\"Get entries for the flatten array. It's a bi-jection (i,j) -> k, k -> (i,j)\n\n Parameters\n ----------\n i : int\n Index for the x-axis i.e., the ith row. \n j: int\n Index for the y-axis i.e., the jth column. \n X_shape: tuple\n Shape of sub-array\n Returns\n -------\n l_x: int\n length of sub-array on x-axis\n entries: int\n Number of entries in flatten array\n square: bool\n Is the matrix a square(True) or a triangle(False).\n \"\"\"\n if i == j:\n l_x = X_shape[0]\n entries = l_x*(l_x - 1)/2\n square = False\n else:\n l_x, l_y = X_shape[0], X_shape[1] \n entries = l_x * l_y\n square = True\n return l_x, entries, square\n \n def _fill_flatten_distMatrix(self, entries, X, dx):\n \"\"\"Fill the flatten distance matrix with data from sub-arrays.\n\n Parameters\n ----------\n entries : int\n Number of entries in flatten array\n X: array\n Sub-array with distance data.\n dx: int\n Length of the sub-array of the complete array to get filled.\n Returns\n -------\n subdistMatrix_flatten: array\n Part of the complete flatten array that have been given distance values. \n \"\"\"\n empty_subdistMatrix_flatten = np.zeros((int(entries)), dtype=self.out_type)\n if self.float == \"float32\":\n subdistMatrix_flatten = cudaFillFlattenArray32(empty_subdistMatrix_flatten, X, dx)\n elif self.float == \"float64\":\n subdistMatrix_flatten = cudaFillFlattenArray64(empty_subdistMatrix_flatten, X, dx)\n return subdistMatrix_flatten\n \n def get_similarity(self, i, j,load_full=False):\n \"\"\"Fill the flatten distance matrix with data from sub-arrays.\n\n Parameters\n ----------\n entries : int\n Number of entries in flatten array\n X: array\n Sub-array with distance data.\n dx: int\n Length of the sub-array of the complete array to get filled.\n Returns\n -------\n subdistMatrix_flatten: array\n Part of the complete flatten array that have been given distance values. \n \"\"\"\n if isinstance(i, str) or isinstance(j, str):\n if self.dictinoray:\n try:\n i = int(self.dictinoray[i])\n j = int(self.dictinoray[j])\n except:\n print(\"The values dont exists in dict.\")\n \n if not self.load_full:\n if load_full:\n self.load_full = load_full\n f_dist = h5py.File(self.filename_dist, 'r')\n self._get_full_distance_matrix(f_dist)\n return self.fullDistMatrix[i, j]\n else:\n if i == j:\n return 1\n f_dist = h5py.File(self.filename_dist, 'r')\n sorted_filenames = self._sort_files(f_dist)\n if i < j:\n f_n = self._get_val(sorted_filenames, j, i)\n val = self._get_ix(f_dist,f_n,j, i)\n \n else: \n f_n = self._get_val(sorted_filenames, i, j)\n val = self._get_ix(f_dist,f_n,i,j)\n return val\n else:\n return self.fullDistMatrix[i, j]\n \n def most_similar(self, i, load_full=False):\n \"\"\"Fill the flatten distance matrix with data from sub-arrays.\n\n Parameters\n ----------\n entries : int\n Number of entries in flatten array\n X: array\n Sub-array with distance data.\n dx: int\n Length of the sub-array of the complete array to get filled.\n Returns\n -------\n subdistMatrix_flatten: array\n Part of the complete flatten array that have been given distance values. \n \"\"\"\n if isinstance(i, str) or isinstance(j, str):\n if self.dictinoray:\n try:\n i = int(self.dictinoray[i])\n except:\n print(\"The values dont exists in dict.\")\n \n\n\n if not self.load_full:\n if load_full:\n self.load_full = load_full\n f_dist = h5py.File(self.filename_dist, 'r')\n self._get_full_distance_matrix(f_dist)\n\n sims = self.fullDistMatrix[i, :]\n else:\n sims = list()\n f_dist = h5py.File(self.filename_dist, 'r')\n sorted_filenames = self._sort_files(f_dist)\n \n for j in range(self.N):\n if i == j:\n val = 1\n elif i < j:\n f_n = self._get_val(sorted_filenames, j, i)\n val = self._get_ix(f_dist,f_n,j, i)\n else:\n f_n = self._get_val(sorted_filenames, i, j)\n val = self._get_ix(f_dist,f_n,i,j)\n sims.append(val)\n sims = np.asarray(sims)\n\n else:\n sims = self.fullDistMatrix[i, :]\n\n if self.dictinoray:\n sorted_val, sorted_name = zip(*sorted(zip(sims, self.dictinoray.keys())))\n return dict(zip(sorted_name[::-1], sorted_val[::-1]))\n else:\n return self.fullDistMatrix[i, :]\n \n \n def _get_bounderies(self, f_n):\n \"\"\"Get bounderies of sub-array in the array.\n\n Parameters\n ----------\n f_n : string\n File name of sub-array\n Returns\n -------\n x_range[0]: int\n Start cordinate in x-axis\n x_range[1]: int\n Stop cordinate in x-axis\n y_range[0]: int\n Start cordinate in y-axis\n y_range[1]: int\n Stop cordinate in y-axis\n \"\"\"\n x, y = f_n.split(\":\")[0].split(\"_\")\n x_range = x.split(\"-\")\n y_range = y.split(\"-\")\n return x_range[0], x_range[1], y_range[0], y_range[1]\n \n def _get_val(self, x, i, j):\n \"\"\"Get (i,j) from under triangle.\n\n Parameters\n ----------\n x : array\n Data array\n i: int\n x index\n j: int\n y index\n Returns\n -------\n val: int\n (i,j) value\n \"\"\"\n if len(x) == 1:\n f_n = x[0]\n x1, x2, y1, y2 = self._get_bounderies(f_n)\n if int(x1) <= i <= int(x2) and int(y1) <= j <= int(y2):\n return f_n\n else:\n return None\n else:\n p = int(np.ceil(len(x) / 2))\n x1, x2, y1, y2 = self._get_bounderies(x[p])\n \n if int(x1) <= i:\n if i <= int(x2):\n if int(y1) <= j:\n if j >= int(y2):\n val = self._get_val(x[p], i, j)\n else:\n val = self._get_val(x[p:], i, j)\n else:\n val = self._get_val(x[:p], i, j)\n else:\n val = self._get_val(x[p:], i, j)\n else:\n val = self._get_val(x[:p], i, j)\n \n return val\n \n def _get_ix(self, f_dist, file_name, i, j):\n \"\"\"Get (i,j) from under triangle.\n\n Parameters\n ----------\n f_dist : object\n Sotre all file data\n file_name: file_name\n Names of subarrays\n i: int\n x index\n j: int\n y index\n Returns\n -------\n val: int\n (i,j) value\n \"\"\"\n f1, f2 = file_name.split(\":\")\n val = f2.split(\"_\")\n dx, dy = f1.split(\"_\")\n x1, x2 = dx.split(\"-\")\n y1, y2 = dy.split(\"-\")\n \n si, sj = int(val[1]), int(val[2])\n X = np.array(f_dist[file_name])\n \n di, dj = int(i) - int(x1), int(j) - int(y1)\n extendX, extendY = self._get_array_extensions(si, sj)\n if si == sj:\n if self.float == \"float32\":\n subArr = np.ones([self.l + extendX, self.l + extendX], dtype=self.out_type)\n A = cudaFillFullArray32(X, subArr, self.l + extendX) \n else:\n A = X.reshape(self.l + extendX, self.l+ extendY)\n \n return A[di, dj]\n\n\n \n def calculate_distmatrix(self, X, nr_square=4):\n \"\"\"Calcualte the whole distane matrix\n\n Parameters\n ----------\n X : array\n Array to calcualte distances for.\n Returns\n -------\n Void\n \"\"\"\n if np.float32 != X.dtype:\n print(\"Warning: Array is not float32. The array will be convered from \", X.dtype, \" to float32 for speed up.\")\n X = X.astype(np.float32)\n l = X.shape[0] / nr_square\n assert l >= 2, \"Please pick fewer number of sub-arrays each has a length longer than 2 elements. Currently \" + str(round(l, 2))\n if self.float==\"float64\":\n assert X.shape[0] >= 10000, \"If using float64 ensure that that X.shape[0] > 10 000. Otherwise use float32 or cpu-version.\"\n self.l = int(np.floor(l))\n self.N = X.shape[0]\n self.nr_square = nr_square\n arr_nr = 0\n for i in range(self.nr_square):\n for j in range(self.nr_square):\n \n if j <= i:\n extendX, extendY = self._get_array_extensions(i, j)\n x_1, x_2, y_1, y_2 = self._get_extensions_coef(i, j, extendX, extendY)\n \n if self.gpu:\n XTX = self._get_XTX_cuda(X,*[x_1,x_2,y_1,y_2])\n else:\n XTX = self._get_XTX(X, *[x_1, x_2, y_1, y_2])\n \n l_x, entries, square = self._get_flatten_entries(i, j, XTX.shape)\n if self.numba: \n if square:\n subdistMatrix_flatten = XTX.flatten()\n else:\n subdistMatrix_flatten = self._fill_flatten_distMatrix(entries, XTX, l_x)\n \n else:\n if square:\n subdistMatrix_flatten = XTX.flatten()\n else:\n subdistMatrix_flatten = XTX[np.tril_indices(l_x, k=-1)]\n \n self.file_dist.create_dataset(str(x_1) + \"-\" + str(x_2 - 1) + \"_\" + str(y_1)+\"-\"+ str(y_2 - 1) + ':subArray_' + str(i) + \"_\" + str(j) + \"_\" + str(arr_nr), data=subdistMatrix_flatten, dtype=subdistMatrix_flatten.dtype)\n arr_nr +=1\n \n self.file_dist.close()\n"
] |
[
[
"numpy.dot",
"numpy.asarray",
"numpy.tril_indices",
"numpy.linalg.norm",
"numpy.ones",
"numpy.floor",
"numpy.array",
"numpy.zeros"
]
] |
RobbinBouwmeester/CALLC_evaluation
|
[
"0125ed88b767c305261cf5731c671f890bfacadd"
] |
[
"CALLC/trainl2.py"
] |
[
"\"\"\"\nRobbin Bouwmeester\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\nThis code is used to train retention time predictors and store\npredictions from a CV procedure for further analysis.\n\nThis project was made possible by MASSTRPLAN. MASSTRPLAN received funding \nfrom the Marie Sklodowska-Curie EU Framework for Research and Innovation \nHorizon 2020, under Grant Agreement No. 675132.\n\"\"\"\n\nimport subprocess\nimport pandas as pd\n\ndef call_ghostbusters(infile_known=\"temp/tempKnownsl2.csv\",infile_unknown=\"temp/tempUnknownsl2.csv\",fold_list=\"temp/tempFolds.txt\"):\n \"\"\"\n Get the dataframe associated with this analysis\n \n Parameters\n ----------\n infile_known : str\n location of a file with known retention time, for Layer 2\n infile_unknown : str\n location of a file with umknown retention time, for Layer 2\n fold_list : str\n the folds to be used in Layer 2\n \n Returns\n -------\n pd.DataFrame\n test predictions\n\tpd.DataFrame\n\t\ttrain predictions\n \"\"\"\n cmd = \"Rscript makeGAM.R %s %s %s\" % (infile_known,infile_unknown,fold_list)\n print(\"Going to execute this command: \",cmd)\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)\n out, err = p.communicate()\n \n preds = pd.read_csv(\"GAMpredTemp.csv\")\n train_preds = pd.read_csv(\"GAMtrainTemp.csv\")\n\n return(preds,train_preds)\n\ndef apply_l2(known_all,unknown_all,ignore_cols=[\"IDENTIFIER\",\"time\"],cv_list=None):\n \"\"\"\n Get the dataframe associated with this analysis\n \n Parameters\n ----------\n known_all : pd.DataFrame\n dataframe with known retention time, for Layer 2\n\tunknown_all : pd.DataFrame\n\t\tdataframe with unknown retention time, for Layer 2\n ignore_cols : list\n ignore these columns\n cv_list : list\n the folds to be used in Layer 2\n \n Returns\n -------\n pd.DataFrame\n test predictions\n\tpd.DataFrame\n\t\ttrain predictions\n \"\"\"\n ret_preds = []\n ret_preds_train = []\n cnames = []\n \n known_all.index = known_all[\"IDENTIFIER\"]\n unknown_all.index = unknown_all[\"IDENTIFIER\"]\n\n infile_known_handle = open(\"temp/tempKnownsl2.csv\",\"w\")\n infile_unknown_handle = open(\"temp/tempUnknownsl2.csv\",\"w\")\n infile_fold_handle = open(\"temp/tempFolds.txt\",\"w\")\n\n known_all.to_csv(infile_known_handle,index=False)\n unknown_all.to_csv(infile_unknown_handle,index=False)\n infile_fold_handle.write(\"\\n\".join(map(str,cv_list)))\n\n infile_known_handle.close()\n infile_unknown_handle.close()\n infile_fold_handle.close()\n\n preds,train_preds = call_ghostbusters()\n\n return(preds,train_preds)\n"
] |
[
[
"pandas.read_csv"
]
] |
swyjay/MRC
|
[
"47b0baeaa1544dbf4d763471692c508cb32ec93d"
] |
[
"tensorflow/vocab.py"
] |
[
"# -*- coding:utf8 -*-\n# ==============================================================================\n# Copyright 2017 Baidu.com, Inc. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"\nThis module implements the Vocab class for converting string to id and back\n\"\"\"\n\nimport numpy as np\n\n\nclass Vocab(object):\n \"\"\"\n Implements a vocabulary to store the tokens in the data, with their corresponding embeddings.\n \"\"\"\n def __init__(self, filename=None, initial_tokens=None, lower=False):\n self.id2token = {}\n self.token2id = {}\n self.token_cnt = {}\n self.lower = lower\n\n self.embed_dim = None\n self.embeddings = None\n\n self.pad_token = '<blank>'\n self.unk_token = '<unk>'\n\n self.initial_tokens = initial_tokens if initial_tokens is not None else []\n self.initial_tokens.extend([self.pad_token, self.unk_token])\n for token in self.initial_tokens:\n self.add(token)\n\n if filename is not None:\n self.load_from_file(filename)\n\n def size(self):\n \"\"\"\n get the size of vocabulary\n Returns:\n an integer indicating the size\n \"\"\"\n return len(self.id2token)\n\n def load_from_file(self, file_path):\n \"\"\"\n loads the vocab from file_path\n Args:\n file_path: a file with a word in each line\n \"\"\"\n for line in open(file_path, 'r'):\n token = line.rstrip('\\n')\n self.add(token)\n\n def get_id(self, token):\n \"\"\"\n gets the id of a token, returns the id of unk token if token is not in vocab\n Args:\n key: a string indicating the word\n Returns:\n an integer\n \"\"\"\n token = token.lower() if self.lower else token\n try:\n return self.token2id[token]\n except KeyError:\n return self.token2id[self.unk_token]\n\n def get_token(self, idx):\n \"\"\"\n gets the token corresponding to idx, returns unk token if idx is not in vocab\n Args:\n idx: an integer\n returns:\n a token string\n \"\"\"\n try:\n return self.id2token[idx]\n except KeyError:\n return self.unk_token\n\n def add(self, token, cnt=1):\n \"\"\"\n adds the token to vocab\n Args:\n token: a string\n cnt: a num indicating the count of the token to add, default is 1\n \"\"\"\n token = token.lower() if self.lower else token\n if token in self.token2id:\n idx = self.token2id[token]\n else:\n idx = len(self.id2token)\n self.id2token[idx] = token\n self.token2id[token] = idx\n if cnt > 0:\n if token in self.token_cnt:\n self.token_cnt[token] += cnt\n else:\n self.token_cnt[token] = cnt\n return idx\n\n def filter_tokens_by_cnt(self, min_cnt):\n \"\"\"\n filter the tokens in vocab by their count\n Args:\n min_cnt: tokens with frequency less than min_cnt is filtered\n \"\"\"\n filtered_tokens = [token for token in self.token2id if self.token_cnt[token] >= min_cnt]\n # rebuild the token x id map\n self.token2id = {}\n self.id2token = {}\n for token in self.initial_tokens:\n self.add(token, cnt=0)\n for token in filtered_tokens:\n self.add(token, cnt=0)\n\n def randomly_init_embeddings(self, embed_dim):\n \"\"\"\n randomly initializes the embeddings for each token\n Args:\n embed_dim: the size of the embedding for each token\n \"\"\"\n self.embed_dim = embed_dim\n self.embeddings = np.random.rand(self.size(), embed_dim)\n for token in [self.pad_token, self.unk_token]:\n self.embeddings[self.get_id(token)] = np.zeros([self.embed_dim])\n\n def load_pretrained_embeddings(self, embedding_path):\n \"\"\"\n loads the pretrained embeddings from embedding_path,\n tokens not in pretrained embeddings will be filtered\n Args:\n embedding_path: the path of the pretrained embedding file\n \"\"\"\n trained_embeddings = {}\n with open(embedding_path, 'r',encoding='utf-8') as fin:\n for line in fin:\n contents = line.strip().split()\n token = contents[0]\n if token not in self.token2id:\n continue\n trained_embeddings[token] = list(map(float, contents[1:]))\n if self.embed_dim is None:\n self.embed_dim = len(contents) - 1\n filtered_tokens = trained_embeddings.keys()\n # rebuild the token x id map\n self.token2id = {}\n self.id2token = {}\n for token in self.initial_tokens:\n self.add(token, cnt=0)\n for token in filtered_tokens:\n self.add(token, cnt=0)\n # load embeddings\n self.embeddings = np.zeros([self.size(), self.embed_dim])\n for token in self.token2id.keys():\n if token in trained_embeddings:\n self.embeddings[self.get_id(token)] = trained_embeddings[token]\n\n def convert_to_ids(self, tokens):\n \"\"\"\n Convert a list of tokens to ids, use unk_token if the token is not in vocab.\n Args:\n tokens: a list of token\n Returns:\n a list of ids\n \"\"\"\n vec = [self.get_id(label) for label in tokens]\n return vec\n\n def recover_from_ids(self, ids, stop_id=None):\n \"\"\"\n Convert a list of ids to tokens, stop converting if the stop_id is encountered\n Args:\n ids: a list of ids to convert\n stop_id: the stop id, default is None\n Returns:\n a list of tokens\n \"\"\"\n tokens = []\n for i in ids:\n tokens += [self.get_token(i)]\n if stop_id is not None and i == stop_id:\n break\n return tokens\n"
] |
[
[
"numpy.zeros"
]
] |
himbeles/geo3d
|
[
"b9a01868207e9f2c0364eb3a6c130c9304cde0b6"
] |
[
"tests/test_frame.py"
] |
[
"import pytest\n\nfrom numpy import sqrt\n\nfrom geo3d import (\n Frame,\n frame_wizard,\n Point,\n Vector,\n UnitFrame,\n RotationMatrix,\n transformation_between_frames,\n)\n\n\ndef test_frame_wizard():\n t = frame_wizard([0, 0, 1], [0, 1, 0], \"z\", \"y\", [0, 0, 0])\n assert t == UnitFrame\n\n\ndef test_manual_frame_creation():\n rot = RotationMatrix.from_euler_angles(\"xyz\", [90, -45, 45], degrees=True)\n vec = Vector([3, 4, 6])\n f = Frame(rotation_matrix=rot, translation_vector=vec)\n assert f.translation == vec\n assert f.rotation == rot\n\n\ndef test_express_frame_in_frame(example_frames):\n fa,fb,fc = example_frames\n t = fb.express_in_frame(fa)\n assert t.euler_angles(\"XYZ\", degrees=True) == pytest.approx([180, 0, -45])\n assert t.translation.as_array() == pytest.approx([sqrt(2), 0, -4])\n\n\ndef test_transformation_between_frames(example_frames):\n fa,fb,fc = example_frames\n t = transformation_between_frames(fa, fb)\n assert t.euler_angles(\"XYZ\", degrees=True) == pytest.approx([180, 0, -45])\n assert t.translation.as_array() == pytest.approx([1, 1, 4])\n"
] |
[
[
"numpy.sqrt"
]
] |
TWCurry/emotion-recognition-training-platform
|
[
"748fcdf2558fbfe9fb1523ef4024e7373543f0e3"
] |
[
"Training/testModel.py"
] |
[
"import sys, os\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\n\nimgHeight = 762\nimgWidth = 562\nemotionCodes = [\"AF\", \"AN\", \"DI\", \"HA\", \"NE\", \"SA\", \"SU\"]\nemotionNames = [\"Afraid\", \"Angry\", \"Disgusted\", \"Happy\", \"Neutral\", \"Sad\", \"Surprised\"]\n\ndef main():\n try:\n modelDir = sys.argv[1]\n except Exception as e:\n print(\"Invalid parameters.\")\n sys.exit(1)\n\n model = keras.models.load_model(modelDir)\n testImg = keras.preprocessing.image.load_img(\"dataSet/test5.jpg\")\n testArr = keras.preprocessing.image.img_to_array(testImg)\n testArr = np.array([testArr])\n probabilityModel = tf.keras.Sequential([model,tf.keras.layers.Softmax()]) # Create model to convert logits to probabilities\n predictions = probabilityModel.predict(testArr)\n # Predictions is list of lists, each list showing how confident the model is on each label\n # np.argmax returns index of highest value in list\n # so we just map that index to the index of the emotion codes to find what it thinks the emotion is\n print(predictions)\n print(\"======================PREDICTION======================\")\n print(f\"Predicted emotion: {emotionNames[np.argmax(predictions[0])]}\")\n print(\"======================================================\")\n\n # print(predictions)\n # print(np.argmax(predictions[0]))\n # print(emotionCodes[np.argmax(predictions[0])])\n plt.bar(emotionCodes, predictions[0])\n plt.xticks(emotionCodes)\n plt.show()\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"tensorflow.keras.models.load_model",
"tensorflow.keras.layers.Softmax",
"tensorflow.keras.preprocessing.image.load_img",
"numpy.argmax",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xticks",
"numpy.array",
"tensorflow.keras.preprocessing.image.img_to_array",
"matplotlib.pyplot.show"
]
] |
tk-ML/SALib
|
[
"2545a439ca474a673fddadf0399f7c4e21000d99"
] |
[
"tests/test_cli_analyze.py"
] |
[
"import sys\nimport subprocess\nfrom SALib.test_functions import Ishigami\nimport numpy as np\nimport re\n\nsalib_cli = \"./src/SALib/scripts/salib.py\"\nishigami_fp = \"./src/SALib/test_functions/params/Ishigami.txt\"\n\nif sys.version_info[0] == 2:\n subprocess.run = subprocess.call\n\n\ndef test_delta():\n cmd = \"python {cli} sample saltelli -p {fn} -o model_input.txt -n 1024\"\\\n .format(cli=salib_cli, fn=ishigami_fp) +\\\n \" --precision 8 --max-order 2 --seed=100\"\n subprocess.run(cmd.split())\n\n # Run model and save output\n np.savetxt('model_output.txt', Ishigami.evaluate(\n np.loadtxt('model_input.txt')))\n\n analyze_cmd = \"python {cli} analyze delta -p {fn} -X model_input.txt \\\n -Y model_output.txt -c 0 -r 10 --seed=100\".format(cli=salib_cli,\n fn=ishigami_fp).split()\n\n result = subprocess.check_output(analyze_cmd, universal_newlines=True)\n result = re.sub(r'[\\n\\t\\s]*', '', result)\n\n expected_output = 'Parameterdeltadelta_confS1S1_confx10.2122850.0074810.3123190.011463x20.3530150.0061840.4306860.013135x30.1613440.0057540.0013880.001545'\n assert len(result) > 0 and result in expected_output, \\\n \"Results did not match expected values:\\n\\n Expected: \\n{} \\n\\n Got: \\n{}\".format(\n expected_output, result)\n\n\ndef test_dgsm():\n # Generate inputs\n cmd = \"python {cli} sample finite_diff -p {fn} -o model_input.txt -d 0.001\\\n --precision=8 -n 1000 --seed=100\".format(cli=salib_cli,\n fn=ishigami_fp).split()\n subprocess.run(cmd)\n\n # Run model and save output\n np.savetxt('model_output.txt', Ishigami.evaluate(\n np.loadtxt('model_input.txt')))\n\n analyze_cmd = \"python {cli} analyze dgsm -p {fn} -X model_input.txt\\\n -Y model_output.txt -c 0 -r 1000 --seed=100\"\\\n .format(cli=salib_cli, fn=ishigami_fp).split()\n\n # run analysis and use regex to strip all whitespace from result\n result = subprocess.check_output(analyze_cmd, universal_newlines=True)\n result = re.sub(r'[\\n\\t\\s]*', '', result)\n\n expected = \"Parametervivi_stddgsmdgsm_confx17.69803416.3731482.2331100.986061x224.48770117.3199737.1035971.092944x311.05754523.7851003.2076651.488346\"\n\n assert len(result) > 0 and result == expected, \\\n \"Unexpected DGSM results.\\n\\nExpected:\\n{}\\n\\nGot:{}\"\\\n .format(expected, result)\n\n\ndef test_fast():\n # Generate inputs\n cmd = \"python {cli} sample fast_sampler -p {fn} -o model_input.txt \\\n --precision=8 -n 1000 -M 4 --seed=100\".format(cli=salib_cli,\n fn=ishigami_fp).split()\n subprocess.run(cmd)\n\n # Run model and save output\n np.savetxt('model_output.txt', Ishigami.evaluate(\n np.loadtxt('model_input.txt')))\n\n analyze_cmd = \"python {cli} analyze fast -p {fn} \\\n -Y model_output.txt -c 0 --seed=100\"\\\n .format(cli=salib_cli, fn=ishigami_fp).split()\n\n # run analysis and use regex to strip all whitespace from result\n result = subprocess.check_output(analyze_cmd, universal_newlines=True)\n result = re.sub(r'[\\n\\t\\s]*', '', result)\n\n expected = \"ParameterFirstTotalx10.3104030.555603x20.4425530.469546x30.0000000.239155\"\n\n assert len(result) > 0 and result == expected, \\\n \"Unexpected FAST results.\\n\\nExpected:\\n{}\\n\\nGot:{}\"\\\n .format(expected, result)\n\n\ndef test_ff():\n # Generate inputs\n cmd = \"python {cli} sample ff -p {fn} -o model_input.txt \\\n --precision=8 -n 1000 --seed=100\".format(cli=salib_cli,\n fn=ishigami_fp).split()\n subprocess.run(cmd)\n\n # Run model and save output\n np.savetxt('model_output.txt', Ishigami.evaluate(\n np.loadtxt('model_input.txt')))\n\n analyze_cmd = \"python {cli} analyze ff -p {fn} -X model_input.txt\\\n -Y model_output.txt -c 0 --seed=100\"\\\n .format(cli=salib_cli, fn=ishigami_fp).split()\n\n # run analysis and use regex to strip all whitespace from result\n result = subprocess.check_output(analyze_cmd, universal_newlines=True)\n result = re.sub(r'[\\n\\t\\s]*', '', result)\n\n expected = \"ParameterMEx10.000000x20.000000x30.000000dummy_00.000000('x1','x2')0.000000('x1','x3')0.000000('x2','x3')0.000000('x1','dummy_0')0.000000('x2','dummy_0')0.000000('x3','dummy_0')0.000000\"\n\n assert len(result) > 0 and result == expected, \\\n \"Unexpected FF results.\\n\\nExpected:\\n{}\\n\\nGot:{}\"\\\n .format(expected, result)\n\n\ndef test_morris():\n\n # Generate inputs\n cmd = \"python {cli} sample morris -p {fn} -o model_input.txt -n 100\\\n --precision=8 --levels=10 --seed=100 -lo False\"\\\n .format(cli=salib_cli, fn=ishigami_fp).split()\n\n subprocess.run(cmd)\n\n # Run model and save output\n np.savetxt('model_output.txt', Ishigami.evaluate(\n np.loadtxt('model_input.txt')))\n\n # run analysis\n analyze_cmd = \"python {cli} analyze morris -p {fn} -X model_input.txt\\\n -Y model_output.txt -c 0 -r 1000 -l 10 --seed=100\"\\\n .format(cli=salib_cli, fn=ishigami_fp).split()\n\n result = subprocess.check_output(analyze_cmd, universal_newlines=True)\n result = re.sub(r'[\\n\\t\\s]*', '', result)\n\n expected_output = \"\"\"ParameterMu_StarMuMu_Star_ConfSigmax17.4997.4991.8019.330x22.215-0.4700.3482.776x35.4240.8641.1487.862\"\"\"\n\n assert len(result) > 0 and result == expected_output, \\\n \"Results did not match expected values:\\n\\n Expected: \\n{} \\n\\n Got: \\n{}\".format(\n expected_output, result)\n\n\ndef test_rbd_fast():\n # Generate inputs\n cmd = \"python {cli} sample ff -p {fn} -o model_input.txt \\\n --precision=8 --seed=100\".format(cli=salib_cli, fn=ishigami_fp).split()\n\n subprocess.run(cmd)\n\n # Run model and save output\n np.savetxt('model_output.txt', Ishigami.evaluate(\n np.loadtxt('model_input.txt')))\n\n analyze_cmd = \"python {cli} analyze rbd_fast -p {fn} -X model_input.txt\\\n -Y model_output.txt --seed=100\"\\\n .format(cli=salib_cli, fn=ishigami_fp).split()\n\n # run analysis and use regex to strip all whitespace from result\n result = subprocess.check_output(analyze_cmd, universal_newlines=True)\n result = re.sub(r'[\\n\\t\\s]*', '', result)\n\n expected = \"ParameterFirstx10.39223x20.299578x30.0342307\"\n\n assert len(result) > 0 and result == expected, \\\n \"Unexpected RBD-FAST results.\\n\\nExpected:\\n{}\\n\\nGot:{}\"\\\n .format(expected, result)\n\n\ndef test_sobol():\n # Generate inputs\n cmd = \"python {cli} sample saltelli -p {fn} -o model_input.txt -n 1024\\\n --precision 8 --max-order 2 --seed=100\".format(cli=salib_cli,\n fn=ishigami_fp)\n cmd = cmd.split()\n\n result = subprocess.check_output(cmd, universal_newlines=True)\n np.savetxt('model_output.txt', Ishigami.evaluate(\n np.loadtxt('model_input.txt')))\n\n analyze_cmd = \"python {cli} analyze sobol -p {fn}\\\n -Y model_output.txt -c 0 --max-order 2\\\n -r 1000 --seed=100\".format(cli=salib_cli, fn=ishigami_fp).split()\n\n result = subprocess.check_output(analyze_cmd, universal_newlines=True)\n result = re.sub(r'[\\n\\t\\s]*', '', result)\n\n expected_output = 'ParameterS1S1_confSTST_confx10.3168320.0622410.5558600.085972x20.4437630.0560470.4418980.041596x30.0122030.0559540.2446750.025332Parameter_1Parameter_2S2S2_confx1x20.0092540.083829x1x30.2381720.101764x2x3-0.0048880.067819'\n assert len(result) > 0 and result == expected_output, \\\n \"Results did not match expected values:\\n\\n Expected: \\n{} \\n\\n Got: \\n{}\".format(\n expected_output, result)\n\n\nif __name__ == '__main__':\n test_delta()\n test_dgsm()\n test_fast()\n test_ff()\n test_morris()\n test_rbd_fast()\n test_sobol()\n"
] |
[
[
"numpy.loadtxt"
]
] |
sschoedel/lanenet-lane-detection
|
[
"210116a7d4d1324fcfb2b8b50404e4c3bf99811f"
] |
[
"test_lanenet.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 18-5-23 上午11:33\n# @Author : MaybeShewill-CV\n# @Site : https://github.com/MaybeShewill-CV/lanenet-lane-detection\n# @File : test_lanenet.py\n# @IDE: PyCharm Community Edition\n\"\"\"\ntest LaneNet model on single image\n\"\"\"\nimport argparse\nimport os.path as ops\nimport time\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nfrom lanenet_model import lanenet\nfrom lanenet_model import lanenet_postprocess\nfrom local_utils.config_utils import parse_config_utils\nfrom local_utils.log_util import init_logger\n\nCFG = parse_config_utils.lanenet_cfg\nLOG = init_logger.get_logger(log_file_name_prefix='lanenet_test')\n\n\ndef init_args():\n \"\"\"\n\n :return:\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--image_path', type=str, help='The image path or the src image save dir')\n parser.add_argument('--weights_path', type=str, help='The model weights path')\n\n return parser.parse_args()\n\n\ndef args_str2bool(arg_value):\n \"\"\"\n\n :param arg_value:\n :return:\n \"\"\"\n if arg_value.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n\n elif arg_value.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Unsupported value encountered.')\n\n\ndef minmax_scale(input_arr):\n \"\"\"\n\n :param input_arr:\n :return:\n \"\"\"\n min_val = np.min(input_arr)\n max_val = np.max(input_arr)\n\n output_arr = (input_arr - min_val) * 255.0 / (max_val - min_val)\n\n return output_arr\n\n\ndef test_lanenet(image_path, weights_path):\n \"\"\"\n\n :param image_path:\n :param weights_path:\n :return:\n \"\"\"\n assert ops.exists(image_path), '{:s} not exist'.format(image_path)\n\n LOG.info('Start reading image and preprocessing')\n t_start = time.time()\n image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n image_vis = image\n image = cv2.resize(image, (512, 256), interpolation=cv2.INTER_LINEAR)\n image = image / 127.5 - 1.0\n LOG.info('Image load complete, cost time: {:.5f}s'.format(time.time() - t_start))\n\n input_tensor = tf.placeholder(dtype=tf.float32, shape=[1, 256, 512, 3], name='input_tensor')\n\n net = lanenet.LaneNet(phase='test', cfg=CFG)\n binary_seg_ret, instance_seg_ret = net.inference(input_tensor=input_tensor, name='LaneNet')\n\n postprocessor = lanenet_postprocess.LaneNetPostProcessor(cfg=CFG)\n\n # Set sess configuration\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.per_process_gpu_memory_fraction = CFG.GPU.GPU_MEMORY_FRACTION\n sess_config.gpu_options.allow_growth = CFG.GPU.TF_ALLOW_GROWTH\n sess_config.gpu_options.allocator_type = 'BFC'\n\n sess = tf.Session(config=sess_config)\n\n # define moving average version of the learned variables for eval\n with tf.variable_scope(name_or_scope='moving_avg'):\n variable_averages = tf.train.ExponentialMovingAverage(\n CFG.SOLVER.MOVING_AVE_DECAY)\n variables_to_restore = variable_averages.variables_to_restore()\n\n # define saver\n saver = tf.train.Saver(variables_to_restore)\n # saver = tf.train.import_meta_graph(variables_to_restore)\n\n with sess.as_default():\n saver.restore(sess=sess, save_path=weights_path)\n # print(\"weights path\")\n # print(weights_path)\n # saver.restore(sess, tf.train.latest_checkpoint(weights_path))\n\n t_start = time.time()\n loop_times = 500\n for i in range(loop_times):\n binary_seg_image, instance_seg_image = sess.run(\n [binary_seg_ret, instance_seg_ret],\n feed_dict={input_tensor: [image]}\n )\n t_cost = time.time() - t_start\n t_cost /= loop_times\n LOG.info('Single image inference cost time: {:.5f}s'.format(t_cost))\n\n postprocess_result = postprocessor.postprocess(\n binary_seg_result=binary_seg_image[0],\n instance_seg_result=instance_seg_image[0],\n source_image=image_vis\n )\n mask_image = postprocess_result['mask_image']\n\n for i in range(CFG.MODEL.EMBEDDING_FEATS_DIMS):\n instance_seg_image[0][:, :, i] = minmax_scale(instance_seg_image[0][:, :, i])\n embedding_image = np.array(instance_seg_image[0], np.uint8)\n\n plt.figure('mask_image')\n plt.imshow(mask_image[:, :, (2, 1, 0)])\n plt.figure('src_image')\n plt.imshow(image_vis[:, :, (2, 1, 0)])\n plt.figure('instance_image')\n plt.imshow(embedding_image[:, :, (2, 1, 0)])\n plt.figure('binary_image')\n plt.imshow(binary_seg_image[0] * 255, cmap='gray')\n plt.show()\n\n sess.close()\n\n return\n\n\nif __name__ == '__main__':\n \"\"\"\n test code\n \"\"\"\n # init args\n args = init_args()\n\n test_lanenet(args.image_path, args.weights_path)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.min",
"tensorflow.placeholder",
"tensorflow.ConfigProto",
"numpy.max",
"tensorflow.train.ExponentialMovingAverage",
"tensorflow.variable_scope",
"tensorflow.Session",
"tensorflow.train.Saver",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
DAIZHENWEI/FastGCN_pytorch
|
[
"87efe350d5acbe517a0642e9862ac9676b55c053",
"87efe350d5acbe517a0642e9862ac9676b55c053"
] |
[
"train_sage_EL2N_increment.py",
"train_sage_AGE.py"
] |
[
"import argparse\nimport time\nimport os\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport dgl\nimport torch.nn as nn\nimport dgl.nn.pytorch as dglnn\nimport numpy as np\nimport pdb\nimport tqdm\nfrom scipy.sparse.linalg import norm as sparse_norm\nfrom utils import get_batches, accuracy, Entropy_loss\nfrom utils import sparse_mx_to_torch_sparse_tensor\nfrom utils_sage import load_data\nfrom models import SAGE\nimport pdb\n\n\ndef compute_acc(pred, labels):\n \"\"\"\n Compute the accuracy of prediction given the labels.\n \"\"\"\n return (torch.argmax(pred, dim=1) == labels).float().sum() / len(pred)\n\ndef evaluate(model, g, nfeat, labels, val_nid, test_nid, device):\n \"\"\"\n Evaluate the model on the validation set specified by ``val_mask``.\n g : The entire graph.\n inputs : The features of all the nodes.\n labels : The labels of all the nodes.\n val_mask : A 0-1 mask indicating which nodes do we actually compute the accuracy for.\n device : The GPU device to evaluate on.\n \"\"\"\n model.eval()\n with torch.no_grad():\n pred = model.inference(g, nfeat, device, args)\n model.train()\n return compute_acc(pred[test_nid], labels[test_nid]), pred\n\ndef load_subtensor(nfeat, labels, seeds, input_nodes):\n \"\"\"\n Extracts features and labels for a set of nodes.\n \"\"\"\n batch_inputs = nfeat[input_nodes]\n batch_labels = labels[seeds]\n return batch_inputs, batch_labels\n\n#### Entry point\ndef run(args, model, device, data, epochs, get_embed = False):\n # Unpack data\n train_nid, val_nid, test_nid, in_feats, labels, n_classes, nfeat, g = data\n\n # Create PyTorch DataLoader for constructing blocks\n sampler = dgl.dataloading.MultiLayerNeighborSampler(\n [int(fanout) for fanout in args.fan_out.split(',')])\n dataloader = dgl.dataloading.NodeDataLoader(\n g,\n train_nid,\n sampler,\n batch_size=args.batchsize,\n shuffle=True,\n drop_last=False,\n num_workers=args.num_workers)\n\n # Training loop\n avg = 0\n iter_tput = []\n best_eval_acc = 0\n best_test_acc = 0\n test_acc_list = []\n for epoch in range(epochs):\n tic = time.time()\n\n # Loop over the dataloader to sample the computation dependency graph as a list of\n # blocks.\n for step, (input_nodes, seeds, blocks) in enumerate(dataloader):\n tic_step = time.time()\n\n # copy block to gpu\n blocks = [blk.int().to(device) for blk in blocks]\n\n # Load the input features as well as output labels\n batch_inputs, batch_labels = load_subtensor(nfeat, labels, seeds, input_nodes)\n\n # Compute loss and prediction\n batch_pred = model(blocks, batch_inputs)\n loss = loss_fcn(batch_pred, batch_labels)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n iter_tput.append(len(seeds) / (time.time() - tic_step))\n if step % args.log_every == 0:\n acc = compute_acc(batch_pred, batch_labels)\n gpu_mem_alloc = torch.cuda.max_memory_allocated() / 1000000 if torch.cuda.is_available() else 0\n print('Epoch {:05d} | Step {:05d} | Loss {:.4f} | Train Acc {:.4f} | Speed (samples/sec) {:.4f} | GPU {:.1f} MB'.format(\n epoch, step, loss.item(), acc.item(), np.mean(iter_tput[3:]), gpu_mem_alloc))\n \n # print('Number of steps per epochs: {}'.format(step+1))\n\n toc = time.time()\n print('Epoch Time(s): {:.4f}'.format(toc - tic))\n if epoch >= 5:\n avg += toc - tic\n if epoch % args.eval_every == 0:\n test_acc, pred = evaluate(model, g, nfeat, labels, val_nid, test_nid, device)\n if args.save_pred:\n np.savetxt(args.save_pred + '%02d' % epoch, pred.argmax(1).cpu().numpy(), '%d')\n # print('Eval Acc {:.4f}'.format(eval_acc))\n # if eval_acc > best_eval_acc:\n # best_eval_acc = eval_acc\n # best_test_acc = test_acc\n print('Test Acc {:.4f}'.format(test_acc))\n test_acc_list += [test_acc.cpu().numpy()]\n # print('Avg epoch time: {}'.format(avg / (epoch - 4)))\n if get_embed:\n return test_acc_list, pred\n return test_acc_list\n\n\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser(\"multi-gpu training\")\n argparser.add_argument('--dataset', type=str, default='cora', help='dataset name.')\n argparser.add_argument('--gpu', type=int, default=0,\n help=\"GPU device ID. Use -1 for CPU training\")\n argparser.add_argument('--pre_train_epochs', type=int, default=100, help='Number of pre-training epochs.')\n argparser.add_argument('--epochs', type=int, default=1000, help='Number of epochs to train.')\n argparser.add_argument('--num-layers', type=int, default=3)\n argparser.add_argument('--fan-out', type=str, default='5,5,5')\n argparser.add_argument('--val-batch-size', type=int, default=10000)\n argparser.add_argument('--log-every', type=int, default=10)\n argparser.add_argument('--eval-every', type=int, default=1)\n argparser.add_argument('--lr', type=float, default=0.001)\n argparser.add_argument('--hidden', type=int, default=64, help='Number of hidden units.')\n argparser.add_argument('--batchsize', type=int, default=256,\n help='batchsize for train')\n argparser.add_argument('--sample_freq', type=int, default=20, help = 'frequnecy of resampling nodes with large uncertainties')\n argparser.add_argument('--dropout', type=float, default=0.0)\n argparser.add_argument('--seed', type=int, default=123, help='Random seed.')\n argparser.add_argument('--num-workers', type=int, default=4, help=\"Number of sampling processes. Use 0 for no extra process.\")\n argparser.add_argument('--pretrain_ratio', type=float, default=0.05,\n help='Proportion of samples used for training')\n argparser.add_argument('--ratio', type=float, default=0.01,\n help='Proportion of samples picked at each round')\n argparser.add_argument('--save-pred', type=str, default='')\n argparser.add_argument('--wd', type=float, default=0)\n argparser.add_argument('--remove_degree_one', action='store_true', default=False,\n help='Recursively remove the nodes with degree one from the adjacency matrix (remove corresponding edges).')\n args = argparser.parse_args()\n \n\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.gpu != -1:\n torch.cuda.manual_seed(args.seed)\n\n if args.gpu >= 0:\n device = torch.device('cuda:%d' % args.gpu)\n else:\n device = torch.device('cpu')\n\n # load ogbn-products data\n train_index, valid_index, test_index, in_feats, labels, n_classes, feats, graph, adj_train, _ = load_data(args.dataset, args)\n y_train = labels[train_index]\n y_train_onehot = F.one_hot(y_train, num_classes=n_classes)\n\n # \"\"\" Pick the nodes with large laplacian norm\"\"\"\n # col_norm = sparse_norm(adj_train, axis=0)\n # train_probs = col_norm / np.sum(col_norm)\n # # train_probs = torch.from_numpy(train_probs)\n # train_index = train_index.numpy()\n # num_sampled = int(len(train_index) * args.ratio)\n # train_ind_sort = torch.from_numpy(train_index[train_probs.argsort()[::-1]])\n # train_ind_sampled = train_ind_sort[:num_sampled]\n\n # Define model and optimizer\n model = SAGE(in_feats, args.hidden, n_classes, args.num_layers, F.relu, args.dropout)\n model = model.to(device)\n loss_fcn = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.wd)\n\n\n num_train_sampled = []\n \"\"\" randomly pick nodes \"\"\"\n train_index = train_index.numpy()\n num_sampled = int(len(train_index) * args.pretrain_ratio)\n train_ind_sampled = np.random.choice(train_index, num_sampled, replace = False)\n\n labels = labels.to(device)\n feats = feats.to(device)\n data = train_ind_sampled, valid_index, test_index, in_feats, labels, n_classes, feats, graph\n\n \"\"\" pretraining model \"\"\"\n test_accs, pred = run(args, model, device, data, args.pre_train_epochs, get_embed=True)\n test_acc_list = test_accs\n num_train_sampled = [num_sampled] * args.pre_train_epochs\n\n \"\"\" Continue training \"\"\"\n Entropy = Entropy_loss()\n sample_freq = args.sample_freq\n for epochs in range(0, (args.epochs - args.pre_train_epochs) // sample_freq):\n y_pred = pred[train_index].detach().cpu()\n EL2N = torch.norm((y_pred - y_train_onehot), dim = 1).numpy()\n del pred\n \"\"\" Pick nodes with large uncertainty \"\"\"\n num_sampled = int(len(train_index) * args.ratio)\n train_index_sort = torch.from_numpy(train_index[EL2N.argsort()[::-1]])\n train_ind_new = train_index_sort[:num_sampled]\n train_ind_new_sampled = np.intersect1d(train_ind_new, train_ind_sampled)\n train_ind_sampled = np.unique(np.concatenate((train_ind_sampled, train_ind_new)))\n print(\"Number of newly picked samples: {}, Number of total selected samples: {}\".format(len(train_ind_new), len(train_ind_sampled)))\n print(\"Number of large entropy nodes already sampled: {}\".format(len(train_ind_new_sampled)))\n data = train_ind_sampled, valid_index, test_index, in_feats, labels, n_classes, feats, graph\n test_accs, pred = run(args, model, device, data, sample_freq, get_embed=True)\n test_acc_list += test_accs\n num_train_sampled += [len(train_ind_sampled)] * sample_freq\n\n\n directory = './save/{}/'.format(args.dataset)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n # np.save('./save/GraphSage_accuracy_list_{}_active_laplacian_uncertain_epochs{}_pretrain{}_ratio{}.npy'.format(args.dataset, \n # args.epochs,\n # args.pre_train_epochs, \n # args.ratio), test_acc_list)\n\n np.save(directory + 'GraphSage_accuracy_list_{}_active_random_EL2N_increment_pretrain{}_epochs{}_pretrain_ratio{}_ratio{}_sample_freq{}.npy'.format(args.dataset, \n args.pre_train_epochs, \n args.epochs,\n args.pretrain_ratio,\n args.ratio,\n args.sample_freq), test_acc_list)\n\n np.save(directory + 'Sample_count_list_{}_active_random_EL2N_increment_pretrain{}_epochs{}_pretrain_ratio{}_ratio{}_sample_freq{}.npy'.format(args.dataset, \n args.pre_train_epochs, \n args.epochs,\n args.pretrain_ratio,\n args.ratio,\n args.sample_freq), num_train_sampled)",
"import argparse\nimport time\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport dgl\nimport dgl.nn.pytorch as dglnn\nimport numpy as np\nimport numpy.linalg as LA\nimport collections\nimport random\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import f1_score\nimport copy\nimport pdb\nimport tqdm\nimport pickle\nfrom scipy.sparse.linalg import norm as sparse_norm\nfrom sklearn.metrics.pairwise import euclidean_distances\nfrom utils import get_batches, accuracy, Entropy_loss\nfrom utils import sparse_mx_to_torch_sparse_tensor\nfrom utils_sage import load_data, margin_score, dataloader, compute_pagerank, perc, percd, perc_input, percd_input\nfrom models import SAGE\n\ndef binary_search(cluster_size_sample, n_sampled, cluster_size):\n if len(cluster_size) == n_sampled:\n return [1] * n_sampled\n cluster_sampled = [max(1, min(int(size), upper)) for size, upper in zip(cluster_size_sample, cluster_size)]\n sum_cluster_sampled = sum(cluster_sampled)\n if sum_cluster_sampled > n_sampled:\n l, r = 0.5, 1.0\n else:\n l, r = 1.0, 1.5\n diff = 1\n while diff:\n mid = (l+r)/2\n l_sampled = [max(1, min(int(size*l), upper)) for size, upper in zip(cluster_size_sample, cluster_size)]\n new_sampled = [max(1, min(int(size*mid), upper)) for size, upper in zip(cluster_size_sample, cluster_size)]\n sum_new_sampled = sum(new_sampled)\n if sum_new_sampled > n_sampled:\n r = mid\n else:\n l = mid\n diff = sum_new_sampled - sum(l_sampled)\n print(diff)\n return l_sampled\n \ndef random_round_robin(Kt, candidates, cluster_dict):\n if len(candidates) == Kt:\n return np.array(candidates)\n cand_clusters=collections.defaultdict(list)\n # pdb.set_trace()\n for cand in candidates:\n cand_clusters[cluster_dict[cand]].append(cand)\n\n for key in cand_clusters:\n random.shuffle(cand_clusters[key])\n S = []\n i = 0\n while i < Kt:\n for key in cand_clusters:\n if cand_clusters[key]:\n item = cand_clusters[key].pop()\n S.append(item)\n i += 1\n return np.array(S)\n\n\ndef Kmeans_sample(Kt, candidates, feats):\n if len(candidates) == Kt:\n return np.array(candidates)\n feats_sample = feats[candidates]\n kmeans = KMeans(n_clusters=Kt, random_state=0).fit(feats_sample)\n Kcenters = kmeans.cluster_centers_\n train_ind_sampled = []\n for center in Kcenters:\n dists = LA.norm(feats_sample - center, axis = 1)\n train_index_sort = candidates[dists.argsort()]\n train_ind_sampled.append(train_index_sort[0])\n return np.array(train_ind_sampled)\n\n\n\ndef compute_acc(pred, labels):\n \"\"\"\n Compute the accuracy of prediction given the labels.\n \"\"\"\n return (torch.argmax(pred, dim=1) == labels).float().sum() / len(pred)\n\ndef macro_f1(pred, labels):\n labels_pred = torch.argmax(pred, dim=1).detach().cpu()\n labels = labels.detach().cpu()\n return f1_score(labels_pred, labels, average='macro')\n\n\ndef evaluate(model, g, nfeat, labels, val_nid, test_nid, device):\n \"\"\"\n Evaluate the model on the validation set specified by ``val_mask``.\n g : The entire graph.\n inputs : The features of all the nodes.\n labels : The labels of all the nodes.\n val_mask : A 0-1 mask indicating which nodes do we actually compute the accuracy for.\n device : The GPU device to evaluate on.\n \"\"\"\n model.eval()\n with torch.no_grad():\n pred = model.inference(g, nfeat, device, args)\n model.train()\n return compute_acc(pred[test_nid], labels[test_nid]), macro_f1(pred[test_nid], labels[test_nid]), pred\n\ndef load_subtensor(nfeat, labels, seeds, input_nodes):\n \"\"\"\n Extracts features and labels for a set of nodes.\n \"\"\"\n batch_inputs = nfeat[input_nodes]\n batch_labels = labels[seeds]\n return batch_inputs, batch_labels\n\nclass GraphSage:\n def __init__(self, args, device, data):\n self.args = args\n self.device = device\n self.train_nid, self.val_nid, self.test_nid, self.in_feats, self.labels, self.n_classes, self.nfeat, self.g = data\n self.sampler = dgl.dataloading.MultiLayerNeighborSampler(\n [int(fanout) for fanout in args.fan_out.split(',')])\n self.model = SAGE(self.in_feats, self.args.hidden, self.n_classes, self.args.num_layers, F.relu, self.args.dropout)\n self.model = self.model.to(device)\n self.loss_fcn = nn.CrossEntropyLoss()\n self.optimizer = optim.Adam(self.model.parameters(), lr=args.lr, weight_decay=args.wd)\n\n def run(self, epochs=None, return_embed=False):\n # Training loop\n avg = 0\n iter_tput = []\n test_acc_list = []\n test_f1_list = []\n dataloader = self.dataloader(self.args.batchsize, shuffle=True)\n if epochs is None:\n epochs = self.args.epochs\n for epoch in range(epochs):\n tic = time.time()\n # Loop over the dataloader to sample the computation dependency graph as a list of\n # blocks.\n for step, (input_nodes, seeds, blocks) in enumerate(dataloader):\n tic_step = time.time()\n # copy block to gpu\n blocks = [blk.int().to(self.device) for blk in blocks]\n # Load the input features as well as output labels\n batch_inputs, batch_labels = load_subtensor(self.nfeat, self.labels, seeds, input_nodes)\n\n # Compute loss and prediction\n batch_pred = self.model(blocks, batch_inputs)\n loss = self.loss_fcn(batch_pred, batch_labels)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n iter_tput.append(len(seeds) / (time.time() - tic_step))\n if step % args.log_every == 0:\n acc = compute_acc(batch_pred, batch_labels)\n gpu_mem_alloc = torch.cuda.max_memory_allocated() / 1000000 if torch.cuda.is_available() else 0\n print('Epoch {:05d} | Step {:05d} | Loss {:.4f} | Train Acc {:.4f} | Speed (samples/sec) {:.4f} | GPU {:.1f} MB'.format(\n epoch, step, loss.item(), acc.item(), np.mean(iter_tput[3:]), gpu_mem_alloc))\n toc = time.time()\n print('Epoch Time(s): {:.4f}'.format(toc - tic))\n if epoch % args.eval_every == 0:\n test_acc, test_f1, pred = self.evaluation()\n test_acc_list += [test_acc.cpu().numpy()]\n test_f1_list += [test_f1]\n if return_embed:\n return test_acc_list, test_f1_list, pred\n\n return test_acc_list, test_f1_list \n\n def compute_gradient(self):\n dataloader = self.dataloader(batchsize=1, shuffle=False)\n grad_norm = []\n for step, (input_nodes, seeds, blocks) in enumerate(dataloader):\n tic_step = time.time()\n # copy block to gpu\n blocks = [blk.int().to(device) for blk in blocks]\n # Load the input features as well as output labels\n batch_inputs, batch_labels = load_subtensor(self.nfeat, self.labels, seeds, input_nodes)\n\n # Compute loss and prediction\n batch_pred = self.model(blocks, batch_inputs)\n loss = self.loss_fcn(batch_pred, batch_labels)\n self.optimizer.zero_grad()\n loss.backward()\n norm = sum([torch.norm(p.grad).item() for p in self.model.parameters()])\n grad_norm.append(norm)\n if step % 200 == 0:\n print('Number of steps {:.4f}'.format(step))\n return np.array(grad_norm)\n\n\n def evaluation(self):\n test_acc, test_f1, pred = evaluate(self.model, self.g, self.nfeat, self.labels, self.val_nid, self.test_nid, self.device)\n print('Test Acc {:.4f}'.format(test_acc))\n print('Test Macro F1 {:.4f}'.format(test_f1))\n return test_acc, test_f1, pred\n\n def dataloader(self, batchsize, shuffle = True):\n return dgl.dataloading.NodeDataLoader(self.g, self.train_nid, self.sampler, batch_size=batchsize,\n shuffle=shuffle, drop_last=False, num_workers=self.args.num_workers) \n \n\n\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser(\"multi-gpu training\")\n argparser.add_argument('--dataset', type=str, default='cora', help='dataset name.')\n argparser.add_argument('--gpu', type=int, default=0,\n help=\"GPU device ID. Use -1 for CPU training\")\n argparser.add_argument('--pre_train_epochs', type=int, default=20, help='Number of pre-training epochs.')\n argparser.add_argument('--epochs', type=int, default=1000, help='Number of epochs to train.')\n argparser.add_argument('--num-layers', type=int, default=3)\n argparser.add_argument('--prop-layers', type=int, default=3)\n argparser.add_argument('--fan-out', type=str, default='5,5,5')\n argparser.add_argument('--val-batch-size', type=int, default=10000)\n argparser.add_argument('--log-every', type=int, default=10)\n argparser.add_argument('--eval-every', type=int, default=1)\n argparser.add_argument('--lr', type=float, default=0.001)\n argparser.add_argument('--hidden', type=int, default=64, help='Number of hidden units.')\n argparser.add_argument('--batchsize', type=int, default=256, help='batchsize for train')\n argparser.add_argument('--test_batchsize', type=int, default=2048, help='batchsize for testing')\n argparser.add_argument('--sample_freq', type=int, default=1, help = 'frequnecy of resampling nodes with large uncertainties')\n argparser.add_argument('--dropout', type=float, default=0.5)\n argparser.add_argument('--seed', type=int, default=123, help='Random seed.')\n argparser.add_argument('--num-workers', type=int, default=4,\n help=\"Number of sampling processes. Use 0 for no extra process.\")\n argparser.add_argument('--pretrain_ratio', type=float, default=0.01, help='Proportion of samples used for training')\n argparser.add_argument('--cluster_per_class', type=int, default=5, help='Number of clusters per class')\n argparser.add_argument('--sample_per_round', type=int, default=1, help='Number of samples per round')\n argparser.add_argument('--ratio', type=float, default=0.01, help='Proportion of samples used for training')\n argparser.add_argument('--save-pred', type=str, default='')\n argparser.add_argument('--wd', type=float, default=1e-4)\n args = argparser.parse_args()\n \n\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if args.gpu != -1:\n torch.cuda.manual_seed(args.seed)\n\n if args.gpu >= 0:\n device = torch.device('cuda:%d' % args.gpu)\n else:\n device = torch.device('cpu')\n\n \"\"\" Load dataset \"\"\"\n loader = dataloader(args.dataset, args)\n train_index, valid_index, test_index, in_feats, labels, n_classes, feats, graph = loader.get_DGL_GCN_inputs()\n\n\n \"\"\" Compute the pagerank centrality \"\"\"\n pagerank = compute_pagerank(graph)\n train_pagerank = pagerank[train_index]\n\n ## Compute the pagerank score\n if args.dataset not in ['pubmed', 'corafull', 'ogbn-products']:\n pagerank_perc = np.asarray([perc(train_pagerank, i) for i in range(len(train_pagerank))])\n else:\n pagerank_perc = perc_input(train_pagerank)\n\n\n num_train = len(train_index)\n num_test = len(test_index)\n train_index = train_index.numpy()\n test_index = test_index.numpy()\n n_sampled = int(args.pretrain_ratio * num_train)\n \n train_ind_sampled = np.random.choice(train_index, n_sampled, replace=False)\n train_ind_sampled = torch.from_numpy(train_ind_sampled)\n print(\"number of sampled nodes: {}:\".format(n_sampled))\n\n labels = labels.to(device)\n feats = feats.to(device)\n\n data = train_ind_sampled, valid_index, test_index, in_feats, labels, n_classes, feats, graph\n\n \"\"\" Pre-training model \"\"\"\n test_accs_list, test_f1_list, num_train_sampled = [], [], []\n GraphModel = GraphSage(args, device, data)\n test_accs, test_f1, pred = GraphModel.run(epochs=args.pre_train_epochs, return_embed=True)\n test_accs_list += test_accs\n test_f1_list += test_f1\n\n NCL = n_classes * args.cluster_per_class\n\n \"\"\" Continue training \"\"\"\n Entropy = Entropy_loss()\n num_total_sampled = int(num_train * args.ratio)\n epoch = 0\n basef = 0.995\n while len(train_ind_sampled) < num_total_sampled: \n gamma = np.random.beta(1, 1.005-basef**epoch)\n alpha = beta = (1-gamma)/2\n ## compute entropy\n entropy_score = Entropy(pred).detach().cpu().numpy()\n train_entropy = entropy_score[train_index]\n if args.dataset not in ['pubmed', 'corafull', 'ogbn-products']:\n entropy_perc = np.asarray([perc(train_entropy,i) for i in range(len(train_entropy))])\n else:\n entropy_perc = perc_input(train_entropy)\n ## compute density score\n pred = pred.detach().cpu().numpy()\n train_pred = pred[train_index]\n kmeans = KMeans(n_clusters=NCL, random_state=0).fit(train_pred)\n ed=euclidean_distances(train_pred, kmeans.cluster_centers_)\n ed_score = np.min(ed,axis=1)\n if args.dataset not in ['pubmed', 'corafull', 'ogbn-products']:\n ed_perc = np.asarray([percd(ed_score,i) for i in range(len(ed_score))])\n else:\n ed_perc = percd_input(ed_score)\n finalweight = alpha*entropy_perc + beta*ed_perc + gamma*pagerank_perc\n\n train_index_sort = torch.from_numpy(train_index[finalweight.argsort()[::-1]])\n ix = 0\n for _ in range(args.sample_per_round):\n while train_index_sort[ix].item() in train_ind_sampled:\n ix += 1\n train_ind_sampled = np.append(train_ind_sampled, train_index_sort[ix])\n print(\"Number of total selected samples: {}\".format(len(train_ind_sampled)))\n GraphModel.train_nid = train_ind_sampled\n test_accs, test_f1, pred = GraphModel.run(epochs=args.sample_freq, return_embed=True)\n test_accs_list += test_accs\n test_f1_list += test_f1\n epoch += 1\n \n test_accs, test_f1 = GraphModel.run(epochs=100)\n test_accs_list += test_accs\n test_f1_list += test_f1\n\n directory = './save/{}/'.format(args.dataset)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\n np.save(directory + 'GraphSage_accuracy_list_{}_AGE_ratio{}.npy'.format(args.dataset, args.ratio), test_accs_list)\n\n np.save(directory + 'GraphSage_macro_f1_{}_AGE_ratio{}.npy'.format(args.dataset, args.ratio), test_f1_list)"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.norm",
"numpy.random.seed",
"numpy.random.choice",
"torch.cuda.manual_seed",
"torch.manual_seed",
"numpy.concatenate",
"numpy.intersect1d",
"torch.cuda.max_memory_allocated",
"torch.no_grad",
"numpy.mean",
"torch.cuda.is_available",
"torch.nn.functional.one_hot",
"torch.device",
"torch.argmax"
],
[
"sklearn.cluster.KMeans",
"torch.no_grad",
"numpy.mean",
"torch.cuda.is_available",
"torch.device",
"sklearn.metrics.f1_score",
"torch.nn.CrossEntropyLoss",
"torch.norm",
"numpy.random.beta",
"torch.from_numpy",
"numpy.random.choice",
"numpy.min",
"sklearn.metrics.pairwise.euclidean_distances",
"numpy.append",
"numpy.array",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.manual_seed",
"numpy.linalg.norm",
"torch.cuda.max_memory_allocated",
"torch.argmax"
]
] |
lavoiems/NeuralWassersteinFlow
|
[
"b120778d75fc7afc9b6a56724768ab39ad7c0b91"
] |
[
"src/models/legendre_duality/train.py"
] |
[
"import time\nimport torch\nfrom torch import optim\nfrom sklearn.decomposition import PCA\nimport matplotlib.pylab as plt\nimport torch.nn.functional as F\n\nfrom common.util import sample, save_models\nfrom common.initialize import initialize, infer_iteration\nfrom . import model\n\n\ndef c_transform(y, ey, lp, critic):\n cy = critic(ey)\n cost = (ey.view(ey.shape[0], -1) - y.view(y.shape[0], -1)).abs().pow(lp).sum(1)\n return (cy - cost).mean()\n\n\ndef encoder_loss(batch_size, lp, z_dim, encoder, generator, critic, device):\n z = torch.randn(batch_size, z_dim, device=device)\n y = generator(z).detach()\n ey = encoder(y)\n return c_transform(y, ey, lp, critic)\n\n\ndef critic_loss(x, lp, z_dim, encoder, critic, generator, device):\n f = critic(x).mean()\n z = torch.randn(x.shape[0], z_dim, device=device)\n y = generator(z).detach()\n ey = encoder(y).detach()\n return f - critic(e(y))\n\n\ndef transfer_loss(batch_size, lp, z_dim, encoder, critic, generator, device):\n z = torch.randn(batch_size, z_dim, device=device)\n y = generator(z)\n ey = encoder(y).detach()\n return -c_transform(y, ey, lp, critic)\n\n\ndef define_models(shape1, **parameters):\n critic = model.Critic(shape1[0], shape1[1], **parameters)\n generator = model.Generator(shape1[0], shape1[1], **parameters)\n encoder = model.Encoder(shape1[0], shape1[1], **parameters)\n return {\n 'generator': generator,\n 'critic': critic,\n 'encoder': encoder,\n }\n\n\ndef evaluate(visualiser, nz, data, encoder, generator, critic, z_dim, id, device):\n z = torch.randn(data.shape[0], nz, device=device)\n z.requires_grad = True\n dec = generator(z)\n visualiser.image(dec.cpu().detach().numpy(), title=f'GAN generated', step=id)\n visualiser.image(data.cpu().numpy(), title=f'Target', step=id)\n\n enc = encoder(dec)\n visualiser.image(enc.cpu().detach().numpy(), title=f'GAN encoded', step=id)\n\n\[email protected]_grad()\ndef evaluate_clusters(visualiser, encoder, target, label, id):\n enc = encoder(target)\n pca = PCA(2)\n emb = pca.fit_transform(enc.reshape(enc.shape[0], -1).cpu().squeeze().numpy())\n fig = plt.figure()\n colors = [f'C{c}' for c in label.cpu().numpy()]\n plt.scatter(*emb.transpose(), c=colors)\n visualiser.matplotlib(fig, f'Embeddings {id}', None)\n plt.clf()\n plt.close(fig)\n\n\[email protected]_grad()\ndef evaluate_distance(visualiser, encoder, loader1, loader2, device):\n ds = torch.zeros(10, 10, device=device)\n totals = torch.zeros(10, 10, device=device)\n for b1, b2 in zip(loader1, loader2):\n d1, d2 = b1[0].to(device), b2[0].to(device)\n l1, l2 = b1[1].to(device), b2[1].to(device)\n z1, z2 = encoder(d1), encoder(d2)\n dist = F.pairwise_distance(z1, z2, 2)\n ds[l1, l2] += dist\n ds[l2, l1] += dist\n totals[l1, l2] += 1\n totals[l2, l1] += 1\n avgs = ds / totals\n\n fig, ax = plt.subplots()\n im = ax.imshow(avgs.cpu().numpy())\n for i, row in enumerate(avgs):\n for j, point in enumerate(row):\n text = ax.text(j, i, f'{point.cpu().item():.3f}', ha='center', va='center', color='w', size=6)\n visualiser.matplotlib(fig, 'distances', None)\n plt.clf()\n plt.close(fig)\n\n\ndef train(args):\n parameters = vars(args)\n train_loader1, test_loader1 = args.loaders1\n\n models = define_models(**parameters)\n initialize(models, args.reload, args.save_path, args.model_path)\n\n generator = models['generator'].to(args.device)\n critic = models['critic'].to(args.device)\n encoder = models['encoder'].to(args.device)\n print(generator)\n print(critic)\n print(encoder)\n\n optim_critic = optim.Adam(critic.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))\n optim_generator = optim.Adam(generator.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))\n optim_encoder = optim.Adam(encoder.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))\n\n iter1 = iter(train_loader1)\n iteration = infer_iteration(list(models.keys())[0], args.reload, args.model_path, args.save_path)\n titer1 = iter(test_loader1)\n mone = torch.FloatTensor([-1]).to(args.device)\n t0 = time.time()\n for i in range(iteration, args.iterations):\n generator.train()\n critic.train()\n encoder.train()\n\n for _ in range(10):\n batchx, iter1 = sample(iter1, train_loader1)\n data = batchx[0].to(args.device)\n optim_encoder.zero_grad()\n optim_generator.zero_grad()\n e_loss = encoder_loss(data.shape[0], args.lp, args.z_dim, encoder, generator, critic, args.device)\n e_loss.backward()\n optim_encoder.step()\n optim_generator.step()\n\n for _ in range(1):\n batchx, iter1 = sample(iter1, train_loader1)\n data = batchx[0].to(args.device)\n optim_critic.zero_grad()\n r_loss = critic_loss(data, args.lp, args.z_dim, encoder, critic, generator, args.device)\n r_loss.backward(mone)\n optim_critic.step()\n\n for _ in range(1):\n batchx, iter1 = sample(iter1, train_loader1)\n data = batchx[0].to(args.device)\n optim_generator.zero_grad()\n t_loss = transfer_loss(data.shape[0], args.lp, args.z_dim, encoder, critic, generator, args.device)\n t_loss.backward()\n optim_generator.step()\n\n if i % args.evaluate == 0:\n encoder.eval()\n generator.eval()\n print('Iter: %s' % i, time.time() - t0)\n batchx, titer1 = sample(titer1, test_loader1)\n data = batchx[0].to(args.device)\n evaluate(args.visualiser, args.z_dim, data, encoder, generator, critic, args.z_dim, i, args.device)\n d_loss = (r_loss).detach().cpu().numpy()\n args.visualiser.plot(step=i, data=d_loss, title=f'Critic loss')\n args.visualiser.plot(step=i, data=e_loss.detach().cpu().numpy(), title=f'Encoder loss')\n args.visualiser.plot(step=i, data=t_loss.detach().cpu().numpy(), title=f'Generator loss')\n t0 = time.time()\n save_models(models, i, args.model_path, args.checkpoint)\n"
] |
[
[
"torch.zeros",
"torch.randn",
"matplotlib.pylab.close",
"torch.nn.functional.pairwise_distance",
"matplotlib.pylab.figure",
"torch.no_grad",
"matplotlib.pylab.subplots",
"matplotlib.pylab.clf",
"torch.FloatTensor",
"sklearn.decomposition.PCA"
]
] |
phecda-xu/PaddleSpeech
|
[
"6bf0d3bf57229091a74912633e837dabc6215c86"
] |
[
"paddlespeech/t2s/exps/synthesize.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.\nimport argparse\nimport logging\nfrom pathlib import Path\n\nimport jsonlines\nimport numpy as np\nimport paddle\nimport soundfile as sf\nimport yaml\nfrom yacs.config import CfgNode\n\nfrom paddlespeech.s2t.utils.dynamic_import import dynamic_import\nfrom paddlespeech.t2s.datasets.data_table import DataTable\nfrom paddlespeech.t2s.modules.normalizer import ZScore\nfrom paddlespeech.t2s.utils import str2bool\n\nmodel_alias = {\n # acoustic model\n \"speedyspeech\":\n \"paddlespeech.t2s.models.speedyspeech:SpeedySpeech\",\n \"speedyspeech_inference\":\n \"paddlespeech.t2s.models.speedyspeech:SpeedySpeechInference\",\n \"fastspeech2\":\n \"paddlespeech.t2s.models.fastspeech2:FastSpeech2\",\n \"fastspeech2_inference\":\n \"paddlespeech.t2s.models.fastspeech2:FastSpeech2Inference\",\n \"tacotron2\":\n \"paddlespeech.t2s.models.tacotron2:Tacotron2\",\n \"tacotron2_inference\":\n \"paddlespeech.t2s.models.tacotron2:Tacotron2Inference\",\n # voc\n \"pwgan\":\n \"paddlespeech.t2s.models.parallel_wavegan:PWGGenerator\",\n \"pwgan_inference\":\n \"paddlespeech.t2s.models.parallel_wavegan:PWGInference\",\n \"mb_melgan\":\n \"paddlespeech.t2s.models.melgan:MelGANGenerator\",\n \"mb_melgan_inference\":\n \"paddlespeech.t2s.models.melgan:MelGANInference\",\n}\n\n\ndef evaluate(args):\n # dataloader has been too verbose\n logging.getLogger(\"DataLoader\").disabled = True\n\n # construct dataset for evaluation\n with jsonlines.open(args.test_metadata, 'r') as reader:\n test_metadata = list(reader)\n\n # Init body.\n with open(args.am_config) as f:\n am_config = CfgNode(yaml.safe_load(f))\n with open(args.voc_config) as f:\n voc_config = CfgNode(yaml.safe_load(f))\n\n print(\"========Args========\")\n print(yaml.safe_dump(vars(args)))\n print(\"========Config========\")\n print(am_config)\n print(voc_config)\n\n # construct dataset for evaluation\n\n # model: {model_name}_{dataset}\n am_name = args.am[:args.am.rindex('_')]\n am_dataset = args.am[args.am.rindex('_') + 1:]\n\n if am_name == 'fastspeech2':\n fields = [\"utt_id\", \"text\"]\n spk_num = None\n if am_dataset in {\"aishell3\", \"vctk\"} and args.speaker_dict:\n print(\"multiple speaker fastspeech2!\")\n with open(args.speaker_dict, 'rt') as f:\n spk_id = [line.strip().split() for line in f.readlines()]\n spk_num = len(spk_id)\n fields += [\"spk_id\"]\n elif args.voice_cloning:\n print(\"voice cloning!\")\n fields += [\"spk_emb\"]\n else:\n print(\"single speaker fastspeech2!\")\n print(\"spk_num:\", spk_num)\n elif am_name == 'speedyspeech':\n fields = [\"utt_id\", \"phones\", \"tones\"]\n elif am_name == 'tacotron2':\n fields = [\"utt_id\", \"text\"]\n if args.voice_cloning:\n print(\"voice cloning!\")\n fields += [\"spk_emb\"]\n\n test_dataset = DataTable(data=test_metadata, fields=fields)\n\n with open(args.phones_dict, \"r\") as f:\n phn_id = [line.strip().split() for line in f.readlines()]\n vocab_size = len(phn_id)\n print(\"vocab_size:\", vocab_size)\n\n tone_size = None\n if args.tones_dict:\n with open(args.tones_dict, \"r\") as f:\n tone_id = [line.strip().split() for line in f.readlines()]\n tone_size = len(tone_id)\n print(\"tone_size:\", tone_size)\n\n # acoustic model\n odim = am_config.n_mels\n am_class = dynamic_import(am_name, model_alias)\n am_inference_class = dynamic_import(am_name + '_inference', model_alias)\n\n if am_name == 'fastspeech2':\n am = am_class(\n idim=vocab_size, odim=odim, spk_num=spk_num, **am_config[\"model\"])\n elif am_name == 'speedyspeech':\n am = am_class(\n vocab_size=vocab_size, tone_size=tone_size, **am_config[\"model\"])\n elif am_name == 'tacotron2':\n am = am_class(idim=vocab_size, odim=odim, **am_config[\"model\"])\n\n am.set_state_dict(paddle.load(args.am_ckpt)[\"main_params\"])\n am.eval()\n am_mu, am_std = np.load(args.am_stat)\n am_mu = paddle.to_tensor(am_mu)\n am_std = paddle.to_tensor(am_std)\n am_normalizer = ZScore(am_mu, am_std)\n am_inference = am_inference_class(am_normalizer, am)\n print(\"am_inference.training0:\", am_inference.training)\n am_inference.eval()\n print(\"acoustic model done!\")\n\n # vocoder\n # model: {model_name}_{dataset}\n voc_name = args.voc[:args.voc.rindex('_')]\n voc_class = dynamic_import(voc_name, model_alias)\n voc_inference_class = dynamic_import(voc_name + '_inference', model_alias)\n voc = voc_class(**voc_config[\"generator_params\"])\n voc.set_state_dict(paddle.load(args.voc_ckpt)[\"generator_params\"])\n voc.remove_weight_norm()\n voc.eval()\n voc_mu, voc_std = np.load(args.voc_stat)\n voc_mu = paddle.to_tensor(voc_mu)\n voc_std = paddle.to_tensor(voc_std)\n voc_normalizer = ZScore(voc_mu, voc_std)\n voc_inference = voc_inference_class(voc_normalizer, voc)\n print(\"voc_inference.training0:\", voc_inference.training)\n voc_inference.eval()\n print(\"voc done!\")\n\n output_dir = Path(args.output_dir)\n output_dir.mkdir(parents=True, exist_ok=True)\n\n for datum in test_dataset:\n utt_id = datum[\"utt_id\"]\n with paddle.no_grad():\n # acoustic model\n if am_name == 'fastspeech2':\n phone_ids = paddle.to_tensor(datum[\"text\"])\n spk_emb = None\n spk_id = None\n # multi speaker\n if args.voice_cloning and \"spk_emb\" in datum:\n spk_emb = paddle.to_tensor(np.load(datum[\"spk_emb\"]))\n elif \"spk_id\" in datum:\n spk_id = paddle.to_tensor(datum[\"spk_id\"])\n mel = am_inference(phone_ids, spk_id=spk_id, spk_emb=spk_emb)\n elif am_name == 'speedyspeech':\n phone_ids = paddle.to_tensor(datum[\"phones\"])\n tone_ids = paddle.to_tensor(datum[\"tones\"])\n mel = am_inference(phone_ids, tone_ids)\n elif am_name == 'tacotron2':\n phone_ids = paddle.to_tensor(datum[\"text\"])\n spk_emb = None\n # multi speaker\n if args.voice_cloning and \"spk_emb\" in datum:\n spk_emb = paddle.to_tensor(np.load(datum[\"spk_emb\"]))\n mel = am_inference(phone_ids, spk_emb=spk_emb)\n # vocoder\n wav = voc_inference(mel)\n sf.write(\n str(output_dir / (utt_id + \".wav\")),\n wav.numpy(),\n samplerate=am_config.fs)\n print(f\"{utt_id} done!\")\n\n\ndef main():\n # parse args and config and redirect to train_sp\n parser = argparse.ArgumentParser(\n description=\"Synthesize with acoustic model & vocoder\")\n # acoustic model\n parser.add_argument(\n '--am',\n type=str,\n default='fastspeech2_csmsc',\n choices=[\n 'speedyspeech_csmsc', 'fastspeech2_csmsc', 'fastspeech2_ljspeech',\n 'fastspeech2_aishell3', 'fastspeech2_vctk', 'tacotron2_csmsc',\n 'tacotron2_ljspeech', 'tacotron2_aishell3'\n ],\n help='Choose acoustic model type of tts task.')\n parser.add_argument(\n '--am_config',\n type=str,\n default=None,\n help='Config of acoustic model. Use deault config when it is None.')\n parser.add_argument(\n '--am_ckpt',\n type=str,\n default=None,\n help='Checkpoint file of acoustic model.')\n parser.add_argument(\n \"--am_stat\",\n type=str,\n default=None,\n help=\"mean and standard deviation used to normalize spectrogram when training acoustic model.\"\n )\n parser.add_argument(\n \"--phones_dict\", type=str, default=None, help=\"phone vocabulary file.\")\n parser.add_argument(\n \"--tones_dict\", type=str, default=None, help=\"tone vocabulary file.\")\n parser.add_argument(\n \"--speaker_dict\", type=str, default=None, help=\"speaker id map file.\")\n\n parser.add_argument(\n \"--voice-cloning\",\n type=str2bool,\n default=False,\n help=\"whether training voice cloning model.\")\n # vocoder\n parser.add_argument(\n '--voc',\n type=str,\n default='pwgan_csmsc',\n choices=[\n 'pwgan_csmsc', 'pwgan_ljspeech', 'pwgan_aishell3', 'pwgan_vctk',\n 'mb_melgan_csmsc'\n ],\n help='Choose vocoder type of tts task.')\n\n parser.add_argument(\n '--voc_config',\n type=str,\n default=None,\n help='Config of voc. Use deault config when it is None.')\n parser.add_argument(\n '--voc_ckpt', type=str, default=None, help='Checkpoint file of voc.')\n parser.add_argument(\n \"--voc_stat\",\n type=str,\n default=None,\n help=\"mean and standard deviation used to normalize spectrogram when training voc.\"\n )\n # other\n parser.add_argument(\n \"--ngpu\", type=int, default=1, help=\"if ngpu == 0, use cpu.\")\n parser.add_argument(\"--test_metadata\", type=str, help=\"test metadata.\")\n parser.add_argument(\"--output_dir\", type=str, help=\"output dir.\")\n\n args = parser.parse_args()\n\n if args.ngpu == 0:\n paddle.set_device(\"cpu\")\n elif args.ngpu > 0:\n paddle.set_device(\"gpu\")\n else:\n print(\"ngpu should >= 0 !\")\n\n evaluate(args)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.load"
]
] |
sigfredonin/NEU_CS6120
|
[
"878fb65f9685af8f4d464398f26d1c5e1a803971"
] |
[
"assignment_1/pos_hmm_bigram.py"
] |
[
"\"\"\"\nNEU CS6120 Assignment 1\nProblem 4 POS Tagging - Hidden Markov Model\n\nThe training set is a collection of files from the Brown corpus.\nThe training set files have sentences of tokenized tagged words,\n w_1/t_1 w_2/t_2 w_3/t_3 ... w_k-1/t_k-1 w_k/t_k\none sentence per line, with leading white space.\nSome lines are empty (i.e., just a newline).\n\n4.1 Obtain frequency counts from all the training files counted together --\n C(w_i,t_i): word-tag counts,\n C(t_i): tag unigram counts,\n C(t_i-1, t_i): tag bigram counts.\n Have to separate words/tags for this counting,\n and have to add beginning and end of sentence token-tag pairs,\n <s>/<$s> and </s>/<s$>.\n Identify infrequent words and replace with 'UNK' before counting.\n4.2 Calculate transition probability:\n P(t_i-1, t_i) = C(t_i-1, t_i) / C(t_i-1)\n4.3 Calculate emission probability:\n P(w_i | t_i) = C(w_i, t_i) / C(t_i)\n4.4 Generate 5 random sentences using HMM.\n Output each sentence (with its POS tags),\n and the probability of it being generated.\n This uses the probabilities of the whole training vocabulary,\n including infrequent words.\n4.5 Use the Viterbi algorithm (NLP ed3 Fig. 8.5) to\n derive the most probable tag sequence for each word\n in the test dataset:\n <sentence = ID=1>\n word, tag\n word, tag\n ...\n word, tag\n <EOS>\n <sentence = ID=1>\n word, tag\n word, tag\n ...\n word, tag\n <EOS>\n ...\n The test data set contains word tokens in this format, but without tags.\n This uses the probabilities of the words-tag pairs where infrequent words\n are collapsed into 'UNK'-tag pairs.\n\nSig Nin\n03 Oct 2018\n\"\"\"\nimport nltk\nimport numpy as np\nimport os\nimport re\nfrom collections import defaultdict\n\n# ------------------------------------------------------------------------\n# Constants ---\n# ------------------------------------------------------------------------\nTOK_SS = '<s>' # start sentence\nTAG_SS = '$S'\nTOK_ES = '</s>' # end sentence\nTAG_ES = 'S$'\n\npathToyPOS = r'D:/Documents/NLP/NEU_CS6120/assignment_1/toyPOS'\npathBrownData = r'D:/Documents/NLP/NEU_CS6120/assignment_1/brown'\npathTestDataFile = r'D:/Documents/NLP/NEU_CS6120/science_sample.txt'\n\n\n# ------------------------------------------------------------------------\n# Main Class - HMM POS Bigram Model ---\n# ------------------------------------------------------------------------\nclass POS_HMM_BiGram:\n \"\"\"\n Bigram HMM POS model.\n\n Initialize with counts from a collection of documents.\n Can generate random sentences.\n Can generate sequences of likely tags for words in sentences,\n using the Viterbi algorithm.\n \"\"\"\n\n# ------------------------------------------------------------------------\n# Cumulative Probabilities and Random Choosing ---\n# ------------------------------------------------------------------------\n\n def _cumulative_probabilities_for_prior(self, probabilities):\n \"\"\"\n Calculate cumulative probabilities for a list of probabilities.\n Input:\n List of probabilities for each possible successor:\n [ ( successor, probability ), ... ]\n Output:\n List of cumulative probabilities for each possible successor:\n [ ( successor, cumulative probability ), ... ]\n \"\"\"\n cps = [] # .. cumulative\n cumulative_probability = 0.0\n for s, p in probabilities:\n cumulative_probability += p\n cps += [(s, cumulative_probability, )]\n return cps\n\n def _cumulative_probabilities(self, successor_probabilities):\n \"\"\"\n Calculate cumulative probabilities for a list of succesor probabilities.\n The successor probabilities for each prior sum to 1.\n The cumulative successor probabilities end in 1.\n Input:\n List of probabilities for each possible successor for each prior:\n { prior : [ ( successor, probability ), ... ] ), ... }\n Output:\n List of cumulative probabilities for each possible successor for each prior:\n { prior, [ ( successor, cumulative probability ), ... ] ), ... }\n \"\"\"\n scps = { }\n for prior, probabilities in successor_probabilities.items():\n cps = self._cumulative_probabilities_for_prior(probabilities)\n last, cp = cps[-1]\n if abs(1.0 - cp) > 1e-14:\n print(\"Warning: Probabilities don't add to 1.0\", prior, last, cp)\n cps[-1] = ( last, 1.0 )\n scps[prior] = cps\n return scps\n\n def _choose_by_probability(self, cps):\n \"\"\"\n Choose an item at random from a list of\n (item, cumulative probability)\n so that each item has its own probability of being chosen.\n Use binary search.\n \"\"\"\n from random import uniform\n cumulative_probability = cps[-1][1]\n r = uniform(0.0, cumulative_probability)\n if self.DEBUG:\n print(\"Random value, r:\", r, \", Item list size:\", len(cps))\n entry = None\n first = 0\n last = len(cps) - 1\n found = False\n while first < last: # while interval size > 1\n i = (first + last) // 2\n entry = cps[i]\n prob = entry[1];\n if self.DEBUG and i < 20:\n print(\"---\", first, i, last, \":\", entry, prob)\n if r < prob:\n last = i # in this or earlier interval\n else:\n first = i + 1 # in later interval\n\n return cps[last]\n\n# ------------------------------------------------------------------------\n# HMM Probabilities - transition and emission ---\n# ------------------------------------------------------------------------\n\n def _emission_probabilities(self, count_tag_unigrams, count_word_tag_pairs):\n \"\"\"\n Calculate emission probability (alpha-smoothed):\n P(w_i | t_i) = (C(w_i, t_i) + alpha) / (C(t_i) + alpha * V)\n where V = count unique word tag pairs and alpha = 0.1\n Inputs:\n count_word_tags:\n { ( w_i, t_i ) : count, ... }\n Outputs:\n emission probabilities:\n { ( w_i , t_i ) : probability, ... }\n word emission probabilities:\n { t_i : [ ( w_i , probability ), ... ], ... }\n \"\"\"\n alpha = 0.1\n V = len(count_word_tag_pairs) # count of unique word tag pairs\n alpha_V = alpha * V\n # Compute probability of unseen word tag pair (count = 0)\n emission_probabilities_unseen = defaultdict(lambda: 1.0 / V)\n for tag, tag_count in count_tag_unigrams.items():\n unseen_probability = alpha / (tag_count + alpha_V)\n emission_probabilities_unseen[tag] = unseen_probability\n # Calculate the emission probability P(w_i | t_i)\n emission_probabilities = { }\n word_emission_probabilities = defaultdict(list)\n for word_tag_pair, word_tag_count in count_word_tag_pairs.items():\n word, tag = word_tag_pair\n tag_count = count_tag_unigrams[tag]\n probability = (float(word_tag_count) + alpha) \\\n / (tag_count + alpha_V)\n emission_probabilities[word_tag_pair] = probability\n word_emission_probabilities[tag] += [ ( word, probability ) ]\n return emission_probabilities, word_emission_probabilities, \\\n emission_probabilities_unseen\n\n def _transition_probabilities(self, count_tag_unigrams, count_tag_bigrams):\n \"\"\"\n Calculate transition probability (alpha-smoothed):\n P(t_i-1, t_i) = (C(t_i-1, t_i) + alpha) / (C(t_i-1) + alpha * V)\n where V = count unique bigrams, alpha = 0.1\n Inputs:\n count_tag_bigrams:\n { ( t_i-1, t_i ) : count, ... }\n Outputs:\n transition probabilities:\n { ( t_i-1, t_i ) : probability, ... }\n tag transition probabilities:\n { t_i-1 : [ ( t_i, probability ) ... ], ... }\n \"\"\"\n alpha = 0.1\n V = len(count_tag_bigrams) # count of unique tag bigrams\n alpha_V = alpha * V\n # Compute probability of unseen bigram (count = 0)\n transition_probabilities_unseen = defaultdict(lambda: 1.0 / V)\n for tag, tag_count in count_tag_unigrams.items():\n unseen_probability = alpha / (tag_count + alpha_V)\n transition_probabilities_unseen[tag] = unseen_probability\n # Calculate the transition probability P(t_i-1, t_i)\n transition_probabilities = { }\n tag_transition_probabilities = defaultdict(list)\n for bigram, bigram_count in count_tag_bigrams.items():\n prev_tag, tag = bigram\n prev_tag_count = count_tag_unigrams[prev_tag]\n probability = (float(bigram_count) + alpha) \\\n / (prev_tag_count + alpha_V)\n transition_probabilities[bigram] = probability\n tag_transition_probabilities[prev_tag] += [ ( tag, probability, ) ]\n return transition_probabilities, tag_transition_probabilities, \\\n transition_probabilities_unseen\n\n# ------------------------------------------------------------------------\n# Infrequent and unknown words, conversion to 'UNK' ---\n# ------------------------------------------------------------------------\n\n def _infrequent_words(self, word_tag_pairs, TOO_FEW):\n \"\"\"\n Return the word counts and infrequent word counts\n in dictionaries with entries (word, tag) : count.\n Inputs:\n word_tag_pairs: [ (word, tag), ... ]\n TOO_FEW: word is infrequent if count <= TOO_FEW\n Outputs:\n count_words: { word : count, ... }\n count_infrequent: { ( word ) : count, ... }\n \"\"\"\n count_words = defaultdict(int)\n for word, tag in word_tag_pairs:\n count_words[word] += 1\n count_infrequent = defaultdict(int)\n for word, count in count_words.items():\n if count <= TOO_FEW:\n count_infrequent[word] += count\n word_tag_pairs_UNK = []\n for word, tag in word_tag_pairs:\n if word in count_infrequent:\n word = 'UNK'\n word_tag_pairs_UNK += [ ( word, tag ) ]\n return count_words, count_infrequent, word_tag_pairs_UNK\n\n def _unknown_word_tags(self, word_tag_pairs, count_infrequent):\n \"\"\"\n Return a copy of the word counts dictionary\n with the infrequent words replaced by a 'UNK' entry\n that has count the sum of their counts.\n Inputs:\n count_word_tags: { ( word, tag ) : count, ... }\n count_infrequent: { word : count, ... }\n Outputs:\n count_word_tag_pairs_UNK: { ( word, tag ): count, ...\n ( 'UNK', tag ) : count_unk, ... }\n ... where count_unk is the sum of the counts of the\n infrequent words with that tag.\n \"\"\"\n count_word_tag_pairs = defaultdict(int)\n for word_tag in word_tag_pairs:\n word, tag = word_tag\n count_word_tag_pairs[word_tag] += 1\n count_word_tag_pairs_UNK = count_word_tag_pairs.copy()\n for word_tag, count in count_word_tag_pairs.items():\n word, tag = word_tag\n if word in count_infrequent:\n count_word_tag_pairs_UNK[('UNK', tag,)] += count\n del count_word_tag_pairs_UNK[word_tag]\n return count_word_tag_pairs_UNK\n\n# ------------------------------------------------------------------------\n# Sentences, words, tags and counts ---\n# ------------------------------------------------------------------------\n\n def _counts_from_word_tag_pairs(self, word_tag_pairs):\n count_word_tags = defaultdict(int)\n count_tag_unigrams = defaultdict(int)\n count_tag_bigrams = defaultdict(int)\n tag_prev = None\n for pair in word_tag_pairs:\n word, tag = pair\n count_word_tags[pair] += 1\n tag_unigram = ( tag, )\n count_tag_unigrams[tag_unigram] += 1\n if tag_prev != None:\n tag_bigram = ( tag_prev, tag, )\n count_tag_bigrams[tag_bigram] += 1\n tag_prev = tag\n return count_word_tags, count_tag_unigrams, count_tag_bigrams\n\n def _tags_from_sentences(self, sents):\n p = re.compile(r'(\\S+)/(\\S+)')\n word_tag_pairs = []\n for sent in sents:\n pairs_in_sent = [ (word.lower(), tag) for word, tag in p.findall(sent) ]\n word_tag_pairs += [ ( TOK_SS, TAG_SS, ) ] # Start of sentence\n word_tag_pairs += pairs_in_sent # words and tags\n word_tag_pairs += [ ( TOK_ES, TAG_ES, ) ] # End of sentence\n return word_tag_pairs\n\n def _tagged_sentences_from_file(self, dirPath, fnx):\n fnxPath = os.path.join(dirPath, fnx)\n re_nl = re.compile(r'\\n')\n re_sb = re.compile(r'( )+')\n sents_in_file = []\n with open(fnxPath) as f:\n print(fnx)\n for line in f:\n nnl = re_nl.sub(' ', line) # '\\n' -> ' '\n sb = re_sb.sub(' ', nnl) # ' '+ -> ' '\n if sb != ' ':\n sents_in_file += [ sb ]\n return sents_in_file\n\n def _tagged_sentences_from_files(self, dirPath, files):\n sents = []\n for fnx in files:\n fnx_sents = self._tagged_sentences_from_file(dirPath, fnx)\n sents += fnx_sents\n return sents\n\n# ------------------------------------------------------------------------\n# Class constructor and training ---\n# ------------------------------------------------------------------------\n\n def init(self, dirPath, TOO_FEW=5):\n self.files = os.listdir(dirPath)\n self.TOO_FEW = TOO_FEW\n # sentences, word/tag pairs, counts\n self.sents = self._tagged_sentences_from_files(dirPath, self.files)\n self.word_tag_pairs = self._tags_from_sentences(self.sents)\n # identify infrequent words and replace with ('UNK',tag) counts\n self.count_words, self.count_infrequent, self.word_tag_pairs_UNK = \\\n self._infrequent_words(self.word_tag_pairs, self.TOO_FEW)\n self.count_word_tag_pairs_UNK = \\\n self._unknown_word_tags(self.word_tag_pairs, self.count_infrequent)\n # bigrams and counts, from word tag pairs with infrequent set to UNK\n self.count_word_tags, self.count_tag_unigrams, self.count_tag_bigrams = \\\n self._counts_from_word_tag_pairs(self.word_tag_pairs_UNK)\n # transition and emission probabilities\n self.pTrans, self.pTagTrans, self.pTransUnseen = \\\n self._transition_probabilities( \\\n self.count_tag_unigrams, self.count_tag_bigrams)\n self.pEmiss, self.pTagEmiss, self.pEmissUnseen = \\\n self._emission_probabilities( \\\n self.count_tag_unigrams, self.count_word_tags)\n self.pEmUNK, self.pTagEmUNK, self.pEmUNKUnseen = \\\n self._emission_probabilities( \\\n self.count_tag_unigrams, self.count_word_tag_pairs_UNK)\n # cumulative probabilities for random choosing\n self.pCumTrans = self._cumulative_probabilities(self.pTagTrans)\n self.pCumEmiss = self._cumulative_probabilities(self.pTagEmiss)\n self.pCumEmUNK = self._cumulative_probabilities(self.pTagEmUNK)\n\n def reset(self):\n # ... over whole training set ...\n self.files = None # List of files in training set\n self.TOO_FEW = None # UNK if word count <= TOO_FEW\n self.sents = None # List of sentences\n self.tags = None # List of (word, tag) pairs\n # counts ...\n self.count_word_tags = None # { (w_i, t_i) : count, .. }\n self.count_words = None # { w_i : count, ... }\n self.count_infrequent = None # { (w_i, t_i) : count, ... }\n self.count_word_tag_pairs_UNK = None # { (w_i, t_i) : count, ... }\n self.count_tag_unigrams = None # { (t_i) : count, ... }\n self.count_tag_bigrams = None # { (t_i-1, t_i) : count, ... }\n # probabilities\n self.pTrans = None # { (t_i-1, t_i) : P(t_i-1, t_i), ... }\n self.pEmiss = None # { (w_i, t_i) : P(w_i | t_i), ... }\n self.pEmUNK = None # { (w_i, t_i) : P(w_i | t_i), ... }\n # conditional probabilities\n self.pTagTrans = None # { t_i-1 : (t_i, P(t_i-1, t_i)), ... }\n self.pTagEmiss = None # { t_i : (w_i, P(w_i | t_i)), ... }\n self.pTagEmUNK = None # { t_i : (w_i, P(w_i | t_i)), ... }\n # cumulative conditional probabilities\n self.pCumTrans = None # { t_i-1 : [ (t_i, cP(t_i-1, t_i)) ], ... }\n self.pCumEmiss = None # { t_i : [ (w_i, cP(w_i | t_i)) ], ... }\n self.pCumEmUNK = None # { t_i : [ (w_i, cP(w_i | t_i)) ], ... }\n\n def set_DEBUG(self, DEBUG=True):\n self.DEBUG=DEBUG\n\n def __init__(self, DEBUG=False):\n self.set_DEBUG(DEBUG)\n self.reset()\n\n# ------------------------------------------------------------------------\n# Sentence Generation ---\n# ------------------------------------------------------------------------\n\n def _assemble_sentence(self, swt):\n sent = \"\"\n sent_tagged = \"\"\n ss = False\n for word, tag in swt:\n if tag == TAG_SS:\n ss = True\n elif tag != TAG_ES:\n if tag == 'np' or ss:\n word = word.capitalize()\n ss = False\n sent += word + ' '\n sent_tagged += word + \"/\" + tag + ' '\n if tag == TAG_ES:\n sent = sent[:-1]\n sent_tagged = sent_tagged[:-1]\n return sent, sent_tagged\n\n def generate_sentence(self, pTrans, pEmiss, pCumTrans, pCumEmiss):\n swt = [] # sentence word/tag pairs\n stp = [] # sentence transition probabilities\n sep = [] # sentence emission probabilities\n # start of sentence word and tag\n word_tag = ( TOK_SS, TAG_SS, )\n swt += [ word_tag ]\n stp += [ 1.0 ]\n sep += [ 1.0 ]\n # Iterate choosing tags and words until end of sentence is chosen\n next_word = None\n next_tag = None\n while next_word != TOK_ES:\n # generate the next word/tag pair\n word, tag = word_tag\n tcps = pCumTrans[tag] # List of cumulative transition probabilities\n next_tag_cumP = self._choose_by_probability(tcps)\n next_tag, tagCumP = next_tag_cumP\n ecps = pCumEmiss[next_tag] # List of cumulative emission probabilities\n next_word_cumP = self._choose_by_probability(ecps)\n next_word, wordCumP = next_word_cumP\n # get the probabilities used\n tp = pTrans[( tag, next_tag, )]\n ep = pEmiss[( next_word, next_tag )]\n # record word/tag pair\n word_tag = ( next_word, next_tag )\n swt += [ word_tag ]\n stp += [ tp ]\n sep += [ ep ]\n # continue generating as long as the next word is not the end of sentence token\n sent, sent_tagged = self._assemble_sentence(swt)\n prob = np.prod(np.array(stp)) * np.prod(np.array(sep))\n return swt, stp, sep, sent, sent_tagged, prob\n\n# ------------------------------------------------------------------------\n# Tests ---\n# ------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n from datetime import datetime\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n\n testPath = pathToyPOS\n hmm = POS_HMM_BiGram()\n TOO_FEW = 1\n\n files = os.listdir(testPath)\n fnx = files[-1]\n print(\"--- \", fnx, \" ---\")\n\n fnx_sents = hmm._tagged_sentences_from_file(testPath, fnx)\n print(\"Len sentences:\", len(fnx_sents))\n print(\"First 5 sentences:\", fnx_sents[:5])\n print(\"last 5 sentences:\", fnx_sents[-5:])\n\n fnx_word_tag_pairs = hmm._tags_from_sentences(fnx_sents)\n print(\"Len word tag pairs:\", len(fnx_word_tag_pairs))\n print(\"First 5 word tag pairs:\", fnx_word_tag_pairs[:5])\n print(\"Last 5 word tag pairs:\", fnx_word_tag_pairs[-5:])\n\n fnx_count_word_tags, fnx_count_tag_unigrams, fnx_count_tag_bigrams = \\\n hmm._counts_from_word_tag_pairs(fnx_word_tag_pairs)\n fnx_count_word_tags_sum = sum([c for p, c in\n fnx_count_word_tags.items()])\n fnx_count_tag_unigrams_sum = sum([c for p, c in\n fnx_count_tag_unigrams.items()])\n fnx_count_tag_bigrams_sum = sum([c for p, c in\n fnx_count_tag_bigrams.items()])\n print(\"Sum counts in count word tag pairs =\", fnx_count_word_tags_sum)\n print(\"Length count word tag pairs:\", len(fnx_count_word_tags))\n print(\"First 5 count word tag pairs:\", list(fnx_count_word_tags.items())[:5])\n print(\"Last 5 count word tag pairs:\", list(fnx_count_word_tags.items())[-5:])\n print(\"Length count tag unigrams:\", len(fnx_count_tag_unigrams))\n print(\"Sum counts in count tag unigrams =\", fnx_count_tag_unigrams_sum)\n print(\"First 5 count tag unigrams:\", list(fnx_count_tag_unigrams.items())[:5])\n print(\"Last 5 count tag unigrams:\", list(fnx_count_tag_unigrams.items())[-5:])\n print(\"Sum counts in count tag bigrams =\", fnx_count_tag_bigrams_sum)\n print(\"Length count tag bigrams:\", len(fnx_count_tag_bigrams))\n print(\"First 5 count tag bigrams:\", list(fnx_count_tag_bigrams.items())[:5])\n print(\"Last 5 count tag bigrams:\", list(fnx_count_tag_bigrams.items())[-5:])\n\n fnx_count_words, fnx_count_infrequent, fnx_word_tag_pairs_UNK = \\\n hmm._infrequent_words(fnx_word_tag_pairs, TOO_FEW)\n fnx_count_words_sum = sum([c for p, c in\n fnx_count_words.items()])\n fnx_count_infrequent_sum = sum([c for p, c in\n fnx_count_infrequent.items()])\n print(\"Sum counts in count words =\", fnx_count_words_sum)\n print(\"Length count words:\", len(fnx_count_words))\n print(\"First 5 count words:\", list(fnx_count_words.items())[:5])\n print(\"Last 5 count words:\", list(fnx_count_words.items())[-5:])\n print(\"Sum counts in count infrequent words =\", fnx_count_infrequent_sum)\n print(\"Length count infrequent words:\", len(fnx_count_infrequent))\n print(\"First 5 count infrequent words:\", list(fnx_count_infrequent.items())[:5])\n print(\"Last 5 count infrequent words:\", list(fnx_count_infrequent.items())[-5:])\n\n fnx_count_word_tags, fnx_count_tag_unigrams, fnx_count_tag_bigrams = \\\n hmm._counts_from_word_tag_pairs(fnx_word_tag_pairs_UNK)\n fnx_count_word_tag_pairs_UNK = \\\n hmm._unknown_word_tags(fnx_word_tag_pairs, fnx_count_infrequent)\n fnx_count_word_tag_pairs_UNK_sum = sum([c for p, c in\n fnx_count_word_tag_pairs_UNK.items()])\n print(\"Sum counts in count word tags UNK =\", fnx_count_word_tag_pairs_UNK_sum)\n print(\"Length count word tags UNK:\", len(fnx_count_word_tag_pairs_UNK))\n print(\"First 5 count word tags UNK:\", list(fnx_count_word_tag_pairs_UNK.items())[:5])\n print(\"Last 5 count word tags UNK:\", list(fnx_count_word_tag_pairs_UNK.items())[-5:])\n\n fnx_pTrans, fnx_pTagTrans, fnx_pTransUnseen = \\\n hmm._transition_probabilities(fnx_count_tag_unigrams, fnx_count_tag_bigrams)\n print(\"Length transition probabilities:\", len(fnx_pTrans))\n print(\"First 5 transition probabilities:\", list(fnx_pTrans.items())[:5])\n print(\"Last 5 transition probabilities:\", list(fnx_pTrans.items())[-5:])\n print(\"Length tag transition probabilities:\", len(fnx_pTagTrans))\n print(\"First 5 tag transition probabilities:\", list(fnx_pTagTrans.items())[:5])\n print(\"Last 5 tag transition probabilities:\", list(fnx_pTagTrans.items())[-5:])\n\n fnx_pEmiss, fnx_pTagEmiss, fnx_pEmissUnseen = \\\n hmm._emission_probabilities(fnx_count_tag_unigrams, fnx_count_word_tags)\n print(\"Length emission probabilities:\", len(fnx_pEmiss))\n print(\"First 5 emission probabilities:\", list(fnx_pEmiss.items())[:5])\n print(\"Last 5 emission probabilities:\", list(fnx_pEmiss.items())[-5:])\n print(\"Length tag emission probabilities:\", len(fnx_pTagEmiss))\n print(\"First 5 tag emission probabilities:\", list(fnx_pTagEmiss.items())[:5])\n print(\"Last 5 tag emission probabilities:\", list(fnx_pTagEmiss.items())[-5:])\n\n fnx_pEmUNK, fnx_pTagEmUNK, fnx_pEmUNKUnknown = \\\n hmm._emission_probabilities(fnx_count_tag_unigrams, fnx_count_word_tag_pairs_UNK)\n print(\"Length emission probabilities UNK:\", len(fnx_pEmUNK))\n print(\"First 5 emission probabilities UNK:\", list(fnx_pEmUNK.items())[:5])\n print(\"Last 5 emission probabilities UNK:\", list(fnx_pEmUNK.items())[-5:])\n print(\"Length tag emission probabilities UNK:\", len(fnx_pTagEmUNK))\n print(\"First 5 tag emission probabilities UNK:\", list(fnx_pTagEmUNK.items())[:5])\n print(\"Last 5 tag emission probabilities UNK:\", list(fnx_pTagEmUNK.items())[-5:])\n\n fnx_pCumTrans = hmm._cumulative_probabilities(fnx_pTagTrans)\n print(\"Length cumulative tag transition probabilities UNK:\", len(fnx_pCumTrans))\n print(\"First 5 cumulative tag transition probabilities UNK:\", list(fnx_pCumTrans.items())[:5])\n print(\"Last 5 cumulative tag transition probabilities UNK:\", list(fnx_pCumTrans.items())[-5:])\n\n fnx_pCumEmiss = hmm._cumulative_probabilities(fnx_pTagEmiss)\n print(\"Length cumulative tag emission probabilities:\", len(fnx_pCumEmiss))\n print(\"First 5 cumulative tag emission probabilities:\", list(fnx_pCumEmiss.items())[:5])\n print(\"Last 5 cumulative tag emission probabilities:\", list(fnx_pCumEmiss.items())[-5:])\n\n fnx_pCumEmUNK = hmm._cumulative_probabilities(fnx_pTagEmUNK)\n print(\"Length cumulative tag emission probabilities UNK:\", len(fnx_pCumEmUNK))\n print(\"First 5 cumulative tag emission probabilities UNK:\", list(fnx_pCumEmUNK.items())[:5])\n print(\"Last 5 cumulative tag emission probabilities UNK:\", list(fnx_pCumEmUNK.items())[-5:])\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n\n print(\"Randomly generated characters ...\")\n cps = [ ('a', 0.5), ('b', 0.6), ('c', 0.8), ('d', 0.95), ('e', 1.0) ]\n print(cps)\n sent = \"\"\n for i in range(30):\n char_prob = hmm._choose_by_probability(cps)\n char, prob = char_prob\n sent += char\n print(char_prob, end='')\n print()\n print(sent)\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n\n print(\"Randomly generated sentences ...\")\n swp = stp = sep = sent = sent_tagged = prob = None\n for i in range(5):\n print(\"--- %d ---\" % i)\n swt, stp, sep, sent, sent_tagged, prob = hmm.generate_sentence( \\\n fnx_pTrans, fnx_pEmiss, fnx_pCumTrans, fnx_pCumEmiss)\n print(\"SWT---\")\n print(swt)\n print(\"STP---\")\n print(stp)\n print(\"SEP---\")\n print(sep)\n print(\"SENTENCE ---\")\n print(sent)\n print(\"TAGGED SENTENCE ---\")\n print(sent_tagged)\n print(\"Sentence probability---\")\n print(prob)\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n\n testPath = pathToyPOS\n print(\"Test with all file in %s -----\" % testPath)\n hmm.init(testPath, TOO_FEW=5)\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n\n print(\"Randomly generated sentences ...\")\n swp = stp = sep = sent = sent_tagged = prob = None\n for i in range(5):\n print(\"--- %d ---\" % i)\n swt, stp, sep, sent, sent_tagged, prob = hmm.generate_sentence( \\\n fnx_pTrans, fnx_pEmiss, fnx_pCumTrans, fnx_pCumEmiss)\n print(\"SWT---\")\n print(swt)\n print(\"STP---\")\n print(stp)\n print(\"SEP---\")\n print(sep)\n print(\"SENTENCE ---\")\n print(sent)\n print(\"TAGGED SENTENCE ---\")\n print(sent_tagged)\n print(\"Sentence probability---\")\n print(prob)\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n\n testPath = pathBrownData\n print(\"Test with all file in %s -----\" % testPath)\n hmm.init(testPath, TOO_FEW=5)\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n\n print(\"Randomly generated sentences ...\")\n swp = stp = sep = sent = sent_tagged = prob = None\n for i in range(5):\n print(\"--- %d ---\" % i)\n swt, stp, sep, sent, sent_tagged, prob = hmm.generate_sentence( \\\n fnx_pTrans, fnx_pEmiss, fnx_pCumTrans, fnx_pCumEmiss)\n print(\"SWT---\")\n print(swt)\n print(\"STP---\")\n print(stp)\n print(\"SEP---\")\n print(sep)\n print(\"SENTENCE ---\")\n print(sent)\n print(\"TAGGED SENTENCE ---\")\n print(sent_tagged)\n print(\"Sentence probability---\")\n print(prob)\n\n nowStr = datetime.now().strftime(\"%B %d, %Y %I:%M:%S %p\")\n print(\"====\" + nowStr + \"====\")\n"
] |
[
[
"numpy.array"
]
] |
Bokubst/homework-scientific-computing
|
[
"4a7e1f896ad19ed55260a584bee2d6d6521de78b"
] |
[
"homework04-python-scientific-ecosystem/exercise 4 code.py"
] |
[
"import numpy as np\n\nrandom1 = np.random.uniform(size=100)\nprint(\"random1 values\")\nprint(random1 , \"\\n\")\n\nrandom2 = np.random.uniform(size=100)\nprint(\"random2 values\")\nprint(random2 , \"\\n\")\n\nfrom matplotlib import pyplot as plt\n\nplt.plot(random1, label = 'random number 1')\nplt.title('random number 1')\nran_mean1 = [np.mean(random1) for i in random1]\nplt.plot(ran_mean1, label = 'mean value')\nplt.show()\n\nplt.plot(random2, label = \"random number 2\")\nplt.title(\"random number 2\")\nran_mean2 = [np.mean(random2) for i in random2]\nplt.plot(ran_mean2, label = 'mean value')\nplt.show()\n\nrandom3 = (np.add(random1, random2))/2\nprint(\"random3 values\")\nprint(random3)\nrandom3means = np.mean(random3)\n\nplt.plot(random3, label = \"random number 3\")\nplt.title(\"random number 3\")\nran_mean3 = [np.mean(random3) for i in random3]\nplt.plot(ran_mean3, label = 'mean value')\nplt.show()\n\nrandom1means = np.mean(random1)\nprint(\"mean of random1\")\nprint(random1means , \"\\n\")\n\nrandom2means = np.mean(random2)\nprint(\"mean of random2\")\nprint(random2means , \"\\n\")\n\nrandom3means = np.mean(random3)\nprint(\"mean of random3\")\nprint(random3means)"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"numpy.add",
"numpy.mean",
"numpy.random.uniform",
"matplotlib.pyplot.show"
]
] |
HongtaoYang/mean-average-precision
|
[
"84a4b72f07e9143948319b75a2b50f1d371a0b11"
] |
[
"base.py"
] |
[
"from abc import abstractmethod\nfrom typing import List, Any, Set\n\nimport numpy as np\n\n\nclass GroundTruthItem:\n def __init__(self, *, clazz: str, location: Any = None) -> None:\n \"\"\"\n Args:\n clazz: the class of the item.\n location: the location of the item.\n In the case of detection, this is the image id where the box come from.\n \"\"\"\n self.clazz = clazz\n self.location = location\n\n\nclass PredictedItem:\n def __init__(self, *, clazz: str, score: float, location: Any = None) -> None:\n \"\"\"\n Args:\n clazz: the class of the item.\n score: the score of the item for the class.\n location: the location of the item.\n In the case of detection, this is the image id where the box come from.\n \"\"\"\n self.clazz = clazz\n self.score = score\n self.location = location\n\n\nclass MeanAveragePrecision:\n def __init__(self, gt_items: Set[GroundTruthItem], predicted_items: Set[PredictedItem]):\n self.gt_items = gt_items\n self.predicted_items = predicted_items\n\n\n def mAP(self, **kwargs) -> float:\n \"\"\"\n Code modified from https://github.com/rafaelpadilla/Object-Detection-Metrics/blob/master/lib/Evaluator.py\n \"\"\"\n all_average_precisions = []\n all_classes = {b.clazz for b in self.gt_items.union(self.predicted_items)}\n\n for c in all_classes:\n pred_items_single_class = [d for d in self.predicted_items if d.clazz == c]\n ground_truths_single_class = [g for g in self.gt_items if g.clazz == c]\n\n if not ground_truths_single_class and pred_items_single_class:\n average_precision = 0.0\n elif ground_truths_single_class and not pred_items_single_class:\n average_precision = 0.0\n elif not ground_truths_single_class and not pred_items_single_class:\n average_precision = 1.0\n else:\n pred_items_single_class = sorted(pred_items_single_class, key=lambda d: d.score, reverse=True)\n prediction_is_correct = self.assign(pred_items_single_class, ground_truths_single_class, **kwargs)\n\n acc_TP = np.cumsum(prediction_is_correct)\n acc_FP = np.cumsum(1 - prediction_is_correct)\n rec = list(acc_TP / len(ground_truths_single_class))\n prec = list(acc_TP / (acc_FP + acc_TP))\n average_precision = self._average_precision(rec, prec)\n\n all_average_precisions.append(average_precision)\n\n return np.mean(all_average_precisions)\n\n @abstractmethod\n def assign(self, predicted_items_single_class, gt_items_single_class, **kwargs) -> np.ndarray:\n \"\"\"\n Args:\n predicted_items_single_class: sorted list of PredictedItem of a single class.\n gt_items_single_class: sorted list of GroundTruthItem of a single class.\n Return:\n A 1-d np.ndarray of the same length as predicted_items_single_class, with each value \n being either 0 or 1, indicating whether the corresponding predicted item is correct or not.\n \"\"\"\n pass\n \n @staticmethod\n def _average_precision(rec: List[float], prec: List[float]) -> float:\n recall_intervals = [r for r in [0] + rec]\n precision_intervals = [p for p in [0] + prec]\n\n average_precision = 0\n for i in range(len(recall_intervals) - 1):\n average_precision += (recall_intervals[i + 1] - recall_intervals[i]) * max(\n precision_intervals[i + 1 :]\n )\n\n return average_precision"
] |
[
[
"numpy.mean",
"numpy.cumsum"
]
] |
souleater42/MMP-Robotic-Artist
|
[
"2a67b611c2a3af5feb34276c0d3d30340667f1fa"
] |
[
"code_v3/edges_style.py"
] |
[
"\"\"\"\nSummary => will apply the EdgesStlye to the image given.\n\nDescription => This class is going to control the proccessing of images for\n the EdgesStlye. It will take a the 'takenPicture.jpg'\n from the Image folder and then stlye it. The output will\n be a list of x and y coordinates for the plotter to print out\n later on.\n\nAuthor => Matthew Howard (mah60).\nVersion => 0.1 - 20/04/2018 - create the basic class for the edges\n algorithm. This code is yet to be complete.\n 0.2 - 21/04/2018 - removed ui from __init_- method as not\n used\n\"\"\"\nfrom __future__ import division\nfrom image_processor import ImageProcessor\nimport numpy as np\nimport cv2\n\n\nclass EdgesStyle(ImageProcessor):\n \"\"\"\n Summary => will apply the dithering algorithm to the image given.\n\n Description => This class is going to control the proccessing of images for\n the dithering algorithm. It will take a the 'takenPicture.jpg'\n from the Image folder and then stlye it. The output will\n be a list of x and y coordinates for the plotter to print out\n later on.\n\n This class inherits Imageprocessor and will take on the\n individual classes for it.\n\n args => None\n\n return => None\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Summary => will initialize the image processor.\n\n Description => will initialize the images processor, to be used later\n on.\n\n args => None\n\n return => None\n \"\"\"\n super(EdgesStyle, self).__init__()\n\n def run(self):\n \"\"\"\n Summary => will find the boarders in the image taken.\n\n Description => will find the boarders in the image take, using\n opencv. The will work by making the image graystyle, then\n using a GaussianBlur to filter the image. Then using sobal\n to calculate where the edges are.\n\n After this we use a threshold to swap the black and white\n colours around.\n\n args => None\n\n return => None\n \"\"\"\n # get the image to be processed\n img = cv2.imread('Images/takenPicture.jpg', 0)\n # resize img given\n img = self.compress_image(img, 3)\n # img_edges = cv2.Canny(img, 80, 80)\n # blur the image so we can tell where the key boarders are\n blur = cv2.GaussianBlur(img, (5, 5), 0)\n # create a sobal diratives\n sobal = cv2.Sobel(blur, cv2.CV_64F, 1, 1, ksize=5)\n # convert the sobal diratives to canny_style\n # to view the edges of the image\n # sobalCopy = np.uint8(sobal) # https://stackoverflow.com/questions\n # /19103933/depth-error-in-2d-image-with-opencv-python\n # canny = cv2.Canny(img, 25, 100, L2gradient=False)\n # save the final output\n # change image type to unit 8\n sobal = np.uint8(sobal)\n # creates a threshold to create a black and white image\n ret, threshold = cv2.threshold(sobal, 25, 255, cv2.THRESH_BINARY_INV)\n\n cv2.imwrite(\"Images/processedImage.jpg\", threshold)\n # cv2.imwrite(\"Images/edges_style_example.jpg\", threshold)\n\n self.calculate_coordinates(threshold)\n"
] |
[
[
"numpy.uint8"
]
] |
luigialberti/pytriangle
|
[
"99ecafc299a692ef0f33e262bc7a1c912d3aa694"
] |
[
"triangle.py"
] |
[
"#!/usr/bin/env python\n\nimport triangulate\nimport sys\n\n\"\"\"\nInterface to the TRIANGLE program by Jonathan Richard Shewchuck\n\"\"\"\n\nclass Triangle:\n\n\n def __init__(self):\n\n \"\"\"\n Constructor\n \"\"\"\n\n # create handles to hold the\n # triangulation structures\n self.hndls = [triangulate.new(),]\n self.h_vor = triangulate.new()\n \n self.area = None\n self.mode = ''\n\n self.has_points = False\n self.has_segmts = False\n self.has_trgltd = False\n\n\n def set_points(self, pts, markers=[]):\n\n \"\"\"\n Set the points\n\n @param pts [(x, y),...]\n @param markers [m, ...] where m is 1 on the outer boundary and 0 in the interior or internal boundary)\n \"\"\"\n\n if not markers:\n # set all the markers to zero\n mrks = [0 for i in range(len(pts))]\n else:\n npts = len(pts)\n nmrk = len(markers)\n if npts != nmrk:\n print('%s: Warning. Incompatible size between marker and point lists len(pts)=%d != len(markers)=%d.' % \\\n (__file__, npts, nmrk))\n n1 = min(npts, nmrk)\n n2 = npts - nmrk\n mrks = [markers[i] for i in range(n1)] + [0 for i in range(n2)]\n else:\n mrks = markers\n \n triangulate.set_points(self.hndls[0], pts, mrks)\n self.has_points = True\n\n\n def set_segments(self, segs, markers=[]):\n\n \"\"\"\n Set the boundary contour. \n\n @param segs [(p0, p1), ....] where p0 and p1 are point indices. The ordering is counterclockwise for an outer boundary\n and clockwise for an internal boundary.\n markers [m1,m2,...] optional markers to assign physical tags to segments\n\n @note invoke this method after 'set_points'.\n \"\"\"\n \n if not markers:\n # set all the markers to zero\n mrks = [0 for i in range(len(segs))]\n else:\n nseg = len(segs)\n nmrk = len(markers)\n if nseg != nmrk:\n print('%s: Warning. Incompatible size between marker and segment lists len(segs)=%d != len(markers)=%d.' % \\\n (__file__, nseg, nmrk))\n n1 = min(nseg, nmrk)\n n2 = nseg - nmrk\n mrks = [markers[i] for i in range(n1)] + [0 for i in range(n2)]\n else:\n mrks = markers\n triangulate.set_segments(self.hndls[0], segs, mrks)\n self.has_sgmts = True\n \n def set_holes(self, xy):\n\n \"\"\"\n Set the list of points in the holes. \n\n @param xy [ (x0, y0), ... ] where (x0,y0) is a point inside a hole\n \"\"\"\n triangulate.set_holes(self.hndls[0], xy)\n\n def set_regions(self, xy):\n\n \"\"\"\n Set the list of regions. \n\n @param xy [ (x0, y0, r, a), ... ] where (x0,y0) is a point inside a region\n r is the region attribute (tag)\n a is the area constraint\n \"\"\"\n triangulate.set_regions(self.hndls[0], xy)\n\n\n def set_point_attributes(self, att):\n\n \"\"\"\n Set the point attributes.\n\n @param att [(a0,..), ...]\n \"\"\"\n triangulate.set_point_attributes(self.hndls[0], att)\n \n\n def set_triangle_attributes(self, att):\n\n \"\"\"\n Set the triangle attributes.\n\n @param att [(a0,..), ...]\n \"\"\"\n triangulate.set_triangle_attributes(self.hndls[1], att)\n\n\n def triangulate(self, area=None, mode='pzq27eQ'):\n\n \"\"\"\n Perform an initial triangulation.\n\n @param area is a max area constraint\n @param mode a string of TRIANGLE switches. Refer to the TRIANGLE doc for more info about mode:\n http://www.cs.cmu.edu/~quake/triangle.switch.html\n\n @note invoke this after setting the boundary points, segments, and optionally hole positions.\n \"\"\"\n\n if not self.has_points and not self.has_segmts:\n print('%s: Error. Must set points, segments, and optionally holes prior to calling \"triangulate\"' \\\n % (__file__))\n return\n\n # mode string\n # z: start indexing with zero\n # q<angle>: quality mesh\n # e: edge\n # p: planar straight line graph\n # Q: quiet mode\n\n self.mode = mode\n if area:\n self.area = area\n mode += 'a%f'% area\n\n if len(self.hndls) <= 1: self.hndls.append( triangulate.new() )\n triangulate.triangulate(mode, self.hndls[0], self.hndls[1], self.h_vor)\n self.has_trgltd = True\n\n\n def get_num_points(self, level=-1):\n \"\"\"\n Get the number of nodes/points.\n\n @param level refinement level (-1 for the last level). The coarsest level is 1.\n @return number\n \"\"\"\n return triangulate.get_num_points(self.hndls[level])\n\n \n def get_num_triangles(self, level=-1):\n \"\"\"\n Get the number of cells/triangles.\n\n @param level refinement level (-1 for the last level). The coarsest level is 1\n @return number\n \"\"\"\n return triangulate.get_num_triangles(self.hndls[level])\n\n\n def refine(self, area_ratio=2.0):\n\n \"\"\"\n Refine the triangulation.\n\n @param area_ratio represents the max triangle area reduction factor\n\n @note should be called after performing an initial triangulation.\n \"\"\"\n\n if not self.has_trgltd:\n print('%s: Error. Must triangulate prior to calling \"refine\"' \\\n % (__file__))\n return\n\n self.hndls.append( triangulate.new() )\n\n mode = self.mode + 'cr'\n if self.area:\n self.area /= area_ratio\n mode += 'a%f' % self.area\n\n triangulate.triangulate(mode, self.hndls[-2],\n self.hndls[-1], self.h_vor)\n\n\n def get_points(self, level=-1):\n\n \"\"\"\n Get the points and their markers.\n\n @param level refinement level (-1 for the last level). The coarsest level is 1. The level can be used\n to retrieve previous triangulation refinements: level=-1 will retrieve the last, \n level=-2 the previous one, etc.\n @return [ [(x, y), marker], ...] where marker is 1 on the boundary and 0 inside. Here, \n \"\"\"\n return triangulate.get_points(self.hndls[level])\n\n\n def get_edges(self, level=-1):\n\n \"\"\"\n Get the list of edges.\n\n @param level refinement level (-1 for the last level). The coarsest level is 1. The level can be used\n to retrieve previous triangulation refinements: level=-1 will retrieve the last, \n level=-2 the previous one, etc.\n @return [((p0, p1), m),..) where (p0, p1) are point indices and \n m is the boundary marker (0=interior, 1=boundary)\n \"\"\"\n return triangulate.get_edges(self.hndls[level])\n \n\n def get_triangles(self, level=-1):\n\n \"\"\"\n Get the list of triangles.\n\n @param level refinement level (-1 for the last level). The coarsest level is 1. The level can be used\n to retrieve previous triangulation refinements: level=-1 will retrieve the last, \n level=-2 the previous one, etc.\n @return [([p0, p1, p2,..], (k0,k1,k2), [a0,a1,..]),..] where p0, p1, p2,.. are the \n point indices at the triangle corners, optionally followed by intermediate points (k0, k1, k2) and triangle cell attributes a1,a2.. \n \"\"\"\n return triangulate.get_triangles(self.hndls[level])\n \n\n def get_point_attributes(self, level=-1):\n\n \"\"\"\n Get the point attributes.\n\n @param level refinement level (-1 for the last level). The coarsest level is 1. The level can be used\n to retrieve previous triangulation refinements: level=-1 will retrieve the last, \n level=-2 the previous one, etc.\n @return [(a0,...), ....]\n \"\"\"\n return triangulate.get_point_attributes(self.hndls[level])\n \n\n def get_triangle_attributes(self, level=-1):\n\n \"\"\"\n Get the triangle attributes.\n\n @param level refinement level (-1 for the last level). The coarsest level is 1. The level can be used\n to retrieve previous triangulation refinements: level=-1 will retrieve the last, \n level=-2 the previous one, etc.\n @return [(a0,...), ....]\n \"\"\"\n return triangulate.get_triangle_attributes(self.hndls[level])\n\n\n # backward compatibility\n get_num_nodes = get_num_points\n set_nodes = set_points\n get_nodes = get_points\n set_attributes = set_point_attributes\n get_attributes = get_point_attributes\n \n \n # add some visualization capability to fast check the mesh\n \n \n def plot_mesh(self,level=-1):\n import matplotlib.pyplot as plt\n from matplotlib.path import Path\n import matplotlib.patches as patches\n \n mesh = self.get_triangles(level)\n points = self.get_points(level)\n\n verts = []\n codes = []\n \n fig, ax = plt.subplots()\n \n for _t in mesh:\n #([n1, n2, n3], (), [regiona_tag])\n p = _t[0]\n x1,y1 = points[p[0]][0]\n x2,y2 = points[p[1]][0]\n x3,y3 = points[p[2]][0]\n\n verts.append((x1, y1))\n verts.append((x2, y2))\n verts.append((x3, y3))\n verts.append((x1, y1))\n codes.append(Path.MOVETO)\n codes.append(Path.LINETO)\n codes.append(Path.LINETO)\n codes.append(Path.CLOSEPOLY)\n \n ax.text((x1+x2+x3)/3, (y1+y2+y3)/3, str(_t[2]))\n \n path = Path(verts, codes)\n\n patch = patches.PathPatch(path, facecolor='None', lw=1)\n ax.add_patch(patch)\n ax.margins(0.05)\n ax.axis('equal')\n\n return plt\n \n\n\n\n \n \n \n"
] |
[
[
"matplotlib.path.Path",
"matplotlib.pyplot.subplots",
"matplotlib.patches.PathPatch"
]
] |
OctThe16th/BetterTrainingDataMnist_RL_GAN
|
[
"fcc75c9ddf768d7c66c9fade3e86973a4c828624"
] |
[
"Environnement/Environnement.py"
] |
[
"import numpy as np\nfrom lightgbm import LGBMClassifier\nfrom keras.datasets import mnist\nfrom sklearn.metrics import f1_score\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nclass Environnement:\n def __init__(self, amount_per_class):\n self.amount_per_class = amount_per_class\n\n (self.x_train, self.y_train), (self.x_test, self.y_test) = mnist.load_data()\n self.x_train = self.x_train.astype(np.float32)\n self.x_test = self.x_test.astype(np.float32)\n\n self.x_train -= 127.5\n self.x_train /= 127.5\n self.x_test -= 127.5\n self.x_test /= 127.5\n\n\n self.class_indexes = [np.where(self.y_train == i) for i in range(10)]\n choices = np.array([np.random.choice(class_index[0], 1000)\n for class_index in self.class_indexes]).flatten()\n self.gbm_x_val = np.reshape(self.x_train[choices], (self.x_train[choices].shape[0], 28*28))\n self.y_val = self.y_train[choices]\n\n self.x_train = self.x_train[~choices]\n self.y_train = self.y_train[~choices]\n\n self.x_train = np.reshape(self.x_train, (self.x_train.shape[0], 28, 28, 1))\n\n self.gbm_x_train = np.reshape(self.x_train, (self.x_train.shape[0], 28 * 28))\n self.gbm_x_test = np.reshape(self.x_test, (self.x_test.shape[0], 28 * 28))\n\n self.model = LGBMClassifier(objective='multiclass', num_class=10, n_jobs=1, min_child_samples=1,\n min_child_weight=0, min_data_in_bin=1, verbosity=-1, verbose=-1)\n\n self.class_indexes = [np.where(self.y_train == i) for i in range(10)]\n\n def get_values(self, actions, targets):\n actions = np.reshape(actions, (actions.shape[0], 28*28))\n self.model.fit(actions, targets)\n pred_val = self.model.predict(self.gbm_x_val)\n pred_test = self.model.predict(self.gbm_x_test)\n val = f1_score(y_true=self.y_val, y_pred=pred_val, average=None)\n test = f1_score(y_true=self.y_test, y_pred=pred_test, average=None)\n\n return val, test\n\n def get_whole_training_set(self):\n return self.x_train, self.y_train\n\n def query_state(self):\n choices = np.array([np.random.choice(class_index[0], self.amount_per_class)\n for class_index in self.class_indexes]).flatten()\n state = self.x_train[choices]\n targets = self.y_train[choices]\n self.model.fit(self.gbm_x_train[choices], self.y_train[choices])\n pred = self.model.predict(self.gbm_x_val)\n f1 = f1_score(y_true=self.y_val, y_pred=pred, average=None)\n\n return state, f1, targets\n\nif __name__ == '__main__':\n env = Environnement(1)\n print(env.query_state())\n"
] |
[
[
"numpy.reshape",
"sklearn.metrics.f1_score",
"numpy.where",
"numpy.random.choice"
]
] |
pietrotrope/SolarSystemSimulation
|
[
"905eec31eb73e1203ee23a32846954b30bbc5925"
] |
[
"RocketSimulation.py"
] |
[
"import sys\nimport csv\nimport json\nimport math\nimport pygame\nimport numpy as np\nfrom pygame.locals import *\nimport pandas as pd\n\nfrom data import *\nfrom agent import agentsList, Agent\n\nglobal screenSize\nscreenSize = [1920, 1080]\n\n\ndef load_parameters(path):\n package = []\n file = open(path, 'r')\n j = json.load(file)\n\n for subgroup in j.values():\n package.append([cast(x) for x in subgroup.values()])\n\n env_variables = package.pop(4)\n file.close()\n return (package, env_variables)\n\n\ndef cast(x):\n try:\n return float(x)\n except Exception:\n return str(x)\n\n\nclass Environment:\n\n def __init__(self, vars):\n # Environmental Constants\n self.elev, self.t, self.g, self.M_air, self.R, self.gamma, self.P_zero = vars # noqa\n self.g_zero = self.g\n self.Re = 6356766\n # Layer base altitudes\n self.hb = [0, 11000, 20000, 32000, 47000, 51000, 71000]\n # Layer base pressures\n self.Pb = [101325, 22632.1, 5474.89,\n 868.019, 110.906, 66.9389, 3.95642]\n # Layer base temperatures\n self.Tb = [288.15, 216.65, 216.65, 228.65, 270.65, 270.65, 214.65]\n # Layer lapse rates\n self.Lm = [-0.0065, 0.0, 0.001, 0.0028, 0.0, -0.0028, -0.002]\n\n def get_geopotential_altitude(self, z: float) -> float:\n return self.Re*z / (self.Re+z)\n\n def atmo_heterosphere_equ(self, z: float, a, b, c, d, e):\n z_km = z/1000\n return math.exp(a * z_km**4 + b * z_km**3 + c * z_km**2 + d * z_km + e) # noqa\n\n def get_gravity(self, z: float) -> float:\n return self.g_zero * (self.Re / (self.Re + z))**2\n\n def get_temp(self, z: float, h: float) -> float:\n if h <= 84852:\n for i in range(len(self.hb)-1):\n if self.hb[i] <= h <= self.hb[i+1]:\n return (self.Tb[i] + self.Lm[i]*(h-self.hb[i]), i)\n return (self.Tb[i+1] + self.Lm[i+1]*(h-self.hb[i+1]), i+1)\n elif 86000 < z <= 91000:\n return (186.87, 7)\n elif 91000 < z <= 110000:\n if 91000 < z <= 100000:\n layer = 8\n elif 100000 < z <= 110000:\n layer = 9\n return (\n 263.1905 - 76.3232 * math.sqrt(1 - ((z - 91000) / -19942.9)**2), # noqa\n layer\n )\n elif 110000 < z <= 120000:\n return (240 + 0.012 * (z - 110000), 10)\n elif 120000 < z <= 1000000:\n if 120000 < z <= 150000:\n layer = 11\n elif 150000 < z <= 200000:\n layer = 12\n elif 200000 < z <= 300000:\n layer = 13\n elif 300000 < z <= 500000:\n layer = 14\n elif 500000 < z <= 750000:\n layer = 15\n elif 750000 < z <= 1000000:\n layer = 16\n xi = (z - 120000) * (6356766 + 120000) / (6356766 + z)\n return (1000 - 640 * math.exp(-0.00001875 * xi), layer)\n\n def get_pressure(self, z: float, h: float, T: float, b: int) -> float:\n\n if b <= 6:\n if self.Lm[b] != 0:\n return self.Pb[b] * (self.Tb[b]/T)**(self.g_zero*self.M_air/(self.R*self.Lm[b])) # noqa\n else:\n return self.Pb[b] * math.exp(-self.g_zero * self.M_air * (h-self.hb[b]) / (self.R*self.Tb[b])) # noqa\n elif b == 7:\n return self.atmo_heterosphere_equ(\n z, 0.000000, 2.159582e-6, -4.836957e-4, -0.1425192, 13.47530)\n elif b == 8:\n return self.atmo_heterosphere_equ(\n z, 0.000000, 3.304895e-5, -0.009062730, 0.6516698, -11.03037)\n elif b == 9:\n return self.atmo_heterosphere_equ(\n z, 0.000000, 6.693926e-5, -0.01945388, 1.719080, -47.75030)\n elif b == 10:\n return self.atmo_heterosphere_equ(\n z, 0.000000, -6.539316e-5, 0.02485568, -3.223620, 135.9355)\n elif b == 11:\n return self.atmo_heterosphere_equ(\n z, 2.283506e-7, -1.343221e-4, 0.02999016, -3.055446, 113.5764)\n elif b == 12:\n return self.atmo_heterosphere_equ(\n z, 1.209434e-8, -9.692458e-6, 0.003002041, -0.4523015, 19.19151)\n elif b == 13:\n return self.atmo_heterosphere_equ(\n z, 8.113942e-10, -9.822568e-7, 4.687616e-4, -0.1231710, 3.067409)\n elif b == 14:\n return self.atmo_heterosphere_equ(\n z, 9.814674e-11, -1.654439e-7, 1.148115e-4, -0.05431334, -2.011365)\n elif b == 15:\n return self.atmo_heterosphere_equ(\n z, -7.835161e-11, 1.964589e-7, -1.657213e-4, 0.04305869, -14.77132)\n elif b == 16:\n return self.atmo_heterosphere_equ(\n z, 2.813255e-11, -1.120689e-7, 1.695568e-4, -0.1188941, 14.56718)\n\n def get_density(self, z: float, P: float, T: float, b) -> float:\n if b <= 6:\n return (P * self.M_air)/(self.R * T)\n elif b == 7:\n return self.atmo_heterosphere_equ(\n z, 0.000000, -3.322622E-06, 9.111460E-04, -0.2609971, 5.944694)\n elif b == 8:\n return self.atmo_heterosphere_equ(\n z, 0.000000, 2.873405e-05, -0.008492037, 0.6541179, -23.62010)\n elif b == 9:\n return self.atmo_heterosphere_equ(\n z, -1.240774e-05, 0.005162063, -0.8048342, 55.55996, -1443.338)\n elif b == 10:\n return self.atmo_heterosphere_equ(\n z, 0.00000, -8.854164e-05, 0.03373254, -4.390837, 176.5294)\n elif b == 11:\n return self.atmo_heterosphere_equ(\n z, 3.661771e-07, -2.154344e-04, 0.04809214, -4.884744, 172.3597)\n elif b == 12:\n return self.atmo_heterosphere_equ(\n z, 1.906032e-08, -1.527799E-05, 0.004724294, -0.6992340, 20.50921)\n elif b == 13:\n return self.atmo_heterosphere_equ(\n z, 1.199282e-09, -1.451051e-06, 6.910474e-04, -0.1736220, -5.321644)\n elif b == 14:\n return self.atmo_heterosphere_equ(\n z, 1.140564e-10, -2.130756e-07, 1.570762e-04, -0.07029296, -12.89844)\n elif b == 15:\n return self.atmo_heterosphere_equ(\n z, 8.105631e-12, -2.358417e-09, -2.635110e-06, -0.01562608, -20.02246)\n elif b == 16:\n return self.atmo_heterosphere_equ(\n z, -3.701195e-12, -8.608611e-09, 5.118829e-05, -0.06600998, -6.137674)\n\n def get_c(self, T: float) -> float:\n return math.sqrt((self.gamma * self.R * T) / self.M_air)\n\n def get_status(self, z: float):\n h = round(self.get_geopotential_altitude(z), 0)\n self.g = self.get_gravity(z)\n self.T, b = self.get_temp(z, h)\n self.P = self.get_pressure(z, h, self.T, b)\n self.Rho = self.get_density(z, self.P, self.T, b)\n self.c = self.get_c(self.T)\n\n\nclass System:\n def __init__(self, params, env, burn_time: float):\n package = params\n print(package)\n\n # Environment\n self.env = env\n\n # Burn time\n self.num_steps = int(burn_time // self.env.t)\n self.burn_time = self.num_steps * self.env.t\n\n # Engine specs\n self.etype = package[0][0]\n package[0].pop(0)\n if self.etype == \"Liquid\":\n self.isp, self.thrust = package[0]\n elif self.etype == \"Solid\":\n self.isp, self.avg_thrust, path = package[0] # noqa\n with(open(path)) as f:\n csv_reader = csv.reader(f)\n self.thrust_curve = {}\n for row in csv_reader:\n self.thrust_curve.update({\n float(row[0]): float(row[1])\n })\n f.close()\n\n # Fuel Specs\n if self.etype == \"Liquid\":\n self.OFratio, self.Reserve = package[1]\n elif self.etype == \"Solid\":\n self.OFratio = 0\n self.Reserve = package[1][0]\n # Flow Rate\n if self.etype == \"Liquid\":\n self.w = (self.thrust/self.env.g_zero)/self.isp\n elif self.etype == \"Solid\":\n self.w = (self.avg_thrust/self.env.g_zero)/self.isp\n self.dF = self.w * (1 / (self.OFratio + 1))\n self.dOx = (self.w - self.dF)\n\n # Fuel & Oxidizer\n self.F = (self.dF * self.burn_time)/(1 - self.Reserve/100)\n self.Ox = (self.dOx * self.burn_time)/(1 - self.Reserve/100)\n\n # Mass\n self.dry_mass = package[2][0]\n\n # Aerodynamics\n self.Cd, self.cross_section = package[3]\n\n # Output\n self.csvout = package[4][0]\n\n self.field_names = [\"t\", \"thrust\", \"drag\", \"m\", \"v\", \"mach\", \"a\", \"altitude\",\n \"asl\", \"twr\", \"max_v\", \"max_mach\", \"max_acc\", \"min_acc\", \"max_g\", \"min_g\"]\n with open(self.csvout, \"w\", newline=\"\") as f:\n csv_writer = csv.writer(f)\n csv_writer.writerow(self.field_names)\n f.close()\n\n# Flight\n def launch(self):\n \"\"\"Runs a simulation within the given parameters.\"\"\"\n # Variables setup\n self.t = 0\n self.altitude = 0\n self.asl = self.altitude + self.env.elev\n self.calc_mass()\n self.env.get_status(self.asl)\n self.calc_thrust()\n self.calc_twr()\n self.drag = 0\n self.v = 0\n self.max_v = 0\n self.mach = 0\n self.max_mach = 0\n self.max_acc = 0\n self.max_g = 0\n self.min_acc = 0\n self.min_g = 0\n self.a = 0\n self.j = 0\n self.s = 0\n\n # Used by matplotlib\n self.data = [[], [], [], [], [], [], [], [], [], [], []]\n\n # Accelaration phase\n for i in range(self.num_steps):\n # Output management\n self.add_data()\n # Environment-related\n self.update_env()\n # Thrust-related\n self.calc_thrust()\n # Accelaration/derivative-related\n self.calc_acc()\n self.calc_additional_derivatives()\n # Position-related\n self.set_altitude()\n # Velocity-related\n self.calc_velocity()\n # Force-related\n self.calc_drag()\n self.calc_twr()\n # Mass-related\n self.calc_propellant()\n self.calc_mass()\n # Time-related\n self.t += self.env.t\n\n if self.a > self.max_acc:\n self.max_acc = self.a\n self.max_g = self.max_acc/self.env.g\n\n if self.v > self.max_v:\n self.max_v = self.v\n self.max_mach = self.mach\n\n self.thrust = 0\n\n # Deceleration phase\n while self.v > 0:\n # Output management\n self.add_data()\n # Environment-related\n self.update_env()\n # Accelaration/derivative-related\n self.calc_acc()\n self.calc_additional_derivatives()\n # Position-related\n self.set_altitude()\n # Velocity-related\n self.calc_velocity()\n # Force-related\n self.calc_drag()\n self.calc_twr()\n # Mass-related\n self.calc_mass()\n # Time-related\n self.t += self.env.t\n\n if self.a < self.min_acc:\n self.min_acc = self.a\n self.min_g = self.min_acc/self.env.g\n\n self.output(\"max_v\", \"max_mach\", \"max_acc\",\n \"min_acc\", \"max_g\", \"min_g\")\n\n def suicide_burn(self):\n \"\"\"Run a suicide burn simulation, will affct ascent simulation.\"\"\"\n self.Vt = math.sqrt((2 * self.m * self.env.g) / (self.env.Rho * self.cross_section * self.Cd)) # noqa\n\n# Mass\n def calc_mass(self):\n self.propellant_mass = (self.Ox + self.F)\n self.m = self.propellant_mass + self.dry_mass\n\n def calc_propellant(self):\n if self.etype == \"Liquid\":\n self.w = (self.thrust/self.env.g_zero)/self.isp\n elif self.etype == \"Solid\":\n self.w = (self.avg_thrust/self.env.g_zero)/self.isp\n self.dF = self.w * (1/(self.OFratio+1))\n self.dOx = (self.w - self.dF)\n self.Ox -= self.dOx * self.env.t\n self.F -= self.dF * self.env.t\n\n# Position\n def set_altitude(self):\n self.altitude += self.v * self.env.t + (self.a * self.env.t**2)/2 # noqa\n self.asl = self.altitude + self.env.elev\n\n# Derivatives of position\n def calc_velocity(self):\n self.v += self.a * self.env.t\n self.mach = self.v/self.env.c\n\n def calc_acc(self):\n self.a = (self.thrust - (self.m * self.env.g + self.drag)) / self.m\n\n def calc_additional_derivatives(self):\n self.j = (self.a - self.data[4][-1]) / self.env.t\n self.s = (self.j - self.data[5][-1]) / self.env.t\n\n# Forces\n def calc_thrust(self):\n if self.etype == \"Liquid\":\n pass\n elif self.etype == \"Solid\":\n self.thrust = self.thrust_curve[round(self.t, 3)]\n\n def calc_drag(self):\n self.drag = 0.5 * (self.env.Rho * self.v**2 * self.Cd * self.cross_section) # noqa\n\n def calc_twr(self):\n self.twr = self.thrust / (self.m * self.env.g)\n\n# Environment\n def update_env(self):\n self.env.get_status(self.asl)\n\n# Ouput\n def output(self, *args):\n values = []\n for field in self.field_names:\n value = str(round(eval(field, self.__dict__), 5))\n values.append(value)\n\n with open(self.csvout, \"a\", newline=\"\") as f:\n csv_writer = csv.writer(f)\n csv_writer.writerow(values)\n f.close()\n\n def add_data(self):\n self.data[0].append(self.t)\n self.data[1].append(self.altitude)\n self.data[2].append(self.v)\n self.data[3].append(self.env.c)\n self.data[4].append(self.a)\n self.data[5].append(self.j)\n self.data[6].append(self.s)\n self.data[7].append(self.drag)\n self.output(\"t\", \"thrust\", \"drag\", \"m\", \"v\",\n \"mach\", \"a\", \"altitude\", \"asl\", \"twr\")\n\n\ndef run_simulation(burn_time):\n params = load_parameters(\"RocketSimulationData/info.json\")\n env = Environment(params[1])\n s = System(params[0], env, burn_time)\n s.launch()\n\n\ndef renderAgents(screen, res, ratio):\n screen.fill((0, 0, 0))\n\n pygame.draw.rect(screen, (0, 0, 255), (0, 1080-108, 1920, 108))\n\n pos = screenSize[1]-158 - res[\"altitude\"]*ratio\n # print(\"altitude: \"+str(res[\"altitude\"])+\", pos: \"+str(pos))\n\n pygame.draw.rect(screen, (255, 255, 255), (940, pos, 20, 50))\n\n pygame.display.update()\n\n\ndef simulateRocket(screen):\n\n run_simulation(150)\n\n df = pd.read_csv('RocketSimulationData/Flight.csv')\n result = df.to_dict(\"index\")\n\n ratio = screenSize[1]/1000000\n\n interestingPoint = None\n\n for res in result:\n # print(\"time: \"+str(result[res][\"t\"])+\" Altitude: \"+str(result[res][\"altitude\"]))\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n renderAgents(screen, result[res], ratio)\n if result[res][\"altitude\"] < 800000:\n interestingPoint = result[res]\n pygame.display.update()\n return interestingPoint\n"
] |
[
[
"pandas.read_csv"
]
] |
wilsonloo/my_traffic_tf2_yolo3
|
[
"322104de934794870822e1ea2494ee8228de2540"
] |
[
"evaluate.py"
] |
[
"#! /usr/bin/env python\n# coding=utf-8\n#================================================================\n# Copyright (C) 2019 * Ltd. All rights reserved.\n#\n# Editor : VIM\n# File name : evaluate.py\n# Author : YunYang1994\n# Created date: 2019-02-21 15:30:26\n# Description :\n#\n#================================================================\n\nimport cv2\nimport os\nimport shutil\nimport numpy as np\n\n#lws\n#import tensorflow as tf\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\nimport core.utils as utils\nfrom core.config import cfg\nfrom core.yolov3 import YOLOV3\n\nclass YoloTest(object):\n def __init__(self):\n self.input_size = cfg.TEST.INPUT_SIZE\n self.anchor_per_scale = cfg.YOLO.ANCHOR_PER_SCALE\n self.classes = utils.read_class_names(cfg.YOLO.CLASSES)\n self.num_classes = len(self.classes)\n self.anchors = np.array(utils.get_anchors(cfg.YOLO.ANCHORS))\n self.score_threshold = cfg.TEST.SCORE_THRESHOLD\n self.iou_threshold = cfg.TEST.IOU_THRESHOLD\n self.moving_ave_decay = cfg.YOLO.MOVING_AVE_DECAY\n self.annotation_path = cfg.TEST.ANNOT_PATH\n self.weight_file = cfg.TEST.WEIGHT_FILE\n self.write_image = cfg.TEST.WRITE_IMAGE\n self.write_image_path = cfg.TEST.WRITE_IMAGE_PATH\n self.show_label = cfg.TEST.SHOW_LABEL\n\n with tf.name_scope('input'):\n self.input_data = tf.placeholder(dtype=tf.float32, name='input_data')\n self.trainable = tf.placeholder(dtype=tf.bool, name='trainable')\n\n model = YOLOV3(self.input_data, self.trainable)\n self.pred_sbbox, self.pred_mbbox, self.pred_lbbox = model.pred_sbbox, model.pred_mbbox, model.pred_lbbox\n\n with tf.name_scope('ema'):\n ema_obj = tf.train.ExponentialMovingAverage(self.moving_ave_decay)\n\n self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\n self.saver = tf.train.Saver(ema_obj.variables_to_restore())\n self.saver.restore(self.sess, self.weight_file)\n\n def predict(self, image):\n\n org_image = np.copy(image)\n org_h, org_w, _ = org_image.shape\n\n image_data = utils.image_preporcess(image, [self.input_size, self.input_size])\n image_data = image_data[np.newaxis, ...]\n\n pred_sbbox, pred_mbbox, pred_lbbox = self.sess.run(\n [self.pred_sbbox, self.pred_mbbox, self.pred_lbbox],\n feed_dict={\n self.input_data: image_data,\n self.trainable: False\n }\n )\n\n pred_bbox = np.concatenate([np.reshape(pred_sbbox, (-1, 5 + self.num_classes)),\n np.reshape(pred_mbbox, (-1, 5 + self.num_classes)),\n np.reshape(pred_lbbox, (-1, 5 + self.num_classes))], axis=0)\n bboxes = utils.postprocess_boxes(pred_bbox, (org_h, org_w), self.input_size, self.score_threshold)\n bboxes = utils.nms(bboxes, self.iou_threshold)\n\n return bboxes\n\n def evaluate(self):\n predicted_dir_path = './mAP/predicted'\n ground_truth_dir_path = './mAP/ground-truth'\n if os.path.exists(predicted_dir_path): shutil.rmtree(predicted_dir_path)\n if os.path.exists(ground_truth_dir_path): shutil.rmtree(ground_truth_dir_path)\n if os.path.exists(self.write_image_path): shutil.rmtree(self.write_image_path)\n os.mkdir(predicted_dir_path)\n os.mkdir(ground_truth_dir_path)\n os.mkdir(self.write_image_path)\n\n with open(self.annotation_path, 'r') as annotation_file:\n for num, line in enumerate(annotation_file):\n annotation = line.strip().split()\n image_path = annotation[0]\n image_name = image_path.split('/')[-1]\n image = cv2.imread(image_path)\n bbox_data_gt = np.array([list(map(int, box.split(','))) for box in annotation[1:]])\n\n if len(bbox_data_gt) == 0:\n bboxes_gt=[]\n classes_gt=[]\n else:\n bboxes_gt, classes_gt = bbox_data_gt[:, :4], bbox_data_gt[:, 4]\n ground_truth_path = os.path.join(ground_truth_dir_path, str(num) + '.txt')\n\n print('=> ground truth of %s:' % image_name)\n num_bbox_gt = len(bboxes_gt)\n with open(ground_truth_path, 'w') as f:\n for i in range(num_bbox_gt):\n class_name = self.classes[classes_gt[i]]\n xmin, ymin, xmax, ymax = list(map(str, bboxes_gt[i]))\n bbox_mess = ' '.join([class_name, xmin, ymin, xmax, ymax]) + '\\n'\n f.write(bbox_mess)\n print('\\t' + str(bbox_mess).strip())\n print('=> predict result of %s:' % image_name)\n predict_result_path = os.path.join(predicted_dir_path, str(num) + '.txt')\n bboxes_pr = self.predict(image)\n\n if self.write_image:\n image = utils.draw_bbox(image, bboxes_pr, show_label=self.show_label)\n cv2.imwrite(self.write_image_path+image_name, image)\n\n with open(predict_result_path, 'w') as f:\n for bbox in bboxes_pr:\n coor = np.array(bbox[:4], dtype=np.int32)\n score = bbox[4]\n class_ind = int(bbox[5])\n class_name = self.classes[class_ind]\n score = '%.4f' % score\n xmin, ymin, xmax, ymax = list(map(str, coor))\n bbox_mess = ' '.join([class_name, score, xmin, ymin, xmax, ymax]) + '\\n'\n f.write(bbox_mess)\n print('\\t' + str(bbox_mess).strip())\n\n def voc_2012_test(self, voc2012_test_path):\n\n img_inds_file = os.path.join(voc2012_test_path, 'ImageSets', 'Main', 'test.txt')\n with open(img_inds_file, 'r') as f:\n txt = f.readlines()\n image_inds = [line.strip() for line in txt]\n\n results_path = 'results/VOC2012/Main'\n if os.path.exists(results_path):\n shutil.rmtree(results_path)\n os.makedirs(results_path)\n\n for image_ind in image_inds:\n image_path = os.path.join(voc2012_test_path, 'JPEGImages', image_ind + '.jpg')\n image = cv2.imread(image_path)\n\n print('predict result of %s:' % image_ind)\n bboxes_pr = self.predict(image)\n for bbox in bboxes_pr:\n coor = np.array(bbox[:4], dtype=np.int32)\n score = bbox[4]\n class_ind = int(bbox[5])\n class_name = self.classes[class_ind]\n score = '%.4f' % score\n xmin, ymin, xmax, ymax = list(map(str, coor))\n bbox_mess = ' '.join([image_ind, score, xmin, ymin, xmax, ymax]) + '\\n'\n with open(os.path.join(results_path, 'comp4_det_test_' + class_name + '.txt'), 'a') as f:\n f.write(bbox_mess)\n print('\\t' + str(bbox_mess).strip())\n\n\nif __name__ == '__main__': YoloTest().evaluate()\n\n\n\n"
] |
[
[
"tensorflow.compat.v1.ConfigProto",
"tensorflow.compat.v1.disable_v2_behavior",
"numpy.reshape",
"tensorflow.compat.v1.train.ExponentialMovingAverage",
"numpy.copy",
"tensorflow.compat.v1.placeholder",
"numpy.array",
"tensorflow.compat.v1.name_scope"
]
] |
ntuecon/2018groupCE
|
[
"51c4442bcae8fbd3841b12b8f87d5eefe11e23f8"
] |
[
"MarketVersion/ConsumerCES_original.py"
] |
[
"class Consumer:\n \"\"\"This class is the optimization of individual choice of consumer\"\"\"\n #def __init__(self,GoodPrices,FacPrices):\n def __init__(self,alpha,beta,theta):\n import numpy as np\n #self.GoodPrices=np.array(GoodPrices)\n #self.FacPrices=np.array(FacPrices)\n self.alpha=np.array(alpha)\n self.gamma=1.0\n self.rho=0.0\n self.beta=1.0*beta\n self.theta=1.0*np.array(theta)\n self.ng=len(self.alpha)\n self.nf=len(self.theta)\n\n def utility(self,GFvec,sign=1.0):\n from math import log\n import numpy as np\n \"\"\"What's below is the linear algebra version of above equation\"\"\"\n \"\"\"Objective function of consumer utility\"\"\"\n GFvec=np.array(GFvec[0:self.ng+self.nf])\n #GFvec=np.array(GFvec[0:self.ng])\n return sign*((self.alpha.dot(GFvec[0:self.ng]**self.gamma))**((1-self.rho)/self.gamma)-np.ones(len(self.theta)).dot(self.beta*GFvec[self.ng:(self.ng+self.nf)]**(self.theta+1)/(self.theta+1)))\n #return sign*(self.alpha.dot(np.log(GFvec)))\n\n \"\"\"def budget(self,GFvec):\n import numpy as np\n return 100-self.GoodPrices.dot(GFvec)\"\"\"\n\n def cons(self):\n \"\"\"\n 1.Budget constraint\n 2&3.Nonnegative criterias\n \"\"\"\n import numpy as np\n return ({'type' : 'ineq',\n 'fun' : lambda GFvec: self.budget(GFvec)},\n {'type' : 'ineq',\n 'fun' : lambda GFvec: GFvec})\n \"\"\"'fun' : lambda goods: np.array(self.FacPrices.dot(GFvec[self.ng:(self.ng+self.nf)])-self.GoodPrices.dot(GFvec[0:self.ng]))},\"\"\"\n \n def utility_max(self):\n import numpy as np\n from scipy.optimize import minimize\n \"\"\"\n 1.The package of minimize can be use as maximize ,if the\n objective function is multiply by -1.\n 2.\"cons\" set as the constrain of optimization problem.\n 3.If we use SLSQP method, the jacobian of objective function is necessary.\n The jacobian means the partial derivative of every independent variables. \n \"\"\"\n #GFvec=[[]]*(self.ng+self.nf)\n \"\"\"res = minimize(self.utility, np.ones(self.ng+self.nf), args=(-1.0,),\"\"\"\n res = minimize(self.utility, [10.0]*(self.ng+self.nf), args=(-1.0,),\n constraints=self.cons(), method='SLSQP', options={'disp': True})\n return res.x\n"
] |
[
[
"numpy.array"
]
] |
fumitoh/spyder
|
[
"12294fec88a2f61c756538ac38bd748d8e7b3f82"
] |
[
"external-deps/spyder-kernels/spyder_kernels/console/kernel.py"
] |
[
"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) 2009- Spyder Kernels Contributors\n#\n# Licensed under the terms of the MIT License\n# (see spyder_kernels/__init__.py for details)\n# -----------------------------------------------------------------------------\n\n\"\"\"\nSpyder kernel for Jupyter.\n\"\"\"\n\n# Standard library imports\nfrom distutils.version import LooseVersion\nimport os\nimport sys\nimport threading\n\n# Third-party imports\nimport ipykernel\nfrom ipykernel.ipkernel import IPythonKernel\nfrom ipykernel.zmqshell import ZMQInteractiveShell\nfrom traitlets.config.loader import LazyConfigValue\n\n# Local imports\nfrom spyder_kernels.py3compat import TEXT_TYPES, to_text_string\nfrom spyder_kernels.comms.frontendcomm import FrontendComm\nfrom spyder_kernels.py3compat import PY3, input\nfrom spyder_kernels.utils.iofuncs import iofunctions\nfrom spyder_kernels.utils.mpl import (\n MPL_BACKENDS_FROM_SPYDER, MPL_BACKENDS_TO_SPYDER, INLINE_FIGURE_FORMATS)\nfrom spyder_kernels.utils.nsview import get_remote_data, make_remote_view\n\n\n# Excluded variables from the Variable Explorer (i.e. they are not\n# shown at all there)\nEXCLUDED_NAMES = ['In', 'Out', 'exit', 'get_ipython', 'quit']\n\n\nclass SpyderShell(ZMQInteractiveShell):\n \"\"\"Spyder shell.\"\"\"\n\n def ask_exit(self):\n \"\"\"Engage the exit actions.\"\"\"\n self.kernel.frontend_comm.close_thread()\n return super(SpyderShell, self).ask_exit()\n\n def get_local_scope(self, stack_depth):\n \"\"\"Get local scope at given frame depth.\"\"\"\n frame = sys._getframe(stack_depth + 1)\n if self.kernel._pdb_frame is frame:\n # we also give the globals because they might not be in\n # self.user_ns\n namespace = frame.f_globals.copy()\n namespace.update(self.kernel._pdb_locals)\n return namespace\n else:\n return frame.f_locals\n\n\nclass SpyderKernel(IPythonKernel):\n \"\"\"Spyder kernel for Jupyter.\"\"\"\n\n shell_class = SpyderShell\n\n def __init__(self, *args, **kwargs):\n super(SpyderKernel, self).__init__(*args, **kwargs)\n\n self.comm_manager.get_comm = self._get_comm\n self.frontend_comm = FrontendComm(self)\n\n # All functions that can be called through the comm\n handlers = {\n 'set_breakpoints': self.set_spyder_breakpoints,\n 'set_pdb_ignore_lib': self.set_pdb_ignore_lib,\n 'set_pdb_execute_events': self.set_pdb_execute_events,\n 'set_pdb_use_exclamation_mark': self.set_pdb_use_exclamation_mark,\n 'get_value': self.get_value,\n 'load_data': self.load_data,\n 'save_namespace': self.save_namespace,\n 'is_defined': self.is_defined,\n 'get_doc': self.get_doc,\n 'get_source': self.get_source,\n 'set_value': self.set_value,\n 'remove_value': self.remove_value,\n 'copy_value': self.copy_value,\n 'set_cwd': self.set_cwd,\n 'get_cwd': self.get_cwd,\n 'get_syspath': self.get_syspath,\n 'get_env': self.get_env,\n 'close_all_mpl_figures': self.close_all_mpl_figures,\n 'show_mpl_backend_errors': self.show_mpl_backend_errors,\n 'get_namespace_view': self.get_namespace_view,\n 'set_namespace_view_settings': self.set_namespace_view_settings,\n 'get_var_properties': self.get_var_properties,\n 'set_sympy_forecolor': self.set_sympy_forecolor,\n 'update_syspath': self.update_syspath,\n 'is_special_kernel_valid': self.is_special_kernel_valid,\n 'get_matplotlib_backend': self.get_matplotlib_backend,\n 'pdb_input_reply': self.pdb_input_reply,\n '_interrupt_eventloop': self._interrupt_eventloop,\n }\n for call_id in handlers:\n self.frontend_comm.register_call_handler(\n call_id, handlers[call_id])\n\n self.namespace_view_settings = {}\n self._pdb_obj = None\n self._pdb_step = None\n self._do_publish_pdb_state = True\n self._mpl_backend_error = None\n self._running_namespace = None\n self._pdb_input_line = None\n\n # -- Public API -----------------------------------------------------------\n def frontend_call(self, blocking=False, broadcast=True,\n timeout=None, callback=None):\n \"\"\"Call the frontend.\"\"\"\n # If not broadcast, send only to the calling comm\n if broadcast:\n comm_id = None\n else:\n comm_id = self.frontend_comm.calling_comm_id\n\n return self.frontend_comm.remote_call(\n blocking=blocking,\n comm_id=comm_id,\n callback=callback,\n timeout=timeout)\n\n # --- For the Variable Explorer\n def set_namespace_view_settings(self, settings):\n \"\"\"Set namespace_view_settings.\"\"\"\n self.namespace_view_settings = settings\n\n def get_namespace_view(self):\n \"\"\"\n Return the namespace view\n\n This is a dictionary with the following structure\n\n {'a':\n {\n 'type': 'str',\n 'size': 1,\n 'view': '1',\n 'python_type': 'int',\n 'numpy_type': 'Unknown'\n }\n }\n\n Here:\n * 'a' is the variable name.\n * 'type' and 'size' are self-evident.\n * 'view' is its value or its repr computed with\n `value_to_display`.\n * 'python_type' is its Python type computed with\n `get_type_string`.\n * 'numpy_type' is its Numpy type (if any) computed with\n `get_numpy_type_string`.\n \"\"\"\n\n settings = self.namespace_view_settings\n if settings:\n ns = self._get_current_namespace()\n view = make_remote_view(ns, settings, EXCLUDED_NAMES)\n return view\n else:\n return None\n\n def get_var_properties(self):\n \"\"\"\n Get some properties of the variables in the current\n namespace\n \"\"\"\n settings = self.namespace_view_settings\n if settings:\n ns = self._get_current_namespace()\n data = get_remote_data(ns, settings, mode='editable',\n more_excluded_names=EXCLUDED_NAMES)\n\n properties = {}\n for name, value in list(data.items()):\n properties[name] = {\n 'is_list': isinstance(value, (tuple, list)),\n 'is_dict': isinstance(value, dict),\n 'is_set': isinstance(value, set),\n 'len': self._get_len(value),\n 'is_array': self._is_array(value),\n 'is_image': self._is_image(value),\n 'is_data_frame': self._is_data_frame(value),\n 'is_series': self._is_series(value),\n 'array_shape': self._get_array_shape(value),\n 'array_ndim': self._get_array_ndim(value)\n }\n\n return properties\n else:\n return None\n\n def get_value(self, name):\n \"\"\"Get the value of a variable\"\"\"\n ns = self._get_current_namespace()\n self._do_publish_pdb_state = False\n return ns[name]\n\n def set_value(self, name, value):\n \"\"\"Set the value of a variable\"\"\"\n ns = self._get_reference_namespace(name)\n ns[name] = value\n self.log.debug(ns)\n\n def remove_value(self, name):\n \"\"\"Remove a variable\"\"\"\n ns = self._get_reference_namespace(name)\n ns.pop(name)\n\n def copy_value(self, orig_name, new_name):\n \"\"\"Copy a variable\"\"\"\n ns = self._get_reference_namespace(orig_name)\n ns[new_name] = ns[orig_name]\n\n def load_data(self, filename, ext, overwrite=False):\n \"\"\"\n Load data from filename.\n\n Use 'overwrite' to determine if conflicts between variable names need\n to be handle or not.\n\n For example, if a loaded variable is call 'var'\n and there is already a variable 'var' in the namespace, having\n 'overwrite=True' will cause 'var' to be updated.\n In the other hand, with 'overwrite=False', a new variable will be\n created with a sufix starting with 000 i.e 'var000' (default behavior).\n \"\"\"\n from spyder_kernels.utils.misc import fix_reference_name\n\n glbs = self._mglobals()\n load_func = iofunctions.load_funcs[ext]\n data, error_message = load_func(filename)\n\n if error_message:\n return error_message\n\n if not overwrite:\n # We convert to list since we mutate this dictionary\n for key in list(data.keys()):\n new_key = fix_reference_name(key, blacklist=list(glbs.keys()))\n if new_key != key:\n data[new_key] = data.pop(key)\n\n try:\n glbs.update(data)\n except Exception as error:\n return str(error)\n\n return None\n\n def save_namespace(self, filename):\n \"\"\"Save namespace into filename\"\"\"\n ns = self._get_current_namespace()\n settings = self.namespace_view_settings\n data = get_remote_data(ns, settings, mode='picklable',\n more_excluded_names=EXCLUDED_NAMES).copy()\n return iofunctions.save(data, filename)\n\n # --- For Pdb\n def is_debugging(self):\n \"\"\"\n Check if we are currently debugging.\n \"\"\"\n return bool(self._pdb_frame)\n\n def _do_complete(self, code, cursor_pos):\n \"\"\"Call parent class do_complete\"\"\"\n return super(SpyderKernel, self).do_complete(code, cursor_pos)\n\n def do_complete(self, code, cursor_pos):\n \"\"\"\n Call PdB complete if we are debugging.\n\n Public method of ipykernel overwritten for debugging.\n \"\"\"\n if self.is_debugging():\n return self._pdb_obj.do_complete(code, cursor_pos)\n return self._do_complete(code, cursor_pos)\n\n def publish_pdb_state(self):\n \"\"\"\n Publish Variable Explorer state and Pdb step through\n send_spyder_msg.\n \"\"\"\n if self._pdb_obj and self._do_publish_pdb_state:\n state = dict(namespace_view = self.get_namespace_view(),\n var_properties = self.get_var_properties(),\n step = self._pdb_step)\n self.frontend_call(blocking=False).pdb_state(state)\n self._do_publish_pdb_state = True\n\n def set_spyder_breakpoints(self, breakpoints):\n \"\"\"\n Handle a message from the frontend\n \"\"\"\n if self._pdb_obj:\n self._pdb_obj.set_spyder_breakpoints(breakpoints)\n\n def set_pdb_ignore_lib(self, state):\n \"\"\"\n Change the \"Ignore libraries while stepping\" debugger setting.\n \"\"\"\n if self._pdb_obj:\n self._pdb_obj.pdb_ignore_lib = state\n\n def set_pdb_execute_events(self, state):\n \"\"\"\n Handle a message from the frontend\n \"\"\"\n if self._pdb_obj:\n self._pdb_obj.pdb_execute_events = state\n\n def set_pdb_use_exclamation_mark(self, state):\n \"\"\"\n Set an option on the current debugging session to decide wether\n the Pdb commands needs to be prefixed by '!'\n \"\"\"\n if self._pdb_obj:\n self._pdb_obj.pdb_use_exclamation_mark = state\n\n def pdb_input_reply(self, line, echo_stack_entry=True):\n \"\"\"Get a pdb command from the frontend.\"\"\"\n if self._pdb_obj:\n self._pdb_obj._disable_next_stack_entry = not echo_stack_entry\n self._pdb_input_line = line\n if self.eventloop:\n # Interrupting the eventloop is only implemented when a message is\n # received on the shell channel, but this message is queued and\n # won't be processed because an `execute` message is being\n # processed. Therefore we process the message here (comm channel)\n # and request a dummy message to be sent on the shell channel to\n # stop the eventloop. This will call back `_interrupt_eventloop`.\n self.frontend_call().request_interrupt_eventloop()\n\n def cmd_input(self, prompt=''):\n \"\"\"\n Special input function for commands.\n Runs the eventloop while debugging.\n \"\"\"\n # Only works if the comm is open and this is a pdb prompt.\n if not self.frontend_comm.is_open() or not self._pdb_frame:\n return input(prompt)\n\n # Flush output before making the request.\n sys.stderr.flush()\n sys.stdout.flush()\n\n # Send the input request.\n self._pdb_input_line = None\n self.frontend_call().pdb_input(prompt)\n\n # Allow GUI event loop to update\n if PY3:\n is_main_thread = (\n threading.current_thread() is threading.main_thread())\n else:\n is_main_thread = isinstance(\n threading.current_thread(), threading._MainThread)\n\n # Get input by running eventloop\n if is_main_thread and self.eventloop:\n while self._pdb_input_line is None:\n eventloop = self.eventloop\n if eventloop:\n eventloop(self)\n else:\n break\n\n # Get input by blocking\n if self._pdb_input_line is None:\n self.frontend_comm.wait_until(\n lambda: self._pdb_input_line is not None)\n\n return self._pdb_input_line\n\n def _interrupt_eventloop(self):\n \"\"\"Interrupts the eventloop.\"\"\"\n # Receiving the request is enough to stop the eventloop.\n pass\n\n # --- For the Help plugin\n def is_defined(self, obj, force_import=False):\n \"\"\"Return True if object is defined in current namespace\"\"\"\n from spyder_kernels.utils.dochelpers import isdefined\n\n ns = self._get_current_namespace(with_magics=True)\n return isdefined(obj, force_import=force_import, namespace=ns)\n\n def get_doc(self, objtxt):\n \"\"\"Get object documentation dictionary\"\"\"\n try:\n import matplotlib\n matplotlib.rcParams['docstring.hardcopy'] = True\n except:\n pass\n from spyder_kernels.utils.dochelpers import getdoc\n\n obj, valid = self._eval(objtxt)\n if valid:\n return getdoc(obj)\n\n def get_source(self, objtxt):\n \"\"\"Get object source\"\"\"\n from spyder_kernels.utils.dochelpers import getsource\n\n obj, valid = self._eval(objtxt)\n if valid:\n return getsource(obj)\n\n # -- For Matplolib\n def get_matplotlib_backend(self):\n \"\"\"Get current matplotlib backend.\"\"\"\n try:\n import matplotlib\n return MPL_BACKENDS_TO_SPYDER[matplotlib.get_backend()]\n except Exception:\n return None\n\n def set_matplotlib_backend(self, backend, pylab=False):\n \"\"\"Set matplotlib backend given a Spyder backend option.\"\"\"\n mpl_backend = MPL_BACKENDS_FROM_SPYDER[to_text_string(backend)]\n self._set_mpl_backend(mpl_backend, pylab=pylab)\n\n def set_mpl_inline_figure_format(self, figure_format):\n \"\"\"Set the inline figure format to use with matplotlib.\"\"\"\n mpl_figure_format = INLINE_FIGURE_FORMATS[figure_format]\n self._set_config_option(\n 'InlineBackend.figure_format', mpl_figure_format)\n\n def set_mpl_inline_resolution(self, resolution):\n \"\"\"Set inline figure resolution.\"\"\"\n if LooseVersion(ipykernel.__version__) < LooseVersion('4.5'):\n option = 'savefig.dpi'\n else:\n option = 'figure.dpi'\n self._set_mpl_inline_rc_config(option, resolution)\n\n def set_mpl_inline_figure_size(self, width, height):\n \"\"\"Set inline figure size.\"\"\"\n value = (width, height)\n self._set_mpl_inline_rc_config('figure.figsize', value)\n\n def set_mpl_inline_bbox_inches(self, bbox_inches):\n \"\"\"\n Set inline print figure bbox inches.\n\n The change is done by updating the 'print_figure_kwargs' config dict.\n \"\"\"\n from IPython.core.getipython import get_ipython\n config = get_ipython().kernel.config\n inline_config = (\n config['InlineBackend'] if 'InlineBackend' in config else {})\n print_figure_kwargs = (\n inline_config['print_figure_kwargs']\n if 'print_figure_kwargs' in inline_config else {})\n bbox_inches_dict = {\n 'bbox_inches': 'tight' if bbox_inches else None}\n print_figure_kwargs.update(bbox_inches_dict)\n\n # This seems to be necessary for newer versions of Traitlets because\n # print_figure_kwargs doesn't return a dict.\n if isinstance(print_figure_kwargs, LazyConfigValue):\n figure_kwargs_dict = print_figure_kwargs.to_dict().get('update')\n if figure_kwargs_dict:\n print_figure_kwargs = figure_kwargs_dict\n\n self._set_config_option(\n 'InlineBackend.print_figure_kwargs', print_figure_kwargs)\n\n # -- For completions\n def set_jedi_completer(self, use_jedi):\n \"\"\"Enable/Disable jedi as the completer for the kernel.\"\"\"\n self._set_config_option('IPCompleter.use_jedi', use_jedi)\n\n def set_greedy_completer(self, use_greedy):\n \"\"\"Enable/Disable greedy completer for the kernel.\"\"\"\n self._set_config_option('IPCompleter.greedy', use_greedy)\n\n def set_autocall(self, autocall):\n \"\"\"Enable/Disable autocall funtionality.\"\"\"\n self._set_config_option('ZMQInteractiveShell.autocall', autocall)\n\n # --- Additional methods\n def set_cwd(self, dirname):\n \"\"\"Set current working directory.\"\"\"\n os.chdir(dirname)\n\n def get_cwd(self):\n \"\"\"Get current working directory.\"\"\"\n try:\n return os.getcwd()\n except (IOError, OSError):\n pass\n\n def get_syspath(self):\n \"\"\"Return sys.path contents.\"\"\"\n return sys.path[:]\n\n def get_env(self):\n \"\"\"Get environment variables.\"\"\"\n return os.environ.copy()\n\n def close_all_mpl_figures(self):\n \"\"\"Close all Matplotlib figures.\"\"\"\n try:\n import matplotlib.pyplot as plt\n plt.close('all')\n del plt\n except:\n pass\n\n def is_special_kernel_valid(self):\n \"\"\"\n Check if optional dependencies are available for special consoles.\n \"\"\"\n try:\n if os.environ.get('SPY_AUTOLOAD_PYLAB_O') == 'True':\n import matplotlib\n elif os.environ.get('SPY_SYMPY_O') == 'True':\n import sympy\n elif os.environ.get('SPY_RUN_CYTHON') == 'True':\n import cython\n except Exception:\n # Use Exception instead of ImportError here because modules can\n # fail to be imported due to a lot of issues.\n if os.environ.get('SPY_AUTOLOAD_PYLAB_O') == 'True':\n return u'matplotlib'\n elif os.environ.get('SPY_SYMPY_O') == 'True':\n return u'sympy'\n elif os.environ.get('SPY_RUN_CYTHON') == 'True':\n return u'cython'\n return None\n\n def update_syspath(self, path_dict, new_path_dict):\n \"\"\"\n Update the PYTHONPATH of the kernel.\n\n `path_dict` and `new_path_dict` have the paths as keys and the state\n as values. The state is `True` for active and `False` for inactive.\n\n `path_dict` corresponds to the previous state of the PYTHONPATH.\n `new_path_dict` corresponds to the new state of the PYTHONPATH.\n \"\"\"\n # Remove old paths\n for path in path_dict:\n while path in sys.path:\n sys.path.remove(path)\n\n # Add new paths\n # We do this in reverse order as we use `sys.path.insert(1, path)`.\n # This ensures the end result has the correct path order.\n for path, active in reversed(new_path_dict.items()):\n if active:\n sys.path.insert(1, path)\n\n # -- Private API ---------------------------------------------------\n # --- For the Variable Explorer\n def _get_current_namespace(self, with_magics=False):\n \"\"\"\n Return current namespace\n\n This is globals() if not debugging, or a dictionary containing\n both locals() and globals() for current frame when debugging\n \"\"\"\n ns = {}\n if self._running_namespace is None:\n ns.update(self._mglobals())\n else:\n running_globals, running_locals = self._running_namespace\n ns.update(running_globals)\n if running_locals is not None:\n ns.update(running_locals)\n\n if self._pdb_frame is not None:\n ns.update(self._pdb_locals)\n\n # Add magics to ns so we can show help about them on the Help\n # plugin\n if with_magics:\n line_magics = self.shell.magics_manager.magics['line']\n cell_magics = self.shell.magics_manager.magics['cell']\n ns.update(line_magics)\n ns.update(cell_magics)\n\n return ns\n\n def _get_reference_namespace(self, name):\n \"\"\"\n Return namespace where reference name is defined\n\n It returns the globals() if reference has not yet been defined\n \"\"\"\n glbs = self._mglobals()\n if self._pdb_frame is None:\n return glbs\n else:\n lcls = self._pdb_locals\n if name in lcls:\n return lcls\n else:\n return glbs\n\n def _mglobals(self):\n \"\"\"Return current globals -- handles Pdb frames\"\"\"\n if self._pdb_frame is not None:\n return self._pdb_frame.f_globals\n else:\n return self.shell.user_ns\n\n def _get_len(self, var):\n \"\"\"Return sequence length\"\"\"\n try:\n return len(var)\n except:\n return None\n\n def _is_array(self, var):\n \"\"\"Return True if variable is a NumPy array\"\"\"\n try:\n import numpy\n return isinstance(var, numpy.ndarray)\n except:\n return False\n\n def _is_image(self, var):\n \"\"\"Return True if variable is a PIL.Image image\"\"\"\n try:\n from PIL import Image\n return isinstance(var, Image.Image)\n except:\n return False\n\n def _is_data_frame(self, var):\n \"\"\"Return True if variable is a DataFrame\"\"\"\n try:\n from pandas import DataFrame\n return isinstance(var, DataFrame)\n except:\n return False\n\n def _is_series(self, var):\n \"\"\"Return True if variable is a Series\"\"\"\n try:\n from pandas import Series\n return isinstance(var, Series)\n except:\n return False\n\n def _get_array_shape(self, var):\n \"\"\"Return array's shape\"\"\"\n try:\n if self._is_array(var):\n return var.shape\n else:\n return None\n except:\n return None\n\n def _get_array_ndim(self, var):\n \"\"\"Return array's ndim\"\"\"\n try:\n if self._is_array(var):\n return var.ndim\n else:\n return None\n except:\n return None\n\n # --- For Pdb\n def _register_pdb_session(self, pdb_obj):\n \"\"\"Register Pdb session to use it later\"\"\"\n self._pdb_obj = pdb_obj\n\n @property\n def _pdb_frame(self):\n \"\"\"Return current Pdb frame if there is any\"\"\"\n if self._pdb_obj is not None and self._pdb_obj.curframe is not None:\n return self._pdb_obj.curframe\n\n @property\n def _pdb_locals(self):\n \"\"\"\n Return current Pdb frame locals if available. Otherwise\n return an empty dictionary\n \"\"\"\n if self._pdb_frame:\n return self._pdb_obj.curframe_locals\n else:\n return {}\n\n # --- For the Help plugin\n def _eval(self, text):\n \"\"\"\n Evaluate text and return (obj, valid)\n where *obj* is the object represented by *text*\n and *valid* is True if object evaluation did not raise any exception\n \"\"\"\n from spyder_kernels.py3compat import is_text_string\n\n assert is_text_string(text)\n ns = self._get_current_namespace(with_magics=True)\n try:\n return eval(text, ns), True\n except:\n return None, False\n\n # --- For Matplotlib\n def _set_mpl_backend(self, backend, pylab=False):\n \"\"\"\n Set a backend for Matplotlib.\n\n backend: A parameter that can be passed to %matplotlib\n (e.g. 'inline' or 'tk').\n pylab: Is the pylab magic should be used in order to populate the\n namespace from numpy and matplotlib\n \"\"\"\n import traceback\n from IPython.core.getipython import get_ipython\n\n generic_error = (\n \"\\n\" + \"=\"*73 + \"\\n\"\n \"NOTE: The following error appeared when setting \"\n \"your Matplotlib backend!!\\n\" + \"=\"*73 + \"\\n\\n\"\n \"{0}\"\n )\n\n magic = 'pylab' if pylab else 'matplotlib'\n\n error = None\n try:\n get_ipython().run_line_magic(magic, backend)\n except RuntimeError as err:\n # This catches errors generated by ipykernel when\n # trying to set a backend. See issue 5541\n if \"GUI eventloops\" in str(err):\n import matplotlib\n previous_backend = matplotlib.get_backend()\n if not backend in previous_backend.lower():\n # Only inform about an error if the user selected backend\n # and the one set by Matplotlib are different. Else this\n # message is very confusing.\n error = (\n \"\\n\"\n \"NOTE: Spyder *can't* set your selected Matplotlib \"\n \"backend because there is a previous backend already \"\n \"in use.\\n\\n\"\n \"Your backend will be {0}\".format(previous_backend)\n )\n del matplotlib\n # This covers other RuntimeError's\n else:\n error = generic_error.format(traceback.format_exc())\n except Exception:\n error = generic_error.format(traceback.format_exc())\n\n self._mpl_backend_error = error\n\n def _set_config_option(self, option, value):\n \"\"\"\n Set config options using the %config magic.\n\n As parameters:\n option: config option, for example 'InlineBackend.figure_format'.\n value: value of the option, for example 'SVG', 'Retina', etc.\n \"\"\"\n from IPython.core.getipython import get_ipython\n try:\n base_config = \"{option} = \"\n value_line = (\n \"'{value}'\" if isinstance(value, TEXT_TYPES) else \"{value}\")\n config_line = base_config + value_line\n get_ipython().run_line_magic(\n 'config',\n config_line.format(option=option, value=value))\n except Exception:\n pass\n\n def _set_mpl_inline_rc_config(self, option, value):\n \"\"\"\n Update any of the Matplolib rcParams given an option and value.\n \"\"\"\n try:\n from matplotlib import rcParams\n rcParams[option] = value\n except Exception:\n # Needed in case matplolib isn't installed\n pass\n\n def show_mpl_backend_errors(self):\n \"\"\"Show Matplotlib backend errors after the prompt is ready.\"\"\"\n if self._mpl_backend_error is not None:\n print(self._mpl_backend_error) # spyder: test-skip\n\n def set_sympy_forecolor(self, background_color='dark'):\n \"\"\"Set SymPy forecolor depending on console background.\"\"\"\n if os.environ.get('SPY_SYMPY_O') == 'True':\n try:\n from sympy import init_printing\n from IPython.core.getipython import get_ipython\n if background_color == 'dark':\n init_printing(forecolor='White', ip=get_ipython())\n elif background_color == 'light':\n init_printing(forecolor='Black', ip=get_ipython())\n except Exception:\n pass\n\n # --- Others\n def _load_autoreload_magic(self):\n \"\"\"Load %autoreload magic.\"\"\"\n from IPython.core.getipython import get_ipython\n try:\n get_ipython().run_line_magic('reload_ext', 'autoreload')\n get_ipython().run_line_magic('autoreload', '2')\n except Exception:\n pass\n\n def _load_wurlitzer(self):\n \"\"\"Load wurlitzer extension.\"\"\"\n # Wurlitzer has no effect on Windows\n if not os.name == 'nt':\n from IPython.core.getipython import get_ipython\n # Enclose this in a try/except because if it fails the\n # console will be totally unusable.\n # Fixes spyder-ide/spyder#8668\n try:\n get_ipython().run_line_magic('reload_ext', 'wurlitzer')\n except Exception:\n pass\n\n def _get_comm(self, comm_id):\n \"\"\"\n We need to redefine this method from ipykernel.comm_manager to\n avoid showing a warning when the comm corresponding to comm_id\n is not present.\n\n Fixes spyder-ide/spyder#15498\n \"\"\"\n try:\n return self.comm_manager.comms[comm_id]\n except KeyError:\n pass\n"
] |
[
[
"matplotlib.get_backend",
"matplotlib.pyplot.close"
]
] |
HuiminHe/PyDy
|
[
"0834605bc2eed8d2768b50f55162bd6ac09cc694"
] |
[
"swing_open_loop.py"
] |
[
"from scipy.integrate import odeint\nfrom swing_config import *\n\nf = cloudpickle.load(open('./swing_open_loop_dynamic.dll', 'rb'))\n\ndef fv_gen(amp, ome, phi, q_max):\n return lambda t, y: amp * np.sin(ome * t + phi) / (1 + np.exp((np.abs(y[1:3])-q_max) / 0.01) * np.logical_or(np.abs(y[1:3]) < q_max, y[1:3] * y[4:] > 0))\n\ndef open_loop_test(amp, ome, phi):\n amp = np.ones(2) * amp_max *amp\n ome = np.ones(2) * ome_max * ome\n phi = np.ones(2) * phi_max * phi\n\n fv = fv_gen(amp, ome, phi, q_max)\n q0 = np.array([np.pi/6, 0, 0])\n a0 = np.array([0, 0])\n v0 = fv(t0, np.r_[q0, np.zeros(3)])\n y0 = np.r_[q0, 0, v0]\n sol = odeint(f, y0, t, args=(param0, con0, a_max, fv, dt))\n return Solution(t, sol, param0)\n\nif __name__ == '__main__':\n import matplotlib.pyplot as plt\n from swing_plot import swing_plot\n from swing_anim import swing_animation\n amp = 0\n ome = 0\n phi = 0\n sol = open_loop_test(amp, ome, phi)\n #fig = swing_plot(sol)\n #plt.show(fig)\n anim = swing_animation(sol)\n plt.show(anim)\n\n"
] |
[
[
"matplotlib.pyplot.show",
"scipy.integrate.odeint"
]
] |
seonho/facenet
|
[
"0804d06a3533a83ff865a3c4343cfca2a5cbe063"
] |
[
"tmp/visualize_vggface.py"
] |
[
"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport vggface16\n\ndef main():\n \n sess = tf.Session()\n \n t_input = tf.placeholder(np.float32, name='input') # define the input tensor\n image_mean = 117.0\n t_preprocessed = tf.expand_dims(t_input-image_mean, 0)\n \n # Build the inference graph\n nodes = vggface16.load('../data/vgg_face.mat', t_preprocessed)\n \n img_noise = np.random.uniform(size=(224,224,3)) + 117.0\n\n # Picking some internal layer. Note that we use outputs before applying the ReLU nonlinearity\n # to have non-zero gradients for features with negative initial activations.\n layer = 'conv5_3'\n channel = 139 # picking some feature channel to visualize\n img = render_naive(sess, t_input, nodes[layer][:,:,:,channel], img_noise)\n showarray(img)\n\ndef showarray(a):\n a = np.uint8(np.clip(a, 0, 1)*255)\n plt.imshow(a)\n plt.show()\n \ndef visstd(a, s=0.1):\n '''Normalize the image range for visualization'''\n return (a-a.mean())/max(a.std(), 1e-4)*s + 0.5\n\ndef render_naive(sess, t_input, t_obj, img0, iter_n=20, step=1.0):\n t_score = tf.reduce_mean(t_obj) # defining the optimization objective\n t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation!\n \n img = img0.copy()\n for _ in range(iter_n):\n g, _ = sess.run([t_grad, t_score], {t_input:img})\n # normalizing the gradient, so the same step size should work \n g /= g.std()+1e-8 # for different layers and networks\n img += g*step\n return visstd(img)\n\n \nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.pyplot.imshow",
"tensorflow.reduce_mean",
"numpy.clip",
"tensorflow.gradients",
"tensorflow.expand_dims",
"tensorflow.placeholder",
"tensorflow.Session",
"numpy.random.uniform",
"matplotlib.pyplot.show"
]
] |
ArmatureSystems/content
|
[
"ddb88044c5b39a17894dd13e7ae260d9854afc30"
] |
[
"Packs/rasterize/Integrations/rasterize/rasterize.py"
] |
[
"import demistomock as demisto\nfrom CommonServerPython import *\nfrom CommonServerUserPython import *\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException, InvalidArgumentException, TimeoutException\nfrom PyPDF2 import PdfFileReader\nfrom pdf2image import convert_from_path\nimport numpy as np\nfrom PIL import Image\nimport tempfile\nfrom io import BytesIO\nimport base64\nimport time\nimport subprocess\nimport traceback\nimport re\nimport os\n\n# Chrome respects proxy env params\nhandle_proxy()\n# Make sure our python code doesn't go through a proxy when communicating with chrome webdriver\nos.environ['no_proxy'] = 'localhost,127.0.0.1'\n\nWITH_ERRORS = demisto.params().get('with_error', True)\nDEFAULT_WAIT_TIME = max(int(demisto.params().get('wait_time', 0)), 0)\nDEFAULT_PAGE_LOAD_TIME = int(demisto.params().get('max_page_load_time', 180))\n\nURL_ERROR_MSG = \"Can't access the URL. It might be malicious, or unreachable for one of several reasons. \" \\\n \"You can choose to receive this message as error/warning in the instance settings\\n\"\nEMPTY_RESPONSE_ERROR_MSG = \"There is nothing to render. This can occur when there is a refused connection.\" \\\n \" Please check your URL.\"\nDEFAULT_W, DEFAULT_H = '600', '800'\nDEFAULT_W_WIDE = '1024'\nCHROME_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36' # noqa\nDRIVER_LOG = f'{tempfile.gettempdir()}/chromedriver.log'\nDEFAULT_CHROME_OPTIONS = [\n '--no-sandbox',\n '--headless',\n '--disable-gpu',\n '--hide-scrollbars',\n '--disable_infobars',\n '--start-maximized',\n '--start-fullscreen',\n '--ignore-certificate-errors',\n '--disable-dev-shm-usage',\n f'--user-agent={CHROME_USER_AGENT}'\n]\n\nUSER_CHROME_OPTIONS = demisto.params().get('chrome_options', \"\")\n\n\ndef return_err_or_warn(msg):\n return_error(msg) if WITH_ERRORS else return_warning(msg, exit=True)\n\n\ndef opt_name(opt):\n return opt.split('=', 1)[0]\n\n\ndef merge_options(default_options, user_options):\n \"\"\"merge the defualt options and user options\n\n Arguments:\n default_options {list} -- list of options to use\n user_options {string} -- user configured options comma seperated (comma value can be escaped with \\\\)\n\n Returns:\n list -- merged options\n \"\"\"\n user_options = re.split(r'(?<!\\\\),', user_options) if user_options else list()\n if not user_options: # nothing to do\n return default_options\n demisto.debug(f'user chrome options: {user_options}')\n options = []\n remove_opts = []\n for opt in user_options:\n opt = opt.strip()\n if opt.startswith('[') and opt.endswith(']'):\n remove_opts.append(opt[1:-1])\n else:\n options.append(opt.replace(r'\\,', ','))\n # remove values (such as in user-agent)\n option_names = [opt_name(x) for x in options]\n # add filtered defaults only if not in removed and we don't have it already\n options.extend([x for x in default_options if (opt_name(x) not in remove_opts and opt_name(x) not in option_names)])\n return options\n\n\ndef check_response(driver):\n EMPTY_PAGE = '<html><head></head><body></body></html>'\n if driver.page_source == EMPTY_PAGE:\n return_err_or_warn(EMPTY_RESPONSE_ERROR_MSG)\n\n\ndef init_driver(offline_mode=False):\n \"\"\"\n Creates headless Google Chrome Web Driver\n \"\"\"\n demisto.debug(f'Creating chrome driver. Mode: {\"OFFLINE\" if offline_mode else \"ONLINE\"}')\n try:\n chrome_options = webdriver.ChromeOptions()\n for opt in merge_options(DEFAULT_CHROME_OPTIONS, USER_CHROME_OPTIONS):\n chrome_options.add_argument(opt)\n driver = webdriver.Chrome(options=chrome_options, service_args=[\n f'--log-path={DRIVER_LOG}',\n ])\n if offline_mode:\n driver.set_network_conditions(offline=True, latency=5, throughput=500 * 1024)\n except Exception as ex:\n return_error(f'Unexpected exception: {ex}\\nTrace:{traceback.format_exc()}')\n\n demisto.debug('Creating chrome driver - COMPLETED')\n return driver\n\n\ndef find_zombie_processes():\n \"\"\"find zombie proceses\n Returns:\n ([process ids], raw ps output) -- return a tuple of zombie process ids and raw ps output\n \"\"\"\n ps_out = subprocess.check_output(['ps', '-e', '-o', 'pid,ppid,state,cmd'],\n stderr=subprocess.STDOUT, universal_newlines=True)\n lines = ps_out.splitlines()\n pid = str(os.getpid())\n zombies = []\n if len(lines) > 1:\n for line in lines[1:]:\n pinfo = line.split()\n if pinfo[2] == 'Z' and pinfo[1] == pid: # zombie process\n zombies.append(pinfo[0])\n return zombies, ps_out\n\n\ndef quit_driver_and_reap_children(driver):\n \"\"\"\n Quits the driver's session and reaps all of zombie child processes\n :param driver: The driver\n :return: None\n \"\"\"\n demisto.debug(f'Quitting driver session: {driver.session_id}')\n driver.quit()\n try:\n zombies, ps_out = find_zombie_processes()\n if zombies:\n demisto.info(f'Found zombie processes will waitpid: {ps_out}')\n for pid in zombies:\n waitres = os.waitpid(int(pid), os.WNOHANG)[1]\n demisto.info(f'waitpid result: {waitres}')\n else:\n demisto.debug(f'No zombie processes found for ps output: {ps_out}')\n except Exception as e:\n demisto.error(f'Failed checking for zombie processes: {e}. Trace: {traceback.format_exc()}')\n\n\ndef rasterize(path: str, width: int, height: int, r_type: str = 'png', wait_time: int = 0,\n offline_mode: bool = False, max_page_load_time: int = 180):\n \"\"\"\n Capturing a snapshot of a path (url/file), using Chrome Driver\n :param offline_mode: when set to True, will block any outgoing communication\n :param path: file path, or website url\n :param width: desired snapshot width in pixels\n :param height: desired snapshot height in pixels\n :param r_type: result type: .png/.pdf\n :param wait_time: time in seconds to wait before taking a screenshot\n \"\"\"\n driver = init_driver(offline_mode)\n page_load_time = max_page_load_time if max_page_load_time > 0 else DEFAULT_PAGE_LOAD_TIME\n try:\n demisto.debug(f'Navigating to path: {path}. Mode: {\"OFFLINE\" if offline_mode else \"ONLINE\"}. page load: {page_load_time}')\n driver.set_page_load_timeout(page_load_time)\n driver.get(path)\n driver.implicitly_wait(5)\n if wait_time > 0 or DEFAULT_WAIT_TIME > 0:\n time.sleep(wait_time or DEFAULT_WAIT_TIME)\n check_response(driver)\n demisto.debug('Navigating to path - COMPLETED')\n\n if r_type.lower() == 'pdf':\n output = get_pdf(driver, width, height)\n else:\n output = get_image(driver, width, height)\n\n return output\n\n except (InvalidArgumentException, NoSuchElementException) as ex:\n if 'invalid argument' in str(ex):\n err_msg = URL_ERROR_MSG + str(ex)\n return_err_or_warn(err_msg)\n else:\n return_err_or_warn(f'Invalid exception: {ex}\\nTrace:{traceback.format_exc()}')\n except TimeoutException as ex:\n return_err_or_warn(f'Timeout exception with max load time of: {page_load_time} seconds. {ex}')\n except Exception as ex:\n err_str = f'General error: {ex}\\nTrace:{traceback.format_exc()}'\n demisto.error(err_str)\n return_err_or_warn(err_str)\n finally:\n quit_driver_and_reap_children(driver)\n\n\ndef get_image(driver, width: int, height: int):\n \"\"\"\n Uses the Chrome driver to generate an image out of a currently loaded path\n :return: .png file of the loaded path\n \"\"\"\n demisto.debug('Capturing screenshot')\n\n # Set windows size\n driver.set_window_size(width, height)\n\n image = driver.get_screenshot_as_png()\n driver.quit()\n\n demisto.debug('Capturing screenshot - COMPLETED')\n\n return image\n\n\ndef get_pdf(driver, width: int, height: int):\n \"\"\"\n Uses the Chrome driver to generate an pdf file out of a currently loaded path\n :return: .pdf file of the loaded path\n \"\"\"\n demisto.debug('Generating PDF')\n\n driver.set_window_size(width, height)\n resource = f'{driver.command_executor._url}/session/{driver.session_id}/chromium/send_command_and_get_result'\n body = json.dumps({'cmd': 'Page.printToPDF', 'params': {'landscape': False}})\n response = driver.command_executor._request('POST', resource, body)\n\n if response.get('status'):\n demisto.results(response.get('status'))\n return_error(response.get('value'))\n\n data = base64.b64decode(response.get('value').get('data'))\n demisto.debug('Generating PDF - COMPLETED')\n\n return data\n\n\ndef convert_pdf_to_jpeg(path: str, max_pages: int, password: str, horizontal: bool = False):\n \"\"\"\n Converts a PDF file into a jpeg image\n :param path: file's path\n :param max_pages: max pages to render\n :param password: PDF password\n :param horizontal: if True, will combine the pages horizontally\n :return: stream of combined image\n \"\"\"\n demisto.debug(f'Loading file at Path: {path}')\n input_pdf = PdfFileReader(open(path, \"rb\"))\n pages = min(max_pages, input_pdf.numPages)\n\n with tempfile.TemporaryDirectory() as output_folder:\n demisto.debug('Converting PDF')\n convert_from_path(\n pdf_path=path,\n fmt='jpeg',\n first_page=1,\n last_page=pages,\n output_folder=output_folder,\n userpw=password,\n output_file='converted_pdf_'\n )\n demisto.debug('Converting PDF - COMPLETED')\n\n demisto.debug('Combining all pages')\n images = []\n for page in sorted(os.listdir(output_folder)):\n if os.path.isfile(os.path.join(output_folder, page)) and 'converted_pdf_' in page:\n images.append(Image.open(os.path.join(output_folder, page)))\n min_shape = min([(np.sum(page_.size), page_.size) for page_ in images])[1] # get the minimal width\n\n if horizontal:\n imgs_comb = np.hstack([np.asarray(i.resize(min_shape)) for i in images])\n else:\n imgs_comb = np.vstack([np.asarray(i.resize(min_shape)) for i in images])\n\n imgs_comb = Image.fromarray(imgs_comb)\n output = BytesIO()\n imgs_comb.save(output, 'JPEG')\n demisto.debug('Combining all pages - COMPLETED')\n\n return output.getvalue()\n\n\ndef rasterize_command():\n url = demisto.getArg('url')\n w = demisto.args().get('width', DEFAULT_W_WIDE).rstrip('px')\n h = demisto.args().get('height', DEFAULT_H).rstrip('px')\n r_type = demisto.args().get('type', 'png')\n wait_time = int(demisto.args().get('wait_time', 0))\n page_load = int(demisto.args().get('max_page_load_time', DEFAULT_PAGE_LOAD_TIME))\n\n if not (url.startswith('http')):\n url = f'http://{url}'\n filename = f'url.{\"pdf\" if r_type == \"pdf\" else \"png\"}' # type: ignore\n\n output = rasterize(path=url, r_type=r_type, width=w, height=h, wait_time=wait_time, max_page_load_time=page_load)\n res = fileResult(filename=filename, data=output)\n if r_type == 'png':\n res['Type'] = entryTypes['image']\n\n demisto.results(res)\n\n\ndef rasterize_image_command():\n args = demisto.args()\n entry_id = args.get('EntryID')\n w = args.get('width', DEFAULT_W).rstrip('px')\n h = args.get('height', DEFAULT_H).rstrip('px')\n\n file_path = demisto.getFilePath(entry_id).get('path')\n filename = f'{entry_id}.pdf'\n\n with open(file_path, 'rb') as f, open('output_image', 'w') as image:\n data = base64.b64encode(f.read()).decode('utf-8')\n image.write(data)\n output = rasterize(path=f'file://{os.path.realpath(f.name)}', width=w, height=h, r_type='pdf')\n res = fileResult(filename=filename, data=output)\n res['Type'] = entryTypes['image']\n\n demisto.results(res)\n\n\ndef rasterize_email_command():\n html_body = demisto.args().get('htmlBody')\n w = demisto.args().get('width', DEFAULT_W).rstrip('px')\n h = demisto.args().get('height', DEFAULT_H).rstrip('px')\n offline = demisto.args().get('offline', 'false') == 'true'\n r_type = demisto.args().get('type', 'png')\n\n filename = f'email.{\"pdf\" if r_type.lower() == \"pdf\" else \"png\"}' # type: ignore\n with open('htmlBody.html', 'w') as f:\n f.write(f'<html style=\"background:white\";>{html_body}</html>')\n path = f'file://{os.path.realpath(f.name)}'\n\n output = rasterize(path=path, r_type=r_type, width=w, height=h, offline_mode=offline)\n res = fileResult(filename=filename, data=output)\n if r_type == 'png':\n res['Type'] = entryTypes['image']\n\n demisto.results(res)\n\n\ndef rasterize_pdf_command():\n entry_id = demisto.args().get('EntryID')\n password = demisto.args().get('pdfPassword')\n max_pages = int(demisto.args().get('maxPages', 30))\n horizontal = demisto.args().get('horizontal', 'false') == 'true'\n\n file_path = demisto.getFilePath(entry_id).get('path')\n\n filename = 'image.jpeg' # type: ignore\n\n with open(file_path, 'rb') as f:\n output = convert_pdf_to_jpeg(path=os.path.realpath(f.name), max_pages=max_pages, password=password,\n horizontal=horizontal)\n res = fileResult(filename=filename, data=output)\n res['Type'] = entryTypes['image']\n\n demisto.results(res)\n\n\ndef module_test():\n # setting up a mock email file\n with tempfile.NamedTemporaryFile('w+') as test_file:\n test_file.write('<html><head><meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html;charset=utf-8\\\">'\n '</head><body><br>---------- TEST FILE ----------<br></body></html>')\n test_file.flush()\n file_path = f'file://{os.path.realpath(test_file.name)}'\n\n # rasterizing the file\n rasterize(path=file_path, width=250, height=250)\n\n demisto.results('ok')\n\n\ndef main():\n try:\n with open(DRIVER_LOG, 'w'):\n pass # truncate the log file\n if demisto.command() == 'test-module':\n module_test()\n\n elif demisto.command() == 'rasterize-image':\n rasterize_image_command()\n\n elif demisto.command() == 'rasterize-email':\n rasterize_email_command()\n\n elif demisto.command() == 'rasterize-pdf':\n rasterize_pdf_command()\n\n elif demisto.command() == 'rasterize':\n rasterize_command()\n\n else:\n return_error('Unrecognized command')\n\n except Exception as ex:\n return_err_or_warn(f'Unexpected exception: {ex}\\nTrace:{traceback.format_exc()}')\n finally:\n if is_debug_mode():\n demisto.debug(f'os.environ: {os.environ}')\n with open(DRIVER_LOG, 'r') as log:\n demisto.debug('Driver log:' + log.read())\n\n\nif __name__ in [\"__builtin__\", \"builtins\", '__main__']:\n main()\n"
] |
[
[
"numpy.sum"
]
] |
YoshikiMas/espnet
|
[
"793b999a50af484a5eaf6227ef7556b48514ef15"
] |
[
"espnet2/bin/enh_scoring.py"
] |
[
"#!/usr/bin/env python3\nimport argparse\nimport logging\nimport sys\nfrom typing import List\nfrom typing import Union\n\nfrom mir_eval.separation import bss_eval_sources\nimport numpy as np\nfrom pystoi import stoi\nimport torch\nfrom typeguard import check_argument_types\n\nfrom espnet.utils.cli_utils import get_commandline_args\nfrom espnet2.enh.loss.criterions.time_domain import SISNRLoss\nfrom espnet2.fileio.datadir_writer import DatadirWriter\nfrom espnet2.fileio.sound_scp import SoundScpReader\nfrom espnet2.utils import config_argparse\n\n\nsi_snr_loss = SISNRLoss()\n\n\ndef scoring(\n output_dir: str,\n dtype: str,\n log_level: Union[int, str],\n key_file: str,\n ref_scp: List[str],\n inf_scp: List[str],\n ref_channel: int,\n):\n assert check_argument_types()\n\n logging.basicConfig(\n level=log_level,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n\n assert len(ref_scp) == len(inf_scp), ref_scp\n num_spk = len(ref_scp)\n\n keys = [\n line.rstrip().split(maxsplit=1)[0] for line in open(key_file, encoding=\"utf-8\")\n ]\n\n ref_readers = [SoundScpReader(f, dtype=dtype, normalize=True) for f in ref_scp]\n inf_readers = [SoundScpReader(f, dtype=dtype, normalize=True) for f in inf_scp]\n\n # get sample rate\n sample_rate, _ = ref_readers[0][keys[0]]\n\n # check keys\n for inf_reader, ref_reader in zip(inf_readers, ref_readers):\n assert inf_reader.keys() == ref_reader.keys()\n\n with DatadirWriter(output_dir) as writer:\n for key in keys:\n ref_audios = [ref_reader[key][1] for ref_reader in ref_readers]\n inf_audios = [inf_reader[key][1] for inf_reader in inf_readers]\n ref = np.array(ref_audios)\n inf = np.array(inf_audios)\n if ref.ndim > inf.ndim:\n # multi-channel reference and single-channel output\n ref = ref[..., ref_channel]\n elif ref.ndim < inf.ndim:\n # single-channel reference and multi-channel output\n inf = inf[..., ref_channel]\n elif ref.ndim == inf.ndim == 3:\n # multi-channel reference and output\n ref = ref[..., ref_channel]\n inf = inf[..., ref_channel]\n assert ref.shape == inf.shape, (ref.shape, inf.shape)\n sdr, sir, sar, perm = bss_eval_sources(ref, inf, compute_permutation=True)\n\n for i in range(num_spk):\n stoi_score = stoi(ref[i], inf[int(perm[i])], fs_sig=sample_rate)\n estoi_score = stoi(\n ref[i], inf[int(perm[i])], fs_sig=sample_rate, extended=True\n )\n si_snr_score = -float(\n si_snr_loss(\n torch.from_numpy(ref[i][None, ...]),\n torch.from_numpy(inf[int(perm[i])][None, ...]),\n )\n )\n writer[f\"STOI_spk{i + 1}\"][key] = str(stoi_score * 100) # in percentage\n writer[f\"ESTOI_spk{i + 1}\"][key] = str(estoi_score * 100)\n writer[f\"SI_SNR_spk{i + 1}\"][key] = str(si_snr_score)\n writer[f\"SDR_spk{i + 1}\"][key] = str(sdr[i])\n writer[f\"SAR_spk{i + 1}\"][key] = str(sar[i])\n writer[f\"SIR_spk{i + 1}\"][key] = str(sir[i])\n # save permutation assigned script file\n writer[f\"wav_spk{i + 1}\"][key] = inf_readers[perm[i]].data[key]\n\n\ndef get_parser():\n parser = config_argparse.ArgumentParser(\n description=\"Frontend inference\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n\n # Note(kamo): Use '_' instead of '-' as separator.\n # '-' is confusing if written in yaml.\n\n parser.add_argument(\n \"--log_level\",\n type=lambda x: x.upper(),\n default=\"INFO\",\n choices=(\"CRITICAL\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\", \"NOTSET\"),\n help=\"The verbose level of logging\",\n )\n\n parser.add_argument(\"--output_dir\", type=str, required=True)\n\n parser.add_argument(\n \"--dtype\",\n default=\"float32\",\n choices=[\"float16\", \"float32\", \"float64\"],\n help=\"Data type\",\n )\n\n group = parser.add_argument_group(\"Input data related\")\n group.add_argument(\n \"--ref_scp\",\n type=str,\n required=True,\n action=\"append\",\n )\n group.add_argument(\n \"--inf_scp\",\n type=str,\n required=True,\n action=\"append\",\n )\n group.add_argument(\"--key_file\", type=str)\n group.add_argument(\"--ref_channel\", type=int, default=0)\n\n return parser\n\n\ndef main(cmd=None):\n print(get_commandline_args(), file=sys.stderr)\n parser = get_parser()\n args = parser.parse_args(cmd)\n kwargs = vars(args)\n kwargs.pop(\"config\", None)\n scoring(**kwargs)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.array",
"torch.from_numpy"
]
] |
open-mmlab/mmrotate
|
[
"e22c8dfa3c309aa68ff18a5a03316f69c6eb2880"
] |
[
"tests/test_data/test_datasets/test_dota.py"
] |
[
"# Copyright (c) OpenMMLab. All rights reserved.\nimport os.path as osp\nimport shutil\nimport tempfile\n\nimport numpy as np\nimport pytest\nfrom mmdet.datasets import build_dataset\n\nfrom mmrotate.datasets.dota import DOTADataset\n\n\ndef _create_dummy_results():\n \"\"\"Create dummy results.\"\"\"\n boxes = [\n np.array([[4.3150e+02, 7.0600e+02, 6.7686e+01, 2.1990e+01, 2.9842e-02],\n [5.6351e+02, 5.3575e+02, 1.0018e+02, 1.8971e+01, 5.5499e-02],\n [5.7450e+02, 5.8450e+02, 9.5567e+01, 2.1094e+01,\n 8.4012e-02]])\n ]\n return [boxes]\n\n\[email protected]('angle_version', ['oc'])\ndef test_dota_dataset(angle_version):\n \"\"\"Test DOTA dataset.\n\n Args:\n angle_version (str, optional): Angle representations.\n \"\"\"\n # test CLASSES\n train_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='DefaultFormatBundle'),\n dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])\n ]\n data_config = dict(\n type=DOTADataset,\n version=angle_version,\n ann_file='tests/data/labelTxt/',\n img_prefix='tests/data/images/',\n pipeline=train_pipeline)\n dataset = build_dataset(data_config)\n assert dataset.CLASSES == ('plane', 'baseball-diamond', 'bridge',\n 'ground-track-field', 'small-vehicle',\n 'large-vehicle', 'ship', 'tennis-court',\n 'basketball-court', 'storage-tank',\n 'soccer-ball-field', 'roundabout', 'harbor',\n 'swimming-pool', 'helicopter')\n\n # test eval\n dataset.CLASSES = ('plane', )\n fake_results = _create_dummy_results()\n eval_results = dataset.evaluate(fake_results)\n np.testing.assert_almost_equal(eval_results['mAP'], 0.7272727)\n\n # test format_results\n tmp_filename = osp.join(tempfile.gettempdir(), 'merge_results')\n if osp.exists(tmp_filename):\n shutil.rmtree(tmp_filename)\n dataset.format_results(fake_results, submission_dir=tmp_filename)\n shutil.rmtree(tmp_filename)\n\n # test filter_empty_gt=False\n full_data_config = dict(\n type=DOTADataset,\n version=angle_version,\n ann_file='tests/data/labelTxt/',\n img_prefix='tests/data/images/',\n pipeline=train_pipeline,\n filter_empty_gt=False)\n full_dataset = build_dataset(full_data_config)\n assert len(dataset) == 1 and len(full_dataset) == 2\n"
] |
[
[
"numpy.testing.assert_almost_equal",
"numpy.array"
]
] |
dkkim93/pytorch-maml
|
[
"039e7ecf9b3d0b7543ebceb31a6443cc5516779a"
] |
[
"misc/batch_sampler.py"
] |
[
"import copy\nimport torch\nimport multiprocessing as mp\nfrom misc.utils import make_env\nfrom misc.batch_episode import BatchEpisode\nfrom env.subproc_vec_env import SubprocVecEnv\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass BatchSampler(object):\n def __init__(self, args):\n self.args = args\n self.num_workers = mp.cpu_count() - 1\n if self.num_workers > args.n_traj:\n self.num_workers = args.n_traj\n\n self.queue = mp.Queue()\n self.envs = SubprocVecEnv(\n envs=[make_env(args.env_name, args.n_agent) for _ in range(self.num_workers)], \n queue=self.queue, args=args)\n\n # Set seed to envs\n self.envs.seed(0)\n\n def sample(self):\n episode = BatchEpisode(1)\n for i in range(1):\n self.queue.put(i)\n for _ in range(self.num_workers):\n self.queue.put(None)\n\n observations, batch_ids = self.envs.reset()\n dones = [False]\n while (not all(dones)) or (not self.queue.empty()):\n actions = copy.deepcopy(observations)\n new_observations, rewards, dones, new_batch_ids, _ = self.envs.step(actions)\n episode.append(observations, actions, rewards, batch_ids)\n observations, batch_ids = new_observations, new_batch_ids\n\n episode.check_length()\n\n return episode\n\n def reset_task(self, task):\n tasks = [task for _ in range(self.num_workers)]\n reset = self.envs.reset_task(tasks)\n return all(reset)\n"
] |
[
[
"torch.cuda.is_available"
]
] |
pingheng001/Cnn-Bert
|
[
"d2be31634d693fbbe3b4bf2b28eb83af015cda72"
] |
[
"modeling.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team 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\"\"\"The main BERT model and related functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport copy\nimport json\nimport math\nimport re\nimport numpy as np\nimport six\nimport tensorflow as tf\n\n\nclass BertConfig(object):\n \"\"\"Configuration for `BertModel`.\"\"\"\n\n def __init__(self,\n vocab_size,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=16,\n initializer_range=0.02):\n \"\"\"Constructs BertConfig.\n\n Args:\n vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.\n hidden_size: Size of the encoder layers and the pooler layer.\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\n num_attention_heads: Number of attention heads for each attention layer in\n the Transformer encoder.\n intermediate_size: The size of the \"intermediate\" (i.e., feed-forward)\n layer in the Transformer encoder.\n hidden_act: The non-linear activation function (function or string) in the\n encoder and pooler.\n hidden_dropout_prob: The dropout probability for all fully connected\n layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob: The dropout ratio for the attention\n probabilities.\n max_position_embeddings: The maximum sequence length that this model might\n ever be used with. Typically set this to something large just in case\n (e.g., 512 or 1024 or 2048).\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\n `BertModel`.\n initializer_range: The stdev of the truncated_normal_initializer for\n initializing all weight matrices.\n \"\"\"\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n\n @classmethod\n def from_dict(cls, json_object):\n \"\"\"Constructs a `BertConfig` from a Python dictionary of parameters.\"\"\"\n config = BertConfig(vocab_size=None)\n for (key, value) in six.iteritems(json_object):\n config.__dict__[key] = value\n return config\n\n @classmethod\n def from_json_file(cls, json_file):\n \"\"\"Constructs a `BertConfig` from a json file of parameters.\"\"\"\n with tf.gfile.GFile(json_file, \"r\") as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass BertModel(object):\n \"\"\"BERT model (\"Bidirectional Encoder Representations from Transformers\").\n\n Example usage:\n\n ```python\n # Already been converted into WordPiece token ids\n input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])\n input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])\n token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])\n\n config = modeling.BertConfig(vocab_size=32000, hidden_size=512,\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\n\n model = modeling.BertModel(config=config, is_training=True,\n input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)\n\n label_embeddings = tf.get_variable(...)\n pooled_output = model.get_pooled_output()\n logits = tf.matmul(pooled_output, label_embeddings)\n ...\n ```\n \"\"\"\n\n def __init__(self,\n config,\n is_training,\n input_ids,\n input_mask=None,\n token_type_ids=None,\n use_one_hot_embeddings=False,\n scope=None):\n \"\"\"Constructor for BertModel.\n\n Args:\n config: `BertConfig` instance.\n is_training: bool. true for training model, false for eval model. Controls\n whether dropout will be applied.\n input_ids: int32 Tensor of shape [batch_size, seq_length].\n input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\n use_one_hot_embeddings: (optional) bool. Whether to use one-hot word\n embeddings or tf.embedding_lookup() for the word embeddings.\n scope: (optional) variable scope. Defaults to \"bert\".\n\n Raises:\n ValueError: The config is invalid or one of the input tensor shapes\n is invalid.\n \"\"\"\n config = copy.deepcopy(config)\n if not is_training:\n config.hidden_dropout_prob = 0.0\n config.attention_probs_dropout_prob = 0.0\n\n input_shape = get_shape_list(input_ids, expected_rank=2)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n\n if input_mask is None:\n input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)\n\n if token_type_ids is None:\n token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)\n\n with tf.variable_scope(scope, default_name=\"bert\"):\n with tf.variable_scope(\"embeddings\"):\n # Perform embedding lookup on the word ids.\n (self.embedding_output, self.embedding_table) = embedding_lookup(\n input_ids=input_ids,\n vocab_size=config.vocab_size,\n embedding_size=config.hidden_size,\n initializer_range=config.initializer_range,\n word_embedding_name=\"word_embeddings\",\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # Add positional embeddings and token type embeddings, then layer\n # normalize and perform dropout.\n self.embedding_output = embedding_postprocessor(\n input_tensor=self.embedding_output,\n use_token_type=True,\n token_type_ids=token_type_ids,\n token_type_vocab_size=config.type_vocab_size,\n token_type_embedding_name=\"token_type_embeddings\",\n use_position_embeddings=True,\n position_embedding_name=\"position_embeddings\",\n initializer_range=config.initializer_range,\n max_position_embeddings=config.max_position_embeddings,\n dropout_prob=config.hidden_dropout_prob)\n\n with tf.variable_scope(\"encoder\"):\n # This converts a 2D mask of shape [batch_size, seq_length] to a 3D\n # mask of shape [batch_size, seq_length, seq_length] which is used\n # for the attention scores.\n attention_mask = create_attention_mask_from_input_mask(\n input_ids, input_mask)\n\n # Run the stacked transformer.\n # `sequence_output` shape = [batch_size, seq_length, hidden_size].\n self.all_encoder_layers = transformer_model(\n input_tensor=self.embedding_output,\n attention_mask=attention_mask,\n hidden_size=config.hidden_size,\n num_hidden_layers=config.num_hidden_layers,\n num_attention_heads=config.num_attention_heads,\n intermediate_size=config.intermediate_size,\n intermediate_act_fn=get_activation(config.hidden_act),\n hidden_dropout_prob=config.hidden_dropout_prob,\n attention_probs_dropout_prob=config.attention_probs_dropout_prob,\n initializer_range=config.initializer_range,\n do_return_all_layers=True)\n\n self.sequence_output = self.all_encoder_layers[-1]\n # The \"pooler\" converts the encoded sequence tensor of shape\n # [batch_size, seq_length, hidden_size] to a tensor of shape\n # [batch_size, hidden_size]. This is necessary for segment-level\n # (or segment-pair-level) classification tasks where we need a fixed\n # dimensional representation of the segment.\n with tf.variable_scope(\"pooler\"):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token. We assume that this has been pre-trained\n first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)\n self.pooled_output = tf.layers.dense(\n first_token_tensor,\n config.hidden_size,\n activation=tf.tanh,\n kernel_initializer=create_initializer(config.initializer_range))\n\n def get_pooled_output(self):\n return self.pooled_output\n\n def get_sequence_output(self):\n \"\"\"Gets final hidden layer of encoder.\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\n to the final hidden of the transformer encoder.\n \"\"\"\n return self.sequence_output\n\n def get_all_encoder_layers(self):\n return self.all_encoder_layers\n\n def get_embedding_output(self):\n \"\"\"Gets output of the embedding lookup (i.e., input to the transformer).\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\n to the output of the embedding layer, after summing the word\n embeddings with the positional embeddings and the token type embeddings,\n then performing layer normalization. This is the input to the transformer.\n \"\"\"\n return self.embedding_output\n\n def get_embedding_table(self):\n return self.embedding_table\n\nclass CNNBertModel(object):\n \"\"\"BERT model (\"Bidirectional Encoder Representations from Transformers\").\n\n Example usage:\n\n ```python\n # Already been converted into WordPiece token ids\n input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])\n input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])\n token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])\n\n config = modeling.BertConfig(vocab_size=32000, hidden_size=512,\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\n\n model = modeling.BertModel(config=config, is_training=True,\n input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)\n\n label_embeddings = tf.get_variable(...)\n pooled_output = model.get_pooled_output()\n logits = tf.matmul(pooled_output, label_embeddings)\n ...\n ```\n \"\"\"\n\n def __init__(self,\n config,\n is_training,\n input_ids,\n input_mask=None,\n token_type_ids=None,\n use_one_hot_embeddings=False,\n scope=None):\n \"\"\"Constructor for BertModel.\n\n Args:\n config: `BertConfig` instance.\n is_training: bool. true for training model, false for eval model. Controls\n whether dropout will be applied.\n input_ids: int32 Tensor of shape [batch_size, seq_length].\n input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\n use_one_hot_embeddings: (optional) bool. Whether to use one-hot word\n embeddings or tf.embedding_lookup() for the word embeddings.\n scope: (optional) variable scope. Defaults to \"bert\".\n\n Raises:\n ValueError: The config is invalid or one of the input tensor shapes\n is invalid.\n \"\"\"\n config = copy.deepcopy(config)\n if not is_training:\n config.hidden_dropout_prob = 0.0\n config.attention_probs_dropout_prob = 0.0\n\n input_shape = get_shape_list(input_ids, expected_rank=2)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n\n if input_mask is None:\n input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)\n\n if token_type_ids is None:\n token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)\n\n with tf.variable_scope(scope, default_name=\"bert\"):\n with tf.variable_scope(\"embeddings\"):\n # Perform embedding lookup on the word ids.\n (self.embedding_output, self.embedding_table) = embedding_lookup(\n input_ids=input_ids,\n vocab_size=config.vocab_size,\n embedding_size=config.hidden_size,\n initializer_range=config.initializer_range,\n word_embedding_name=\"word_embeddings\",\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # Add positional embeddings and token type embeddings, then layer\n # normalize and perform dropout.\n self.embedding_output = embedding_postprocessor(\n input_tensor=self.embedding_output,\n use_token_type=True,\n token_type_ids=token_type_ids,\n token_type_vocab_size=config.type_vocab_size,\n token_type_embedding_name=\"token_type_embeddings\",\n use_position_embeddings=True,\n position_embedding_name=\"position_embeddings\",\n initializer_range=config.initializer_range,\n max_position_embeddings=config.max_position_embeddings,\n dropout_prob=config.hidden_dropout_prob)\n\n with tf.variable_scope(\"encoder\"):\n # This converts a 2D mask of shape [batch_size, seq_length] to a 3D\n # mask of shape [batch_size, seq_length, seq_length] which is used\n # for the attention scores.\n attention_mask = create_attention_mask_from_input_mask(\n input_ids, input_mask)\n\n # Run the stacked transformer.\n # `sequence_output` shape = [batch_size, seq_length, hidden_size].\n self.all_encoder_layers = transformer_model(\n input_tensor=self.embedding_output,\n attention_mask=attention_mask,\n hidden_size=config.hidden_size,\n num_hidden_layers=config.num_hidden_layers,\n num_attention_heads=config.num_attention_heads,\n intermediate_size=config.intermediate_size,\n intermediate_act_fn=get_activation(config.hidden_act),\n hidden_dropout_prob=config.hidden_dropout_prob,\n attention_probs_dropout_prob=config.attention_probs_dropout_prob,\n initializer_range=config.initializer_range,\n do_return_all_layers=True)\n\n self.all_cnn_layers = cnn_model(\n input_tensor=self.embedding_output,\n attention_mask=attention_mask,\n hidden_size=config.hidden_size,\n num_hidden_layers=config.num_hidden_layers,\n num_attention_heads=config.num_attention_heads,\n intermediate_size=config.intermediate_size,\n intermediate_act_fn=get_activation(config.hidden_act),\n hidden_dropout_prob=config.hidden_dropout_prob,\n attention_probs_dropout_prob=config.attention_probs_dropout_prob,\n initializer_range=config.initializer_range,\n do_return_all_layers=True)\n\n\n self.sequence_output_transformer = self.all_encoder_layers[-1]\n self.sequence_output_cnn = self.all_encoder_layers[-1]\n with tf.variable_scope(\"merge_cnn_transformer\"):\n merge_input = tf.concat([self.sequence_output_transformer, self.sequence_output_cnn], axis=-1)\n self.sequence_output = tf.layers.dense(\n merge_input,\n config.hidden_size,\n kernel_initializer=create_initializer(config.initializer_range))\n # The \"pooler\" converts the encoded sequence tensor of shape\n # [batch_size, seq_length, hidden_size] to a tensor of shape\n # [batch_size, hidden_size]. This is necessary for segment-level\n # (or segment-pair-level) classification tasks where we need a fixed\n # dimensional representation of the segment.\n with tf.variable_scope(\"pooler\"):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token. We assume that this has been pre-trained\n first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)\n self.pooled_output = tf.layers.dense(\n first_token_tensor,\n config.hidden_size,\n activation=tf.tanh,\n kernel_initializer=create_initializer(config.initializer_range))\n\n def get_pooled_output(self):\n return self.pooled_output\n\n def get_sequence_output(self):\n \"\"\"Gets final hidden layer of encoder.\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\n to the final hidden of the transformer encoder.\n \"\"\"\n return self.sequence_output\n\n def get_all_encoder_layers(self):\n return self.all_encoder_layers\n\n def get_embedding_output(self):\n \"\"\"Gets output of the embedding lookup (i.e., input to the transformer).\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\n to the output of the embedding layer, after summing the word\n embeddings with the positional embeddings and the token type embeddings,\n then performing layer normalization. This is the input to the transformer.\n \"\"\"\n return self.embedding_output\n\n def get_embedding_table(self):\n return self.embedding_table\n\n\n\ndef gelu(x):\n \"\"\"Gaussian Error Linear Unit.\n\n This is a smoother version of the RELU.\n Original paper: https://arxiv.org/abs/1606.08415\n Args:\n x: float Tensor to perform activation.\n\n Returns:\n `x` with the GELU activation applied.\n \"\"\"\n cdf = 0.5 * (1.0 + tf.tanh(\n (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))\n return x * cdf\n\n\ndef get_activation(activation_string):\n \"\"\"Maps a string to a Python function, e.g., \"relu\" => `tf.nn.relu`.\n\n Args:\n activation_string: String name of the activation function.\n\n Returns:\n A Python function corresponding to the activation function. If\n `activation_string` is None, empty, or \"linear\", this will return None.\n If `activation_string` is not a string, it will return `activation_string`.\n\n Raises:\n ValueError: The `activation_string` does not correspond to a known\n activation.\n \"\"\"\n\n # We assume that anything that\"s not a string is already an activation\n # function, so we just return it.\n if not isinstance(activation_string, six.string_types):\n return activation_string\n\n if not activation_string:\n return None\n\n act = activation_string.lower()\n if act == \"linear\":\n return None\n elif act == \"relu\":\n return tf.nn.relu\n elif act == \"gelu\":\n return gelu\n elif act == \"tanh\":\n return tf.tanh\n else:\n raise ValueError(\"Unsupported activation: %s\" % act)\n\n\ndef get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n assignment_map = {}\n initialized_variable_names = {}\n\n name_to_variable = collections.OrderedDict()\n for var in tvars:\n name = var.name\n m = re.match(\"^(.*):\\\\d+$\", name)\n if m is not None:\n name = m.group(1)\n name_to_variable[name] = var\n\n init_vars = tf.train.list_variables(init_checkpoint)\n\n assignment_map = collections.OrderedDict()\n for x in init_vars:\n (name, var) = (x[0], x[1])\n if name not in name_to_variable:\n continue\n assignment_map[name] = name\n initialized_variable_names[name] = 1\n initialized_variable_names[name + \":0\"] = 1\n\n return (assignment_map, initialized_variable_names)\n\n\ndef dropout(input_tensor, dropout_prob):\n \"\"\"Perform dropout.\n\n Args:\n input_tensor: float Tensor.\n dropout_prob: Python float. The probability of dropping out a value (NOT of\n *keeping* a dimension as in `tf.nn.dropout`).\n\n Returns:\n A version of `input_tensor` with dropout applied.\n \"\"\"\n if dropout_prob is None or dropout_prob == 0.0:\n return input_tensor\n\n output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)\n return output\n\n\ndef layer_norm(input_tensor, name=None):\n \"\"\"Run layer normalization on the last dimension of the tensor.\"\"\"\n return tf.contrib.layers.layer_norm(\n inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)\n\n\ndef layer_norm_and_dropout(input_tensor, dropout_prob, name=None):\n \"\"\"Runs layer normalization followed by dropout.\"\"\"\n output_tensor = layer_norm(input_tensor, name)\n output_tensor = dropout(output_tensor, dropout_prob)\n return output_tensor\n\n\ndef create_initializer(initializer_range=0.02):\n \"\"\"Creates a `truncated_normal_initializer` with the given range.\"\"\"\n return tf.truncated_normal_initializer(stddev=initializer_range)\n\n\ndef embedding_lookup(input_ids,\n vocab_size,\n embedding_size=128,\n initializer_range=0.02,\n word_embedding_name=\"word_embeddings\",\n use_one_hot_embeddings=False):\n \"\"\"Looks up words embeddings for id tensor.\n\n Args:\n input_ids: int32 Tensor of shape [batch_size, seq_length] containing word\n ids.\n vocab_size: int. Size of the embedding vocabulary.\n embedding_size: int. Width of the word embeddings.\n initializer_range: float. Embedding initialization range.\n word_embedding_name: string. Name of the embedding table.\n use_one_hot_embeddings: bool. If True, use one-hot method for word\n embeddings. If False, use `tf.gather()`.\n\n Returns:\n float Tensor of shape [batch_size, seq_length, embedding_size].\n \"\"\"\n # This function assumes that the input is of shape [batch_size, seq_length,\n # num_inputs].\n #\n # If the input is a 2D tensor of shape [batch_size, seq_length], we\n # reshape to [batch_size, seq_length, 1].\n if input_ids.shape.ndims == 2:\n input_ids = tf.expand_dims(input_ids, axis=[-1])\n\n embedding_table = tf.get_variable(\n name=word_embedding_name,\n shape=[vocab_size, embedding_size],\n initializer=create_initializer(initializer_range))\n\n flat_input_ids = tf.reshape(input_ids, [-1])\n if use_one_hot_embeddings:\n one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)\n output = tf.matmul(one_hot_input_ids, embedding_table)\n else:\n output = tf.gather(embedding_table, flat_input_ids)\n\n input_shape = get_shape_list(input_ids)\n\n output = tf.reshape(output,\n input_shape[0:-1] + [input_shape[-1] * embedding_size])\n return (output, embedding_table)\n\n\ndef embedding_postprocessor(input_tensor,\n use_token_type=False,\n token_type_ids=None,\n token_type_vocab_size=16,\n token_type_embedding_name=\"token_type_embeddings\",\n use_position_embeddings=True,\n position_embedding_name=\"position_embeddings\",\n initializer_range=0.02,\n max_position_embeddings=512,\n dropout_prob=0.1):\n \"\"\"Performs various post-processing on a word embedding tensor.\n\n Args:\n input_tensor: float Tensor of shape [batch_size, seq_length,\n embedding_size].\n use_token_type: bool. Whether to add embeddings for `token_type_ids`.\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\n Must be specified if `use_token_type` is True.\n token_type_vocab_size: int. The vocabulary size of `token_type_ids`.\n token_type_embedding_name: string. The name of the embedding table variable\n for token type ids.\n use_position_embeddings: bool. Whether to add position embeddings for the\n position of each token in the sequence.\n position_embedding_name: string. The name of the embedding table variable\n for positional embeddings.\n initializer_range: float. Range of the weight initialization.\n max_position_embeddings: int. Maximum sequence length that might ever be\n used with this model. This can be longer than the sequence length of\n input_tensor, but cannot be shorter.\n dropout_prob: float. Dropout probability applied to the final output tensor.\n\n Returns:\n float tensor with same shape as `input_tensor`.\n\n Raises:\n ValueError: One of the tensor shapes or input values is invalid.\n \"\"\"\n input_shape = get_shape_list(input_tensor, expected_rank=3)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n width = input_shape[2]\n\n output = input_tensor\n\n if use_token_type:\n if token_type_ids is None:\n raise ValueError(\"`token_type_ids` must be specified if\"\n \"`use_token_type` is True.\")\n token_type_table = tf.get_variable(\n name=token_type_embedding_name,\n shape=[token_type_vocab_size, width],\n initializer=create_initializer(initializer_range))\n # This vocab will be small so we always do one-hot here, since it is always\n # faster for a small vocabulary.\n flat_token_type_ids = tf.reshape(token_type_ids, [-1])\n one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)\n token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)\n token_type_embeddings = tf.reshape(token_type_embeddings,\n [batch_size, seq_length, width])\n output += token_type_embeddings\n\n if use_position_embeddings:\n assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)\n with tf.control_dependencies([assert_op]):\n full_position_embeddings = tf.get_variable(\n name=position_embedding_name,\n shape=[max_position_embeddings, width],\n initializer=create_initializer(initializer_range))\n # Since the position embedding table is a learned variable, we create it\n # using a (long) sequence length `max_position_embeddings`. The actual\n # sequence length might be shorter than this, for faster training of\n # tasks that do not have long sequences.\n #\n # So `full_position_embeddings` is effectively an embedding table\n # for position [0, 1, 2, ..., max_position_embeddings-1], and the current\n # sequence has positions [0, 1, 2, ... seq_length-1], so we can just\n # perform a slice.\n position_embeddings = tf.slice(full_position_embeddings, [0, 0],\n [seq_length, -1])\n num_dims = len(output.shape.as_list())\n\n # Only the last two dimensions are relevant (`seq_length` and `width`), so\n # we broadcast among the first dimensions, which is typically just\n # the batch size.\n position_broadcast_shape = []\n for _ in range(num_dims - 2):\n position_broadcast_shape.append(1)\n position_broadcast_shape.extend([seq_length, width])\n position_embeddings = tf.reshape(position_embeddings,\n position_broadcast_shape)\n output += position_embeddings\n\n output = layer_norm_and_dropout(output, dropout_prob)\n return output\n\n\ndef create_attention_mask_from_input_mask(from_tensor, to_mask):\n \"\"\"Create 3D attention mask from a 2D tensor mask.\n\n Args:\n from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].\n to_mask: int32 Tensor of shape [batch_size, to_seq_length].\n\n Returns:\n float Tensor of shape [batch_size, from_seq_length, to_seq_length].\n \"\"\"\n from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])\n batch_size = from_shape[0]\n from_seq_length = from_shape[1]\n\n to_shape = get_shape_list(to_mask, expected_rank=2)\n to_seq_length = to_shape[1]\n\n to_mask = tf.cast(\n tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)\n\n # We don't assume that `from_tensor` is a mask (although it could be). We\n # don't actually care if we attend *from* padding tokens (only *to* padding)\n # tokens so we create a tensor of all ones.\n #\n # `broadcast_ones` = [batch_size, from_seq_length, 1]\n broadcast_ones = tf.ones(\n shape=[batch_size, from_seq_length, 1], dtype=tf.float32)\n\n # Here we broadcast along two dimensions to create the mask.\n mask = broadcast_ones * to_mask\n\n return mask\n\n\ndef attention_layer(from_tensor,\n to_tensor,\n attention_mask=None,\n num_attention_heads=1,\n size_per_head=512,\n query_act=None,\n key_act=None,\n value_act=None,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n do_return_2d_tensor=False,\n batch_size=None,\n from_seq_length=None,\n to_seq_length=None):\n \"\"\"Performs multi-headed attention from `from_tensor` to `to_tensor`.\n\n This is an implementation of multi-headed attention based on \"Attention\n is all you Need\". If `from_tensor` and `to_tensor` are the same, then\n this is self-attention. Each timestep in `from_tensor` attends to the\n corresponding sequence in `to_tensor`, and returns a fixed-with vector.\n\n This function first projects `from_tensor` into a \"query\" tensor and\n `to_tensor` into \"key\" and \"value\" tensors. These are (effectively) a list\n of tensors of length `num_attention_heads`, where each tensor is of shape\n [batch_size, seq_length, size_per_head].\n\n Then, the query and key tensors are dot-producted and scaled. These are\n softmaxed to obtain attention probabilities. The value tensors are then\n interpolated by these probabilities, then concatenated back to a single\n tensor and returned.\n\n In practice, the multi-headed attention are done with transposes and\n reshapes rather than actual separate tensors.\n\n Args:\n from_tensor: float Tensor of shape [batch_size, from_seq_length,\n from_width].\n to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].\n attention_mask: (optional) int32 Tensor of shape [batch_size,\n from_seq_length, to_seq_length]. The values should be 1 or 0. The\n attention scores will effectively be set to -infinity for any positions in\n the mask that are 0, and will be unchanged for positions that are 1.\n num_attention_heads: int. Number of attention heads.\n size_per_head: int. Size of each attention head.\n query_act: (optional) Activation function for the query transform.\n key_act: (optional) Activation function for the key transform.\n value_act: (optional) Activation function for the value transform.\n attention_probs_dropout_prob: (optional) float. Dropout probability of the\n attention probabilities.\n initializer_range: float. Range of the weight initializer.\n do_return_2d_tensor: bool. If True, the output will be of shape [batch_size\n * from_seq_length, num_attention_heads * size_per_head]. If False, the\n output will be of shape [batch_size, from_seq_length, num_attention_heads\n * size_per_head].\n batch_size: (Optional) int. If the input is 2D, this might be the batch size\n of the 3D version of the `from_tensor` and `to_tensor`.\n from_seq_length: (Optional) If the input is 2D, this might be the seq length\n of the 3D version of the `from_tensor`.\n to_seq_length: (Optional) If the input is 2D, this might be the seq length\n of the 3D version of the `to_tensor`.\n\n Returns:\n float Tensor of shape [batch_size, from_seq_length,\n num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is\n true, this will be of shape [batch_size * from_seq_length,\n num_attention_heads * size_per_head]).\n\n Raises:\n ValueError: Any of the arguments or tensor shapes are invalid.\n \"\"\"\n\n def transpose_for_scores(input_tensor, batch_size, num_attention_heads,\n seq_length, width):\n output_tensor = tf.reshape(\n input_tensor, [batch_size, seq_length, num_attention_heads, width])\n\n output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])\n return output_tensor\n\n from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])\n to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])\n\n if len(from_shape) != len(to_shape):\n raise ValueError(\n \"The rank of `from_tensor` must match the rank of `to_tensor`.\")\n\n if len(from_shape) == 3:\n batch_size = from_shape[0]\n from_seq_length = from_shape[1]\n to_seq_length = to_shape[1]\n elif len(from_shape) == 2:\n if (batch_size is None or from_seq_length is None or to_seq_length is None):\n raise ValueError(\n \"When passing in rank 2 tensors to attention_layer, the values \"\n \"for `batch_size`, `from_seq_length`, and `to_seq_length` \"\n \"must all be specified.\")\n\n # Scalar dimensions referenced here:\n # B = batch size (number of sequences)\n # F = `from_tensor` sequence length\n # T = `to_tensor` sequence length\n # N = `num_attention_heads`\n # H = `size_per_head`\n\n from_tensor_2d = reshape_to_matrix(from_tensor)\n to_tensor_2d = reshape_to_matrix(to_tensor)\n\n # `query_layer` = [B*F, N*H]\n query_layer = tf.layers.dense(\n from_tensor_2d,\n num_attention_heads * size_per_head,\n activation=query_act,\n name=\"query\",\n kernel_initializer=create_initializer(initializer_range))\n\n # `key_layer` = [B*T, N*H]\n key_layer = tf.layers.dense(\n to_tensor_2d,\n num_attention_heads * size_per_head,\n activation=key_act,\n name=\"key\",\n kernel_initializer=create_initializer(initializer_range))\n\n # `value_layer` = [B*T, N*H]\n value_layer = tf.layers.dense(\n to_tensor_2d,\n num_attention_heads * size_per_head,\n activation=value_act,\n name=\"value\",\n kernel_initializer=create_initializer(initializer_range))\n\n # `query_layer` = [B, N, F, H]\n query_layer = transpose_for_scores(query_layer, batch_size,\n num_attention_heads, from_seq_length,\n size_per_head)\n\n # `key_layer` = [B, N, T, H]\n key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,\n to_seq_length, size_per_head)\n\n # Take the dot product between \"query\" and \"key\" to get the raw\n # attention scores.\n # `attention_scores` = [B, N, F, T]\n attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)\n attention_scores = tf.multiply(attention_scores,\n 1.0 / math.sqrt(float(size_per_head)))\n\n if attention_mask is not None:\n # `attention_mask` = [B, 1, F, T]\n attention_mask = tf.expand_dims(attention_mask, axis=[1])\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0\n\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n attention_scores += adder\n\n # Normalize the attention scores to probabilities.\n # `attention_probs` = [B, N, F, T]\n attention_probs = tf.nn.softmax(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = dropout(attention_probs, attention_probs_dropout_prob)\n\n # `value_layer` = [B, T, N, H]\n value_layer = tf.reshape(\n value_layer,\n [batch_size, to_seq_length, num_attention_heads, size_per_head])\n\n # `value_layer` = [B, N, T, H]\n value_layer = tf.transpose(value_layer, [0, 2, 1, 3])\n\n # `context_layer` = [B, N, F, H]\n context_layer = tf.matmul(attention_probs, value_layer)\n\n # `context_layer` = [B, F, N, H]\n context_layer = tf.transpose(context_layer, [0, 2, 1, 3])\n\n if do_return_2d_tensor:\n # `context_layer` = [B*F, N*H]\n context_layer = tf.reshape(\n context_layer,\n [batch_size * from_seq_length, num_attention_heads * size_per_head])\n else:\n # `context_layer` = [B, F, N*H]\n context_layer = tf.reshape(\n context_layer,\n [batch_size, from_seq_length, num_attention_heads * size_per_head])\n\n return context_layer\n\ndef transformer_model(input_tensor,\n attention_mask=None,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n intermediate_act_fn=gelu,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n do_return_all_layers=False):\n \"\"\"Multi-headed, multi-layer Transformer from \"Attention is All You Need\".\n\n This is almost an exact implementation of the original Transformer encoder.\n\n See the original paper:\n https://arxiv.org/abs/1706.03762\n\n Also see:\n https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py\n\n Args:\n input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].\n attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,\n seq_length], with 1 for positions that can be attended to and 0 in\n positions that should not be.\n hidden_size: int. Hidden size of the Transformer.\n num_hidden_layers: int. Number of layers (blocks) in the Transformer.\n num_attention_heads: int. Number of attention heads in the Transformer.\n intermediate_size: int. The size of the \"intermediate\" (a.k.a., feed\n forward) layer.\n intermediate_act_fn: function. The non-linear activation function to apply\n to the output of the intermediate/feed-forward layer.\n hidden_dropout_prob: float. Dropout probability for the hidden layers.\n attention_probs_dropout_prob: float. Dropout probability of the attention\n probabilities.\n initializer_range: float. Range of the initializer (stddev of truncated\n normal).\n do_return_all_layers: Whether to also return all layers or just the final\n layer.\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size], the final\n hidden layer of the Transformer.\n\n Raises:\n ValueError: A Tensor shape or parameter is invalid.\n \"\"\"\n if hidden_size % num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (hidden_size, num_attention_heads))\n\n attention_head_size = int(hidden_size / num_attention_heads)\n input_shape = get_shape_list(input_tensor, expected_rank=3)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n input_width = input_shape[2]\n\n # The Transformer performs sum residuals on all layers so the input needs\n # to be the same as the hidden size.\n if input_width != hidden_size:\n raise ValueError(\"The width of the input tensor (%d) != hidden size (%d)\" %\n (input_width, hidden_size))\n\n # We keep the representation as a 2D tensor to avoid re-shaping it back and\n # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on\n # the GPU/CPU but may not be free on the TPU, so we want to minimize them to\n # help the optimizer.\n prev_output = reshape_to_matrix(input_tensor)\n\n all_layer_outputs = []\n for layer_idx in range(num_hidden_layers):\n with tf.variable_scope(\"layer_%d\" % layer_idx):\n layer_input = prev_output\n\n with tf.variable_scope(\"attention\"):\n attention_heads = []\n with tf.variable_scope(\"self\"):\n attention_head = attention_layer(\n from_tensor=layer_input,\n to_tensor=layer_input,\n attention_mask=attention_mask,\n num_attention_heads=num_attention_heads,\n size_per_head=attention_head_size,\n attention_probs_dropout_prob=attention_probs_dropout_prob,\n initializer_range=initializer_range,\n do_return_2d_tensor=True,\n batch_size=batch_size,\n from_seq_length=seq_length,\n to_seq_length=seq_length)\n attention_heads.append(attention_head)\n\n attention_output = None\n if len(attention_heads) == 1:\n attention_output = attention_heads[0]\n else:\n # In the case where we have other sequences, we just concatenate\n # them to the self-attention head before the projection.\n attention_output = tf.concat(attention_heads, axis=-1)\n\n # Run a linear projection of `hidden_size` then add a residual\n # with `layer_input`.\n with tf.variable_scope(\"output\"):\n attention_output = tf.layers.dense(\n attention_output,\n hidden_size,\n kernel_initializer=create_initializer(initializer_range))\n attention_output = dropout(attention_output, hidden_dropout_prob)\n attention_output = layer_norm(attention_output + layer_input)\n\n # The activation is only applied to the \"intermediate\" hidden layer.\n with tf.variable_scope(\"intermediate\"):\n intermediate_output = tf.layers.dense(\n attention_output,\n intermediate_size,\n activation=intermediate_act_fn,\n kernel_initializer=create_initializer(initializer_range))\n\n # Down-project back to `hidden_size` then add the residual.\n with tf.variable_scope(\"output\"):\n layer_output = tf.layers.dense(\n intermediate_output,\n hidden_size,\n kernel_initializer=create_initializer(initializer_range))\n layer_output = dropout(layer_output, hidden_dropout_prob)\n layer_output = layer_norm(layer_output + attention_output)\n prev_output = layer_output\n all_layer_outputs.append(layer_output)\n\n if do_return_all_layers:\n final_outputs = []\n for layer_output in all_layer_outputs:\n final_output = reshape_from_matrix(layer_output, input_shape)\n final_outputs.append(final_output)\n return final_outputs\n else:\n final_output = reshape_from_matrix(prev_output, input_shape)\n return final_output\n\n\ndef cnn_model(input_tensor,\n attention_mask=None,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n intermediate_act_fn=gelu,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n do_return_all_layers=False):\n\n # if hidden_size % num_attention_heads != 0:\n # raise ValueError(\n # \"The hidden size (%d) is not a multiple of the number of attention \"\n # \"heads (%d)\" % (hidden_size, num_attention_heads))\n\n # attention_head_size = int(hidden_size / num_attention_heads)\n input_shape = get_shape_list(input_tensor, expected_rank=3)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n input_width = input_shape[2]\n\n # The Transformer performs sum residuals on all layers so the input needs\n # to be the same as the hidden size.\n if input_width != hidden_size:\n raise ValueError(\"The width of the input tensor (%d) != hidden size (%d)\" %\n (input_width, hidden_size))\n\n # We keep the representation as a 2D tensor to avoid re-shaping it back and\n # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on\n # the GPU/CPU but may not be free on the TPU, so we want to minimize them to\n # help the optimizer.\n prev_output = reshape_to_matrix(input_tensor)\n\n all_layer_outputs = []\n for layer_idx in range(num_hidden_layers):\n with tf.variable_scope(\"cnn_layer_%d\" % layer_idx):\n layer_input = prev_output\n\n with tf.variable_scope(\"cnn_compute\"):\n cnn_output = tf.layers.conv1d(layer_input, 100, layer_idx+1, padding='same')\n\n\n # The activation is only applied to the \"intermediate\" hidden layer.\n with tf.variable_scope(\"intermediate\"):\n intermediate_output = tf.layers.dense(\n cnn_output,\n intermediate_size,\n activation=intermediate_act_fn,\n kernel_initializer=create_initializer(initializer_range))\n\n # Down-project back to `hidden_size` then add the residual.\n with tf.variable_scope(\"output\"):\n layer_output = tf.layers.dense(\n intermediate_output,\n hidden_size,\n kernel_initializer=create_initializer(initializer_range))\n layer_output = dropout(layer_output, hidden_dropout_prob)\n layer_output = layer_norm(layer_output + cnn_output)\n prev_output = layer_output\n all_layer_outputs.append(layer_output)\n\n if do_return_all_layers:\n final_outputs = []\n for layer_output in all_layer_outputs:\n final_output = reshape_from_matrix(layer_output, input_shape)\n final_outputs.append(final_output)\n return final_outputs\n else:\n final_output = reshape_from_matrix(prev_output, input_shape)\n return final_output\n\n\n\ndef get_shape_list(tensor, expected_rank=None, name=None):\n \"\"\"Returns a list of the shape of tensor, preferring static dimensions.\n\n Args:\n tensor: A tf.Tensor object to find the shape of.\n expected_rank: (optional) int. The expected rank of `tensor`. If this is\n specified and the `tensor` has a different rank, and exception will be\n thrown.\n name: Optional name of the tensor for the error message.\n\n Returns:\n A list of dimensions of the shape of tensor. All static dimensions will\n be returned as python integers, and dynamic dimensions will be returned\n as tf.Tensor scalars.\n \"\"\"\n if name is None:\n name = tensor.name\n\n if expected_rank is not None:\n assert_rank(tensor, expected_rank, name)\n\n shape = tensor.shape.as_list()\n\n non_static_indexes = []\n for (index, dim) in enumerate(shape):\n if dim is None:\n non_static_indexes.append(index)\n\n if not non_static_indexes:\n return shape\n\n dyn_shape = tf.shape(tensor)\n for index in non_static_indexes:\n shape[index] = dyn_shape[index]\n return shape\n\n\ndef reshape_to_matrix(input_tensor):\n \"\"\"Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix).\"\"\"\n ndims = input_tensor.shape.ndims\n if ndims < 2:\n raise ValueError(\"Input tensor must have at least rank 2. Shape = %s\" %\n (input_tensor.shape))\n if ndims == 2:\n return input_tensor\n\n width = input_tensor.shape[-1]\n output_tensor = tf.reshape(input_tensor, [-1, width])\n return output_tensor\n\n\ndef reshape_from_matrix(output_tensor, orig_shape_list):\n \"\"\"Reshapes a rank 2 tensor back to its original rank >= 2 tensor.\"\"\"\n if len(orig_shape_list) == 2:\n return output_tensor\n\n output_shape = get_shape_list(output_tensor)\n\n orig_dims = orig_shape_list[0:-1]\n width = output_shape[-1]\n\n return tf.reshape(output_tensor, orig_dims + [width])\n\n\ndef assert_rank(tensor, expected_rank, name=None):\n \"\"\"Raises an exception if the tensor rank is not of the expected rank.\n\n Args:\n tensor: A tf.Tensor to check the rank of.\n expected_rank: Python integer or list of integers, expected rank.\n name: Optional name of the tensor for the error message.\n\n Raises:\n ValueError: If the expected shape doesn't match the actual shape.\n \"\"\"\n if name is None:\n name = tensor.name\n\n expected_rank_dict = {}\n if isinstance(expected_rank, six.integer_types):\n expected_rank_dict[expected_rank] = True\n else:\n for x in expected_rank:\n expected_rank_dict[x] = True\n\n actual_rank = tensor.shape.ndims\n if actual_rank not in expected_rank_dict:\n scope_name = tf.get_variable_scope().name\n raise ValueError(\n \"For the tensor `%s` in scope `%s`, the actual rank \"\n \"`%d` (shape = %s) is not equal to the expected rank `%s`\" %\n (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))\n"
] |
[
[
"tensorflow.layers.conv1d",
"tensorflow.concat",
"numpy.sqrt",
"tensorflow.control_dependencies",
"tensorflow.zeros",
"tensorflow.gfile.GFile",
"tensorflow.cast",
"tensorflow.assert_less_equal",
"tensorflow.truncated_normal_initializer",
"tensorflow.squeeze",
"tensorflow.gather",
"tensorflow.train.list_variables",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.pow",
"tensorflow.one_hot",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.slice",
"tensorflow.reshape",
"tensorflow.ones",
"tensorflow.expand_dims",
"tensorflow.contrib.layers.layer_norm",
"tensorflow.variable_scope",
"tensorflow.get_variable_scope"
]
] |
gregdp/segger
|
[
"d4c112fd43f0b088145e225f976335800874ebe5"
] |
[
"Segger/quaternion.py"
] |
[
"\nimport chimera\nimport numpy\n\n\nclass Quaternion :\n\n def __init__ ( self, s=1.0, v=chimera.Vector(0,0,0) ) :\n self.s = s\n self.v = v\n\n def length (self) :\n return numpy.sqrt ( (self.s*self.s) + self.v.sqlength() )\n\n\n def rotation (self, angDegrees, axis) :\n angRad = 0.5 * angDegrees * numpy.pi / 180.0\n self.s = numpy.cos ( angRad )\n self.v = axis * numpy.sin ( angRad )\n\n\n def inverse ( self ) :\n return Quaternion ( self.s, self.v * -1.0 )\n\n\n def fromXform ( self, xf ) :\n\n axis, angle = xf.getRotation ()\n if angle >= -180.0 and angle <= 180.0 :\n self.rotation ( angle, axis )\n elif angle < -180.0 :\n blah\n self.rotation ( angle, axis*-1.0 )\n else :\n blah\n self.rotation ( angle, axis*-1.0 )\n\n m = numpy.reshape ( xf.getOpenGLMatrix(), (4,4) )\n m = numpy.transpose ( m )\n self.fromMatrix ( m )\n\n\n def dot ( self, q ) :\n return self.s * q.s + self.v * q.v\n\n def angleTo ( self, q2 ) :\n self.normalize()\n q2.normalize()\n return 2.0 * numpy.arccos ( self * q2 )\n\n\n def normalize (self) :\n l = self.length()\n if (l > 1e-4) :\n self.s = self.s / l\n self.v = self.v / l\n else :\n raise (\"quaternion normalization error\")\n\n def __mul__(self, x) :\n if type(x) == type(1.0) or type(x) == numpy.float64 :\n return Quaternion ( self.s*x, self.v*x )\n else :\n return self.dot ( x )\n\n def __add__(self, x) :\n return Quaternion ( self.s + x.s, self.v + x.v )\n\n def __sub__(self, x) :\n return Quaternion ( self.s - x.s, self.v - x.v )\n\n def __copy__ (self) :\n return Quaternion ( self.s, self.v.__copy__() )\n\n def Xform (self) :\n #self.normalize()\n s = self.s\n v = self.v\n return chimera.Xform.xform (\n 1-2*v.y*v.y-2*v.z*v.z, 2*v.x*v.y-2*s*v.z, 2*v.x*v.z+2*s*v.y, 0,\n 2*v.x*v.y+2*s*v.z, 1-2*v.x*v.x-2*v.z*v.z, 2*v.y*v.z-2*s*v.x, 0,\n 2*v.x*v.z-2*s*v.y, 2*v.y*v.z+2*s*v.x, 1-2*v.x*v.x-2*v.y*v.y, 0\n )\n\n def matrix (self) :\n #self.normalize()\n s = self.s\n v = self.v\n return [\n [1-2*v.y*v.y-2*v.z*v.z, 2*v.x*v.y-2*s*v.z, 2*v.x*v.z+2*s*v.y],\n [2*v.x*v.y+2*s*v.z, 1-2*v.x*v.x-2*v.z*v.z, 2*v.y*v.z-2*s*v.x],\n [2*v.x*v.z-2*s*v.y, 2*v.y*v.z+2*s*v.x, 1-2*v.x*v.x-2*v.y*v.y],\n ]\n\n\n def fromMatrix ( self, rkRot ) :\n # Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n # article \"Quaternion Calculus and Fast Animation\".\n\n fTrace = rkRot[0,0] + rkRot[1,1] + rkRot[2,2]\n fRoot = 0.0\n if fTrace > 0.0 :\n # |w| > 1/2, may as well choose w > 1/2\n fRoot = numpy.sqrt (fTrace + 1.0) # 2w\n self.s = 0.5 * fRoot;\n fRoot = 0.5 / fRoot; # 1/(4w)\n self.v[0] = (rkRot[2,1]-rkRot[1,2])*fRoot;\n self.v[1] = (rkRot[0,2]-rkRot[2,0])*fRoot;\n self.v[2] = (rkRot[1,0]-rkRot[0,1])*fRoot;\n\n else :\n # |w| <= 1/2\n i = 0\n if rkRot[1,1] > rkRot[0,0] :\n i = 1\n if rkRot[2,2] > rkRot[i,i] :\n i = 2\n\n j = (i + 1) % 3 # ms_iNext[i];\n k = (j + 1) % 3 # ms_iNext[j];\n\n fRoot = numpy.sqrt(rkRot[i,i]-rkRot[j,j]-rkRot[k,k]+1.0);\n\n # Real* apfQuat[3] = { &m_afTuple[1], &m_afTuple[2], &m_afTuple[3] };\n self.v[i] = 0.5 * fRoot # *apfQuat[i] = ((Real)0.5)*fRoot;\n\n fRoot = 0.5 / fRoot\n self.s = (rkRot[k,j]-rkRot[j,k])*fRoot\n self.v[j] = (rkRot[j,i]+rkRot[i,j])*fRoot # *apfQuat[j]\n self.v[k] = (rkRot[k,i]+rkRot[i,k])*fRoot # *apfQuat[k]\n\n\ndef mult (a, b) :\n return Quaternion (a.s*b.s - a.v*b.v, b.v*a.s + a.v*b.s + chimera.cross(a.v,b.v))\n\n\ndef slerp0 (p, q, t) :\n\n cs = p.dot(q)\n angle = numpy.arccos ( cs )\n\n if abs (angle) > 0.0 :\n sn = numpy.sin ( angle )\n invSn = 1.0 / sn;\n tAngle = t*angle;\n c0 = numpy.sin(angle - tAngle)*invSn;\n c1 = numpy.sin(tAngle)*invSn;\n\n #mTuple[0] = coeff0*p.mTuple[0] + coeff1*q.mTuple[0];\n #mTuple[1] = coeff0*p.mTuple[1] + coeff1*q.mTuple[1];\n #mTuple[2] = coeff0*p.mTuple[2] + coeff1*q.mTuple[2];\n #mTuple[3] = coeff0*p.mTuple[3] + coeff1*q.mTuple[3];\n return Quaternion (p.s*c0+q.s*c1, p.v*c0 + q.v*c1)\n\n else :\n return Quaternion (p.s, chimera.Vector(p.v[0], p.v[1], p.v[2]))\n\n\ndef slerp (v0, v1, t) :\n\n # http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/\n\n #; Inputs are: unit vectors v0 and v1, scalar t\n #; v0 and v1 are linearly independent\n\n # Quaternion slerp(Quaternion const &v0, Quaternion const &v1, double t) {\n # // v0 and v1 should be unit length or else\n # // something broken will happen.\n #\n # // Compute the cosine of the angle between the two vectors.\n # double dot = dot_product(v0, v1);\n #\n # const double DOT_THRESHOLD = 0.9995;\n # if (dot > DOT_THRESHOLD) {\n # // If the inputs are too close for comfort, linearly interpolate\n # // and normalize the result.\n #\n # Quaternion result = v0 + t*(v1 - v0)\n # result.normalize();\n # return result;\n # }\n #\n # Clamp(dot, -1, 1); // Robustness: Stay within domain of acos()\n # double theta_0 = acos(dot); // theta_0 = angle between input vectors\n # double theta = theta_0*t; // theta = angle between v0 and result\n #\n # Quaternion v2 = v1 - v0*dot\n # v2.normalize(); // { v0, v2 } is now an orthonormal basis\n #\n # return v0*cos(theta) + v2*sin(theta);\n\n\n\n dot = v0.dot(v1)\n #print dot\n\n if 1 or dot > 0.9995 :\n r = v0 + (v1-v0) * t\n r.normalize()\n return r\n\n if dot < -1.0 : dot = -1.0\n if dot > 1.0 : dot = 1.0\n\n theta_0 = numpy.arccos ( dot )\n theta = theta_0*t\n\n v2 = v1 - v0 * dot\n v2.normalize()\n\n r = v0 * numpy.cos(theta) + v2 * numpy.sin(theta)\n\n if 0 :\n # from http://graphics.cs.cmu.edu/nsp/course/15-464/Fall05/assignments/p245-shoemake.pdf\n a0 = numpy.sin( (1-t) * theta_0 ) / numpy.sin(theta_0)\n a1 = numpy.sin ( t * theta_0 ) / numpy.sin ( theta_0 )\n r = v0 * a0 + v1 * a1\n\n return r\n"
] |
[
[
"numpy.sqrt",
"numpy.cos",
"numpy.arccos",
"numpy.sin",
"numpy.transpose"
]
] |
ikaroszhang96/Convex-AlphaZero
|
[
"d96c9790529e48ff4e2ec34649bdc312a0abcc53"
] |
[
"Main/AlphaZero/DistributedSelfPlay/SelfPlay.py"
] |
[
"from Main.AlphaZero.DistributedSelfPlay import Constants\nfrom Main.Training.Connect4 import MemoryBuffers\nfrom Main import Hyperparameters\nimport multiprocessing as mp\nimport numpy as np\nimport time\n\n'''\nListen for data from the Remote Worker and forward it to the Replay Watcher.\nEvery worker will continue to work until the pre-determined number of games has been collected.\n\nAfter the Remote Workers have been aborted by the Replay Watcher, the will message the listener and the listener quits\n'''\ndef _waitForWorker(connection, dumpPipe):\n gamesCollected = 0\n collectingDataFromWorker = True\n while (collectingDataFromWorker):\n msg, data = connection.readMessage()\n\n dumpPipe.put((msg, data))\n if (msg == Constants.RemoteProtocol.DUMP_VISITED_STATES_TO_OVERLORD):\n collectingDataFromWorker = False\n elif (msg == Constants.RemoteProtocol.DUMP_REPLAY_DATA_TO_OVERLORD):\n amountOfGames = data[0]\n gamesCollected += amountOfGames\n\n print(\"Worker Finished: {} Amount of Games: {}\".format(connection.id, gamesCollected))\n\n\ndef _stopRemoteWorkers(connections):\n print(\"Aborting remoteWorkers\")\n for c in connections:\n c.sendMessage(Constants.RemoteProtocol.OVERLORD_REPLAY_BUFFER_FULL, (\"\",))\n\n\n# Collect data from all listeners and upon reaching a pre-determined number of games abort all Remote Workers\n# As the main data is stored at the Looping Trainer we clear the Replay Buffer at the start\ndef _replayWatcher(connections, dumpPipe):\n print(\"Starting replay watcher\")\n collectedGamesThisCycle = 0\n MemoryBuffers.clearReplayBuffer()\n startTimeSelfPlay = time.time()\n\n while (True):\n msg, data = dumpPipe.get() # Data passed from a listener\n\n if (msg == Constants.RemoteProtocol.DUMP_REPLAY_DATA_TO_OVERLORD):\n amountOfGames, states, evals, polices, weights = data\n MemoryBuffers.addLabelsToReplayBuffer(states, evals, polices)\n collectedGamesThisCycle += amountOfGames\n\n # Display a formatted message\n cycleProgressMsg = \"{} / {}\".format(collectedGamesThisCycle, Hyperparameters.AMOUNT_OF_NEW_GAMES_PER_CYCLE)\n elapsedTime = np.around(time.time() - startTimeSelfPlay, 3)\n elapsedTimeMsg = \"Time: {}\".format(elapsedTime)\n gamesPerSecondMsg = \"Games/Sec: {}\".format(np.around(collectedGamesThisCycle / elapsedTime, 3))\n print(cycleProgressMsg + \"\\t\\t\" + elapsedTimeMsg + \"\\t\\t\" + gamesPerSecondMsg)\n\n # Upon receving sufficent number of games we send a message to all Remote Workers to abort\n if (collectedGamesThisCycle >= Hyperparameters.AMOUNT_OF_NEW_GAMES_PER_CYCLE):\n _stopRemoteWorkers(connections)\n return\n\n\n'''\n*** CURRENTLY INNACTIVATED ***\nThe argmax scheduele deceides at what point in a game we start playing deterministicly according to the policy .\n'''\n\n\ndef _getCurrentArgMaxLevel(modelGeneration):\n for a in Hyperparameters.ARG_MAX_SCHEDULE:\n cycleNumber, argMaxLevel = a\n if (modelGeneration < cycleNumber):\n return argMaxLevel\n\n _, finalArgMaxLevel = Hyperparameters.ARG_MAX_SCHEDULE[-1]\n return finalArgMaxLevel\n\n\n'''\nBroadcast the current: (Network Parameters, MCTS simulations per move, ArgMax schedule) to all Remote Workers. \nThen start a listener for every worker that collects game data.\nThese listeners forwards the collected data to the Replay Watcher\n\nFinishes after a fixed number of games. \n'''\n\n\ndef selfPlay(workerConnections, modelAsBytes, modelGeneration):\n t1 = time.time() # Only used for displaying elapsed time to the user\n\n argMaxLevel = _getCurrentArgMaxLevel(modelGeneration)\n workerCounter = 0\n for c in workerConnections:\n c.sendMessage(Constants.RemoteProtocol.START_SELF_PLAY,\n (workerCounter, modelAsBytes, Hyperparameters.MCTS_SIMULATIONS_PER_MOVE, argMaxLevel))\n workerCounter += 1\n print(\"Sending out models finished:\", time.time() - t1)\n\n # Start a listener for every remote worker\n dumpPipe = mp.Queue()\n procs = [mp.Process(target=_waitForWorker, args=(c, dumpPipe)) for c in workerConnections]\n for p in procs:\n p.start()\n\n # Wait until all listeners have reported that they have finished, then stop all Remote Workers\n _replayWatcher(workerConnections, dumpPipe)\n print(\"Self-Play finished: {}\".format(time.time() - t1))\n"
] |
[
[
"numpy.around"
]
] |
m214089/lorenz-da
|
[
"da02fddcac6eb85e285843da35bf1a3e7c07fe62"
] |
[
"src/comp_varDA.py"
] |
[
"#!/usr/bin/env python\n\n###############################################################\n# < next few lines under version control, D O N O T E D I T >\n# $Date$\n# $Revision$\n# $Author$\n# $Id$\n###############################################################\n\n###############################################################\n# comp_varDA.py - compare the effects of inflating static cov\n# on the performance of a variational DA\n###############################################################\n\n###############################################################\n__author__ = \"Rahul Mahajan\"\n__email__ = \"[email protected]\"\n__copyright__ = \"Copyright 2012, NASA / GSFC / GMAO\"\n__license__ = \"GPL\"\n__status__ = \"Prototype\"\n###############################################################\n\n###############################################################\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot\nfrom argparse import ArgumentParser,ArgumentDefaultsHelpFormatter\nfrom netCDF4 import Dataset\nfrom module_IO import *\n###############################################################\n\n###############################################################\ndef main():\n\n # name of starting ensDA output diagnostic file, starting index and measure\n\n parser = ArgumentParser(description='compare the diag files written by varDA.py',formatter_class=ArgumentDefaultsHelpFormatter)\n parser.add_argument('-f','--filename',help='name of the diag file to read',required=True)\n parser.add_argument('-m','--measure',help='measure to evaluate performance',required=False,choices=['obs','truth'],default='truth')\n parser.add_argument('-b','--begin_index',help='starting index to read',type=int,required=False,default=101)\n parser.add_argument('-e','--end_index',help='ending index to read',type=int,required=False,default=-1)\n parser.add_argument('-s','--save_figure',help='save figures',action='store_true',required=False)\n args = parser.parse_args()\n\n fname = args.filename\n measure = args.measure\n sOI = args.begin_index\n eOI = args.end_index\n save_fig = args.save_figure\n\n # Inflation factors to compare\n #alpha = [1.0, 2.0, 3.0, 3.1, 3.2, 3.4]\n alpha = [0.25, 0.3, 0.35, 0.4, 0.5, 0.6, 0.7, 1.0]\n alpha = [1.0, 2.0, 2.5]\n\n # some more arguments, currently hard-coded\n save_figures = False # save plots as eps\n yscale = 'linear' # y-axis of RMSE plots (linear/semilog)\n yFix = 0.18 # fix the y-axis of RMSE plots ( None = automatic )\n fOrient = 'portrait' # figure orientation (landscape/portrait)\n\n if ( not measure ): measure = 'truth'\n if ( sOI == -1 ): sOI = 0\n\n nf = len(alpha)\n fnames = []\n for i in range(nf): fnames.append( fname + '%3.2f.nc4' % ((alpha[i])) )\n\n if ( len(fnames) <= 15):\n fcolor = [\"#000000\", \"#C0C0C0\", \"#808080\", \"#800000\", \"#FF0000\",\\\n \"#800080\", \"#FF00FF\", \"#008000\", \"#00FF00\", \"#808000\",\\\n \"#FFFF00\", \"#000080\", \"#0000FF\", \"#008080\", \"#00FFFF\"]\n # black, silver, gray, maroon, red\n # purple, fuchsia, green, lime, olive\n # yellow, navy, blue, teal, aqua\n else:\n fcolor = get_Ndistinct_colors(len(fnames))\n\n # read general dimensions and necessary attributes from the diagnostic file\n [model, DA, _, gvarDA] = read_diag_info(fnames[0])\n\n Bc = read_clim_cov(model=model,norm=True)\n\n if ( gvarDA.update == 1 ): vstr = '3DVar'\n elif ( gvarDA.update == 2 ): vstr = '4DVar'\n\n # allocate room for variables\n print('computing RMSE against %s' % measure)\n xbrmse = np.zeros((len(fnames),DA.nassim))\n xarmse = np.zeros((len(fnames),DA.nassim))\n xyrmse = np.zeros((len(fnames),DA.nassim))\n flabel = []\n blabel = []\n mean_prior = np.zeros(len(fnames))\n mean_posterior = np.zeros(len(fnames))\n std_prior = np.zeros(len(fnames))\n std_posterior = np.zeros(len(fnames))\n mean_niters = np.zeros(len(fnames))\n std_niters = np.zeros(len(fnames))\n innov = np.zeros(len(fnames))\n mean_evratio = np.zeros(len(fnames))\n std_evratio = np.zeros(len(fnames))\n\n for fname in fnames:\n\n print('reading ... %s' % fname)\n f = fnames.index(fname)\n\n try:\n nc = Dataset(fname, mode='r', format='NETCDF4')\n flabel.append(r'$\\alpha = %3.2f$' % alpha[f])\n blabel.append('%3.2f' % alpha[f])\n nc.close()\n except Exception as Instance:\n print('Exception occurred during read of ' + fname)\n print(type(Instance))\n print(Instance.args)\n print(Instance)\n sys.exit(1)\n\n # read the varDA for the specific diagnostic file\n [_, _, _, varDA] = read_diag_info(fname)\n\n # read the diagnostic file\n xt, xb, xa, y, H, R, niters = read_diag(fname, 0, end_time=DA.nassim)\n if ( varDA.update == 2 ): y = y[:,:model.Ndof]\n\n # compute RMSE in prior, posterior and observations\n if ( measure == 'truth' ):\n xbrmse[f,] = np.sqrt( np.sum( (xt - xb)**2, axis = 1) / model.Ndof )\n xarmse[f,] = np.sqrt( np.sum( (xt - xa)**2, axis = 1) / model.Ndof )\n else:\n xbrmse[f,] = np.sqrt( np.sum( (y - xb)**2, axis = 1) / model.Ndof )\n xarmse[f,] = np.sqrt( np.sum( (y - xa)**2, axis = 1) / model.Ndof )\n xyrmse[f,] = np.sqrt( np.sum( (xt - y)**2 ) / model.Ndof )\n\n evratio = niters.copy()\n evratio = np.zeros(len(niters))\n for i in range(DA.nassim):\n innov = np.sum((y[i,:] - np.dot(np.diag(H[i,:]),xb[ i,:]))**2)\n totvar = np.sum(varDA.inflation.infl_fac*np.diag(Bc) + R[i,:])\n evratio[i] = innov / totvar\n mean_evratio[f] = np.mean(evratio[sOI:])\n std_evratio[f] = np.std( evratio[sOI:],ddof=1)\n\n # compute mean and std. dev. in the iteration count\n mean_niters[f] = np.mean(niters[sOI+1:])\n std_niters[f] = np.std( niters[sOI+1:], ddof=1)\n\n # start plotting\n\n #-----------------------------------------------------------\n fig = pyplot.figure()\n pyplot.clf()\n pyplot.hold(True)\n for fname in fnames:\n f = fnames.index(fname)\n q = np.squeeze(xbrmse[f,sOI:])\n if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1)\n elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1)\n\n yl = pyplot.get(pyplot.gca(),'ylim')\n xl = pyplot.get(pyplot.gca(),'xlim')\n if ( yFix is None ): ymax = yl[1]\n else: ymax = yFix\n pyplot.ylim(0.0, ymax)\n pyplot.xlim(0.0, len(q))\n\n for fname in fnames:\n f = fnames.index(fname)\n q = np.squeeze(xbrmse[f,sOI:])\n mean_prior[f] = np.mean(q)\n std_prior[f] = np.std(q,ddof=1)\n str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1))\n pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10)\n\n pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12)\n pyplot.ylabel('RMSE',fontweight='bold',fontsize=12)\n pyplot.title('RMSE - Prior',fontweight='bold',fontsize=14)\n pyplot.legend(loc=1)\n pyplot.hold(False)\n if save_figures:\n fig.savefig('%s_varDA_RMSE_Prior.pdf' % (model.Name),orientation=fOrient,format='pdf')\n #-----------------------------------------------------------\n\n #-----------------------------------------------------------\n fig = pyplot.figure()\n pyplot.clf()\n pyplot.hold(True)\n for fname in fnames:\n f = fnames.index(fname)\n q = np.squeeze(xarmse[f,sOI:])\n if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1)\n elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1)\n\n yl = pyplot.get(pyplot.gca(),'ylim')\n xl = pyplot.get(pyplot.gca(),'xlim')\n if ( yFix is None ): ymax = yl[1]\n else: ymax = yFix\n pyplot.ylim(0.0, ymax)\n pyplot.xlim(0.0, len(q))\n\n for fname in fnames:\n f = fnames.index(fname)\n q = np.squeeze(xarmse[f,sOI:])\n mean_posterior[f] = np.mean(q)\n std_posterior[f] = np.std(q,ddof=1)\n str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1))\n pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10)\n\n pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12)\n pyplot.ylabel('RMSE',fontweight='bold',fontsize=12)\n pyplot.title('RMSE - Posterior',fontweight='bold',fontsize=14)\n pyplot.legend(loc=1)\n pyplot.hold(False)\n if save_figures:\n fig.savefig('%s_varDA_RMSE_Posterior.pdf' % (model.Name),orientation=fOrient,format='pdf')\n #-----------------------------------------------------------\n\n #-----------------------------------------------------------\n fig = pyplot.figure()\n pyplot.clf()\n pyplot.hold(True)\n\n index = np.arange(nf) + 0.15\n width = 0.35\n\n bottom = 0.0\n pyplot.bar(index,mean_prior-bottom,width,bottom=bottom,linewidth=0.0,color='0.75',edgecolor='0.75',yerr=std_prior, error_kw=dict(ecolor='black',elinewidth=3,capsize=5))\n pyplot.bar(index+width,mean_posterior-bottom,width,bottom=bottom,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_posterior,error_kw=dict(ecolor='black',elinewidth=3,capsize=5))\n\n pyplot.xticks(index+width, blabel)\n\n pyplot.xlabel('Inflation Factor', fontweight='bold',fontsize=12)\n pyplot.ylabel('RMSE', fontweight='bold',fontsize=12)\n pyplot.title( 'RMSE', fontweight='bold',fontsize=14)\n pyplot.hold(False)\n if save_figures:\n fig.savefig('%s_varDA_RMSE.pdf' % (model.Name),orientation=fOrient,format='pdf')\n #-----------------------------------------------------------\n\n #-----------------------------------------------------------\n fig = pyplot.figure()\n pyplot.clf()\n pyplot.hold(True)\n\n index = np.arange(nf) + 0.2\n width = 0.6\n\n pyplot.bar(index,mean_niters,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_niters,error_kw=dict(ecolor='black',elinewidth=3,capsize=5))\n\n pyplot.xticks(index+width/2, blabel)\n\n pyplot.xlabel('Inflation Factor', fontweight='bold',fontsize=12)\n pyplot.ylabel('No. of Iterations', fontweight='bold',fontsize=12)\n pyplot.title( 'No. of Iterations', fontweight='bold',fontsize=14)\n pyplot.hold(False)\n if save_figures:\n fig.savefig('%s_varDA_niters.pdf' % (model.Name),orientation=fOrient,format='pdf')\n #-----------------------------------------------------------\n\n #-----------------------------------------------------------\n fig = pyplot.figure()\n pyplot.clf()\n pyplot.hold(True)\n\n index = np.arange(nf) + 0.2\n width = 0.6\n pyplot.bar(index,mean_evratio,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_evratio,error_kw=dict(ecolor='black',elinewidth=3,capsize=5))\n\n pyplot.xticks(index+width/2, blabel)\n\n pyplot.xlabel('Inflation Factor', fontweight='bold',fontsize=12)\n pyplot.ylabel('Error - Variance Ratio', fontweight='bold',fontsize=12)\n pyplot.title( 'Error - Variance Ratio', fontweight='bold',fontsize=14)\n pyplot.hold(False)\n if save_figures:\n fig.savefig('%s_varDA_evratio.pdf' % (model.Name),orientation=fOrient,format='pdf')\n #-----------------------------------------------------------\n\n\n if not save_figures: pyplot.show()\n print('... all done ...')\n sys.exit(0)\n###############################################################\n\n###############################################################\ndef get_Ndistinct_colors(num_colors):\n from colorsys import hls_to_rgb\n colors=[]\n for i in np.arange(0.0, 360.0, 360.0 / num_colors):\n hue = i/360.0\n lightness = (50 + np.random.rand() * 10)/100.0\n saturation = (90 + np.random.rand() * 10)/100.0\n colors.append(hls_to_rgb(hue, lightness, saturation))\n return colors\n###############################################################\n\n###############################################################\nif __name__ == \"__main__\":\n\tmain()\n###############################################################\n"
] |
[
[
"numpy.diag",
"matplotlib.pyplot.legend",
"numpy.squeeze",
"matplotlib.pyplot.hold",
"matplotlib.pyplot.plot",
"numpy.mean",
"matplotlib.pyplot.gca",
"numpy.arange",
"numpy.std",
"matplotlib.pyplot.text",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"numpy.random.rand",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.semilogy",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.