repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
hugoFranco21/draft-qb-backend
[ "b290f825a8cfcbafed29ec25ff7810d2f9d47932" ]
[ "algorithms/expected_rookies.py" ]
[ "import pandas as pd\nfrom sklearn import linear_model\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.preprocessing import MinMaxScaler\nimport matplotlib.pyplot as plt\n\nrenamed = {\n 'Heisman': 'Heisman',\n 'Pct': 'Completion Percentage',\n 'Y/A.1': 'Yards per Attempt',\n 'Rate.1': 'Efficiency Rating', \n 'Rate': 'QB Rating',\n 'Sk%': 'Sacked %'\n}\n\ncolumns = [\n 'Draft',\n 'Sacked %',\n 'Completion Percentage',\n 'Yards per Attempt',\n 'Efficiency Rating'\n]\n\ndf = pd.read_excel('../datasets/collegeToPros.xlsx', header=1, usecols=[0, 4, 6, 20, 28, 29, 30, 31])\ndf.rename(columns = renamed, inplace = True)\ndf['Sacked %'] = df['Sacked %']*100\nprint(df)\nx_plot = df[['Rk']]\n\ndf_y = df['QB Rating']\ndf_x = df[['Draft',\n 'Sacked %',\n 'Completion Percentage',\n 'Yards per Attempt',\n 'Efficiency Rating']]\n\nX = df_x\ny = df_y\nx = 0\nn = -1\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=531)\nmin_max_scaler = MinMaxScaler()\ndata_minmax = min_max_scaler.fit_transform(X_train)\n\nf = open(\"../output/script1.txt\", \"w\")\nf.write(\"Output of the script 1\\n\")\n\nregr = linear_model.LinearRegression()\n\nsample_weight = y_train.apply(lambda h: 3 if h < 90 else 2)\n\nregr.fit(data_minmax, y_train, sample_weight=sample_weight)\n\n# Make predictions using the testing set\ny_pred = regr.predict(min_max_scaler.transform(X_test))\n\ny_plot = regr.predict(min_max_scaler.transform(df_x.to_numpy()))\nplt.plot(x_plot.to_numpy(), df_y.to_numpy())\nplt.plot(x_plot.to_numpy(), y_plot)\nplt.savefig('../assets/comparison1.png')\n\nf.write('\\nscale ' + str(min_max_scaler.scale_))\nf.write('\\nmin ' + str(min_max_scaler.min_))\n# The coefficients\nf.write('\\nCoefficients: \\n' + str(regr.coef_))\nf.write('\\nIntercept: \\n' + str(regr.intercept_))\n# The mean squared error\nf.write('\\nMean squared error: %.2f\\n'\n % mean_squared_error(y_test, y_pred))\n# The coefficient of determination: 1 is perfect prediction\nf.write('\\nCoefficient of determination: %.2f\\n'\n % r2_score(y_test, y_pred))\n\nf.close()" ]
[ [ "pandas.read_excel", "sklearn.metrics.r2_score", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.savefig", "sklearn.metrics.mean_squared_error", "sklearn.linear_model.LinearRegression", "sklearn.preprocessing.MinMaxScaler" ] ]
evo3cx/arcface-tf2
[ "b5bcdba1ddd6aba879d58793fdc8e84c461c48ab" ]
[ "modules/evaluations.py" ]
[ "\"\"\"\nThis script was modified from https://github.com/ZhaoJ9014/face.evoLVe.PyTorch\n\"\"\"\nimport os\nimport cv2\nimport bcolz\nimport numpy as np\nimport tqdm\nfrom sklearn.model_selection import KFold\n\nfrom .utils import l2_norm\n\n\ndef get_val_pair(path, name):\n carray = bcolz.carray(rootdir=os.path.join(path, name), mode='r')\n issame = np.load('{}/{}_list.npy'.format(path, name))\n\n return carray, issame\n\n\ndef get_val_data(data_path):\n \"\"\"get validation data\"\"\"\n lfw, lfw_issame = get_val_pair(data_path, 'lfw_align_112/lfw')\n agedb_30, agedb_30_issame = get_val_pair(data_path,\n 'agedb_align_112/agedb_30')\n cfp_fp, cfp_fp_issame = get_val_pair(data_path, 'cfp_align_112/cfp_fp')\n\n return lfw, agedb_30, cfp_fp, lfw_issame, agedb_30_issame, cfp_fp_issame\n\n\ndef ccrop_batch(imgs):\n assert len(imgs.shape) == 4\n resized_imgs = np.array([cv2.resize(img, (128, 128)) for img in imgs])\n ccropped_imgs = resized_imgs[:, 8:-8, 8:-8, :]\n\n return ccropped_imgs\n\n\ndef hflip_batch(imgs):\n assert len(imgs.shape) == 4\n return imgs[:, :, ::-1, :]\n\n\ndef calculate_accuracy(threshold, dist, actual_issame):\n predict_issame = np.less(dist, threshold)\n tp = np.sum(np.logical_and(predict_issame, actual_issame))\n fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))\n tn = np.sum(np.logical_and(np.logical_not(predict_issame),\n np.logical_not(actual_issame)))\n fn = np.sum(np.logical_and(np.logical_not(predict_issame), actual_issame))\n\n tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn)\n fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn)\n acc = float(tp + tn) / dist.size\n return tpr, fpr, acc\n\n\ndef calculate_roc(thresholds, embeddings1, embeddings2, actual_issame,\n nrof_folds=10):\n assert (embeddings1.shape[0] == embeddings2.shape[0])\n assert (embeddings1.shape[1] == embeddings2.shape[1])\n nrof_pairs = min(len(actual_issame), embeddings1.shape[0])\n nrof_thresholds = len(thresholds)\n k_fold = KFold(n_splits=nrof_folds, shuffle=False)\n\n tprs = np.zeros((nrof_folds, nrof_thresholds))\n fprs = np.zeros((nrof_folds, nrof_thresholds))\n accuracy = np.zeros((nrof_folds))\n best_thresholds = np.zeros((nrof_folds))\n indices = np.arange(nrof_pairs)\n\n diff = np.subtract(embeddings1, embeddings2)\n dist = np.sum(np.square(diff), 1)\n\n for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):\n # Find the best threshold for the fold\n acc_train = np.zeros((nrof_thresholds))\n for threshold_idx, threshold in enumerate(thresholds):\n _, _, acc_train[threshold_idx] = calculate_accuracy(\n threshold, dist[train_set], actual_issame[train_set])\n best_threshold_index = np.argmax(acc_train)\n\n best_thresholds[fold_idx] = thresholds[best_threshold_index]\n for threshold_idx, threshold in enumerate(thresholds):\n tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], _ = \\\n calculate_accuracy(threshold,\n dist[test_set],\n actual_issame[test_set])\n _, _, accuracy[fold_idx] = calculate_accuracy(\n thresholds[best_threshold_index],\n dist[test_set],\n actual_issame[test_set])\n\n tpr = np.mean(tprs, 0)\n fpr = np.mean(fprs, 0)\n return tpr, fpr, accuracy, best_thresholds\n\n\ndef evaluate(embeddings, actual_issame, nrof_folds=10):\n # Calculate evaluation metrics\n thresholds = np.arange(0, 4, 0.01)\n embeddings1 = embeddings[0::2]\n embeddings2 = embeddings[1::2]\n tpr, fpr, accuracy, best_thresholds = calculate_roc(\n thresholds, embeddings1, embeddings2, np.asarray(actual_issame),\n nrof_folds=nrof_folds)\n\n return tpr, fpr, accuracy, best_thresholds\n\n\ndef perform_val(embedding_size, batch_size, model,\n carray, issame, nrof_folds=10, is_ccrop=False, is_flip=True):\n \"\"\"perform val\"\"\"\n embeddings = np.zeros([len(carray), embedding_size])\n\n for idx in tqdm.tqdm(range(0, len(carray), batch_size)):\n batch = carray[idx:idx + batch_size]\n batch = np.transpose(batch, [0, 2, 3, 1]) * 0.5 + 0.5\n batch = batch[:, :, :, ::-1] # convert BGR to RGB\n\n if is_ccrop:\n batch = ccrop_batch(batch)\n if is_flip:\n fliped = hflip_batch(batch)\n emb_batch = model(batch) + model(fliped)\n embeddings[idx:idx + batch_size] = l2_norm(emb_batch)\n else:\n emb_batch = model(batch)\n embeddings[idx:idx + batch_size] = l2_norm(emb_batch)\n\n tpr, fpr, accuracy, best_thresholds = evaluate(\n embeddings, issame, nrof_folds)\n\n return accuracy.mean(), best_thresholds.mean()\n" ]
[ [ "numpy.square", "numpy.logical_not", "numpy.asarray", "numpy.less", "numpy.arange", "numpy.subtract", "sklearn.model_selection.KFold", "numpy.argmax", "numpy.mean", "numpy.transpose", "numpy.logical_and", "numpy.zeros" ] ]
Umesh-01/NavigateMe
[ "8085baa2eed50b2318cf9c84bb9df841988bfdc0" ]
[ "test_utilities.py" ]
[ "import utilities\nimport pytest\n\n\nclass TestClass:\n test_input = \"The quick brown fox jumps over the lazy dog.\"\n clf = utilities.classify_model()\n\n def test_setup_nltk(self):\n result = utilities.setup_nltk()\n assert result\n\n @pytest.mark.skip(reason=\"No way of currently testing this\")\n def test_parse_sentence(self):\n triples, root = utilities.parse_sentence(self.test_input)\n triples = list(triples)\n assert ((\"jumps\", \"VBZ\"), \"nsubj\", (\"fox\", \"NN\")) in triples\n assert ((\"jumps\", \"VBZ\"), \"nmod\", (\"dog\", \"NN\")) in triples\n assert root == \"jumps\"\n\n def test_classify_model(self):\n from features import features_dict\n import hashlib\n import numpy as np\n\n keys = [\n \"id\",\n \"wordCount\",\n \"stemmedCount\",\n \"stemmedEndNN\",\n \"CD\",\n \"NN\",\n \"NNP\",\n \"NNPS\",\n \"NNS\",\n \"PRP\",\n \"VBG\",\n \"VBZ\",\n \"startTuple0\",\n \"endTuple0\",\n \"endTuple1\",\n \"endTuple2\",\n \"verbBeforeNoun\",\n \"qMark\",\n \"qVerbCombo\",\n \"qTripleScore\",\n \"sTripleScore\",\n \"class\",\n ]\n sentence_id = hashlib.md5(str(self.test_input).encode(\"utf-8\")).hexdigest()[:16]\n f = features_dict(sentence_id, self.test_input)\n features = [f[k] for k in keys][1:-1]\n features = np.array(features).reshape(1, -1)\n\n assert self.clf.predict(features)[0] == \"S\"\n\n def test_classify_sentence(self):\n result = utilities.classify_sentence(self.clf, self.test_input)\n assert result == \"S\"\n" ]
[ [ "numpy.array" ] ]
tinyclues/ipython
[ "a924f50c0f7b84127391f1c396326258c2b303e2" ]
[ "IPython/utils/newserialized.py" ]
[ "# encoding: utf-8\n# -*- test-case-name: IPython.kernel.test.test_newserialized -*-\n\n\"\"\"Refactored serialization classes and interfaces.\"\"\"\n\n__docformat__ = \"restructuredtext en\"\n\n# Tell nose to skip this module\n__test__ = {}\n\n#-------------------------------------------------------------------------------\n# Copyright (C) 2008 The IPython Development Team\n#\n# Distributed under the terms of the BSD License. The full license is in\n# the file COPYING, distributed as part of this software.\n#-------------------------------------------------------------------------------\n\n#-------------------------------------------------------------------------------\n# Imports\n#-------------------------------------------------------------------------------\n\nimport sys\nimport cPickle as pickle\n\ntry:\n import numpy\nexcept ImportError:\n numpy = None\n\nclass SerializationError(Exception):\n pass\n\nif sys.version_info[0] >= 3:\n buffer = memoryview\n py3k = True\nelse:\n py3k = False\n if sys.version_info[:2] <= (2,6):\n memoryview = buffer\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\nclass ISerialized:\n \n def getData():\n \"\"\"\"\"\"\n\n def getDataSize(units=10.0**6):\n \"\"\"\"\"\"\n\n def getTypeDescriptor():\n \"\"\"\"\"\"\n\n def getMetadata():\n \"\"\"\"\"\"\n \n \nclass IUnSerialized:\n \n def getObject():\n \"\"\"\"\"\"\n \nclass Serialized(object):\n \n # implements(ISerialized)\n \n def __init__(self, data, typeDescriptor, metadata={}):\n self.data = data\n self.typeDescriptor = typeDescriptor\n self.metadata = metadata\n \n def getData(self):\n return self.data\n \n def getDataSize(self, units=10.0**6):\n return len(self.data)/units\n \n def getTypeDescriptor(self):\n return self.typeDescriptor\n \n def getMetadata(self):\n return self.metadata\n\n \nclass UnSerialized(object):\n \n # implements(IUnSerialized)\n \n def __init__(self, obj):\n self.obj = obj\n \n def getObject(self):\n return self.obj\n\n \nclass SerializeIt(object):\n \n # implements(ISerialized)\n \n def __init__(self, unSerialized):\n self.data = None\n self.obj = unSerialized.getObject()\n if numpy is not None and isinstance(self.obj, numpy.ndarray):\n if len(self.obj.shape) == 0: # length 0 arrays are just pickled\n self.typeDescriptor = 'pickle'\n self.metadata = {}\n else:\n self.obj = numpy.ascontiguousarray(self.obj, dtype=None)\n self.typeDescriptor = 'ndarray'\n self.metadata = {'shape':self.obj.shape,\n 'dtype':self.obj.dtype.str}\n elif isinstance(self.obj, bytes):\n self.typeDescriptor = 'bytes'\n self.metadata = {}\n elif isinstance(self.obj, buffer):\n self.typeDescriptor = 'buffer'\n self.metadata = {}\n else:\n self.typeDescriptor = 'pickle'\n self.metadata = {}\n self._generateData()\n \n def _generateData(self):\n if self.typeDescriptor == 'ndarray':\n self.data = buffer(self.obj)\n elif self.typeDescriptor in ('bytes', 'buffer'):\n self.data = self.obj\n elif self.typeDescriptor == 'pickle':\n self.data = pickle.dumps(self.obj, -1)\n else:\n raise SerializationError(\"Really wierd serialization error.\")\n del self.obj\n \n def getData(self):\n return self.data\n \n def getDataSize(self, units=10.0**6):\n return 1.0*len(self.data)/units\n \n def getTypeDescriptor(self):\n return self.typeDescriptor\n \n def getMetadata(self):\n return self.metadata\n\n\nclass UnSerializeIt(UnSerialized):\n \n # implements(IUnSerialized)\n \n def __init__(self, serialized):\n self.serialized = serialized\n \n def getObject(self):\n typeDescriptor = self.serialized.getTypeDescriptor()\n if numpy is not None and typeDescriptor == 'ndarray':\n buf = self.serialized.getData()\n if isinstance(buf, (bytes, buffer, memoryview)):\n result = numpy.frombuffer(buf, dtype = self.serialized.metadata['dtype'])\n else:\n raise TypeError(\"Expected bytes or buffer/memoryview, but got %r\"%type(buf))\n result.shape = self.serialized.metadata['shape']\n elif typeDescriptor == 'pickle':\n result = pickle.loads(self.serialized.getData())\n elif typeDescriptor in ('bytes', 'buffer'):\n result = self.serialized.getData()\n else:\n raise SerializationError(\"Really wierd serialization error.\")\n return result\n\ndef serialize(obj):\n return SerializeIt(UnSerialized(obj))\n \ndef unserialize(serialized):\n return UnSerializeIt(serialized).getObject()\n" ]
[ [ "numpy.ascontiguousarray", "numpy.frombuffer" ] ]
XJTUexperiment/tensorlayer
[ "690766535a591367ad86907835b39730f4aa1dea" ]
[ "tensorlayer/layers/recurrent.py" ]
[ "#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.util.tf_inspect import getfullargspec\nfrom tensorflow.contrib.rnn import stack_bidirectional_dynamic_rnn\nfrom tensorflow.python.ops.rnn_cell import LSTMStateTuple\n\nfrom tensorlayer.layers.core import Layer\nfrom tensorlayer.layers.core import LayersConfig\nfrom tensorlayer.layers.core import TF_GRAPHKEYS_VARIABLES\n\nfrom tensorlayer import logging\n\nfrom tensorlayer.decorators import deprecated_alias\n\n__all__ = [\n 'RNNLayer',\n 'BiRNNLayer',\n 'ConvRNNCell',\n 'BasicConvLSTMCell',\n 'ConvLSTMLayer',\n 'advanced_indexing_op',\n 'retrieve_seq_length_op',\n 'retrieve_seq_length_op2',\n 'retrieve_seq_length_op3',\n 'target_mask_op',\n 'DynamicRNNLayer',\n 'BiDynamicRNNLayer',\n 'Seq2Seq',\n]\n\n\nclass RNNLayer(Layer):\n \"\"\"\n The :class:`RNNLayer` class is a fixed length recurrent layer for implementing vanilla RNN,\n LSTM, GRU and etc.\n\n Parameters\n ----------\n prev_layer : :class:`Layer`\n Previous layer.\n cell_fn : TensorFlow cell function\n A TensorFlow core RNN cell\n - See `RNN Cells in TensorFlow <https://www.tensorflow.org/api_docs/python/>`__\n - Note TF1.0+ and TF1.0- are different\n cell_init_args : dictionary\n The arguments for the cell function.\n n_hidden : int\n The number of hidden units in the layer.\n initializer : initializer\n The initializer for initializing the model parameters.\n n_steps : int\n The fixed sequence length.\n initial_state : None or RNN State\n If None, `initial_state` is zero state.\n return_last : boolean\n Whether return last output or all outputs in each step.\n - If True, return the last output, \"Sequence input and single output\"\n - If False, return all outputs, \"Synced sequence input and output\"\n - In other word, if you want to stack more RNNs on this layer, set to False.\n return_seq_2d : boolean\n Only consider this argument when `return_last` is `False`\n - If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.\n - If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.\n name : str\n A unique layer name.\n\n Attributes\n ----------\n outputs : Tensor\n The output of this layer.\n\n final_state : Tensor or StateTuple\n The finial state of this layer.\n - When `state_is_tuple` is `False`, it is the final hidden and cell states, `states.get_shape() = [?, 2 * n_hidden]`.\n - When `state_is_tuple` is `True`, it stores two elements: `(c, h)`.\n - In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.\n\n initial_state : Tensor or StateTuple\n The initial state of this layer.\n - In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.\n\n batch_size : int or Tensor\n It is an integer, if it is able to compute the `batch_size`; otherwise, tensor for dynamic batch size.\n\n Examples\n --------\n - For synced sequence input and output, see `PTB example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_ptb_lstm_state_is_tuple.py>`__\n\n - For encoding see below.\n\n >>> import tensorflow as tf\n >>> import tensorlayer as tl\n >>> batch_size = 32\n >>> num_steps = 5\n >>> vocab_size = 3000\n >>> hidden_size = 256\n >>> keep_prob = 0.8\n >>> is_train = True\n >>> input_data = tf.placeholder(tf.int32, [batch_size, num_steps])\n >>> net = tl.layers.EmbeddingInputlayer(inputs=input_data, vocabulary_size=vocab_size,\n ... embedding_size=hidden_size, name='embed')\n >>> net = tl.layers.DropoutLayer(net, keep=keep_prob, is_fix=True, is_train=is_train, name='drop1')\n >>> net = tl.layers.RNNLayer(net, cell_fn=tf.contrib.rnn.BasicLSTMCell,\n ... n_hidden=hidden_size, n_steps=num_steps, return_last=False, name='lstm1')\n >>> net = tl.layers.DropoutLayer(net, keep=keep_prob, is_fix=True, is_train=is_train, name='drop2')\n >>> net = tl.layers.RNNLayer(net, cell_fn=tf.contrib.rnn.BasicLSTMCell,\n ... n_hidden=hidden_size, n_steps=num_steps, return_last=True, name='lstm2')\n >>> net = tl.layers.DropoutLayer(net, keep=keep_prob, is_fix=True, is_train=is_train, name='drop3')\n >>> net = tl.layers.DenseLayer(net, n_units=vocab_size, name='output')\n\n - For CNN+LSTM\n\n >>> image_size = 100\n >>> batch_size = 10\n >>> num_steps = 5\n >>> x = tf.placeholder(tf.float32, shape=[batch_size, image_size, image_size, 1])\n >>> net = tl.layers.InputLayer(x, name='in')\n >>> net = tl.layers.Conv2d(net, 32, (5, 5), (2, 2), tf.nn.relu, name='cnn1')\n >>> net = tl.layers.MaxPool2d(net, (2, 2), (2, 2), name='pool1')\n >>> net = tl.layers.Conv2d(net, 10, (5, 5), (2, 2), tf.nn.relu, name='cnn2')\n >>> net = tl.layers.MaxPool2d(net, (2, 2), (2, 2), name='pool2')\n >>> net = tl.layers.FlattenLayer(net, name='flatten')\n >>> net = tl.layers.ReshapeLayer(net, shape=[-1, num_steps, int(net.outputs._shape[-1])])\n >>> rnn = tl.layers.RNNLayer(net, cell_fn=tf.contrib.rnn.BasicLSTMCell, n_hidden=200, n_steps=num_steps, return_last=False, return_seq_2d=True, name='rnn')\n >>> net = tl.layers.DenseLayer(rnn, 3, name='out')\n\n Notes\n -----\n Input dimension should be rank 3 : [batch_size, n_steps, n_features], if no, please see :class:`ReshapeLayer`.\n\n References\n ----------\n - `Neural Network RNN Cells in TensorFlow <https://www.tensorflow.org/api_docs/python/rnn_cell/>`__\n - `tensorflow/python/ops/rnn.py <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn.py>`__\n - `tensorflow/python/ops/rnn_cell.py <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell.py>`__\n - see TensorFlow tutorial ``ptb_word_lm.py``, TensorLayer tutorials ``tutorial_ptb_lstm*.py`` and ``tutorial_generate_text.py``\n\n \"\"\"\n\n @deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release\n def __init__(\n self,\n prev_layer,\n cell_fn,\n cell_init_args=None,\n n_hidden=100,\n initializer=tf.random_uniform_initializer(-0.1, 0.1),\n n_steps=5,\n initial_state=None,\n return_last=False,\n return_seq_2d=False,\n name='rnn',\n ):\n\n if cell_fn is None:\n raise Exception(\"Please put in cell_fn\")\n\n super(RNNLayer, self).__init__(prev_layer=prev_layer, cell_init_args=cell_init_args, name=name)\n\n if 'GRU' in cell_fn.__name__:\n try:\n self.cell_init_args.pop('state_is_tuple')\n except Exception:\n logging.warning('pop state_is_tuple fails.')\n\n logging.info(\n \"RNNLayer %s: n_hidden: %d n_steps: %d in_dim: %d in_shape: %s cell_fn: %s \" %\n (self.name, n_hidden, n_steps, self.inputs.get_shape().ndims, self.inputs.get_shape(), cell_fn.__name__)\n )\n\n # You can get the dimension by .get_shape() or ._shape, and check the\n # dimension by .with_rank() as follow.\n # self.inputs.get_shape().with_rank(2)\n # self.inputs.get_shape().with_rank(3)\n\n # Input dimension should be rank 3 [batch_size, n_steps(max), n_features]\n try:\n self.inputs.get_shape().with_rank(3)\n except Exception:\n raise Exception(\"RNN : Input dimension should be rank 3 : [batch_size, n_steps, n_features]\")\n\n # is_reshape : boolean (deprecate)\n # Reshape the inputs to 3 dimension tensor.\\n\n # If input is[batch_size, n_steps, n_features], we do not need to reshape it.\\n\n # If input is [batch_size * n_steps, n_features], we need to reshape it.\n # if is_reshape:\n # self.inputs = tf.reshape(self.inputs, shape=[-1, n_steps, int(self.inputs._shape[-1])])\n\n fixed_batch_size = self.inputs.get_shape().with_rank_at_least(1)[0]\n\n if fixed_batch_size.value:\n batch_size = fixed_batch_size.value\n logging.info(\" RNN batch_size (concurrent processes): %d\" % batch_size)\n\n else:\n batch_size = array_ops.shape(self.inputs)[0]\n logging.info(\" non specified batch_size, uses a tensor instead.\")\n\n self.batch_size = batch_size\n\n # Simplified version of tensorflow.models.rnn.rnn.py's rnn().\n # This builds an unrolled LSTM for tutorial purposes only.\n # In general, use the rnn() or state_saving_rnn() from rnn.py.\n #\n # The alternative version of the code below is:\n #\n # from tensorflow.models.rnn import rnn\n # inputs = [tf.squeeze(input_, [1])\n # for input_ in tf.split(1, num_steps, inputs)]\n # outputs, state = rnn.rnn(cell, inputs, initial_state=self._initial_state)\n outputs = []\n\n if 'reuse' in getfullargspec(cell_fn.__init__).args:\n self.cell = cell = cell_fn(num_units=n_hidden, reuse=tf.get_variable_scope().reuse, **self.cell_init_args)\n else:\n self.cell = cell = cell_fn(num_units=n_hidden, **self.cell_init_args)\n\n if initial_state is None:\n self.initial_state = cell.zero_state(batch_size, dtype=LayersConfig.tf_dtype) #dtype=tf.float32) # 1.2.3\n\n state = self.initial_state\n\n with tf.variable_scope(name, initializer=initializer) as vs:\n for time_step in range(n_steps):\n if time_step > 0: tf.get_variable_scope().reuse_variables()\n (cell_output, state) = cell(self.inputs[:, time_step, :], state)\n outputs.append(cell_output)\n\n # Retrieve just the RNN variables.\n # rnn_variables = [v for v in tf.all_variables() if v.name.startswith(vs.name)]\n rnn_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n logging.info(\" n_params : %d\" % (len(rnn_variables)))\n\n if return_last:\n # 2D Tensor [batch_size, n_hidden]\n self.outputs = outputs[-1]\n else:\n if return_seq_2d:\n # PTB tutorial: stack dense layer after that, or compute the cost from the output\n # 2D Tensor [n_example, n_hidden]\n\n self.outputs = tf.reshape(tf.concat(outputs, 1), [-1, n_hidden])\n\n else:\n # <akara>: stack more RNN layer after that\n # 3D Tensor [n_example/n_steps, n_steps, n_hidden]\n\n self.outputs = tf.reshape(tf.concat(outputs, 1), [-1, n_steps, n_hidden])\n\n self.final_state = state\n\n self._add_layers(self.outputs)\n self._add_params(rnn_variables)\n\n\nclass BiRNNLayer(Layer):\n \"\"\"\n The :class:`BiRNNLayer` class is a fixed length Bidirectional recurrent layer.\n\n Parameters\n ----------\n prev_layer : :class:`Layer`\n Previous layer.\n cell_fn : TensorFlow cell function\n A TensorFlow core RNN cell.\n - See `RNN Cells in TensorFlow <https://www.tensorflow.org/api_docs/python/>`__.\n - Note TF1.0+ and TF1.0- are different.\n cell_init_args : dictionary or None\n The arguments for the cell function.\n n_hidden : int\n The number of hidden units in the layer.\n initializer : initializer\n The initializer for initializing the model parameters.\n n_steps : int\n The fixed sequence length.\n fw_initial_state : None or forward RNN State\n If None, `initial_state` is zero state.\n bw_initial_state : None or backward RNN State\n If None, `initial_state` is zero state.\n dropout : tuple of float or int\n The input and output keep probability (input_keep_prob, output_keep_prob).\n If one int, input and output keep probability are the same.\n n_layer : int\n The number of RNN layers, default is 1.\n return_last : boolean\n Whether return last output or all outputs in each step.\n - If True, return the last output, \"Sequence input and single output\"\n - If False, return all outputs, \"Synced sequence input and output\"\n - In other word, if you want to stack more RNNs on this layer, set to False.\n return_seq_2d : boolean\n Only consider this argument when `return_last` is `False`\n - If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.\n - If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.\n name : str\n A unique layer name.\n\n Attributes\n ----------\n outputs : tensor\n The output of this layer.\n fw(bw)_final_state : tensor or StateTuple\n The finial state of this layer.\n - When `state_is_tuple` is `False`, it is the final hidden and cell states, `states.get_shape() = [?, 2 * n_hidden]`.\n - When `state_is_tuple` is `True`, it stores two elements: `(c, h)`.\n - In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.\n fw(bw)_initial_state : tensor or StateTuple\n The initial state of this layer.\n - In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.\n batch_size : int or tensor\n It is an integer, if it is able to compute the `batch_size`; otherwise, tensor for dynamic batch size.\n\n Notes\n -----\n Input dimension should be rank 3 : [batch_size, n_steps, n_features]. If not, please see :class:`ReshapeLayer`.\n For predicting, the sequence length has to be the same with the sequence length of training, while, for normal\n RNN, we can use sequence length of 1 for predicting.\n\n References\n ----------\n `Source <https://github.com/akaraspt/deepsleep/blob/master/deepsleep/model.py>`__\n\n \"\"\"\n\n @deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release\n def __init__(\n self,\n prev_layer,\n cell_fn,\n cell_init_args=None,\n n_hidden=100,\n initializer=tf.random_uniform_initializer(-0.1, 0.1),\n n_steps=5,\n fw_initial_state=None,\n bw_initial_state=None,\n dropout=None,\n n_layer=1,\n return_last=False,\n return_seq_2d=False,\n name='birnn',\n ):\n super(BiRNNLayer, self).__init__(prev_layer=prev_layer, cell_init_args=cell_init_args, name=name)\n\n if self.cell_init_args:\n self.cell_init_args['state_is_tuple'] = True # 'use_peepholes': True,\n\n if 'GRU' in cell_fn.__name__:\n try:\n self.cell_init_args.pop('state_is_tuple')\n except Exception:\n logging.warning(\"pop state_is_tuple fails.\")\n\n if cell_fn is None:\n raise Exception(\"Please put in cell_fn\")\n\n logging.info(\n \"BiRNNLayer %s: n_hidden: %d n_steps: %d in_dim: %d in_shape: %s cell_fn: %s dropout: %s n_layer: %d \" % (\n self.name, n_hidden, n_steps, self.inputs.get_shape().ndims, self.inputs.get_shape(), cell_fn.__name__,\n dropout, n_layer\n )\n )\n\n fixed_batch_size = self.inputs.get_shape().with_rank_at_least(1)[0]\n\n if fixed_batch_size.value:\n self.batch_size = fixed_batch_size.value\n logging.info(\" RNN batch_size (concurrent processes): %d\" % self.batch_size)\n\n else:\n self.batch_size = array_ops.shape(self.inputs)[0]\n logging.info(\" non specified batch_size, uses a tensor instead.\")\n\n # Input dimension should be rank 3 [batch_size, n_steps(max), n_features]\n try:\n self.inputs.get_shape().with_rank(3)\n except Exception:\n raise Exception(\"RNN : Input dimension should be rank 3 : [batch_size, n_steps, n_features]\")\n\n with tf.variable_scope(name, initializer=initializer) as vs:\n rnn_creator = lambda: cell_fn(num_units=n_hidden, **self.cell_init_args)\n # Apply dropout\n if dropout:\n\n if isinstance(dropout, (tuple, list)): # type(dropout) in [tuple, list]:\n in_keep_prob = dropout[0]\n out_keep_prob = dropout[1]\n\n elif isinstance(dropout, float):\n in_keep_prob, out_keep_prob = dropout, dropout\n\n else:\n raise Exception(\"Invalid dropout type (must be a 2-D tuple of \" \"float)\")\n\n DropoutWrapper_fn = tf.contrib.rnn.DropoutWrapper\n\n cell_creator = lambda is_last=True: DropoutWrapper_fn(\n rnn_creator(), input_keep_prob=in_keep_prob, output_keep_prob=out_keep_prob if is_last else 1.0\n )\n\n else:\n cell_creator = rnn_creator\n\n self.fw_cell = cell_creator()\n self.bw_cell = cell_creator()\n\n # Apply multiple layers\n if n_layer > 1:\n MultiRNNCell_fn = tf.contrib.rnn.MultiRNNCell\n\n if dropout:\n try:\n self.fw_cell = MultiRNNCell_fn(\n [cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)], state_is_tuple=True\n )\n self.bw_cell = MultiRNNCell_fn(\n [cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)], state_is_tuple=True\n )\n except Exception:\n self.fw_cell = MultiRNNCell_fn([cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)])\n self.bw_cell = MultiRNNCell_fn([cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)])\n else:\n try:\n self.fw_cell = MultiRNNCell_fn([cell_creator() for _ in range(n_layer)], state_is_tuple=True)\n self.bw_cell = MultiRNNCell_fn([cell_creator() for _ in range(n_layer)], state_is_tuple=True)\n except Exception:\n self.fw_cell = MultiRNNCell_fn([cell_creator() for _ in range(n_layer)])\n self.bw_cell = MultiRNNCell_fn([cell_creator() for _ in range(n_layer)])\n\n # Initial state of RNN\n if fw_initial_state is None:\n self.fw_initial_state = self.fw_cell.zero_state(\n self.batch_size, dtype=LayersConfig.tf_dtype\n ) # dtype=tf.float32)\n else:\n self.fw_initial_state = fw_initial_state\n if bw_initial_state is None:\n self.bw_initial_state = self.bw_cell.zero_state(\n self.batch_size, dtype=LayersConfig.tf_dtype\n ) # dtype=tf.float32)\n else:\n self.bw_initial_state = bw_initial_state\n # exit()\n # Feedforward to MultiRNNCell\n list_rnn_inputs = tf.unstack(self.inputs, axis=1)\n\n bidirectional_rnn_fn = tf.contrib.rnn.static_bidirectional_rnn\n\n outputs, fw_state, bw_state = bidirectional_rnn_fn( # outputs, fw_state, bw_state = tf.contrib.rnn.static_bidirectional_rnn(\n cell_fw=self.fw_cell,\n cell_bw=self.bw_cell,\n inputs=list_rnn_inputs,\n initial_state_fw=self.fw_initial_state,\n initial_state_bw=self.bw_initial_state\n )\n\n if return_last:\n raise Exception(\"Do not support return_last at the moment.\")\n # self.outputs = outputs[-1]\n else:\n self.outputs = outputs\n if return_seq_2d:\n # 2D Tensor [n_example, n_hidden]\n self.outputs = tf.reshape(tf.concat(outputs, 1), [-1, n_hidden * 2])\n\n else:\n # <akara>: stack more RNN layer after that\n # 3D Tensor [n_example/n_steps, n_steps, n_hidden]\n\n self.outputs = tf.reshape(tf.concat(outputs, 1), [-1, n_steps, n_hidden * 2])\n\n self.fw_final_state = fw_state\n self.bw_final_state = bw_state\n\n # Retrieve just the RNN variables.\n rnn_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n logging.info(\" n_params : %d\" % (len(rnn_variables)))\n\n self._add_layers(self.outputs)\n self._add_params(rnn_variables)\n\n\nclass ConvRNNCell(object):\n \"\"\"Abstract object representing an Convolutional RNN Cell.\"\"\"\n\n def __call__(self, inputs, state, scope=None):\n \"\"\"Run this RNN cell on inputs, starting from the given state.\"\"\"\n raise NotImplementedError(\"Abstract method\")\n\n @property\n def state_size(self):\n \"\"\"size(s) of state(s) used by this cell.\"\"\"\n raise NotImplementedError(\"Abstract method\")\n\n @property\n def output_size(self):\n \"\"\"Integer or TensorShape: size of outputs produced by this cell.\"\"\"\n raise NotImplementedError(\"Abstract method\")\n\n def zero_state(self, batch_size, dtype=LayersConfig.tf_dtype):\n \"\"\"Return zero-filled state tensor(s).\n Args:\n batch_size: int, float, or unit Tensor representing the batch size.\n Returns:\n tensor of shape '[batch_size x shape[0] x shape[1] x num_features]\n filled with zeros\n\n \"\"\"\n shape = self.shape\n num_features = self.num_features\n # TODO : TypeError: 'NoneType' object is not subscriptable\n zeros = tf.zeros([batch_size, shape[0], shape[1], num_features * 2], dtype=dtype)\n return zeros\n\n\nclass BasicConvLSTMCell(ConvRNNCell):\n \"\"\"Basic Conv LSTM recurrent network cell.\n\n Parameters\n -----------\n shape : tuple of int\n The height and width of the cell.\n filter_size : tuple of int\n The height and width of the filter\n num_features : int\n The hidden size of the cell\n forget_bias : float\n The bias added to forget gates (see above).\n input_size : int\n Deprecated and unused.\n state_is_tuple : boolen\n If True, accepted and returned states are 2-tuples of the `c_state` and `m_state`.\n If False, they are concatenated along the column axis. The latter behavior will soon be deprecated.\n act : activation function\n The activation function of this layer, tanh as default.\n\n \"\"\"\n\n def __init__(\n self, shape, filter_size, num_features, forget_bias=1.0, input_size=None, state_is_tuple=False,\n act=tf.nn.tanh\n ):\n \"\"\"Initialize the basic Conv LSTM cell.\"\"\"\n # if not state_is_tuple:\n # logging.warn(\"%s: Using a concatenated state is slower and will soon be \"\n # \"deprecated. Use state_is_tuple=True.\", self)\n if input_size is not None:\n logging.warn(\"%s: The input_size parameter is deprecated.\", self)\n self.shape = shape\n self.filter_size = filter_size\n self.num_features = num_features\n self._forget_bias = forget_bias\n self._state_is_tuple = state_is_tuple\n self._activation = act\n\n @property\n def state_size(self):\n \"\"\"State size of the LSTMStateTuple.\"\"\"\n return (LSTMStateTuple(self._num_units, self._num_units) if self._state_is_tuple else 2 * self._num_units)\n\n @property\n def output_size(self):\n \"\"\"Number of units in outputs.\"\"\"\n return self._num_units\n\n def __call__(self, inputs, state, scope=None):\n \"\"\"Long short-term memory cell (LSTM).\"\"\"\n with tf.variable_scope(scope or type(self).__name__): # \"BasicLSTMCell\"\n # Parameters of gates are concatenated into one multiply for efficiency.\n if self._state_is_tuple:\n c, h = state\n else:\n # print state\n # c, h = tf.split(3, 2, state)\n c, h = tf.split(state, 2, 3)\n concat = _conv_linear([inputs, h], self.filter_size, self.num_features * 4, True)\n\n # i = input_gate, j = new_input, f = forget_gate, o = output_gate\n # i, j, f, o = tf.split(3, 4, concat)\n i, j, f, o = tf.split(concat, 4, 3)\n\n new_c = (c * tf.nn.sigmoid(f + self._forget_bias) + tf.nn.sigmoid(i) * self._activation(j))\n new_h = self._activation(new_c) * tf.nn.sigmoid(o)\n\n if self._state_is_tuple:\n new_state = LSTMStateTuple(new_c, new_h)\n else:\n new_state = tf.concat([new_c, new_h], 3)\n return new_h, new_state\n\n\ndef _conv_linear(args, filter_size, num_features, bias, bias_start=0.0, scope=None):\n \"\"\"convolution:\n\n Parameters\n ----------\n args : tensor\n 4D Tensor or a list of 4D, batch x n, Tensors.\n filter_size : tuple of int\n Filter height and width.\n num_features : int\n Nnumber of features.\n bias_start : float\n Starting value to initialize the bias; 0 by default.\n scope : VariableScope\n For the created subgraph; defaults to \"Linear\".\n\n Returns\n --------\n - A 4D Tensor with shape [batch h w num_features]\n\n Raises\n -------\n - ValueError : if some of the arguments has unspecified or wrong shape.\n\n \"\"\"\n # Calculate the total size of arguments on dimension 1.\n total_arg_size_depth = 0\n shapes = [a.get_shape().as_list() for a in args]\n for shape in shapes:\n if len(shape) != 4:\n raise ValueError(\"Linear is expecting 4D arguments: %s\" % str(shapes))\n if not shape[3]:\n raise ValueError(\"Linear expects shape[4] of arguments: %s\" % str(shapes))\n else:\n total_arg_size_depth += shape[3]\n\n dtype = [a.dtype for a in args][0]\n\n # Now the computation.\n with tf.variable_scope(scope or \"Conv\"):\n matrix = tf.get_variable(\n \"Matrix\", [filter_size[0], filter_size[1], total_arg_size_depth, num_features], dtype=dtype\n )\n if len(args) == 1:\n res = tf.nn.conv2d(args[0], matrix, strides=[1, 1, 1, 1], padding='SAME')\n else:\n res = tf.nn.conv2d(tf.concat(args, 3), matrix, strides=[1, 1, 1, 1], padding='SAME')\n if not bias:\n return res\n bias_term = tf.get_variable(\n \"Bias\", [num_features], dtype=dtype, initializer=tf.constant_initializer(bias_start, dtype=dtype)\n )\n return res + bias_term\n\n\nclass ConvLSTMLayer(Layer):\n \"\"\"A fixed length Convolutional LSTM layer.\n\n See this `paper <https://arxiv.org/abs/1506.04214>`__ .\n\n Parameters\n ----------\n prev_layer : :class:`Layer`\n Previous layer\n cell_shape : tuple of int\n The shape of each cell width * height\n filter_size : tuple of int\n The size of filter width * height\n cell_fn : a convolutional RNN cell\n Cell function like :class:`BasicConvLSTMCell`\n feature_map : int\n The number of feature map in the layer.\n initializer : initializer\n The initializer for initializing the parameters.\n n_steps : int\n The sequence length.\n initial_state : None or ConvLSTM State\n If None, `initial_state` is zero state.\n return_last : boolean\n Whether return last output or all outputs in each step.\n - If True, return the last output, \"Sequence input and single output\".\n - If False, return all outputs, \"Synced sequence input and output\".\n - In other word, if you want to stack more RNNs on this layer, set to False.\n return_seq_2d : boolean\n Only consider this argument when `return_last` is `False`\n - If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.\n - If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.\n name : str\n A unique layer name.\n\n Attributes\n ----------\n outputs : tensor\n The output of this RNN. return_last = False, outputs = all cell_output, which is the hidden state.\n cell_output.get_shape() = (?, h, w, c])\n\n final_state : tensor or StateTuple\n The finial state of this layer.\n - When state_is_tuple = False, it is the final hidden and cell states,\n - When state_is_tuple = True, You can get the final state after each iteration during training, then feed it to the initial state of next iteration.\n\n initial_state : tensor or StateTuple\n It is the initial state of this ConvLSTM layer, you can use it to initialize\n your state at the beginning of each epoch or iteration according to your\n training procedure.\n\n batch_size : int or tensor\n Is int, if able to compute the batch_size, otherwise, tensor for ``?``.\n\n \"\"\"\n\n @deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release\n def __init__(\n self,\n prev_layer,\n cell_shape=None,\n feature_map=1,\n filter_size=(3, 3),\n cell_fn=BasicConvLSTMCell,\n initializer=tf.random_uniform_initializer(-0.1, 0.1),\n n_steps=5,\n initial_state=None,\n return_last=False,\n return_seq_2d=False,\n name='convlstm',\n ):\n super(ConvLSTMLayer, self).__init__(prev_layer=prev_layer, name=name)\n\n logging.info(\n \"ConvLSTMLayer %s: feature_map: %d, n_steps: %d, \"\n \"in_dim: %d %s, cell_fn: %s \" %\n (self.name, feature_map, n_steps, self.inputs.get_shape().ndims, self.inputs.get_shape(), cell_fn.__name__)\n )\n # You can get the dimension by .get_shape() or ._shape, and check the\n # dimension by .with_rank() as follow.\n # self.inputs.get_shape().with_rank(2)\n # self.inputs.get_shape().with_rank(3)\n\n # Input dimension should be rank 5 [batch_size, n_steps(max), h, w, c]\n try:\n self.inputs.get_shape().with_rank(5)\n except Exception:\n raise Exception(\n \"RNN : Input dimension should be rank 5 : [batch_size, n_steps, input_x, \"\n \"input_y, feature_map]\"\n )\n\n fixed_batch_size = self.inputs.get_shape().with_rank_at_least(1)[0]\n\n if fixed_batch_size.value:\n batch_size = fixed_batch_size.value\n logging.info(\" RNN batch_size (concurrent processes): %d\" % batch_size)\n\n else:\n batch_size = array_ops.shape(self.inputs)[0]\n logging.info(\" non specified batch_size, uses a tensor instead.\")\n self.batch_size = batch_size\n outputs = []\n self.cell = cell = cell_fn(shape=cell_shape, filter_size=filter_size, num_features=feature_map)\n\n if initial_state is None:\n self.initial_state = cell.zero_state(batch_size, dtype=LayersConfig.tf_dtype)\n else:\n self.initial_state = initial_state\n\n state = self.initial_state\n\n # with tf.variable_scope(\"model\", reuse=None, initializer=initializer):\n with tf.variable_scope(name, initializer=initializer) as vs:\n for time_step in range(n_steps):\n if time_step > 0: tf.get_variable_scope().reuse_variables()\n (cell_output, state) = cell(self.inputs[:, time_step, :, :, :], state)\n outputs.append(cell_output)\n\n # Retrieve just the RNN variables.\n # rnn_variables = [v for v in tf.all_variables() if v.name.startswith(vs.name)]\n rnn_variables = tf.get_collection(tf.GraphKeys.VARIABLES, scope=vs.name)\n\n logging.info(\" n_params : %d\" % (len(rnn_variables)))\n\n if return_last:\n # 2D Tensor [batch_size, n_hidden]\n self.outputs = outputs[-1]\n else:\n if return_seq_2d:\n # PTB tutorial: stack dense layer after that, or compute the cost from the output\n # 4D Tensor [n_example, h, w, c]\n self.outputs = tf.reshape(tf.concat(outputs, 1), [-1, cell_shape[0] * cell_shape[1] * feature_map])\n else:\n # <akara>: stack more RNN layer after that\n # 5D Tensor [n_example/n_steps, n_steps, h, w, c]\n self.outputs = tf.reshape(\n tf.concat(outputs, 1), [-1, n_steps, cell_shape[0], cell_shape[1], feature_map]\n )\n\n self.final_state = state\n\n self._add_layers(self.outputs)\n self._add_params(rnn_variables)\n\n\n# Advanced Ops for Dynamic RNN\ndef advanced_indexing_op(inputs, index):\n \"\"\"Advanced Indexing for Sequences, returns the outputs by given sequence lengths.\n When return the last output :class:`DynamicRNNLayer` uses it to get the last outputs with the sequence lengths.\n\n Parameters\n -----------\n inputs : tensor for data\n With shape of [batch_size, n_step(max), n_features]\n index : tensor for indexing\n Sequence length in Dynamic RNN. [batch_size]\n\n Examples\n ---------\n >>> import numpy as np\n >>> import tensorflow as tf\n >>> import tensorlayer as tl\n >>> batch_size, max_length, n_features = 3, 5, 2\n >>> z = np.random.uniform(low=-1, high=1, size=[batch_size, max_length, n_features]).astype(np.float32)\n >>> b_z = tf.constant(z)\n >>> sl = tf.placeholder(dtype=tf.int32, shape=[batch_size])\n >>> o = advanced_indexing_op(b_z, sl)\n >>>\n >>> sess = tf.InteractiveSession()\n >>> tl.layers.initialize_global_variables(sess)\n >>>\n >>> order = np.asarray([1,1,2])\n >>> print(\"real\",z[0][order[0]-1], z[1][order[1]-1], z[2][order[2]-1])\n >>> y = sess.run([o], feed_dict={sl:order})\n >>> print(\"given\",order)\n >>> print(\"out\", y)\n real [-0.93021595 0.53820813] [-0.92548317 -0.77135968] [ 0.89952248 0.19149846]\n given [1 1 2]\n out [array([[-0.93021595, 0.53820813],\n [-0.92548317, -0.77135968],\n [ 0.89952248, 0.19149846]], dtype=float32)]\n\n References\n -----------\n - Modified from TFlearn (the original code is used for fixed length rnn), `references <https://github.com/tflearn/tflearn/blob/master/tflearn/layers/recurrent.py>`__.\n\n \"\"\"\n batch_size = tf.shape(inputs)[0]\n # max_length = int(inputs.get_shape()[1]) # for fixed length rnn, length is given\n max_length = tf.shape(inputs)[1] # for dynamic_rnn, length is unknown\n dim_size = int(inputs.get_shape()[2])\n index = tf.range(0, batch_size) * max_length + (index - 1)\n flat = tf.reshape(inputs, [-1, dim_size])\n relevant = tf.gather(flat, index)\n return relevant\n\n\ndef retrieve_seq_length_op(data):\n \"\"\"An op to compute the length of a sequence from input shape of [batch_size, n_step(max), n_features],\n it can be used when the features of padding (on right hand side) are all zeros.\n\n Parameters\n -----------\n data : tensor\n [batch_size, n_step(max), n_features] with zero padding on right hand side.\n\n Examples\n ---------\n >>> data = [[[1],[2],[0],[0],[0]],\n ... [[1],[2],[3],[0],[0]],\n ... [[1],[2],[6],[1],[0]]]\n >>> data = np.asarray(data)\n >>> print(data.shape)\n (3, 5, 1)\n >>> data = tf.constant(data)\n >>> sl = retrieve_seq_length_op(data)\n >>> sess = tf.InteractiveSession()\n >>> tl.layers.initialize_global_variables(sess)\n >>> y = sl.eval()\n [2 3 4]\n\n Multiple features\n >>> data = [[[1,2],[2,2],[1,2],[1,2],[0,0]],\n ... [[2,3],[2,4],[3,2],[0,0],[0,0]],\n ... [[3,3],[2,2],[5,3],[1,2],[0,0]]]\n >>> print(sl)\n [4 3 4]\n\n References\n ------------\n Borrow from `TFlearn <https://github.com/tflearn/tflearn/blob/master/tflearn/layers/recurrent.py>`__.\n\n \"\"\"\n with tf.name_scope('GetLength'):\n used = tf.sign(tf.reduce_max(tf.abs(data), 2))\n length = tf.reduce_sum(used, 1)\n\n return tf.cast(length, tf.int32)\n\n\ndef retrieve_seq_length_op2(data):\n \"\"\"An op to compute the length of a sequence, from input shape of [batch_size, n_step(max)],\n it can be used when the features of padding (on right hand side) are all zeros.\n\n Parameters\n -----------\n data : tensor\n [batch_size, n_step(max)] with zero padding on right hand side.\n\n Examples\n --------\n >>> data = [[1,2,0,0,0],\n ... [1,2,3,0,0],\n ... [1,2,6,1,0]]\n >>> o = retrieve_seq_length_op2(data)\n >>> sess = tf.InteractiveSession()\n >>> tl.layers.initialize_global_variables(sess)\n >>> print(o.eval())\n [2 3 4]\n\n \"\"\"\n return tf.reduce_sum(tf.cast(tf.greater(data, tf.zeros_like(data)), tf.int32), 1)\n\n\ndef retrieve_seq_length_op3(data, pad_val=0): # HangSheng: return tensor for sequence length, if input is tf.string\n \"\"\"Return tensor for sequence length, if input is ``tf.string``.\"\"\"\n data_shape_size = data.get_shape().ndims\n if data_shape_size == 3:\n return tf.reduce_sum(tf.cast(tf.reduce_any(tf.not_equal(data, pad_val), axis=2), dtype=tf.int32), 1)\n elif data_shape_size == 2:\n return tf.reduce_sum(tf.cast(tf.not_equal(data, pad_val), dtype=tf.int32), 1)\n elif data_shape_size == 1:\n raise ValueError(\"retrieve_seq_length_op3: data has wrong shape!\")\n else:\n raise ValueError(\n \"retrieve_seq_length_op3: handling data_shape_size %s hasn't been implemented!\" % (data_shape_size)\n )\n\n\ndef target_mask_op(data, pad_val=0): # HangSheng: return tensor for mask,if input is tf.string\n \"\"\"Return tensor for mask, if input is ``tf.string``.\"\"\"\n data_shape_size = data.get_shape().ndims\n if data_shape_size == 3:\n return tf.cast(tf.reduce_any(tf.not_equal(data, pad_val), axis=2), dtype=tf.int32)\n elif data_shape_size == 2:\n return tf.cast(tf.not_equal(data, pad_val), dtype=tf.int32)\n elif data_shape_size == 1:\n raise ValueError(\"target_mask_op: data has wrong shape!\")\n else:\n raise ValueError(\"target_mask_op: handling data_shape_size %s hasn't been implemented!\" % (data_shape_size))\n\n\nclass DynamicRNNLayer(Layer):\n \"\"\"\n The :class:`DynamicRNNLayer` class is a dynamic recurrent layer, see ``tf.nn.dynamic_rnn``.\n\n Parameters\n ----------\n prev_layer : :class:`Layer`\n Previous layer\n cell_fn : TensorFlow cell function\n A TensorFlow core RNN cell\n - See `RNN Cells in TensorFlow <https://www.tensorflow.org/api_docs/python/>`__\n - Note TF1.0+ and TF1.0- are different\n cell_init_args : dictionary or None\n The arguments for the cell function.\n n_hidden : int\n The number of hidden units in the layer.\n initializer : initializer\n The initializer for initializing the parameters.\n sequence_length : tensor, array or None\n The sequence length of each row of input data, see ``Advanced Ops for Dynamic RNN``.\n - If None, it uses ``retrieve_seq_length_op`` to compute the sequence length, i.e. when the features of padding (on right hand side) are all zeros.\n - If using word embedding, you may need to compute the sequence length from the ID array (the integer features before word embedding) by using ``retrieve_seq_length_op2`` or ``retrieve_seq_length_op``.\n - You can also input an numpy array.\n - More details about TensorFlow dynamic RNN in `Wild-ML Blog <http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/>`__.\n initial_state : None or RNN State\n If None, `initial_state` is zero state.\n dropout : tuple of float or int\n The input and output keep probability (input_keep_prob, output_keep_prob).\n - If one int, input and output keep probability are the same.\n n_layer : int\n The number of RNN layers, default is 1.\n return_last : boolean or None\n Whether return last output or all outputs in each step.\n - If True, return the last output, \"Sequence input and single output\"\n - If False, return all outputs, \"Synced sequence input and output\"\n - In other word, if you want to stack more RNNs on this layer, set to False.\n return_seq_2d : boolean\n Only consider this argument when `return_last` is `False`\n - If True, return 2D Tensor [n_example, n_hidden], for stacking DenseLayer after it.\n - If False, return 3D Tensor [n_example/n_steps, n_steps, n_hidden], for stacking multiple RNN after it.\n dynamic_rnn_init_args : dictionary\n The arguments for ``tf.nn.dynamic_rnn``.\n name : str\n A unique layer name.\n\n Attributes\n ------------\n outputs : tensor\n The output of this layer.\n\n final_state : tensor or StateTuple\n The finial state of this layer.\n - When `state_is_tuple` is `False`, it is the final hidden and cell states, `states.get_shape() = [?, 2 * n_hidden]`.\n - When `state_is_tuple` is `True`, it stores two elements: `(c, h)`.\n - In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.\n\n initial_state : tensor or StateTuple\n The initial state of this layer.\n - In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.\n\n batch_size : int or tensor\n It is an integer, if it is able to compute the `batch_size`; otherwise, tensor for dynamic batch size.\n\n sequence_length : a tensor or array\n The sequence lengths computed by Advanced Opt or the given sequence lengths, [batch_size]\n\n Notes\n -----\n Input dimension should be rank 3 : [batch_size, n_steps(max), n_features], if no, please see :class:`ReshapeLayer`.\n\n Examples\n --------\n Synced sequence input and output, for loss function see ``tl.cost.cross_entropy_seq_with_mask``.\n\n >>> input_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"input\")\n >>> net = tl.layers.EmbeddingInputlayer(\n ... inputs=input_seqs,\n ... vocabulary_size=vocab_size,\n ... embedding_size=embedding_size,\n ... name='embedding')\n >>> net = tl.layers.DynamicRNNLayer(net,\n ... cell_fn=tf.contrib.rnn.BasicLSTMCell, # for TF0.2 use tf.nn.rnn_cell.BasicLSTMCell,\n ... n_hidden=embedding_size,\n ... dropout=(0.7 if is_train else None),\n ... sequence_length=tl.layers.retrieve_seq_length_op2(input_seqs),\n ... return_last=False, # for encoder, set to True\n ... return_seq_2d=True, # stack denselayer or compute cost after it\n ... name='dynamicrnn')\n >>> net = tl.layers.DenseLayer(net, n_units=vocab_size, name=\"output\")\n\n References\n ----------\n - `Wild-ML Blog <http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/>`__\n - `dynamic_rnn.ipynb <https://github.com/dennybritz/tf-rnn/blob/master/dynamic_rnn.ipynb>`__\n - `tf.nn.dynamic_rnn <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/api_docs/python/functions_and_classes/shard8/tf.nn.dynamic_rnn.md>`__\n - `tflearn rnn <https://github.com/tflearn/tflearn/blob/master/tflearn/layers/recurrent.py>`__\n - ``tutorial_dynamic_rnn.py``\n\n \"\"\"\n\n @deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release\n def __init__(\n self,\n prev_layer,\n cell_fn, #tf.nn.rnn_cell.LSTMCell,\n cell_init_args=None,\n n_hidden=256,\n initializer=tf.random_uniform_initializer(-0.1, 0.1),\n sequence_length=None,\n initial_state=None,\n dropout=None,\n n_layer=1,\n return_last=None,\n return_seq_2d=False,\n dynamic_rnn_init_args=None,\n name='dyrnn',\n ):\n if cell_fn is None:\n raise Exception(\"Please put in cell_fn\")\n\n super(DynamicRNNLayer, self).__init__(\n prev_layer=prev_layer, cell_init_args=cell_init_args, dynamic_rnn_init_args=dynamic_rnn_init_args, name=name\n )\n\n if self.cell_init_args:\n self.cell_init_args['state_is_tuple'] = True # 'use_peepholes': True\n\n if 'GRU' in cell_fn.__name__:\n try:\n self.cell_init_args.pop('state_is_tuple')\n except Exception:\n logging.warning(\"pop state_is_tuple fails.\")\n\n if return_last is None:\n return_last = True\n\n logging.info(\n \"DynamicRNNLayer %s: n_hidden: %d, in_dim: %d in_shape: %s cell_fn: %s dropout: %s n_layer: %d\" % (\n self.name, n_hidden, self.inputs.get_shape().ndims, self.inputs.get_shape(), cell_fn.__name__, dropout,\n n_layer\n )\n )\n\n # Input dimension should be rank 3 [batch_size, n_steps(max), n_features]\n try:\n self.inputs.get_shape().with_rank(3)\n except Exception:\n raise Exception(\"RNN : Input dimension should be rank 3 : [batch_size, n_steps(max), n_features]\")\n\n # Get the batch_size\n fixed_batch_size = self.inputs.get_shape().with_rank_at_least(1)[0]\n if fixed_batch_size.value:\n batch_size = fixed_batch_size.value\n logging.info(\" batch_size (concurrent processes): %d\" % batch_size)\n\n else:\n batch_size = array_ops.shape(self.inputs)[0]\n logging.info(\" non specified batch_size, uses a tensor instead.\")\n\n self.batch_size = batch_size\n\n # Creats the cell function\n # cell_instance_fn=lambda: cell_fn(num_units=n_hidden, **self.cell_init_args) # HanSheng\n rnn_creator = lambda: cell_fn(num_units=n_hidden, **self.cell_init_args)\n\n # Apply dropout\n if dropout:\n if isinstance(dropout, (tuple, list)):\n in_keep_prob = dropout[0]\n out_keep_prob = dropout[1]\n\n elif isinstance(dropout, float):\n in_keep_prob, out_keep_prob = dropout, dropout\n\n else:\n raise Exception(\"Invalid dropout type (must be a 2-D tuple of \" \"float)\")\n\n DropoutWrapper_fn = tf.contrib.rnn.DropoutWrapper\n\n # cell_instance_fn1=cell_instance_fn # HanSheng\n # cell_instance_fn=DropoutWrapper_fn(\n # cell_instance_fn1(),\n # input_keep_prob=in_keep_prob,\n # output_keep_prob=out_keep_prob)\n cell_creator = lambda is_last=True: DropoutWrapper_fn(\n rnn_creator(), input_keep_prob=in_keep_prob, output_keep_prob=out_keep_prob if is_last else 1.0\n )\n else:\n cell_creator = rnn_creator\n self.cell = cell_creator()\n # Apply multiple layers\n if n_layer > 1:\n try:\n MultiRNNCell_fn = tf.contrib.rnn.MultiRNNCell\n except Exception:\n MultiRNNCell_fn = tf.nn.rnn_cell.MultiRNNCell\n\n # cell_instance_fn2=cell_instance_fn # HanSheng\n if dropout:\n try:\n # cell_instance_fn=lambda: MultiRNNCell_fn([cell_instance_fn2() for _ in range(n_layer)], state_is_tuple=True) # HanSheng\n self.cell = MultiRNNCell_fn(\n [cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)], state_is_tuple=True\n )\n except Exception: # when GRU\n # cell_instance_fn=lambda: MultiRNNCell_fn([cell_instance_fn2() for _ in range(n_layer)]) # HanSheng\n self.cell = MultiRNNCell_fn([cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)])\n else:\n try:\n self.cell = MultiRNNCell_fn([cell_creator() for _ in range(n_layer)], state_is_tuple=True)\n except Exception: # when GRU\n self.cell = MultiRNNCell_fn([cell_creator() for _ in range(n_layer)])\n\n # self.cell=cell_instance_fn() # HanSheng\n\n # Initialize initial_state\n if initial_state is None:\n self.initial_state = self.cell.zero_state(batch_size, dtype=LayersConfig.tf_dtype) # dtype=tf.float32)\n else:\n self.initial_state = initial_state\n\n # Computes sequence_length\n if sequence_length is None:\n\n sequence_length = retrieve_seq_length_op(\n self.inputs if isinstance(self.inputs, tf.Tensor) else tf.stack(self.inputs)\n )\n\n # Main - Computes outputs and last_states\n with tf.variable_scope(name, initializer=initializer) as vs:\n outputs, last_states = tf.nn.dynamic_rnn(\n cell=self.cell,\n # inputs=X\n inputs=self.inputs,\n # dtype=tf.float64,\n sequence_length=sequence_length,\n initial_state=self.initial_state,\n **self.dynamic_rnn_init_args\n )\n rnn_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n # logging.info(\" n_params : %d\" % (len(rnn_variables)))\n # Manage the outputs\n if return_last:\n # [batch_size, n_hidden]\n # outputs = tf.transpose(tf.pack(outputs), [1, 0, 2])\n self.outputs = advanced_indexing_op(outputs, sequence_length)\n\n else:\n # [batch_size, n_step(max), n_hidden]\n # self.outputs = result[0][\"outputs\"]\n # self.outputs = outputs # it is 3d, but it is a list\n if return_seq_2d:\n # PTB tutorial:\n # 2D Tensor [n_example, n_hidden]\n self.outputs = tf.reshape(tf.concat(outputs, 1), [-1, n_hidden])\n\n else:\n # <akara>:\n # 3D Tensor [batch_size, n_steps(max), n_hidden]\n max_length = tf.shape(outputs)[1]\n batch_size = tf.shape(outputs)[0]\n\n self.outputs = tf.reshape(tf.concat(outputs, 1), [batch_size, max_length, n_hidden])\n # self.outputs = tf.reshape(tf.concat(1, outputs), [-1, max_length, n_hidden])\n\n # Final state\n self.final_state = last_states\n\n self.sequence_length = sequence_length\n\n self._add_layers(self.outputs)\n self._add_params(rnn_variables)\n\n\nclass BiDynamicRNNLayer(Layer):\n \"\"\"\n The :class:`BiDynamicRNNLayer` class is a RNN layer, you can implement vanilla RNN,\n LSTM and GRU with it.\n\n Parameters\n ----------\n prev_layer : :class:`Layer`\n Previous layer.\n cell_fn : TensorFlow cell function\n A TensorFlow core RNN cell\n - See `RNN Cells in TensorFlow <https://www.tensorflow.org/api_docs/python/>`__.\n - Note TF1.0+ and TF1.0- are different.\n cell_init_args : dictionary\n The arguments for the cell initializer.\n n_hidden : int\n The number of hidden units in the layer.\n initializer : initializer\n The initializer for initializing the parameters.\n sequence_length : tensor, array or None\n The sequence length of each row of input data, see ``Advanced Ops for Dynamic RNN``.\n - If None, it uses ``retrieve_seq_length_op`` to compute the sequence length, i.e. when the features of padding (on right hand side) are all zeros.\n - If using word embedding, you may need to compute the sequence length from the ID array (the integer features before word embedding) by using ``retrieve_seq_length_op2`` or ``retrieve_seq_length_op``.\n - You can also input an numpy array.\n - More details about TensorFlow dynamic RNN in `Wild-ML Blog <http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/>`__.\n fw_initial_state : None or forward RNN State\n If None, `initial_state` is zero state.\n bw_initial_state : None or backward RNN State\n If None, `initial_state` is zero state.\n dropout : tuple of float or int\n The input and output keep probability (input_keep_prob, output_keep_prob).\n - If one int, input and output keep probability are the same.\n n_layer : int\n The number of RNN layers, default is 1.\n return_last : boolean\n Whether return last output or all outputs in each step.\n - If True, return the last output, \"Sequence input and single output\"\n - If False, return all outputs, \"Synced sequence input and output\"\n - In other word, if you want to stack more RNNs on this layer, set to False.\n return_seq_2d : boolean\n Only consider this argument when `return_last` is `False`\n - If True, return 2D Tensor [n_example, 2 * n_hidden], for stacking DenseLayer after it.\n - If False, return 3D Tensor [n_example/n_steps, n_steps, 2 * n_hidden], for stacking multiple RNN after it.\n dynamic_rnn_init_args : dictionary\n The arguments for ``tf.nn.bidirectional_dynamic_rnn``.\n name : str\n A unique layer name.\n\n Attributes\n -----------------------\n outputs : tensor\n The output of this layer. (?, 2 * n_hidden)\n\n fw(bw)_final_state : tensor or StateTuple\n The finial state of this layer.\n - When `state_is_tuple` is `False`, it is the final hidden and cell states, `states.get_shape() = [?, 2 * n_hidden]`.\n - When `state_is_tuple` is `True`, it stores two elements: `(c, h)`.\n - In practice, you can get the final state after each iteration during training, then feed it to the initial state of next iteration.\n\n fw(bw)_initial_state : tensor or StateTuple\n The initial state of this layer.\n - In practice, you can set your state at the begining of each epoch or iteration according to your training procedure.\n\n batch_size : int or tensor\n It is an integer, if it is able to compute the `batch_size`; otherwise, tensor for dynamic batch size.\n\n sequence_length : a tensor or array\n The sequence lengths computed by Advanced Opt or the given sequence lengths, [batch_size].\n\n Notes\n -----\n Input dimension should be rank 3 : [batch_size, n_steps(max), n_features], if no, please see :class:`ReshapeLayer`.\n\n References\n ----------\n - `Wild-ML Blog <http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/>`__\n - `bidirectional_rnn.ipynb <https://github.com/dennybritz/tf-rnn/blob/master/bidirectional_rnn.ipynb>`__\n\n \"\"\"\n\n @deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release\n def __init__(\n self,\n prev_layer,\n cell_fn, #tf.nn.rnn_cell.LSTMCell,\n cell_init_args=None,\n n_hidden=256,\n initializer=tf.random_uniform_initializer(-0.1, 0.1),\n sequence_length=None,\n fw_initial_state=None,\n bw_initial_state=None,\n dropout=None,\n n_layer=1,\n return_last=False,\n return_seq_2d=False,\n dynamic_rnn_init_args=None,\n name='bi_dyrnn_layer',\n ):\n super(BiDynamicRNNLayer, self).__init__(\n prev_layer=prev_layer, cell_init_args=cell_init_args, dynamic_rnn_init_args=dynamic_rnn_init_args, name=name\n )\n\n if self.cell_init_args:\n self.cell_init_args['state_is_tuple'] = True # 'use_peepholes': True,\n\n if 'GRU' in cell_fn.__name__:\n try:\n self.cell_init_args.pop('state_is_tuple')\n except Exception:\n logging.warning(\"pop state_is_tuple fails.\")\n\n if cell_fn is None:\n raise Exception(\"Please put in cell_fn\")\n\n logging.info(\n \"BiDynamicRNNLayer %s: n_hidden: %d in_dim: %d in_shape: %s cell_fn: %s dropout: %s n_layer: %d\" % (\n self.name, n_hidden, self.inputs.get_shape().ndims, self.inputs.get_shape(), cell_fn.__name__, dropout,\n n_layer\n )\n )\n\n # Input dimension should be rank 3 [batch_size, n_steps(max), n_features]\n try:\n self.inputs.get_shape().with_rank(3)\n except Exception:\n raise Exception(\"RNN : Input dimension should be rank 3 : [batch_size, n_steps(max), n_features]\")\n\n # Get the batch_size\n fixed_batch_size = self.inputs.get_shape().with_rank_at_least(1)[0]\n\n if fixed_batch_size.value:\n batch_size = fixed_batch_size.value\n logging.info(\" batch_size (concurrent processes): %d\" % batch_size)\n\n else:\n batch_size = array_ops.shape(self.inputs)[0]\n logging.info(\" non specified batch_size, uses a tensor instead.\")\n\n self.batch_size = batch_size\n\n with tf.variable_scope(name, initializer=initializer) as vs:\n # Creats the cell function\n # cell_instance_fn=lambda: cell_fn(num_units=n_hidden, **self.cell_init_args) # HanSheng\n rnn_creator = lambda: cell_fn(num_units=n_hidden, **self.cell_init_args)\n\n # Apply dropout\n if dropout:\n if isinstance(dropout, (tuple, list)):\n in_keep_prob = dropout[0]\n out_keep_prob = dropout[1]\n elif isinstance(dropout, float):\n in_keep_prob, out_keep_prob = dropout, dropout\n else:\n raise Exception(\"Invalid dropout type (must be a 2-D tuple of \" \"float)\")\n try:\n DropoutWrapper_fn = tf.contrib.rnn.DropoutWrapper\n except Exception:\n DropoutWrapper_fn = tf.nn.rnn_cell.DropoutWrapper\n\n # cell_instance_fn1=cell_instance_fn # HanSheng\n # cell_instance_fn=lambda: DropoutWrapper_fn(\n # cell_instance_fn1(),\n # input_keep_prob=in_keep_prob,\n # output_keep_prob=out_keep_prob)\n cell_creator = lambda is_last=True: DropoutWrapper_fn(\n rnn_creator(), input_keep_prob=in_keep_prob, output_keep_prob=out_keep_prob if is_last else 1.0\n )\n else:\n cell_creator = rnn_creator\n\n # if dropout:\n # self.fw_cell = DropoutWrapper_fn(self.fw_cell, input_keep_prob=1.0, output_keep_prob=out_keep_prob)\n # self.bw_cell = DropoutWrapper_fn(self.bw_cell, input_keep_prob=1.0, output_keep_prob=out_keep_prob)\n\n # self.fw_cell=cell_instance_fn()\n # self.bw_cell=cell_instance_fn()\n # Initial state of RNN\n\n self.fw_initial_state = fw_initial_state\n self.bw_initial_state = bw_initial_state\n # Computes sequence_length\n if sequence_length is None:\n\n sequence_length = retrieve_seq_length_op(\n self.inputs if isinstance(self.inputs, tf.Tensor) else tf.stack(self.inputs)\n )\n\n if n_layer > 1:\n if dropout:\n self.fw_cell = [cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)]\n self.bw_cell = [cell_creator(is_last=i == n_layer - 1) for i in range(n_layer)]\n\n else:\n self.fw_cell = [cell_creator() for _ in range(n_layer)]\n self.bw_cell = [cell_creator() for _ in range(n_layer)]\n\n outputs, states_fw, states_bw = stack_bidirectional_dynamic_rnn(\n cells_fw=self.fw_cell, cells_bw=self.bw_cell, inputs=self.inputs, sequence_length=sequence_length,\n initial_states_fw=self.fw_initial_state, initial_states_bw=self.bw_initial_state,\n dtype=LayersConfig.tf_dtype, **self.dynamic_rnn_init_args\n )\n\n else:\n self.fw_cell = cell_creator()\n self.bw_cell = cell_creator()\n outputs, (states_fw, states_bw) = tf.nn.bidirectional_dynamic_rnn(\n cell_fw=self.fw_cell, cell_bw=self.bw_cell, inputs=self.inputs, sequence_length=sequence_length,\n initial_state_fw=self.fw_initial_state, initial_state_bw=self.bw_initial_state,\n dtype=LayersConfig.tf_dtype, **self.dynamic_rnn_init_args\n )\n\n rnn_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n logging.info(\" n_params : %d\" % (len(rnn_variables)))\n\n # Manage the outputs\n outputs = tf.concat(outputs, 2)\n\n if return_last:\n # [batch_size, 2 * n_hidden]\n raise NotImplementedError(\"Return last is not implemented yet.\")\n # self.outputs = advanced_indexing_op(outputs, sequence_length)\n else:\n # [batch_size, n_step(max), 2 * n_hidden]\n if return_seq_2d:\n # PTB tutorial:\n # 2D Tensor [n_example, 2 * n_hidden]\n self.outputs = tf.reshape(tf.concat(outputs, 1), [-1, 2 * n_hidden])\n\n else:\n # <akara>:\n # 3D Tensor [batch_size, n_steps(max), 2 * n_hidden]\n max_length = tf.shape(outputs)[1]\n batch_size = tf.shape(outputs)[0]\n\n self.outputs = tf.reshape(tf.concat(outputs, 1), [batch_size, max_length, 2 * n_hidden])\n\n # Final state\n self.fw_final_states = states_fw\n self.bw_final_states = states_bw\n\n self.sequence_length = sequence_length\n\n self._add_layers(self.outputs)\n self._add_params(rnn_variables)\n\n\nclass Seq2Seq(Layer):\n \"\"\"\n The :class:`Seq2Seq` class is a simple :class:`DynamicRNNLayer` based Seq2seq layer without using `tl.contrib.seq2seq <https://www.tensorflow.org/api_guides/python/contrib.seq2seq>`__.\n See `Model <https://camo.githubusercontent.com/9e88497fcdec5a9c716e0de5bc4b6d1793c6e23f/687474703a2f2f73757269796164656570616e2e6769746875622e696f2f696d672f736571327365712f73657132736571322e706e67>`__\n and `Sequence to Sequence Learning with Neural Networks <https://arxiv.org/abs/1409.3215>`__.\n\n - Please check this example `Chatbot in 200 lines of code <https://github.com/tensorlayer/seq2seq-chatbot>`__.\n - The Author recommends users to read the source code of :class:`DynamicRNNLayer` and :class:`Seq2Seq`.\n\n Parameters\n ----------\n net_encode_in : :class:`Layer`\n Encode sequences, [batch_size, None, n_features].\n net_decode_in : :class:`Layer`\n Decode sequences, [batch_size, None, n_features].\n cell_fn : TensorFlow cell function\n A TensorFlow core RNN cell\n - see `RNN Cells in TensorFlow <https://www.tensorflow.org/api_docs/python/>`__\n - Note TF1.0+ and TF1.0- are different\n cell_init_args : dictionary or None\n The arguments for the cell initializer.\n n_hidden : int\n The number of hidden units in the layer.\n initializer : initializer\n The initializer for the parameters.\n encode_sequence_length : tensor\n For encoder sequence length, see :class:`DynamicRNNLayer` .\n decode_sequence_length : tensor\n For decoder sequence length, see :class:`DynamicRNNLayer` .\n initial_state_encode : None or RNN state\n If None, `initial_state_encode` is zero state, it can be set by placeholder or other RNN.\n initial_state_decode : None or RNN state\n If None, `initial_state_decode` is the final state of the RNN encoder, it can be set by placeholder or other RNN.\n dropout : tuple of float or int\n The input and output keep probability (input_keep_prob, output_keep_prob).\n - If one int, input and output keep probability are the same.\n n_layer : int\n The number of RNN layers, default is 1.\n return_seq_2d : boolean\n Only consider this argument when `return_last` is `False`\n - If True, return 2D Tensor [n_example, 2 * n_hidden], for stacking DenseLayer after it.\n - If False, return 3D Tensor [n_example/n_steps, n_steps, 2 * n_hidden], for stacking multiple RNN after it.\n name : str\n A unique layer name.\n\n Attributes\n ------------\n outputs : tensor\n The output of RNN decoder.\n initial_state_encode : tensor or StateTuple\n Initial state of RNN encoder.\n initial_state_decode : tensor or StateTuple\n Initial state of RNN decoder.\n final_state_encode : tensor or StateTuple\n Final state of RNN encoder.\n final_state_decode : tensor or StateTuple\n Final state of RNN decoder.\n\n Notes\n --------\n - How to feed data: `Sequence to Sequence Learning with Neural Networks <https://arxiv.org/pdf/1409.3215v3.pdf>`__\n - input_seqs : ``['how', 'are', 'you', '<PAD_ID>']``\n - decode_seqs : ``['<START_ID>', 'I', 'am', 'fine', '<PAD_ID>']``\n - target_seqs : ``['I', 'am', 'fine', '<END_ID>', '<PAD_ID>']``\n - target_mask : ``[1, 1, 1, 1, 0]``\n - related functions : tl.prepro <pad_sequences, precess_sequences, sequences_add_start_id, sequences_get_mask>\n\n Examples\n ----------\n >>> from tensorlayer.layers import *\n >>> batch_size = 32\n >>> encode_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"encode_seqs\")\n >>> decode_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"decode_seqs\")\n >>> target_seqs = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"target_seqs\")\n >>> target_mask = tf.placeholder(dtype=tf.int64, shape=[batch_size, None], name=\"target_mask\") # tl.prepro.sequences_get_mask()\n >>> with tf.variable_scope(\"model\"):\n >>> # for chatbot, you can use the same embedding layer,\n >>> # for translation, you may want to use 2 seperated embedding layers\n >>> with tf.variable_scope(\"embedding\") as vs:\n >>> net_encode = EmbeddingInputlayer(\n ... inputs = encode_seqs,\n ... vocabulary_size = 10000,\n ... embedding_size = 200,\n ... name = 'seq_embedding')\n >>> vs.reuse_variables()\n >>> tl.layers.set_name_reuse(True)\n >>> net_decode = EmbeddingInputlayer(\n ... inputs = decode_seqs,\n ... vocabulary_size = 10000,\n ... embedding_size = 200,\n ... name = 'seq_embedding')\n >>> net = Seq2Seq(net_encode, net_decode,\n ... cell_fn = tf.contrib.rnn.BasicLSTMCell,\n ... n_hidden = 200,\n ... initializer = tf.random_uniform_initializer(-0.1, 0.1),\n ... encode_sequence_length = retrieve_seq_length_op2(encode_seqs),\n ... decode_sequence_length = retrieve_seq_length_op2(decode_seqs),\n ... initial_state_encode = None,\n ... dropout = None,\n ... n_layer = 1,\n ... return_seq_2d = True,\n ... name = 'seq2seq')\n >>> net_out = DenseLayer(net, n_units=10000, act=None, name='output')\n >>> e_loss = tl.cost.cross_entropy_seq_with_mask(logits=net_out.outputs, target_seqs=target_seqs, input_mask=target_mask, return_details=False, name='cost')\n >>> y = tf.nn.softmax(net_out.outputs)\n >>> net_out.print_params(False)\n\n \"\"\"\n\n def __init__(\n self,\n net_encode_in,\n net_decode_in,\n cell_fn, #tf.nn.rnn_cell.LSTMCell,\n cell_init_args=None,\n n_hidden=256,\n initializer=tf.random_uniform_initializer(-0.1, 0.1),\n encode_sequence_length=None,\n decode_sequence_length=None,\n initial_state_encode=None,\n initial_state_decode=None,\n dropout=None,\n n_layer=1,\n return_seq_2d=False,\n name='seq2seq',\n ):\n super(Seq2Seq,\n self).__init__(prev_layer=[net_encode_in, net_decode_in], cell_init_args=cell_init_args, name=name)\n\n if self.cell_init_args:\n self.cell_init_args['state_is_tuple'] = True # 'use_peepholes': True,\n\n if cell_fn is None:\n raise ValueError(\"cell_fn cannot be set to None\")\n\n if 'GRU' in cell_fn.__name__:\n try:\n cell_init_args.pop('state_is_tuple')\n except Exception:\n logging.warning(\"pop state_is_tuple fails.\")\n\n logging.info(\n \"[*] Seq2Seq %s: n_hidden: %d cell_fn: %s dropout: %s n_layer: %d\" %\n (self.name, n_hidden, cell_fn.__name__, dropout, n_layer)\n )\n\n with tf.variable_scope(name):\n # tl.layers.set_name_reuse(reuse)\n # network = InputLayer(self.inputs, name=name+'/input')\n network_encode = DynamicRNNLayer(\n net_encode_in, cell_fn=cell_fn, cell_init_args=self.cell_init_args, n_hidden=n_hidden,\n initializer=initializer, initial_state=initial_state_encode, dropout=dropout, n_layer=n_layer,\n sequence_length=encode_sequence_length, return_last=False, return_seq_2d=True, name='encode'\n )\n # vs.reuse_variables()\n # tl.layers.set_name_reuse(True)\n network_decode = DynamicRNNLayer(\n net_decode_in, cell_fn=cell_fn, cell_init_args=self.cell_init_args, n_hidden=n_hidden,\n initializer=initializer,\n initial_state=(network_encode.final_state if initial_state_decode is None else\n initial_state_decode), dropout=dropout, n_layer=n_layer,\n sequence_length=decode_sequence_length, return_last=False, return_seq_2d=return_seq_2d, name='decode'\n )\n self.outputs = network_decode.outputs\n\n # rnn_variables = tf.get_collection(TF_GRAPHKEYS_VARIABLES, scope=vs.name)\n\n # Initial state\n self.initial_state_encode = network_encode.initial_state\n self.initial_state_decode = network_decode.initial_state\n\n # Final state\n self.final_state_encode = network_encode.final_state\n self.final_state_decode = network_decode.final_state\n\n # self.sequence_length = sequence_length\n self._add_layers(network_encode.all_layers)\n self._add_params(network_encode.all_params)\n self._add_dropout_layers(network_encode.all_drop)\n\n self._add_layers(network_decode.all_layers)\n self._add_params(network_decode.all_params)\n self._add_dropout_layers(network_decode.all_drop)\n\n self._add_layers(self.outputs)\n" ]
[ [ "tensorflow.get_variable", "tensorflow.nn.dynamic_rnn", "tensorflow.concat", "tensorflow.python.ops.array_ops.shape", "tensorflow.zeros", "tensorflow.python.util.tf_inspect.getfullargspec", "tensorflow.reduce_sum", "tensorflow.stack", "tensorflow.cast", "tensorflow.nn.bidirectional_dynamic_rnn", "tensorflow.nn.conv2d", "tensorflow.random_uniform_initializer", "tensorflow.get_collection", "tensorflow.gather", "tensorflow.name_scope", "tensorflow.nn.sigmoid", "tensorflow.unstack", "tensorflow.shape", "tensorflow.zeros_like", "tensorflow.split", "tensorflow.not_equal", "tensorflow.contrib.rnn.stack_bidirectional_dynamic_rnn", "tensorflow.range", "tensorflow.reshape", "tensorflow.python.ops.rnn_cell.LSTMStateTuple", "tensorflow.constant_initializer", "tensorflow.variable_scope", "tensorflow.get_variable_scope", "tensorflow.abs" ] ]
leeseedong/book-cryptocurrency
[ "58c0bb3f5a80f8cc73ba47c4839be3bd33c9d67c" ]
[ "ch07/07_09.py" ]
[ "import pybithumb\nimport numpy as np\n\ndf = pybithumb.get_ohlcv(\"BTC\")\ndf = df['2018']\n\ndf['range'] = (df['high'] - df['low']) * 0.5\ndf['target'] = df['open'] + df['range'].shift(1)\n\ndf['ror'] = np.where(df['high'] > df['target'],\n df['close'] / df['target'],\n 1)\n\nror = df['ror'].cumprod()[-2]\nprint(ror)\n" ]
[ [ "numpy.where" ] ]
WenZhihao666/MI-GNN
[ "0edb0b1b8874efdca52788fa1039380bff8caee6" ]
[ "learner_1.py" ]
[ "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass Learner_1(nn.Module):\n def __init__(self, config):\n super(Learner_1, self).__init__()\n self.config = config\n self.vars = nn.ParameterList()\n\n for i, (name, param) in enumerate(self.config):\n if name == 'linear':\n w = nn.Parameter(torch.ones(*param))\n torch.nn.init.kaiming_normal_(w)\n self.vars.append(w)\n self.vars.append(nn.Parameter(torch.zeros(param[0])))\n\n def forward(self, x, neighs, vars=None):\n if vars is None:\n vars = self.vars\n neighs_features = []\n filmed_neighs_features = []\n for i in range(len(neighs)):\n neighs_features.append(x[torch.stack(neighs[i])])\n filmed_neigh_feature = torch.mean(neighs_features[i], dim=0)\n filmed_neighs_features.append(filmed_neigh_feature)\n x1 = torch.stack(filmed_neighs_features)\n x1 = F.linear(x1, vars[0], vars[1])\n neighs_features_1 = []\n filmed_neighs_features_1 = []\n for i in range(len(neighs)):\n neighs_features_1.append(x1[torch.stack(neighs[i])])\n filmed_neigh_feature_1 = torch.mean(neighs_features_1[i], dim=0)\n filmed_neighs_features_1.append(filmed_neigh_feature_1)\n x2 = torch.stack(filmed_neighs_features_1)\n x2 = F.linear(x2, vars[2], vars[3])\n\n return x1, x2\n\n def zero_grad(self, vars=None):\n with torch.no_grad():\n if vars is None:\n for p in self.vars:\n if p.grad is not None:\n p.grad.zero_()\n else:\n for p in vars:\n if p.grad is not None:\n p.grad.zero_()\n\n def parameters(self):\n return self.vars\n" ]
[ [ "torch.mean", "torch.ones", "torch.zeros", "torch.no_grad", "torch.nn.ParameterList", "torch.stack", "torch.nn.functional.linear", "torch.nn.init.kaiming_normal_" ] ]
AhmedAbouzaid1/Medical-Question-Answering-System
[ "4006b52adc8434d762e69342e21e4f7d98b67a6d" ]
[ "fetch_bilstm.py" ]
[ "import operator\n\nfrom nltk import tokenize\nfrom operator import itemgetter\nimport math\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nstop_words = set(stopwords.words('english'))\nfrom nltk.corpus import wordnet as guru\nfrom nltk.corpus import wordnet\nimport pandas as pd\nimport mysql.connector\nimport string\nimport re\nfrom collections import Counter\nfrom MedicalKG_.MedicalKBQA.answer_search import AnswerSearcher\nfrom MedicalKG_.MedicalKBQA.question_classifier import QuestionClassifier\nfrom MedicalKG_.MedicalKBQA.question_parser import QuestionPaser\n\n\n\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n port = \"3306\",\n user=\"root\",\n password=\"0000\",\n database=\"questiontags\"\n)\n\nmycursor = mydb.cursor()\nimport tensorflow as tf\nfrom AttentionLayer import AttentionLayer\nimport pandas as pd\nfrom bert_serving.client import BertClient\nfrom keras.models import load_model\nfrom util import ManDist\nimport numpy as np\nimport sys\n\n\n\nnp.set_printoptions(threshold=sys.maxsize)\n\ndf = pd.read_csv(\"icliniqQAs.csv\")\nmodel = load_model(\n 'newmodel.h5')\n\n\nclass KG:\n def __init__(self):\n self.classifier = QuestionClassifier()\n self.parser = QuestionPaser()\n self.searcher = AnswerSearcher()\n\n def KGanswer(self, sent):\n answer = False\n res_classify = self.classifier.classify(sent)\n #print(res_classify)\n if not res_classify:\n return answer\n res_sql = self.parser.parser_main(res_classify)\n #print(res_sql)\n final_answers = self.searcher.search_main(res_sql)\n #print(final_answers)\n\n if not final_answers:\n return answer\n else:\n return '\\n'.join(final_answers)\n\n\ndef tagsanswer(question):\n\n question = question.lower()\n question = question.translate(str.maketrans('', '', string.punctuation))\n\n\n total_words = question.split()\n total_word_length = len(total_words)\n # print(total_word_length)\n\n total_sentences = tokenize.sent_tokenize(question)\n total_sent_len = len(total_sentences)\n # print(total_sent_len)\n\n tf_score = {}\n for each_word in total_words:\n each_word = each_word.replace('.','')\n if each_word not in stop_words:\n if each_word in tf_score:\n tf_score[each_word] += 1\n else:\n tf_score[each_word] = 1\n\n # Dividing by total_word_length for each dictionary element\n tf_score.update((x, y/int(total_word_length)) for x, y in tf_score.items())\n # print(tf_score)\n\n\n def check_sent(word, sentences):\n final = [all([w in x for w in word]) for x in sentences]\n sent_len = [sentences[i] for i in range(0, len(final)) if final[i]]\n return int(len(sent_len))\n\n\n idf_score = {}\n for each_word in total_words:\n each_word = each_word.replace('.','')\n if each_word not in stop_words:\n if each_word in idf_score:\n idf_score[each_word] = check_sent(each_word, total_sentences)\n else:\n idf_score[each_word] = 1\n\n # Performing a log and divide\n idf_score.update((x, math.log(int(total_sent_len)/y)) for x, y in idf_score.items())\n\n # print(idf_score)\n\n\n tf_idf_score = {key: tf_score[key] * idf_score.get(key, 0) for key in tf_score.keys()}\n # print(tf_idf_score)\n\n def get_top_n(dict_elem, n):\n result = dict(sorted(dict_elem.items(), key = itemgetter(1), reverse = True)[:n])\n return result\n\n res = get_top_n(tf_idf_score, 100)\n tags = list(res.keys())[:]\n\n query = \"SELECT id FROM questiontags.tags WHERE tag = \"\n for x in tags:\n\n query = query + \"'\" + x + \"'\" + \" or tag = \"\n\n query = query[:len(query)-10]\n #print(query)\n mycursor.execute(query)\n\n myresult = mycursor.fetchall()\n import collections\n Output = collections.defaultdict(int)\n\n for elem in myresult:\n Output[elem[0]] += 1\n\n # Printing output\n a = sorted(Output.items(), key=lambda x: x[1], reverse=True)[:3]\n BERT_train_question1 = []\n\n res = []\n bc = BertClient()\n\n f = bc.encode([question])\n f = tf.convert_to_tensor(f)\n BERT_train_question1.append(f[0])\n BERT_train_question1 = tf.stack(BERT_train_question1)\n\n #print(a)\n for x in a:\n BERT_train_question2 = []\n # print(x[0])\n q2 = df['question']\n q2 = q2[x[0]-1]\n # print(q2)\n f = bc.encode([q2])\n f = tf.convert_to_tensor(f)\n BERT_train_question2.append(f[0])\n BERT_train_question2 = tf.stack(BERT_train_question2)\n xx = model.predict([BERT_train_question1, BERT_train_question2], steps=1)\n # print(xx)\n res.append(xx[0])\n\n\n\n index = res.index(max(res))\n index = a[index]\n # print(index[0])\n Ans = df[\"answer\"]\n answer = Ans[index[0] - 1]\n\n return answer, index[0] - 1\ndef accuracy():\n counter_max = 0\n kng = KG()\n for num, question in enumerate(df['question']):\n\n print(num)\n if num == 330 or num == 331 or num == 191:\n answer, index = tagsanswer(question)\n if index == num:\n counter_max += 1\n #print(index, num)\n else:\n answer = kng.KGanswer(question)\n if answer == False:\n answer, index = tagsanswer(question)\n if index == num:\n counter_max += 1\n #print( index, num)\n else:\n print(question, answer)\n counter_max += 1\n\n\n print(counter_max/num)\n\ndef main():\n accuracy()\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.stack", "numpy.set_printoptions", "pandas.read_csv" ] ]
NEBYUzekarias/five-video-classification-methods
[ "57b0c62d7452240e9b68abbb27754c5e22c2c805" ]
[ "demo1.py" ]
[ "from data import DataSet\n\nimport time\nimport cv2\n \n\n\n\nfrom extractor import Extractor\nfrom keras.models import Model, load_model\nfrom keras.layers import Input\nimport numpy as np\n\n\n\n\ndef show_webcam(mirror=False): \n\n \n # initialize the video stream and pointer to output video file, then\n # allow the camera sensor to warm up\n print(\"[INFO] starting video stream...\")\n writer = None\n #\n saved_model = 'data/checkpoints/lstm-features.037-0.131.h5'\n vs = cv2.VideoCapture(-1)\n time.sleep(2)\n # Set defaults.\n seq_length = 40\n class_limit = 10 # Number of classes to extract. Can be 1-101 or None for all.\n data = DataSet(seq_length=seq_length, class_limit=class_limit)\n # get the model.\n\n modelE = Extractor()\n model = load_model(saved_model)\n # loop over frames from the video file stream\n \n while True:\n # grab the frame from the threaded video stream\n \n first =\"\"\n v1 =\"\"\n\n sequence = []\n for i in range (0,40):\n \n ret_val,frame = vs.read()\n if ret_val == True:\n if mirror: \n frame = cv2.flip(frame, 1)\n width = np.size(frame, 1)\n height = np.size(frame, 0)\n x = width/2\n y = height/2\n cv2.imshow('my webcam', frame)\n cv2.putText(frame, first + v1, (x,y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255,0,0), thickness=1)\n frame = cv2.resize(frame,(299,299), interpolation = cv2.INTER_CUBIC)\n if cv2.waitKey(1) == 27: \n break # esc to quit\n else:\n break\n features = modelE.extract(frame)\n\n sequence.append(features)\n\n \n \n # Predict!\n print( np.shape(sequence))\n prediction = model.predict(np.expand_dims(sequence, axis=0))\n print(prediction)\n sorted_lps = data.print_class_from_prediction(np.squeeze(prediction, axis=0))\n for i, class_prediction in enumerate(sorted_lps):\n if i > 10 - 1 or class_prediction[1] == 0.0:\n break\n print(\"%s: %.2f\" % (class_prediction[0], class_prediction[1]))\n first = class_prediction[0]\n v1 = class_prediction[1]\n\n\n\n\n\ndef main():\n show_webcam(mirror=True)\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "numpy.size", "numpy.squeeze", "numpy.expand_dims", "numpy.shape" ] ]
WeiHao97/tiny-imagenet-tfds
[ "f5faa6fd7c39c4f04cc83b792cbfa0a8f62873cd" ]
[ "tiny_imagenet/_imagenet.py" ]
[ "import os\nfrom enum import Enum\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_URL = \"http://cs231n.stanford.edu/tiny-imagenet-200.zip\"\n_EXTRACTED_FOLDER_NAME = \"tiny-imagenet-200\"\n\nSUPPORTED_IMAGE_FORMAT = (\".jpg\", \".jpeg\", \".png\")\n\nchecksum_dir = os.path.join(os.path.dirname(__file__), 'url_checksums/')\nchecksum_dir = os.path.normpath(checksum_dir)\ntfds.download.add_checksums_dir(checksum_dir)\n\n\ndef _list_folders(root_dir):\n return [\n f for f in tf.io.gfile.listdir(root_dir)\n if tf.io.gfile.isdir(os.path.join(root_dir, f))\n ]\n\n\ndef _list_imgs(root_dir):\n return [\n os.path.join(root_dir, f)\n for f in tf.io.gfile.listdir(root_dir)\n if any(f.lower().endswith(ext) for ext in SUPPORTED_IMAGE_FORMAT)\n ]\n\n\nclass TinyImagenetDataset(tfds.core.GeneratorBasedBuilder):\n \"\"\" tiny-imagenet dataset \"\"\"\n VERSION = tfds.core.Version('0.1.0')\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=(\"\"\"Tiny ImageNet Challenge is a similar challenge as ImageNet with a smaller dataset but\n less image classes. It contains 200 image classes, a training\n dataset of 100, 000 images, a validation dataset of 10, 000\n images, and a test dataset of 10, 000 images. All images are\n of size 64×64.\"\"\"),\n features=tfds.features.FeaturesDict({\n \"image\": tfds.features.Image(shape=(64, 64, 3), encoding_format=\"jpeg\"),\n \"id\": tfds.features.Text(),\n \"label\": tfds.features.ClassLabel(num_classes=200),\n }),\n supervised_keys=(\"image\", \"label\"),\n citation=r\"\"\"@article{tiny-imagenet,\n author = {Li,Fei-Fei}, {Karpathy,Andrej} and {Johnson,Justin}\"}\"\"\",\n )\n\n def _process_train_ds(self, ds_folder, identities):\n path_to_ds = os.path.join(ds_folder, 'train')\n names = _list_folders(path_to_ds)\n\n label_images = {}\n for n in names:\n images_dir = os.path.join(path_to_ds, n, 'images')\n total_images = _list_imgs(images_dir)\n label_images[n] = {\n 'images': total_images,\n 'id': identities.index(n)\n }\n\n return label_images\n\n def _process_val_ds(self, ds_folder, identities):\n path_to_ds = os.path.join(ds_folder, 'val')\n\n # read the val_annotations.txt file\n with tf.io.gfile.GFile(os.path.join(path_to_ds, 'val_annotations.txt')) as f:\n data_raw = f.read()\n\n lines = data_raw.split(\"\\n\")\n\n label_images = {}\n for line in lines:\n if line == '':\n continue\n row_values = line.strip().split()\n label_name = row_values[1]\n if not label_name in label_images.keys():\n label_images[label_name] = {\n 'images': [],\n 'id': identities.index(label_name)\n }\n\n label_images[label_name]['images'].append(\n os.path.join(path_to_ds, 'images', row_values[0]))\n\n return label_images\n\n def _split_generators(self, dl_manager):\n extracted_path = dl_manager.extract(dl_manager.download(_URL))\n\n ds_folder = os.path.join(extracted_path, _EXTRACTED_FOLDER_NAME)\n\n with tf.io.gfile.GFile(os.path.join(ds_folder, 'wnids.txt')) as f:\n data_raw = f.read()\n\n lines = data_raw.split(\"\\n\")\n\n train_label_images = self._process_train_ds(ds_folder, lines)\n validation_label_images = self._process_val_ds(ds_folder, lines)\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs=dict(label_images=train_label_images,)),\n\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs=dict(label_images=validation_label_images,)),\n ]\n\n def _generate_examples(self, label_images):\n for label, image_info in label_images.items():\n for image_path in image_info['images']:\n key = \"%s/%s\" % (label, os.path.basename(image_path))\n yield key, {\n \"image\": image_path,\n \"id\": label,\n \"label\": image_info['id'],\n }\n" ]
[ [ "tensorflow.io.gfile.listdir" ] ]
TidalPaladin/combustion
[ "69b9a2b9baf90b81ed9098b4f0391f5c15efaee7" ]
[ "tests/test_combustion/test_vision/test_points_to_anchors.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pytest\nimport torch\nfrom torch.distributions import Binomial\n\nfrom combustion.testing import cuda_or_skip\nfrom combustion.vision import PointsToAnchors\n\n\[email protected](params=[None, 1, 2])\ndef batch_size(request):\n return request.param\n\n\[email protected](params=[10, 20])\ndef max_rois(request):\n return request.param\n\n\[email protected](params=[(32, 32), (128, 64)])\ndef input_size(request):\n return request.param\n\n\[email protected](params=[2, 4])\ndef upsample(request):\n return request.param\n\n\[email protected](params=[2, 4])\ndef num_classes(request):\n return request.param\n\n\[email protected](params=[0.0, 0.5])\ndef threshold(request):\n return request.param\n\n\[email protected]\ndef one_hot_indices(batch_size, num_classes, input_size, max_rois):\n torch.random.manual_seed(42)\n height, width = input_size\n\n if batch_size is not None:\n out_shape = (batch_size, num_classes, height, width)\n else:\n out_shape = (num_classes, height, width)\n\n d = Binomial(1, torch.tensor([max_rois / (height * width)]))\n return d.sample(out_shape).squeeze(-1).bool()\n\n\[email protected]\ndef points(batch_size, input_size, num_classes, one_hot_indices, threshold):\n height, width = input_size\n torch.random.manual_seed(42)\n\n if batch_size is None:\n regs = torch.ones(4, height, width)\n points = torch.zeros(num_classes, height, width)\n positive_points = torch.rand(num_classes, height, width)\n else:\n regs = torch.ones(batch_size, 4, height, width)\n points = torch.zeros(batch_size, num_classes, height, width)\n positive_points = torch.rand(batch_size, num_classes, height, width)\n\n regs[2:, ...].mul_(2)\n positive_points.clamp_(min=threshold + 0.01)\n _ = torch.where(one_hot_indices, positive_points, points)\n return torch.cat([_, regs], dim=-3)\n\n\[email protected]\ndef bbox(label):\n return label[..., :4]\n\n\[email protected]\ndef classes(label):\n return label[..., 4:]\n\n\ndef test_points_to_anchors(points, upsample, max_rois, num_classes, batch_size, threshold):\n layer = PointsToAnchors(upsample, max_rois, threshold)\n output: Tensor = layer(points) # type: ignore\n\n if batch_size is None:\n assert output.shape[0] <= max_rois\n assert output.shape[1] == 6\n else:\n assert output.shape[0] == batch_size\n assert output.shape[1] <= max_rois\n assert output.shape[2] == 6\n\n cls, score, reg = output[..., :, 4:5].round(), output[..., :, 5:], output[..., :, :4]\n\n assert ((cls >= -1) & (cls < num_classes)).all()\n assert (reg[..., 0] <= reg[..., 2]).all()\n assert (reg[..., 1] <= reg[..., 3]).all()\n\n\n@cuda_or_skip\ndef test_cuda(batch_size):\n layer = PointsToAnchors(2, 10, 0.0)\n if batch_size is not None:\n points = torch.rand(batch_size, 6, 32, 32).cuda()\n else:\n points = torch.rand(6, 32, 32).cuda()\n output: Tensor = layer(points) # type: ignore\n assert output.device == points.device\n\n\ndef test_input_unchanged():\n layer = PointsToAnchors(2, 10, 0.0)\n points = torch.rand(6, 32, 32)\n points_orig = points.clone()\n layer(points)\n assert torch.allclose(points, points_orig)\n\n\[email protected]\ndef test_corner_case():\n input = torch.tensor(\n [\n [0.0, 1.0, 2.0, 2.0, 200.0, 100.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [1.0, 0.0, 1.0, 1.0, 100.0, 100.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [0.0, 0.0, -1.0, -1.0, -1.0, -1.0],\n [1.0, 0.0, 1.0, 1.0, 100.0, 100.0],\n ]\n )\n input = input.view(2, 8, 6).permute(-1, 0, 1).contiguous()\n layer = PointsToAnchors(1, 10, 0.0)\n output: Tensor = layer(input) # type: ignore\n expected = torch.tensor(\n [\n [-98.0, -48.0, 102.0, 52.0, 1.0, 1.0],\n [-42.0, -48.0, 58.0, 52.0, 1.0, 0.0],\n [-45.0, -49.0, 55.0, 51.0, 1.0, 0.0],\n ]\n )\n assert torch.allclose(expected, output)\n" ]
[ [ "torch.ones", "torch.cat", "torch.zeros", "torch.random.manual_seed", "torch.tensor", "torch.rand", "torch.where", "torch.allclose" ] ]
shawntan/lexical
[ "d407642676fe60b7087825748d1585518af8dd2a" ]
[ "src/kirchhoff.py" ]
[ "import torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nDEBUG = False\n\nEPS = torch.finfo(torch.float32).tiny\n\nclass KirchhoffNormalisation(nn.Module):\n def __init__(self, dropout, plus_one=False, smoothing_eps=5e-4,\n tril=False):\n super(KirchhoffNormalisation, self).__init__()\n self.plus_one = plus_one\n self.dropout = dropout\n self.neg_inf = torch.log(torch.tensor(EPS))\n self.smoothing_eps = smoothing_eps\n self.max_trick = False\n self.no_root_score = True\n\n self.tril = tril\n\n def forward(self, head_dep_score, head_root_score, mask,\n entropy=True):\n length_mask = ~mask[:, :, None] | ~mask[:, None, :]\n eye = torch.eye(head_root_score.size(1),\n device=length_mask.device)\n diagonal_mask = eye.bool()\n idxs = torch.arange(head_root_score.size(1),\n dtype=torch.long,\n device=length_mask.device)\n dep_mask = diagonal_mask | length_mask\n\n if self.plus_one:\n head_dep_score = F.pad(head_dep_score, (0, 1), 'constant', 0.)\n root_dep_score = F.pad(head_root_score, (0, 1), 'constant', 0.)\n\n head_dep_score = head_dep_score.masked_fill(dep_mask[..., None], self.neg_inf)\n head_root_score = head_root_score.masked_fill(~mask[..., None], self.neg_inf)\n\n if self.training:\n pred_dep_mask = torch.rand_like(head_dep_score) < self.dropout\n pred_root_mask = torch.rand_like(head_root_score) < self.dropout\n head_dep_score = head_dep_score.masked_fill(pred_dep_mask, self.neg_inf)\n head_root_score = head_root_score.masked_fill(pred_root_mask, self.neg_inf)\n\n if self.max_trick:\n k = torch.maximum(\n torch.amax(\n torch.logsumexp(head_dep_score, dim=(-2, -1)),\n dim=-1\n ),\n torch.amax(head_root_score, dim=(-2, -1))\n )\n head_dep_score = head_dep_score - k[:, None, None, None]\n head_root_score = head_root_score - k[:, None, None]\n\n with torch.enable_grad():\n if self.no_root_score:\n head_root_score = 0 * head_root_score\n if not self.training and not head_dep_score.requires_grad:\n head_dep_score.requires_grad = True\n head_root_score.requires_grad = True\n dep_score = torch.logsumexp(head_dep_score, dim=-1)\n root_score = torch.logsumexp(head_root_score, dim=-1)\n\n A = torch.exp(dep_score)\n A = A + self.smoothing_eps\n A = A.masked_fill(dep_mask, 0.)\n if self.training:\n A = A / (1 - self.dropout)\n if self.no_root_score:\n rho = torch.exp(root_score)\n rho = rho.masked_fill(~mask, 0.)\n else:\n rho = torch.exp(root_score)\n rho = rho + self.smoothing_eps\n rho = rho.masked_fill(~mask, 0.)\n if self.training:\n rho = rho / (1 - self.dropout)\n if self.tril:\n A = torch.tril(A)\n\n L = torch.diag_embed(torch.sum(A, dim=-1)) - A\n L[:, :, 0] = rho\n L = L.masked_fill(length_mask, 0.) \\\n .masked_fill((diagonal_mask[None, :] &\n ~mask[:, None, :]), 1.) # 'eye' the padding\n logdet_L = torch.logdet(L)\n head_parents, head_root = torch.autograd.grad(\n torch.sum(logdet_L),\n (head_dep_score, head_root_score),\n create_graph=True\n )\n head_parents = head_parents.masked_fill(dep_mask[..., None], 0.)\n parents_ = head_parents.sum(-1)\n\n if DEBUG:\n if (parents_ < 0.).any():\n violating = (parents_.detach() < 0.)\n print(\"parents < 0\")\n print(parents_[violating])\n print(A[violating])\n print(dep_score[violating])\n # head_parents[violating] = 0.\n\n if (parents_ > 1.).any():\n violating = (parents_.detach() > 1.)\n print(\"parents > 1\")\n print(parents_[violating])\n print(A[violating])\n\n if (~torch.isfinite(parents_)).any():\n violating = (~torch.isfinite(parents_.detach()))\n print(\"parents nan\")\n print(parents_[violating])\n print(A[violating])\n\n if self.training:\n head_parents = head_parents.masked_fill(pred_dep_mask, 0.)\n if self.plus_one:\n head_parents = head_parents[..., :-1]\n if entropy:\n entropy = logdet_L - torch.einsum('bij,bij->b', parents_, dep_score)\n return head_parents, head_root, entropy\n else:\n return head_parents, head_root\n" ]
[ [ "torch.enable_grad", "torch.rand_like", "torch.amax", "torch.einsum", "torch.sum", "torch.tril", "torch.tensor", "torch.exp", "torch.logdet", "torch.isfinite", "torch.finfo", "torch.logsumexp", "torch.nn.functional.pad" ] ]
DataCircles/FortuneCookie
[ "e43ad6a3bdffffa5e426b11f7999593249a6da3f" ]
[ "gpt2.py" ]
[ "import gpt_2_simple as gpt2\nimport tensorflow as tf\nimport pandas as pd\n\nfrom library.common import _random_prefix\n\ngpt2.download_gpt2(model_name=\"124M\")\nfile_name = \"training_data/data.txt\"\n\ndef gpt2_finetune(data, steps, run_name):\n\n tf.reset_default_graph()\n sess = gpt2.start_tf_sess()\n\n return gpt2.finetune(sess,\n dataset=data,\n steps=steps,\n run_name=run_name,\n model_name='124M',\n restore_from='fresh',\n print_every=10,\n sample_every=200,\n save_every=500\n )\n\n\ndef text_generator(model_name, prefix, temperature, **kwargs):\n\n tf.reset_default_graph()\n sess = gpt2.start_tf_sess()\n gpt2.load_gpt2(sess, run_name=model_name)\n\n return gpt2.generate(sess,\n length=20,\n temperature=temperature,\n prefix=prefix,\n nsamples=5,\n batch_size=5\n )\n\ndata = pd.read_csv(file_name)\ncorpus = data['Fortune Cookie Quotes']\nstart_word = _random_prefix(corpus)\n\ngpt2_finetune(data=file_name, steps=100, run_name='run1')\ntext_generator(model_name='run1', prefix=start_word, temperature=1)\n" ]
[ [ "tensorflow.reset_default_graph", "pandas.read_csv" ] ]
ashishs-til/learn-tf
[ "6b7f01df63ec59bfc6c54ad90cd3e0fbb8edb7a4" ]
[ "hello3.py" ]
[ "import tensorflow as tf\n\nsess = tf.Session()\n\nW = tf.Variable([.3], tf.float32)\nb = tf.Variable([-.3], tf.float32)\nx = tf.placeholder(tf.float32)\nlinear_model = W * x + b\n\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nprint(sess.run([W,b]))\nprint(sess.run(linear_model, {x:[10,2,3,4]}))\n\ny = tf.placeholder(tf.float32)\nsq_deltas = tf.square(linear_model - y)\nloss = tf.reduce_sum(sq_deltas)\nprint(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))\n\nfixW = tf.assign(W, [-1.])\nfixb = tf.assign(b, [1.])\nsess.run([fixW, fixb])\nprint(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))\n" ]
[ [ "tensorflow.Variable", "tensorflow.reduce_sum", "tensorflow.assign", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.square", "tensorflow.Session" ] ]
protoget/espnet
[ "a52bdebb08558b63df23564d6e67dfcba8a41d78" ]
[ "tools/check_install.py" ]
[ "#!/usr/bin/env python3\n\n# Copyright 2018 Nagoya University (Tomoki Hayashi)\n# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\nimport argparse\nimport importlib\nimport logging\nimport sys\n\n\ndef main(args):\n parser = argparse.ArgumentParser()\n parser.add_argument('--no-cupy', action='store_true', default=False,\n help='Disable CUPY tests')\n args = parser.parse_args(args)\n\n # you should add the libraries which are not included in setup.py\n MANUALLY_INSTALLED_LIBRARIES = [\n ('espnet', None),\n ('kaldiio', None),\n ('matplotlib', None),\n ('torch', (\"0.4.1\", \"1.0.0\", \"1.0.1.post2\")),\n ('chainer', (\"6.0.0\")),\n ('chainer_ctc', None),\n ('warpctc_pytorch', (\"0.1.1\")),\n ('warprnnt_pytorch', (\"0.1\"))\n ]\n\n if not args.no_cupy:\n MANUALLY_INSTALLED_LIBRARIES.append(('cupy', (\"6.0.0\")))\n\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(levelname)s: %(message)s\")\n\n logging.info(\"python version = \" + sys.version)\n\n library_list = []\n library_list.extend(MANUALLY_INSTALLED_LIBRARIES)\n\n # check library availableness\n logging.info(\"library availableness check start.\")\n logging.info(\"# libraries to be checked = %d\" % len(library_list))\n is_correct_installed_list = []\n for idx, (name, version) in enumerate(library_list):\n try:\n importlib.import_module(name)\n logging.info(\"--> %s is installed.\" % name)\n is_correct_installed_list.append(True)\n except ImportError:\n logging.warning(\"--> %s is not installed.\" % name)\n is_correct_installed_list.append(False)\n logging.info(\"library availableness check done.\")\n logging.info(\"%d / %d libraries are correctly installed.\" % (\n sum(is_correct_installed_list), len(library_list)))\n\n if len(library_list) != sum(is_correct_installed_list):\n logging.info(\"please try to setup again and then re-run this script.\")\n sys.exit(1)\n\n # check library version\n num_version_specified = sum([True if v is not None else False for n, v in library_list])\n logging.info(\"library version check start.\")\n logging.info(\"# libraries to be checked = %d\" % num_version_specified)\n is_correct_version_list = []\n for idx, (name, version) in enumerate(library_list):\n if version is not None:\n # Note: temp. fix for warprnnt_pytorch\n # not found version with importlib\n if name == \"warprnnt_pytorch\":\n import pkg_resources\n vers = pkg_resources.get_distribution(name).version\n else:\n vers = importlib.import_module(name).__version__\n if vers != None:\n is_correct = vers in version\n if is_correct:\n logging.info(\"--> %s version is matched.\" % name)\n is_correct_version_list.append(True)\n else:\n logging.warning(\"--> %s version is not matched (%s is not in %s).\" % (\n name, vers, str(version)))\n is_correct_version_list.append(False)\n else:\n logging.info(\"--> %s has no version info, but version is specified.\" % name)\n logging.info(\"--> maybe it is better to reinstall the latest version.\")\n is_correct_version_list.append(False)\n logging.info(\"library version check done.\")\n logging.info(\"%d / %d libraries are correct version.\" % (\n sum(is_correct_version_list), num_version_specified))\n\n if sum(is_correct_version_list) != num_version_specified:\n logging.info(\"please try to setup again and then re-run this script.\")\n sys.exit(1)\n\n # check cuda availableness\n logging.info(\"cuda availableness check start.\")\n import chainer\n import torch\n try:\n assert torch.cuda.is_available()\n logging.info(\"--> cuda is available in torch.\")\n except AssertionError:\n logging.warning(\"--> it seems that cuda is not available in torch.\")\n try:\n assert torch.backends.cudnn.is_available()\n logging.info(\"--> cudnn is available in torch.\")\n except AssertionError:\n logging.warning(\"--> it seems that cudnn is not available in torch.\")\n try:\n assert chainer.backends.cuda.available\n logging.info(\"--> cuda is available in chainer.\")\n except AssertionError:\n logging.warning(\"--> it seems that cuda is not available in chainer.\")\n try:\n assert chainer.backends.cuda.cudnn_enabled\n logging.info(\"--> cudnn is available in chainer.\")\n except AssertionError:\n logging.warning(\"--> it seems that cudnn is not available in chainer.\")\n try:\n from cupy.cuda import nccl # NOQA\n logging.info(\"--> nccl is installed.\")\n except ImportError:\n logging.warning(\"--> it seems that nccl is not installed. multi-gpu is not enabled.\")\n logging.warning(\"--> if you want to use multi-gpu, please install it and then re-setup.\")\n try:\n assert torch.cuda.device_count() > 1\n logging.info(\"--> multi-gpu is available (#gpus = %d).\" % torch.cuda.device_count())\n except AssertionError:\n logging.warning(\"--> it seems that only single gpu is available.\")\n logging.warning('--> maybe your machine has only one gpu.')\n logging.info(\"cuda availableness check done.\")\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n" ]
[ [ "torch.cuda.device_count", "torch.backends.cudnn.is_available", "torch.cuda.is_available" ] ]
sumacm/fairattr
[ "72b56d718a6fbe695093d24715c75b9b485ab6b8" ]
[ "aif360/metrics/mdss/MDSS.py" ]
[ "from aif360.metrics.mdss.ScoringFunctions.ScoringFunction import ScoringFunction\nfrom aif360.metrics.mdss.generator import get_entire_subset, get_random_subset\n\nimport pandas as pd\nimport numpy as np\n\n\nclass MDSS(object):\n\n def __init__(self, scoring_function: ScoringFunction):\n self.scoring_function = scoring_function\n\n def get_aggregates(self, coordinates: pd.DataFrame, outcomes: pd.Series, probs: pd.Series,\n current_subset: dict, column_name: str, penalty: float):\n \"\"\"\n Conditioned on the current subsets of values for all other attributes,\n compute the summed outcome (observed_sum = \\sum_i y_i) and all probabilities p_i\n for each value of the current attribute.\n Also use additive linear-time subset scanning to compute the set of distinct thresholds\n for which different subsets of attribute values have positive scores. Note that the number\n of such thresholds will be linear rather than exponential in the arity of the attribute.\n\n :param coordinates: data frame containing having as columns the covariates/features\n :param probs: data series containing the probabilities/expected outcomes\n :param outcomes: data series containing the outcomes/observed outcomes\n :param current_subset: current subset to compute aggregates\n :param column_name: attribute name to scan over\n :param penalty: penalty coefficient\n :return: dictionary of aggregates, sorted thresholds (roots), observed sum of the subset, array of observed\n probabilities\n \"\"\"\n\n # compute the subset of records matching the current subgroup along all other dimensions\n # temp_df includes the covariates x_i, outcome y_i, and predicted probability p_i for each matching record\n if current_subset:\n to_choose = coordinates[current_subset.keys()].isin(current_subset).all(axis=1)\n temp_df = pd.concat([coordinates.loc[to_choose], outcomes[to_choose], probs[to_choose]], axis=1)\n else:\n temp_df = pd.concat([coordinates, outcomes, probs], axis=1)\n\n # these wil be used to keep track of the aggregate values and the distinct thresholds to be considered\n aggregates = {}\n thresholds = set()\n\n scoring_function = self.scoring_function\n\n # consider each distinct value of the given attribute (column_name)\n for name, group in temp_df.groupby(column_name):\n # compute the sum of outcomes \\sum_i y_i\n observed_sum = group.iloc[:, -2].sum()\n\n # all probabilities p_i\n probs = group.iloc[:, -1].values\n\n # compute q_min and q_max for the attribute value\n exist, q_mle, q_min, q_max = scoring_function.compute_qs(observed_sum, probs, penalty)\n\n # Add to aggregates, and add q_min and q_max to thresholds.\n # Note that thresholds is a set so duplicates will be removed automatically.\n if exist:\n aggregates[name] = {\n 'q_mle': q_mle,\n 'q_min': q_min,\n 'q_max': q_max,\n 'observed_sum': observed_sum,\n 'probs': probs\n }\n thresholds.update([q_min, q_max])\n\n # We also keep track of the summed outcomes \\sum_i y_i and the probabilities p_i for the case where _\n # all_ values of that attribute are considered (regardless of whether they contribute positively to score).\n # This is necessary because of the way we compute the penalty term: including all attribute values, equivalent\n # to ignoring the attribute, has the lowest penalty (of 0) and thus we need to score that subset as well.\n all_observed_sum = temp_df.iloc[:, -2].sum()\n all_probs = temp_df.iloc[:, -1].values\n\n return [aggregates, sorted(thresholds), all_observed_sum, all_probs]\n\n def choose_aggregates(self, aggregates: dict, thresholds: list, penalty: float, all_observed_sum: float,\n all_probs: list):\n \"\"\"\n Having previously computed the aggregates and the distinct q thresholds\n to consider in the get_aggregates function,we are now ready to choose the best\n subset of attribute values for the given attribute.\n For each range defined by these thresholds, we will choose all of the positive contributions,\n compute the MLE value of q, and the corresponding score.\n We then pick the best q and score over all of the ranges considered.\n\n :param aggregates: dictionary of aggregates. For each feature value, it has q_mle, q_min, q_max, observed_sum,\n and the probabilities\n :param thresholds: sorted thresholds (roots)\n :param penalty: penalty coefficient\n :param all_observed_sum: sum of observed binary outcomes for all i\n :param all_probs: data series containing all the probabilities/expected outcomes\n :return:\n \"\"\"\n # initialize\n best_score = 0\n best_names = []\n\n scoring_function = self.scoring_function\n\n # for each threshold\n for i in range(len(thresholds) - 1):\n threshold = (thresholds[i] + thresholds[i + 1]) / 2\n observed_sum = 0.0\n probs = []\n names = []\n\n # keep only the aggregates which have a positive contribution to the score in that q range\n # we must keep track of the sum of outcome values as well as all predicted probabilities\n for key, value in aggregates.items():\n if (value['q_min'] < threshold) & (value['q_max'] > threshold):\n names.append(key)\n observed_sum += value['observed_sum']\n probs = probs + value['probs'].tolist()\n\n if len(probs) == 0:\n continue\n\n # compute the MLE value of q, making sure to only consider the desired direction (positive or negative)\n probs = np.asarray(probs)\n current_q_mle = scoring_function.qmle(observed_sum, probs)\n\n # Compute the score for the given subset at the MLE value of q.\n # Notice that each included value gets a penalty, so the total penalty\n # is multiplied by the number of included values.\n current_interval_score = scoring_function.score(observed_sum, probs, penalty * len(names), current_q_mle)\n\n # keep track of the best score, best q, and best subset of attribute values found so far\n if current_interval_score > best_score:\n best_score = current_interval_score\n best_names = names\n\n # Now we also have to consider the case of including all attribute values,\n # including those that never make positive contributions to the score.\n # Note that the penalty term is 0 in this case. (We are neglecting penalties\n # from all other attributes, just considering the current attribute.)\n\n # compute the MLE value of q, making sure to only consider the desired direction (positive or negative)\n current_q_mle = scoring_function.qmle(all_observed_sum, all_probs)\n\n # Compute the score for the given subset at the MLE value of q.\n # Again, the penalty (for that attribute) is 0 when all attribute values are included.\n \n current_score = scoring_function.score(all_observed_sum, all_probs, 0, current_q_mle)\n\n # Keep track of the best score, best q, and best subset of attribute values found.\n # Note that if the best subset contains all values of the given attribute,\n # we return an empty list for best_names.\n if current_score > best_score:\n best_score = current_score\n best_names = []\n\n return [best_names, best_score]\n\n def score_current_subset(self, coordinates: pd.DataFrame, probs: pd.Series, outcomes: pd.Series,\n current_subset: dict, penalty: float):\n \"\"\"\n Just scores the subset without performing ALTSS.\n We still need to determine the MLE value of q.\n\n :param coordinates: data frame containing having as columns the covariates/features\n :param probs: data series containing the probabilities/expected outcomes\n :param outcomes: data series containing the outcomes/observed outcomes\n :param current_subset: current subset to be scored\n :param penalty: penalty coefficient\n :return: penalized score of subset\n \"\"\"\n\n # compute the subset of records matching the current subgroup along all dimensions\n # temp_df includes the covariates x_i, outcome y_i, and predicted probability p_i for each matching record\n if current_subset:\n to_choose = coordinates[current_subset.keys()].isin(current_subset).all(axis=1)\n temp_df = pd.concat([coordinates.loc[to_choose], outcomes[to_choose], probs[to_choose]], axis=1)\n else:\n temp_df = pd.concat([coordinates, outcomes, probs], axis=1)\n\n scoring_function = self.scoring_function\n\n # we must keep track of the sum of outcome values as well as all predicted probabilities\n observed_sum = temp_df.iloc[:, -2].sum()\n probs = temp_df.iloc[:, -1].values\n\n # compute the MLE value of q, making sure to only consider the desired direction (positive or negative)\n current_q_mle = scoring_function.qmle(observed_sum, probs)\n\n # total_penalty = penalty * sum of list lengths in current_subset\n total_penalty = 0\n for key, values in current_subset.items():\n total_penalty += len(values)\n\n total_penalty *= penalty\n\n # Compute and return the penalized score \n penalized_score = scoring_function.score(observed_sum, probs, total_penalty, current_q_mle)\n return penalized_score\n\n def scan(self, coordinates: pd.DataFrame, probs: pd.Series, outcomes: pd.Series, penalty: float,\n num_iters: int, verbose: bool = False, seed: int = 0):\n \"\"\"\n :param coordinates: data frame containing having as columns the covariates/features\n :param probs: data series containing the probabilities/expected outcomes\n :param outcomes: data series containing the outcomes/observed outcomes\n :param penalty: penalty coefficient\n :param num_iters: number of iteration\n :param verbose: logging flag\n :param seed: numpy seed. Default equals 0\n :return: [best subset, best score]\n \"\"\"\n np.random.seed(seed)\n\n # initialize\n best_subset = {}\n best_score = -1e10\n best_scores = []\n for i in range(num_iters):\n # flags indicates that the method has optimized over subsets for a given attribute.\n # The iteration ends when it cannot further increase score by optimizing over\n # subsets of any attribute, i.e., when all flags are 1.\n flags = np.empty(len(coordinates.columns))\n flags.fill(0)\n\n # Starting subset. Note that we start with all values for the first iteration\n # and random values for succeeding iterations.\n current_subset = get_entire_subset() if (i == 0) \\\n else get_random_subset(coordinates, np.random.rand(1).item(), 10)\n\n # score the entire population\n current_score = self.score_current_subset(\n coordinates=coordinates,\n probs=probs,\n outcomes=outcomes,\n penalty=penalty,\n current_subset=current_subset\n )\n\n while flags.sum() < len(coordinates.columns):\n\n # choose random attribute that we haven't scanned yet\n attribute_number_to_scan = np.random.choice(len(coordinates.columns))\n while flags[attribute_number_to_scan]:\n attribute_number_to_scan = np.random.choice(len(coordinates.columns))\n attribute_to_scan = coordinates.columns.values[attribute_number_to_scan]\n\n # clear current subset of attribute values for that subset\n if attribute_to_scan in current_subset:\n del current_subset[attribute_to_scan]\n\n # call get_aggregates and choose_aggregates to find best subset of attribute values\n aggregates, thresholds, all_observed_sum, all_probs = self.get_aggregates(\n coordinates=coordinates,\n outcomes=outcomes,\n probs=probs,\n current_subset=current_subset,\n column_name=attribute_to_scan,\n penalty=penalty\n )\n\n temp_names, temp_score = self.choose_aggregates(\n aggregates=aggregates,\n thresholds=thresholds,\n penalty=penalty,\n all_observed_sum=all_observed_sum,\n all_probs=all_probs\n )\n\n temp_subset = current_subset.copy()\n # if temp_names is not empty (or null)\n if temp_names:\n temp_subset[attribute_to_scan] = temp_names\n\n # Note that this call to score_current_subset ensures that\n # we are penalizing complexity for all attribute values.\n # The value of temp_score computed by choose_aggregates\n # above includes only the penalty for the current attribute.\n temp_score = self.score_current_subset(\n coordinates=coordinates,\n probs=probs,\n outcomes=outcomes,\n penalty=penalty,\n current_subset=temp_subset\n )\n\n # reset flags to 0 if we have improved score\n if temp_score > current_score + 1E-6:\n flags.fill(0)\n\n # TODO: confirm with Skyler: sanity check to make sure score has not decreased\n assert temp_score >= current_score - 1E-6, \\\n \"WARNING SCORE HAS DECREASED from %.3f to %.3f\" % (current_score, temp_score)\n\n flags[attribute_number_to_scan] = 1\n current_subset = temp_subset\n current_score = temp_score\n\n # print out results for current iteration\n if verbose:\n print(\"Subset found on iteration\", i + 1, \"of\", num_iters, \"with score\", current_score, \":\")\n print(current_subset)\n\n # update best_score and best_subset if necessary\n if current_score > best_score:\n best_subset = current_subset.copy()\n best_score = current_score\n\n if verbose:\n print(\"Best score is now\", best_score)\n\n elif verbose:\n print(\"Current score of\", current_score, \"does not beat best score of\", best_score)\n best_scores.append(best_score)\n return best_subset, best_score\n" ]
[ [ "numpy.asarray", "pandas.concat", "numpy.random.rand", "numpy.random.seed" ] ]
tlmakinen/deep21
[ "fb51d7e76f6059d5e9cd1ce5d19148a1375e23d3" ]
[ "train.py" ]
[ "\n# code for a UNet architecture for learning how to remove \n# the foreground from a 21ccm signal\n\nfrom __future__ import absolute_import, division, print_function\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom tensorflow import keras\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nimport time\nfrom tensorflow.python.client import device_lib\nimport pickle\nfrom sklearn.externals.joblib import dump, load\nimport h5py\nimport healpy as hp\nfrom tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau\nimport multiprocessing\nimport json\n# for parallelizing slurm jobs\nimport os, sys\n# import relevant unet model\nfrom unet import unet_3d\nfrom data_utils import dataloaders, my_callbacks\n\n\n########################################################################################################################\n\nconfig_file_path = './configs/configs_deep21.json'\n\nwith open(config_file_path) as f:\n configs = json.load(f)\n\n\n\n########################################################################################################################\n\n# DEFINE INPUT PARAMS\nrun_params = {\n 'model_num' : int(sys.argv[1]),\n 'load_model' : False,\n}\n\nparams = configs['unet_params']\npca_params = configs['pca_params'] \n# update parameter dict\nparams.update(run_params)\n\n########################################################################################################################\nimport tensorflow.keras.backend as K\ndef custom_loss(y_true, y_pred):\n sig = K.mean(K.std(y_true - y_pred)) + 1e-6 # for numerical stability\n return K.log(sig) + (keras.metrics.mse(y_true, y_pred) / (2*K.square(sig))) + 10\n\ndef custom_loss2(y_true, y_pred):\n return None\n\n########################################################################################################################\n\n# HELPER FUNCTIONS\ndef get_available_gpus():\n local_device_protos = device_lib.list_local_devices()\n return [x.name for x in local_device_protos if x.device_type == \"GPU\"]\n\ndef build_compile(net, params, N_GPU):\n\n if N_GPU > 1:\n\n if params['load_model']:\n print('loading weights')\n model = net.build_model()\n model.load_weights(out_dir + 'best_weights_{}.h5'.format(params['model_num']))\n #model = keras.utils.multi_gpu_model(model, gpus=N_GPU)\n\n else:\n #model = keras.utils.multi_gpu_model(net.build_model(), gpus=N_GPU)\n model = net.build_model()\n else:\n if params['load_model']:\n print('loading weights')\n model = keras.models.load_model(out_dir + 'best_model_{}.h5'.format(params['model_num']))\n \n else:\n model = net.build_model()\n\n \n # model.compile(optimizer=keras.optimizers.Adam(learning_rate=best_params['lr'],\n # beta_1=0.9, beta_2=0.999, amsgrad=False), loss=\"mse\",metrics=[\"mse\", custom_loss])\n model.compile(optimizer=tfa.optimizers.AdamW(learning_rate=params['lr'], weight_decay=params['wd'], \n beta_1=0.9, beta_2=0.999, amsgrad=False), \n loss=\"logcosh\",metrics=[\"mse\", \"logcosh\"]) \n\n return model\n\n########################################################################################################################\n\n# MAIN TRAINING FUNCTION\ndef train_unet(params, out_dir):\n # initialize model\n model = unet_3d.unet3D(n_filters=params['n_filters'], \n conv_width=params['conv_width'],\n nu_dim=params['nu_dim'],\n x_dim=params['x_dim'],\n network_depth=params['network_depth'], \n batchnorm_down=params['batchnorm_down'],\n batchnorm_in=params['batchnorm_in'], \n batchnorm_out=params['batchnorm_out'],\n batchnorm_up=params['batchnorm_up'], \n momentum=params['momentum']\n )\n \n # check available gpus\n N_GPU = len(get_available_gpus())\n\n if N_GPU > 1:\n strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()\n NUM_WORKERS = N_GPU\n N_BATCH = params['batch_size'] * NUM_WORKERS\n\n with strategy.scope():\n # Model building/compiling need to be within `strategy.scope()`.\n model = build_compile(model, params, N_GPU)\n\n print(\"Training using multiple GPUs..\")\n\n else:\n N_BATCH = params['batch_size']\n\n model = build_compile(model, params, N_GPU)\n print(\"Training using single GPU..\")\n\n print('-'*10, 'now training unet on ', N_GPU, ' GPUs, output writing to ', out_dir, '-'*10)\n print('\\n','-'*10, 'learning within frequency bins %d--%d'%(params['bin_min'], params['bin_max']-1), '-'*10)\n print('\\n', '-'*10, 'skipping every %d frequency, starting from nu=%d'%(params['nu_skip'], params['nu_start']), '-'*10)\n # create output directory\n if not os.path.exists(out_dir): \n os.mkdir(out_dir)\n\n\n # load data \n path = params['data_path']\n workers = 4\n sample_size = 70\n train_generator = dataloaders.dataLoaderDeep21(\n path,\n bin_min=params['bin_min'], \n bin_max=params['bin_max'], \n is_3d=True, data_type='train', \n batch_size=N_BATCH, num_sets=pca_params['num_sets'],\n nu_skip=params['nu_skip'],\n sample_size=sample_size,\n nwinds=192,\n stoch=True,\n aug=True)\n\n sample_size=9\n val_generator = dataloaders.dataLoaderDeep21(\n path,\n bin_min=params['bin_min'],\n bin_max=params['bin_max'], \n is_3d=True, data_type='val', \n batch_size=N_BATCH, num_sets=pca_params['num_sets'],\n nu_skip=params['nu_skip'],\n sample_size=sample_size,\n nwinds=192,\n stoch=True,\n aug=True)\n\n\n # DEFINE CALLBACKS \n # create checkpoint method to save model in the event of walltime timeout\n ## LATER: modify to compute 2D power spectrum\n best_fname = out_dir + 'best_model_%d.h5'%(params['model_num'])\n model_checkpoint = ModelCheckpoint(best_fname, monitor='val_mse', verbose=0,\n save_best_only=True, mode='auto', save_freq='epoch')\n best_fname = out_dir + 'best_weights_%d.h5'%(params['model_num'])\n weight_checkpoint = ModelCheckpoint(best_fname, monitor='val_mse', verbose=0, save_weights_only=True,\n save_best_only=True, mode='auto', save_freq='epoch')\n\n\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1,\n patience=10, min_lr=1e-15, verbose=1)\n\n clr = my_callbacks.CyclicLR(base_lr=1e-9, max_lr=params['lr'],\n step_size=560, mode='exp_range', gamma=0.99994)\n\n #transfer = my_callbacks.transfer(val_generator, 10, batch_size=N_BATCH, patience=1)\n\n N_EPOCHS = params['num_epochs']\n history = model.fit(train_generator, epochs=N_EPOCHS,validation_data=val_generator, \n use_multiprocessing=True, workers=workers, \n callbacks=[reduce_lr, model_checkpoint, weight_checkpoint])\n #test = np.concatenate([np.expand_dims(\n # np.load('/mnt/home/tmakinen/ceph/data_ska/bin1/test/pca3_sim%03d.npy'%(i+1)), \n # axis=-1) for i in range(90, 100)])\n # make test predictioni\n #y_pred = model.predict(test, batch_size=N_BATCH)\n \n # save transfer function computations\n return history, model#, y_pred\n\n########################################################################################################################\n\nif __name__ == '__main__':\n\n # create output directoryi\n out_dir = params['out_dir'] + 'unet_results_{}_{}/'.format(params['bin_min'], params['bin_max'])\n if not os.path.exists(out_dir): \n os.mkdir(out_dir)\n\n # make specific output dir for model #\n #out_dir = params['out_dir']\n \n\n t1 = time.time()\n\n history,model = train_unet(params, out_dir)\n\n t2 = time.time()\n\n print('total training time for ', params['num_epochs'], ' epochs : ', (t2-t1) / (60*60), ' hours')\n\n # save the results of the training\n # make outdirectories\n model_fname = 'model_{}.h5'.format(params['model_num'])\n history_fname = 'history_{}'.format(params['model_num'])\n weights_fname = \"weights_{}.h5\".format(params['model_num'])\n #transfer_fname = 'transfer'\n if params['load_model']:\n history_fname += '_continued'\n #transfer_fname += '_continued'\n\n outfile = out_dir + model_fname\n model.save(outfile)\n\n # save weights\n outfile = out_dir + weights_fname\n model.save_weights(outfile)\n\n # pickle the training history object\n outfile = out_dir + history_fname\t\n with open(outfile, 'wb') as file_pi:\n pickle.dump(history.history, file_pi)\n file_pi.close()\n\n # pickle the transfer object\n # outfile = out_dir + transfer_fname\t\n # with open(outfile, 'wb') as file_pi:\n # pickle.dump(transfer, file_pi)\n # file_pi.close()\n\n # compute y_pred using the best model weights\n #outfile = out_dir + 'y_pred'\n #np.save(outfile, y_pred)\n\n # save all model params for later reference\n outfile = out_dir + 'params'\n with open(outfile, 'wb') as file_pi:\n pickle.dump(params, file_pi)\n file_pi.close()\n" ]
[ [ "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.python.client.device_lib.list_local_devices", "tensorflow.keras.callbacks.ReduceLROnPlateau", "tensorflow.distribute.experimental.MultiWorkerMirroredStrategy", "tensorflow.keras.backend.square", "tensorflow.keras.backend.std", "tensorflow.keras.backend.log", "tensorflow.keras.metrics.mse" ] ]
vincentchen003/tvm
[ "b3e832a1f1eb73153fd71aa4842fc1938d728b52" ]
[ "tests/python/relay/aot/aot_test_utils.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport io\nimport struct\nimport numpy as np\nimport pathlib\nimport shutil\nimport subprocess\nimport tempfile\nimport tarfile\nimport json\n\n\nimport tvm\nfrom tvm import relay\nfrom tvm.relay import transform\nfrom tvm.contrib import utils, graph_executor\nfrom tvm.relay.backend import compile_engine\nfrom tvm.relay.backend.utils import mangle_module_name\nfrom tvm.contrib import utils\nfrom tvm.micro import export_model_library_format\n\n\ndef mangle_name(mod_name, name):\n mod_name = mangle_module_name(mod_name)\n return mod_name + \"_\" + name\n\n\ndef convert_to_relay(\n tflite_model_buf,\n input_data,\n input_node,\n):\n \"\"\"Convert a tflite model buffer in a Relay module\"\"\"\n\n def convert_to_list(x):\n if not isinstance(x, list):\n x = [x]\n return x\n\n # TFLite.Model.Model has changed to TFLite.Model from 1.14 to 2.1\n try:\n import tflite.Model\n\n tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)\n except AttributeError:\n import tflite\n\n tflite_model = tflite.Model.GetRootAsModel(tflite_model_buf, 0)\n except ImportError:\n raise ImportError(\"The tflite package must be installed\")\n\n input_data = convert_to_list(input_data)\n input_node = convert_to_list(input_node)\n\n shape_dict = {}\n dtype_dict = {}\n for i, e in enumerate(input_node):\n shape_dict[e] = input_data[i].shape\n dtype_dict[e] = input_data[i].dtype.name\n\n mod, params = relay.frontend.from_tflite(\n tflite_model, shape_dict=shape_dict, dtype_dict=dtype_dict\n )\n mod[\"main\"] = relay.build_module.bind_params_by_name(mod[\"main\"], params)\n return mod, params\n\n\ndef subprocess_with_stdout_and_log(cmd, cwd, logfile, stdout):\n \"\"\"\n This method runs a process and logs the output to both a log file and stdout\n \"\"\"\n with subprocess.Popen(\n cmd, cwd=cwd, shell=True, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT\n ) as proc, open(logfile, \"a\") as f:\n while True:\n data = proc.stdout.readline()\n result = proc.poll()\n # process is done if there is no data and the result is valid\n if data == b\"\" and result is not None:\n return int(result)\n if data:\n text = data.decode(\"ascii\", errors=\"backslashreplace\")\n f.write(text)\n if stdout:\n print(text, end=\"\")\n\n\ndef emit_main_network_definition(main_file, mod_name):\n main_file.write(f'extern tvm_model_t {mangle_name(mod_name,\"network\")};\\n')\n\n\ndef emit_main_prologue(main_file, workspace_bytes):\n # Add TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES because of memory alignment.\n main_file.write(\n f\"#define WORKSPACE_SIZE ({workspace_bytes} + TVM_RUNTIME_ALLOC_ALIGNMENT_BYTES)\\n\"\n )\n main_file.write(\"static uint8_t g_aot_memory[WORKSPACE_SIZE];\\n\")\n main_file.write(\"tvm_workspace_t app_workspace;\\n\")\n main_file.write(\n \"\"\"\ntvm_crt_error_t TVMPlatformMemoryAllocate(size_t num_bytes, DLDevice dev, void** out_ptr) {\n return StackMemoryManager_Allocate(&app_workspace, num_bytes, out_ptr);\n}\n\ntvm_crt_error_t TVMPlatformMemoryFree(void* ptr, DLDevice dev) {\n return StackMemoryManager_Free(&app_workspace,ptr);\n}\n\nvoid TVMPlatformAbort(tvm_crt_error_t code) { }\n\nvoid TVMLogf(const char* msg, ...) { }\n\nTVM_DLL int TVMFuncRegisterGlobal(const char* name, TVMFunctionHandle f, int override) {}\nint main(){\\n \n\"\"\"\n )\n\n\ndef emit_main_data(main_file, input_list, output_list, mod_name):\n for i in range(0, len(input_list)):\n main_file.write(f'#include \"{mangle_name(mod_name,\"input_data\")}{i}.h\"\\n')\n\n for i in range(0, len(output_list)):\n main_file.write(f'#include \"{mangle_name(mod_name,\"expected_output_data\")}{i}.h\"\\n')\n main_file.write(f'#include \"{mangle_name(mod_name,\"output_data\")}{i}.h\"\\n')\n\n\ndef emit_main_run(main_file, input_list, output_list, mod_name):\n num_outputs = len(output_list)\n num_inputs = len(input_list)\n\n main_file.write(f'void* {mangle_name(mod_name,\"inputs\")}[{num_inputs}] = {{ ')\n\n for i in range(0, len(input_list)):\n main_file.write(f'{mangle_name(mod_name,\"input_data\")}{i}, ')\n main_file.write(\"};\\n\")\n\n main_file.write(f'void* {mangle_name(mod_name,\"outputs\")}[{num_outputs}] = {{ ')\n for i in range(0, len(output_list)):\n main_file.write(f'{mangle_name(mod_name,\"output_data\")}{i}, ')\n main_file.write(\"};\\n\")\n main_file.write(\n f'tvm_runtime_run(&{mangle_name(mod_name,\"network\")}, {mangle_name(mod_name,\"inputs\")}, {mangle_name(mod_name,\"outputs\")});'\n )\n main_file.write(\"\\n\")\n\n\ndef emit_main_compare(main_file, output_list, mod_name):\n for i in range(0, len(output_list)):\n is_float_dtype = output_list[i].dtype == \"float32\"\n main_file.write(f'for (int i = 0; i<{mangle_name(mod_name,\"output_data\")}{i}_len; i++){{\\n')\n if is_float_dtype:\n main_file.write(\n f'if (fabs({mangle_name(mod_name,\"output_data\")}{i}[i]-{mangle_name(mod_name,\"expected_output_data\")}{i}[i]) > 0.001f){{\\n\\tprintf(\"ko\\\\n\");\\n\\treturn -1;}}\\n'\n )\n else:\n main_file.write(\n f'if ({mangle_name(mod_name,\"output_data\")}{i}[i]!={mangle_name(mod_name, \"expected_output_data\")}{i}[i]){{\\n\\tprintf(\"ko\\\\n\");\\n\\treturn -1;}}\\n'\n )\n main_file.write(\"}\\n\")\n\n\ndef emit_main_init_memory_manager(main_file):\n main_file.write(\"StackMemoryManager_Init(&app_workspace, g_aot_memory, WORKSPACE_SIZE);\")\n main_file.write(\"\\n\")\n\n\ndef emit_main_epilogue(main_file):\n main_file.write('printf(\"ok\\\\n\");')\n main_file.write(\"return 0;\")\n main_file.write(\"}\\n\")\n\n\ndef emit_main_common_includes(main_file):\n main_file.write(\"#include <stdio.h>\\n\")\n main_file.write(\"#include <math.h>\\n\")\n main_file.write('#include \"tvm/runtime/crt/internal/aot_executor/aot_executor.h\"\\n')\n main_file.write('#include \"tvm/runtime/crt/stack_allocator.h\"\\n')\n\n\ndef create_main(test_name, input_list_map, output_list_map, output_path, workspace_bytes):\n file_path = pathlib.Path(f\"{output_path}/\" + test_name).resolve()\n # create header file\n raw_path = file_path.with_suffix(\".c\").resolve()\n with open(raw_path, \"w\") as main_file:\n emit_main_common_includes(main_file)\n\n for k in input_list_map:\n emit_main_network_definition(main_file, k)\n\n emit_main_prologue(main_file, workspace_bytes)\n\n for k in input_list_map:\n emit_main_data(main_file, input_list_map[k], output_list_map[k], k)\n\n emit_main_init_memory_manager(main_file)\n\n for k in input_list_map:\n emit_main_run(main_file, input_list_map[k], output_list_map[k], k)\n\n for k in input_list_map:\n emit_main_compare(main_file, output_list_map[k], k)\n\n emit_main_epilogue(main_file)\n\n\ndef create_header_file(tensor_name, npy_data, output_path):\n \"\"\"\n This method generates a header file containing the data contained in the numpy array provided.\n It is used to capture the tensor data (for both inputs and expected outputs) to be bundled into the standalone application.\n \"\"\"\n file_path = pathlib.Path(f\"{output_path}/\" + tensor_name).resolve()\n # create header file\n raw_path = file_path.with_suffix(\".h\").resolve()\n with open(raw_path, \"w\") as header_file:\n header_file.write(\"#include <stddef.h>\\n\")\n header_file.write(\"#include <stdint.h>\\n\")\n header_file.write(\"#include <dlpack/dlpack.h>\\n\")\n header_file.write(f\"const size_t {tensor_name}_len = {npy_data.size};\\n\")\n\n if npy_data.dtype == \"int8\":\n header_file.write(f\"int8_t {tensor_name}[] =\")\n elif npy_data.dtype == \"int32\":\n header_file.write(f\"int32_t {tensor_name}[] = \")\n elif npy_data.dtype == \"uint8\":\n header_file.write(f\"uint8_t {tensor_name}[] = \")\n elif npy_data.dtype == \"float32\":\n header_file.write(f\"float {tensor_name}[] = \")\n\n header_file.write(\"{\")\n for i in np.ndindex(npy_data.shape):\n header_file.write(f\"{npy_data[i]}, \")\n header_file.write(\"};\\n\\n\")\n\n\ndef extract_main_workspace_sizebytes(extract_dir):\n with open(os.path.join(extract_dir, \"metadata.json\")) as json_f:\n metadata = json.load(json_f)\n return metadata[\"memory\"][\"functions\"][\"main\"][0][\"workspace_size_bytes\"]\n\n\ndef compile_and_run(\n mod,\n input_list,\n output_list,\n target_options,\n use_calculated_workspaces,\n params=None,\n workspace_byte_alignment=8,\n mod_name=None,\n enable_op_fusion=True,\n):\n \"\"\"\n This method verifies the generated source\n \"\"\"\n target = f\"c -runtime=c --link-params --executor=aot --workspace-byte-alignment={workspace_byte_alignment} {target_options}\"\n cflags = f\"-DTVM_RUNTIME_ALLOC_ALIGNMENT_BYTES={workspace_byte_alignment} \"\n\n # The calculated workspaces will not account for stack allocator tags used for debugging\n if not use_calculated_workspaces:\n cflags += \"-DTVM_CRT_STACK_ALLOCATOR_ENABLE_LIFO_CHECK \"\n\n config = {\"tir.disable_vectorize\": True}\n if not enable_op_fusion:\n config[\"relay.FuseOps.max_depth\"] = 1\n\n with tvm.transform.PassContext(opt_level=3, config=config):\n lib = tvm.relay.build(mod, target, target_host=target, params=params, mod_name=mod_name)\n\n tmp_path = utils.tempdir()\n tmp_dir = tmp_path.temp_dir\n\n base_path = os.path.join(tmp_dir, \"test\")\n build_path = os.path.join(base_path, \"build\")\n os.makedirs(build_path, exist_ok=True)\n\n tar_file = os.path.join(base_path, \"test.tar\")\n export_model_library_format(lib, tar_file)\n t = tarfile.open(tar_file)\n t.extractall(base_path)\n if use_calculated_workspaces:\n workspace_bytes = extract_main_workspace_sizebytes(base_path)\n else:\n workspace_bytes = 16384 * 1024\n\n for i in range(len(input_list)):\n create_header_file((f'{mangle_name(mod_name, \"input_data\")}{i}'), input_list[i], build_path)\n\n for i in range(len(output_list)):\n create_header_file(\n (f'{mangle_name(mod_name,\"output_data\")}{i}'),\n np.zeros(output_list[i].shape, output_list[i].dtype),\n build_path,\n )\n create_header_file(\n (f'{mangle_name(mod_name, \"expected_output_data\")}{i}'), output_list[i], build_path\n )\n\n create_main(\n \"test.c\", {mod_name: input_list}, {mod_name: output_list}, build_path, workspace_bytes\n )\n\n # Verify that compiles fine\n file_dir = os.path.dirname(os.path.abspath(__file__))\n makefile = os.path.join(file_dir, \"aot_test.mk\")\n make_cmd = (\n f\"make CFLAGS='{cflags}' -f {makefile} build_dir=\"\n + build_path\n + f\" TVM_ROOT={file_dir}/../../../..\"\n )\n\n compile_log_path = os.path.join(build_path, \"test_compile.log\")\n ret = subprocess_with_stdout_and_log(make_cmd, \".\", compile_log_path, False)\n assert ret == 0\n\n # Verify that runs fine\n run_log_path = os.path.join(build_path, \"test_run.log\")\n ret = subprocess_with_stdout_and_log(\"./aot_test_runner\", build_path, run_log_path, False)\n assert ret == 0\n\n\ndef compile_and_run_multiple_models(\n mod_map, input_list_map, output_list_map, target_options, param_map\n):\n \"\"\"\n This method verifies the generated source\n \"\"\"\n target = f\"c -runtime=c --link-params --executor=aot {target_options}\"\n tmp_path = utils.tempdir()\n tmp_dir = tmp_path.temp_dir\n\n base_path = os.path.join(tmp_dir, \"test\")\n build_path = os.path.join(base_path, \"build\")\n os.makedirs(build_path, exist_ok=True)\n for mod_name, mod in mod_map.items():\n\n with tvm.transform.PassContext(opt_level=3, config={\"tir.disable_vectorize\": True}):\n lib = tvm.relay.build(\n mod, target, target_host=target, params=param_map[mod_name], mod_name=mod_name\n )\n\n tar_file = os.path.join(base_path, \"test.tar\")\n export_model_library_format(lib, tar_file)\n t = tarfile.open(tar_file)\n t.extractall(base_path)\n\n input_list = input_list_map[mod_name]\n output_list = output_list_map[mod_name]\n\n for i in range(len(input_list_map[mod_name])):\n create_header_file(\n (f'{mangle_name(mod_name,\"input_data\")}{i}'), input_list[i], build_path\n )\n\n for i in range(len(output_list_map[mod_name])):\n create_header_file(\n (f'{mangle_name(mod_name,\"output_data\")}{i}'),\n np.zeros(output_list[i].shape, output_list[i].dtype),\n build_path,\n )\n create_header_file(\n (f'{mangle_name(mod_name,\"expected_output_data\")}{i}'), output_list[i], build_path\n )\n\n create_main(\"test.c\", input_list_map, output_list_map, build_path, workspace_bytes=16384 * 1024)\n\n # Verify that compiles fine\n file_dir = os.path.dirname(os.path.abspath(__file__))\n makefile = os.path.join(file_dir, \"aot_test.mk\")\n make_cmd = f\"make -f {makefile} build_dir=\" + build_path + f\" TVM_ROOT={file_dir}/../../../..\"\n\n compile_log_path = os.path.join(build_path, \"test_compile.log\")\n ret = subprocess_with_stdout_and_log(make_cmd, \".\", compile_log_path, False)\n assert ret == 0\n\n # Verify that runs fine\n run_log_path = os.path.join(build_path, \"test_run.log\")\n ret = subprocess_with_stdout_and_log(\"./aot_test_runner\", build_path, run_log_path, False)\n assert ret == 0\n\n\ndef generate_ref_data(mod, input_data, params=None, target=\"llvm\"):\n \"\"\"Generate reference data through executing the relay module\"\"\"\n compile_engine.get().clear()\n with tvm.transform.PassContext(opt_level=3):\n lib = relay.build(mod, target=target, params=params)\n\n lib_name = \"mod.so\"\n temp = utils.tempdir()\n lib_path = temp.relpath(lib_name)\n lib.export_library(lib_path)\n lib = tvm.runtime.load_module(lib_path)\n grt_mod = graph_executor.GraphModule(lib[\"default\"](tvm.cpu()))\n grt_mod.set_input(**input_data)\n grt_mod.run()\n output_count = grt_mod.get_num_outputs()\n out = [grt_mod.get_output(i).numpy() for i in range(output_count)]\n return out\n" ]
[ [ "numpy.ndindex", "numpy.zeros" ] ]
stw666/oneflow
[ "186a7c5e9c99626b03861ab61ee93eb723aa3d92" ]
[ "python/oneflow/test/modules/test_activation.py" ]
[ "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\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.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\n\nfrom oneflow.test_utils.automated_test_util import *\nfrom scipy import special\nfrom test_util import GenArgList\n\nimport oneflow as flow\nimport oneflow.unittest\n\n\[email protected]_unless_1n1d()\nclass TestReLUModule(flow.unittest.TestCase):\n @autotest(check_graph=True)\n def test_relu_module_with_random_data(test_case):\n m = torch.nn.ReLU()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n @autotest(auto_backward=False, check_graph=True)\n def test_relu_module_with_0_size_data(test_case):\n m = torch.nn.ReLU()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor(4, 2, 3, 0, 3).to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestReLU6Module(flow.unittest.TestCase):\n @autotest(check_graph=True)\n def test_relu6_module_with_random_data(test_case):\n m = torch.nn.ReLU6()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n @autotest(auto_backward=False, check_graph=True)\n def test_relu6_module_with_0_size_data(test_case):\n m = torch.nn.ReLU6()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor(4, 2, 3, 0, 3).to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestTanh(flow.unittest.TestCase):\n @autotest()\n def test_tanh_module_with_random_data(test_case):\n m = torch.nn.Tanh()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n @autotest(auto_backward=False, check_graph=True)\n def test_tanh_module_with_0_size_data(test_case):\n m = torch.nn.Tanh()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor(4, 2, 3, 0, 3).to(device)\n y = m(x)\n return y\n\n @autotest(check_graph=False)\n def test_flow_tanh_with_random_data(test_case):\n device = random_device()\n x = random_pytorch_tensor().to(device)\n y = torch.tanh(x)\n return y\n\n @autotest(auto_backward=False, check_graph=True)\n def test_flow_tanh_with_0_size_data(test_case):\n device = random_device()\n x = random_pytorch_tensor(4, 2, 3, 0, 3).to(device)\n y = torch.tanh(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestELUModule(flow.unittest.TestCase):\n @autotest()\n def test_elu_module_with_random_data(test_case):\n m = torch.nn.ELU(alpha=random() | nothing())\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n @autotest(auto_backward=False, check_graph=True)\n def test_elu_module_with_0_size_data(test_case):\n m = torch.nn.ELU(alpha=random() | nothing())\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor(4, 2, 3, 0, 3).to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestCELUModule(flow.unittest.TestCase):\n @autotest()\n def test_celu_module_with_random_data(test_case):\n m = torch.nn.CELU(alpha=random() | nothing())\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n @autotest(auto_backward=False, check_graph=True)\n def test_celu_module_with_0_size_data(test_case):\n m = torch.nn.CELU(alpha=random() | nothing())\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor(4, 2, 3, 0, 3).to(device)\n y = m(x)\n return y\n\n @autotest()\n def test_inplace_celu_module(test_case):\n m = torch.nn.CELU(alpha=random() | nothing(), inplace=True)\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = x + 0.001\n m(y)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestGelu(flow.unittest.TestCase):\n @autotest()\n def test_gelu_module_with_random_data(test_case):\n m = torch.nn.GELU()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestSigmoidModule(flow.unittest.TestCase):\n @autotest()\n def test_sigmoid_module_with_random_data(test_case):\n m = torch.nn.Sigmoid()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n @autotest(check_graph=False)\n def test_sigmoid_flow_with_random_data(test_case):\n device = random_device()\n x = random_pytorch_tensor().to(device)\n y = torch.sigmoid(x)\n return y\n\n @autotest(check_graph=False)\n def test_sigmoid_tensor_with_random_data(test_case):\n device = random_device()\n x = random_pytorch_tensor().to(device)\n y = x.sigmoid()\n return y\n\n\[email protected]_unless_1n1d()\nclass TestHardsigmoidModule(flow.unittest.TestCase):\n def test_hardsigmoid_inplace(test_case):\n def np_hardsigmoid(input):\n input_shape = input.shape\n input = input.flatten()\n elem_cnt = input.size\n _zero = np.zeros_like(input)\n for i in range(elem_cnt):\n if input[i] >= 3:\n _zero[i] = 1\n elif input[i] <= -3:\n _zero[i] = 0\n else:\n _zero[i] = input[i] / 6 + 0.5\n np_hsigmoid_out = np.reshape(_zero, newshape=input_shape)\n return np.array(np_hsigmoid_out)\n\n def test_hardsigmoid_inplace_impl(test_case, shape, device):\n x = flow.tensor(\n np.random.randn(*shape),\n dtype=flow.float32,\n device=flow.device(device),\n requires_grad=True,\n )\n x_inplace = x + 1\n np_out = np_hardsigmoid(x_inplace.numpy())\n\n id_old = id(x_inplace)\n y_inplace = flow.nn.functional.hardsigmoid(x_inplace, inplace=True)\n\n test_case.assertEqual(id_old, id(y_inplace))\n test_case.assertTrue(np.allclose(y_inplace.numpy(), np_out, 1e-5, 1e-5))\n\n arg_dict = OrderedDict()\n arg_dict[\"shape\"] = [(2, 3), (2, 3, 4), (2, 3, 4, 5)]\n arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n for arg in GenArgList(arg_dict):\n test_hardsigmoid_inplace_impl(test_case, *arg)\n\n @autotest()\n def test_hardsigmoid_module_with_random_data(test_case):\n m = torch.nn.Hardsigmoid()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n @autotest(check_graph=True)\n def test_functional_hardsigmoid_with_random_data(test_case):\n device = random_device()\n x = random_pytorch_tensor().to(device)\n y = torch.nn.functional.hardsigmoid(x, random_bool())\n return y\n\n\ndef test_softmax(batch_size: int, log_softmax: bool = False):\n num_dims = random(low=1, high=5).to(int)\n m = torch.nn.Softmax(dim=random(low=0, high=num_dims).to(int) | nothing())\n if log_softmax:\n m = torch.nn.LogSoftmax(dim=random(low=0, high=num_dims).to(int) | nothing())\n m.train(random())\n device = random_device()\n m.to(device)\n x = (\n random_pytorch_tensor(ndim=num_dims).to(device)\n if batch_size < 0\n else random_pytorch_tensor(ndim=num_dims, dim0=batch_size).to(device)\n )\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestSoftmax(flow.unittest.TestCase):\n @autotest(check_graph=False)\n def test_softmax_module_with_random_data(test_case):\n return test_softmax(batch_size=-1, log_softmax=False)\n\n @autotest(check_graph=False)\n def test_softmax_module_with_batch_size_equal_1024(test_case):\n return test_softmax(batch_size=1024, log_softmax=False)\n\n @autotest(n=5, check_graph=False)\n def test_softmax_module_with_batch_size_equal_5120(test_case):\n return test_softmax(batch_size=5120, log_softmax=False)\n\n @autotest(n=2, check_graph=False)\n def test_softmax_module_with_batch_size_equal_10240(test_case):\n return test_softmax(batch_size=10240, log_softmax=False)\n\n\[email protected]_unless_1n1d()\nclass TestLogSoftmaxModule(flow.unittest.TestCase):\n @autotest(check_graph=False)\n def test_logsoftmax_module_with_random_data(test_case):\n return test_softmax(batch_size=-1, log_softmax=True)\n\n @autotest()\n def test_softmax_module_with_batch_size_equal_1024(test_case):\n return test_softmax(batch_size=1024, log_softmax=True)\n\n @autotest(n=5, check_graph=False)\n def test_softmax_module_with_batch_size_equal_5120(test_case):\n return test_softmax(batch_size=5120, log_softmax=True)\n\n @autotest(n=2, check_graph=False)\n def test_softmax_module_with_batch_size_equal_10240(test_case):\n return test_softmax(batch_size=10240, log_softmax=True)\n\n\[email protected]_unless_1n1d()\nclass TestLogSigmoidModule(flow.unittest.TestCase):\n @autotest()\n def test_logsigmoid_module_with_random_data(test_case):\n m = torch.nn.LogSigmoid()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\ndef numpy_softplus(x, beta, threshold):\n return np.where(\n x * beta > threshold, x, 1.0 / beta * np.log(1.0 + np.exp(beta * x))\n )\n\n\ndef _test_softplus(test_case, device):\n m = flow.nn.Softplus()\n arr = np.random.randn(2, 3, 4, 5)\n np_out = numpy_softplus(arr, 1.0, 20)\n x = flow.tensor(arr, device=flow.device(device))\n of_out = m(x)\n test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-05, 1e-05))\n\n\ndef _test_softplus_beta(test_case, device):\n m = flow.nn.Softplus(beta=1.11)\n arr = np.random.randn(2, 3, 4, 5)\n np_out = numpy_softplus(arr, 1.11, 20)\n x = flow.tensor(arr, device=flow.device(device))\n of_out = m(x)\n test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-05, 1e-05))\n\n\ndef _test_softplus_threshold(test_case, device):\n m = flow.nn.Softplus(beta=1.11, threshold=1.55)\n arr = np.random.randn(2, 3, 4, 5)\n np_out = np.where(\n arr * 1.11 > 1.55, arr, 1.0 / 1.11 * np.log(1.0 + np.exp(1.11 * arr))\n )\n np_out = numpy_softplus(arr, 1.11, 1.55)\n x = flow.tensor(arr, device=flow.device(device))\n of_out = m(x)\n test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-05, 1e-05))\n\n\ndef _test_softplus_backward(test_case, device):\n m = flow.nn.Softplus()\n arr = np.array([1.0, 2.0, 21.0, 20.0, 4.0])\n x = flow.tensor(arr, device=flow.device(device), requires_grad=True)\n of_out = m(x)\n of_out = of_out.sum()\n of_out.backward()\n np_grad = [0.7310585786300049, 0.8807970779778824, 1.0, 1.0, 0.9820137900379085]\n test_case.assertTrue(np.allclose(x.grad.numpy(), np_grad, 1e-05, 1e-05))\n\n\[email protected]_unless_1n1d()\nclass TestSoftplusModule(flow.unittest.TestCase):\n def test_softplus(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_fun\"] = [\n _test_softplus,\n _test_softplus_beta,\n _test_softplus_threshold,\n _test_softplus_backward,\n ]\n arg_dict[\"device\"] = [\"cpu\"]\n for arg in GenArgList(arg_dict):\n arg[0](test_case, *arg[1:])\n\n @unittest.skip(\"pytorch softplus backward has bug\")\n @autotest()\n def test_softplus_module_with_random_data(test_case):\n m = torch.nn.Softplus(beta=random() | nothing(), threshold=random() | nothing())\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestHardswishModule(flow.unittest.TestCase):\n @autotest()\n def test_hardswish_module_with_random_data(test_case):\n m = torch.nn.Hardswish()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestHardtanhModule(flow.unittest.TestCase):\n @autotest()\n def test_hardtanh_module_with_random_data(test_case):\n m = torch.nn.Hardtanh(\n min_val=random().to(float) | nothing(),\n max_val=random().to(float) | nothing(),\n )\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor(ndim=4).to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestLeakyReLUModule(flow.unittest.TestCase):\n @autotest()\n def test_leakyrelu_module_with_random_data(test_case):\n m = torch.nn.LeakyReLU(negative_slope=random() | nothing())\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestMishModule(flow.unittest.TestCase):\n @autotest(n=5)\n def test_mish_module_with_random_data(test_case):\n m = torch.nn.Mish()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestSiluModule(flow.unittest.TestCase):\n @autotest(n=5)\n def test_silu_module_with_random_data(test_case):\n m = torch.nn.SiLU()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestSeluModule(flow.unittest.TestCase):\n @autotest(n=5)\n def test_selu_module_with_random_data(test_case):\n m = torch.nn.SELU()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected](\"still have error in ci test\")\nclass TestSoftsignModule(flow.unittest.TestCase):\n @autotest(n=5)\n def test_softsign_module_with_random_data(test_case):\n m = torch.nn.Softsign()\n m.train(random())\n device = random_device()\n m.to(device)\n x = random_pytorch_tensor().to(device)\n y = m(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestReluFunction(flow.unittest.TestCase):\n @autotest(check_graph=False)\n def test_flow_relu_with_random_data(test_case):\n device = random_device()\n x = random_pytorch_tensor(ndim=2, dim1=3).to(device)\n y = torch.relu(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestRelu6Function(flow.unittest.TestCase):\n @autotest(check_graph=False)\n def test_flow_nn_functional_relu6_with_random_data(test_case):\n device = random_device()\n x = random_pytorch_tensor(ndim=2, dim1=3).to(device)\n y = torch.nn.functional.relu6(x)\n return y\n\n\[email protected]_unless_1n1d()\nclass TestLogSigmoidFunction(flow.unittest.TestCase):\n @autotest(check_graph=False)\n def test_flow_nn_functional_logsigmoid_with_random_data(test_case):\n device = random_device()\n x = random_pytorch_tensor(ndim=2, dim1=3).to(device)\n y = torch.nn.functional.logsigmoid(x)\n return y\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.reshape", "numpy.random.randn", "numpy.zeros_like", "numpy.exp", "numpy.array" ] ]
ayansiddiqui007/jina
[ "2a764410de47cc11e53c8f652ea1095d5dab5435" ]
[ "jina/executors/indexers/keyvalue.py" ]
[ "__copyright__ = \"Copyright (c) 2020 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nimport mmap\nfrom typing import Iterator, Optional\n\nimport numpy as np\n\nfrom . import BaseKVIndexer\nfrom ...proto import jina_pb2, uid\n\n\nclass BinaryPbIndexer(BaseKVIndexer):\n class WriteHandler:\n def __init__(self, path, mode):\n self.body = open(path, mode)\n self.header = open(path + '.head', mode)\n\n def close(self):\n self.body.close()\n self.header.close()\n\n def flush(self):\n self.body.flush()\n self.header.flush()\n\n class ReadHandler:\n def __init__(self, path):\n with open(path + '.head', 'rb') as fp:\n tmp = np.frombuffer(fp.read(), dtype=np.int64).reshape([-1, 4])\n self.header = {r[0]: r[1:] for r in tmp}\n self._body = open(path, 'r+b')\n self.body = self._body.fileno()\n\n def close(self):\n self._body.close()\n\n def get_add_handler(self):\n # keep _start position as in pickle serialization\n return self.WriteHandler(self.index_abspath, 'ab')\n\n def get_create_handler(self):\n self._start = 0 # override _start position\n return self.WriteHandler(self.index_abspath, 'wb')\n\n def get_query_handler(self):\n return self.ReadHandler(self.index_abspath)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._total_byte_len = 0\n self._start = 0\n self._page_size = mmap.ALLOCATIONGRANULARITY\n\n def add(self, keys: Iterator[int], values: Iterator[bytes], *args, **kwargs):\n for key, value in zip(keys, values):\n l = len(value) #: the length\n p = int(self._start / self._page_size) * self._page_size #: offset of the page\n r = self._start % self._page_size #: the remainder, i.e. the start position given the offset\n self.write_handler.header.write(\n np.array(\n (key, p, r, r + l),\n dtype=np.int64\n ).tobytes()\n )\n self._start += l\n self.write_handler.body.write(value)\n self._size += 1\n # print(f'l: {l} p: {p} r: {r} r+l: {r + l} size: {self._size}')\n\n def query(self, key: int) -> Optional['jina_pb2.Document']:\n # print(f'key={key}')\n pos_info = self.query_handler.header.get(key, None)\n if pos_info is not None:\n p, r, l = pos_info\n with mmap.mmap(self.query_handler.body, offset=p, length=l) as m:\n return m[r:]\n\n\nclass DataURIPbIndexer(BinaryPbIndexer):\n \"\"\"Shortcut for :class:`DocPbIndexer` equipped with ``requests.on`` for storing doc-level protobuf and data uri info,\n differ with :class:`ChunkPbIndexer` only in ``requests.on`` \"\"\"\n" ]
[ [ "numpy.array" ] ]
zouhairm/plotly.py
[ "e53e626d59495d440341751f60aeff73ff365c28" ]
[ "packages/python/plotly/plotly/matplotlylib/mplexporter/tests/test_basic.py" ]
[ "import matplotlib\nimport numpy as np\nfrom distutils.version import LooseVersion\nfrom nose.plugins.skip import SkipTest\nfrom numpy.testing import assert_warns\n\nfrom ..exporter import Exporter\nfrom ..renderers import FakeRenderer, FullFakeRenderer\nfrom . import plt\n\n\ndef fake_renderer_output(fig, Renderer):\n renderer = Renderer()\n exporter = Exporter(renderer)\n exporter.run(fig)\n return renderer.output\n\n\ndef _assert_output_equal(text1, text2):\n for line1, line2 in zip(text1.strip().split(), text2.strip().split()):\n assert line1 == line2\n\n\ndef test_lines():\n fig, ax = plt.subplots()\n ax.plot(range(20), '-k')\n\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path with 20 vertices\n closing axes\n closing figure\n \"\"\")\n\n _assert_output_equal(fake_renderer_output(fig, FullFakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw line with 20 points\n closing axes\n closing figure\n \"\"\")\n\n\ndef test_markers():\n fig, ax = plt.subplots()\n ax.plot(range(2), 'ok')\n\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path with 25 vertices\n draw path with 25 vertices\n closing axes\n closing figure\n \"\"\")\n\n _assert_output_equal(fake_renderer_output(fig, FullFakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw 2 markers\n closing axes\n closing figure\n \"\"\")\n\n\ndef test_path_collection():\n fig, ax = plt.subplots()\n ax.scatter(range(3), range(3))\n\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path with 25 vertices\n draw path with 25 vertices\n draw path with 25 vertices\n closing axes\n closing figure\n \"\"\")\n\n _assert_output_equal(fake_renderer_output(fig, FullFakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path collection with 3 offsets\n closing axes\n closing figure\n \"\"\")\n\n\ndef test_text():\n fig, ax = plt.subplots()\n ax.set_xlabel(\"my x label\")\n ax.set_ylabel(\"my y label\")\n ax.set_title(\"my title\")\n ax.text(0.5, 0.5, \"my text\")\n\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw text 'my text' None\n draw text 'my x label' xlabel\n draw text 'my y label' ylabel\n draw text 'my title' title\n closing axes\n closing figure\n \"\"\")\n\n\ndef test_path():\n fig, ax = plt.subplots()\n ax.add_patch(plt.Circle((0, 0), 1))\n ax.add_patch(plt.Rectangle((0, 0), 1, 2))\n\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path with 25 vertices\n draw path with 4 vertices\n closing axes\n closing figure\n \"\"\")\n\ndef test_Figure():\n \"\"\" if the fig is not associated with a canvas, FakeRenderer shall\n not fail. \"\"\"\n fig = plt.Figure()\n ax = fig.add_subplot(111)\n ax.add_patch(plt.Circle((0, 0), 1))\n ax.add_patch(plt.Rectangle((0, 0), 1, 2))\n\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path with 25 vertices\n draw path with 4 vertices\n closing axes\n closing figure\n \"\"\")\n\ndef test_multiaxes():\n fig, ax = plt.subplots(2)\n ax[0].plot(range(4))\n ax[1].plot(range(10))\n\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path with 4 vertices\n closing axes\n opening axes\n draw path with 10 vertices\n closing axes\n closing figure\n \"\"\")\n\n\ndef test_image():\n # Test fails for matplotlib 1.5+ because the size of the image\n # generated by matplotlib has changed.\n if LooseVersion(matplotlib.__version__) >= LooseVersion('1.5.0'):\n raise SkipTest(\"Test fails for matplotlib version > 1.5.0\");\n np.random.seed(0) # image size depends on the seed\n fig, ax = plt.subplots(figsize=(2, 2))\n ax.imshow(np.random.random((10, 10)),\n cmap=plt.cm.jet, interpolation='nearest')\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw image of size 1240 \n closing axes\n closing figure\n \"\"\")\n\n\ndef test_legend():\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3], label='label')\n ax.legend().set_visible(False)\n _assert_output_equal(fake_renderer_output(fig, FakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw path with 3 vertices\n opening legend\n closing legend\n closing axes\n closing figure\n \"\"\")\n\n\ndef test_legend_dots():\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3], label='label')\n ax.plot([2, 2, 2], 'o', label='dots')\n ax.legend().set_visible(True)\n _assert_output_equal(fake_renderer_output(fig, FullFakeRenderer),\n \"\"\"\n opening figure\n opening axes\n draw line with 3 points\n draw 3 markers\n opening legend\n draw line with 2 points\n draw text 'label' None\n draw 2 markers\n draw text 'dots' None\n draw path with 4 vertices\n closing legend\n closing axes\n closing figure\n \"\"\")\n\n\ndef test_blended():\n fig, ax = plt.subplots()\n ax.axvline(0)\n #assert_warns(UserWarning, fake_renderer_output, fig, FakeRenderer)\n" ]
[ [ "numpy.random.random", "numpy.random.seed" ] ]
ramism16/opencv-image-processing
[ "544734571797e578bc66fca509893c41ca537f30" ]
[ "RamisMustafa_224248_DIPLab11/ramismustafa_224248_diplab11_task1.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"RamisMustafa_224248_DIPLab11.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1mzul1vb4ktOngYvV9pJ5yzGEMB1hgYr0\n\n Importing modules (and mounting drive)\n\"\"\"\n\nimport cv2\nimport numpy as np\n#from google.colab.patches import cv2_imshow\nprint(\"modules imported\")\n\n#from google.colab import drive\n#drive.mount('/content/drive')\n\n\"\"\"\n Reading the example image (smarties)\n\"\"\"\n#reading the image in color\nsmarties = cv2.imread(\"smarties.jpg\", cv2.IMREAD_COLOR)\n\n#creating a copy of the image\nsmartiesCopy = smarties.copy()\n\n#displaying the input image\nprint(\"Smarties image\\n\")\n\ncv2.imshow(\"Smarties\", smarties)\nprint(\"Image in the output window\")\ncv2.waitKey(1500)\n\n#cv2_imshow(smarties)\n\n\"\"\"\n1: Isolating green smarties from the image\n\n Converting BGR image to HSV\n\"\"\"\n#converting the image to HSV\nsmartiesHSV = cv2.cvtColor(smarties, cv2.COLOR_BGR2HSV)\n\n#displaying the converted color space image\nprint(\"Smarties HSV image\\n\")\ncv2.imshow(\"Smarties\", smartiesHSV)\nprint(\"\\nHSV image in the output window\\n\")\ncv2.waitKey(1500)\n\n#printing one of the pixel values from the HSV image\nprint(smartiesHSV[50][50])\ncv2.destroyAllWindows()\n\n\"\"\"\n Creating and using trackbars to control HSV channels' limits\n\"\"\"\n\n#create a named window container for the trackbars first\nwname = \"HSV Channels Trackbars\"\ntrackbarWindow = cv2.namedWindow(wname)\n\n#create a copy of the HSV image\nsmartiesHSVCopy = smartiesHSV.copy()\n\n#creating HSV Channels limits varaibles\nlowH = highH = lowS = highS = lowV = highV = 0\n\n#creating a switch variable for trackbar toggling\nswitch = 0\n\n#creating a blank callable function to pass the onChange argument in cv2.inRange()\ndef dont(x):\n pass\n\n#creating trackbars for channels and switch\n#values for the minimum and maximum were based on true HSV values earlier [360,100,100]\n#but traded with cv2 8-bit values, because practically changes will be made in reflected in those\ncv2.createTrackbar(\"Low Hue\", wname, 0, 255, dont)\ncv2.createTrackbar(\"High Hue\",wname, 0, 255, dont)\ncv2.createTrackbar(\"Low Sat\", wname, 0, 255, dont)\ncv2.createTrackbar(\"High Sat\",wname, 0, 255, dont)\ncv2.createTrackbar(\"Low Value\", wname, 0, 255, dont)\ncv2.createTrackbar(\"High Value\",wname, 0, 255, dont)\ncv2.createTrackbar(\"Switch 0/1\", wname, 0, 1, dont)\n\nprint(\"\\nCreating trackbar and image window\\n\")\n\n#getting and assigning the positions of the four trackbars\nwhile(True):\n #1 ms refresh delay in image frame display and break loop on ESC keyboard interrupt\n #waitkey() & 0XFF returns numlock-state bitwise-separated key input code (for 64-bit machines)\n cv2.imshow(\"Smarties HSV\", smartiesHSVCopy)\n cv2.imshow(\"Smarties (2)\", smartiesCopy)\n key = cv2.waitKey(1) & 0xFF\n if key == 27:\n print(\"Trackbars interrupted\")\n break\n\n #get trackbar positions for channel limits\n switch = cv2.getTrackbarPos(\"Switch 0/1\", wname)\n lowH = cv2.getTrackbarPos(\"Low Hue\", wname)\n highH = cv2.getTrackbarPos(\"High Hue\", wname)\n lowS = cv2.getTrackbarPos(\"Low Sat\", wname)\n highS = cv2.getTrackbarPos(\"High Sat\", wname)\n lowV = cv2.getTrackbarPos(\"Low Value\", wname)\n highV = cv2.getTrackbarPos(\"High Value\", wname)\n\n #high and low value arrays\n low = np.array([lowH, lowS, lowV])\n high = np.array([highH, highS, highV])\n\n #make changes to the image\n #if switched trackbars\n if switch:\n #flags array from cv2.inRange(src, lowerB, upperb)\n #lower[0] <_ src[0] <_ higher[0] and lower[1] ...\n #terminal print bounds when switch is on\n print(low,high)\n #flags from original image as the copy is changed in each iteration\n dstFlags = cv2.inRange(smartiesHSV, low, high)\n #bitwise-and on numpy arrays behaves much the same like logical-and\n smartiesCopy = cv2.bitwise_and(smarties, smarties, mask=dstFlags)\n\ncv2.destroyAllWindows()\n" ]
[ [ "numpy.array" ] ]
JiaruiFeng/pyG-GNN-framework
[ "03651de475251dc1e58a34b8576dfc8f615a2afe" ]
[ "utils.py" ]
[ "\"\"\"\nJiarui Feng\nThis file contains util functions\n\"\"\"\n\nimport networkx as nx\nimport ujson as json\nimport numpy as np\nimport torch\nimport os\nimport queue\nimport shutil\nimport logging\nimport tqdm\nfrom sklearn.metrics import roc_curve,auc\nimport torch.utils.data as data\nfrom torch_geometric.data import Data,Batch\nfrom sklearn.model_selection import train_test_split\n\ndef reindex_nx_graph(G,ordered_node_list):\n \"\"\"reindex the nodes in nx graph according to given ordering\n Args:\n G: nx graph object\n ordered_node_list: a list served as node ordering, the first is 0\n \"\"\"\n ordered_node_dict=dict(zip(ordered_node_list,range(len(ordered_node_list))))\n return nx.relabel_nodes(G,ordered_node_dict)\n\n\ndef save_json(filename, obj, message=None,ascii=True):\n \"\"\"Save data in JSON format\n Args:\n filename(str):name of save directory(including file name)\n obj(object):data you want to save\n message(str):anything you want to print\n \"\"\"\n if message is not None:\n print(f\"Saving {message}...\")\n with open(filename, \"w\") as fh:\n json.dump(obj, fh,ensure_ascii=ascii)\n\ndef nx_to_graph_data(G,x,y):\n \"\"\"convert nx graph to torch geometric Data object\n Args\n G(networkx): nx graph\n x(numpy.array): node feature for each node given index\n \"\"\"\n edge_list=G.edges\n edge_index = torch.from_numpy(np.array(edge_list).T).to(torch.long)\n\n edge_attr=list(nx.get_edge_attributes(G,\"edge_type\").values())\n if len(edge_attr)>0:\n edge_attr = torch.from_numpy(np.array(edge_attr)).to(torch.long)\n return Data(x=x,edge_index=edge_index,edge_attr=edge_attr,y=y)\n else:\n return Data(x=x,edge_index=edge_index,edge_attr=None,y=y)\n\n\ndef make_ad_dataset(ad_data_path,group,val_ratio,test_ratio,seed=234):\n \"\"\"Make ad dataset\n Args:\n ad_data_path(str): file path of ad data\n group(str): which group used for training or testing, support male or female\n val_ratio(float):ratio of validation dataset\n test_ratio(float):ratio of test dataset\n seed(int): random seed\n \"\"\"\n ad_data=np.load(ad_data_path,allow_pickle=True)\n\n if group==\"female\":\n positive_data=ad_data[\"ex_early_female\"]\n negative_data=ad_data[\"ex_normal_female\"]\n elif group==\"male\":\n positive_data=ad_data[\"ex_early_male\"]\n negative_data=ad_data[\"ex_normal_male\"]\n else:\n raise ValueError(\"invaild scRNA data group\")\n\n expression_data=np.concatenate([positive_data,negative_data],axis=0)\n positive_y=np.ones([positive_data.shape[0]])\n negative_y=np.zeros([negative_data.shape[0]])\n y=np.concatenate([positive_y,negative_y],axis=0)\n train_expression,remain_expression,train_y,remain_y=\\\n train_test_split(expression_data,y,test_size=(val_ratio+test_ratio),stratify=y,random_state=seed)\n\n val_expression,test_expression,val_y,test_y=\\\n train_test_split(remain_expression,remain_y,test_size=test_ratio/(val_ratio+test_ratio),\n stratify=remain_y,random_state=seed)\n A=ad_data[\"A\"].tolist()\n gene_list=ad_data[\"gene_list\"]\n gene_feature=ad_data[\"gene_feature\"]\n return train_expression,train_y,val_expression,val_y,test_expression,test_y,\\\n A,gene_feature,gene_list\n\n\n\nclass LoadTrainDataset(data.Dataset):\n \"\"\"load ad dataset for training\n Args:\n expression(numpy.array):scRNA expression data\n y(numpy.array): prediction label\n A(numpy.array): adajacency matrix\n gene_feature(numpy.array): gene feature matrix\n gene_list(list): gene name list\n device(list): the device used in training\n \"\"\"\n def __init__(self,expression,y,A,gene_feature,gene_list):\n super(LoadTrainDataset, self).__init__()\n self.gene_list=gene_list\n expression=torch.from_numpy(expression).float()\n self.length=expression.size(0)\n self.y=torch.from_numpy(y).long()\n G=nx.from_scipy_sparse_matrix(A)\n gene_feature=torch.from_numpy(gene_feature).float()\n data_list=[]\n for idx in range(expression.size(0)):\n expression_data=expression[idx].unsqueeze(-1)\n x=torch.cat([gene_feature,expression_data],dim=-1)\n data_list.append(nx_to_graph_data(G,x,self.y[idx].view(-1)))\n\n self.data_list=Batch.from_data_list(data_list)\n\n def __len__(self):\n return self.length\n\n def __getitem__(self,idx):\n return self.data_list[idx]\n\n\ndef collate_fn(examples):\n data_list=Batch.from_data_list(examples)\n return (data_list)\n\n\n\n\nclass AverageMeter:\n \"\"\"Keep track of average values over time.\n\n Adapted from:\n > https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n def __init__(self):\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def reset(self):\n \"\"\"Reset meter.\"\"\"\n self.__init__()\n\n def update(self, val, num_samples=1):\n \"\"\"Update meter with new value `val`, the average of `num` samples.\n\n Args:\n val (float): Average value to update the meter with.\n num_samples (int): Number of samples that were averaged to\n produce `val`.\n \"\"\"\n self.count += num_samples\n self.sum += val * num_samples\n self.avg = self.sum / self.count\n\n\nclass EMA:\n \"\"\"Exponential moving average of model parameters.\n Args:\n model (torch.nn.Module): Model with parameters whose EMA will be kept.\n decay (float): Decay rate for exponential moving average.\n \"\"\"\n def __init__(self, model, decay):\n self.decay = decay\n self.shadow = {}\n self.original = {}\n\n # Register model parameters\n for name, param in model.named_parameters():\n if param.requires_grad:\n self.shadow[name] = param.data.clone()\n\n def __call__(self, model, num_updates):\n decay = min(self.decay, (1.0 + num_updates) / (10.0 + num_updates))\n for name, param in model.named_parameters():\n if param.requires_grad:\n assert name in self.shadow\n new_average = \\\n (1.0 - decay) * param.data + decay * self.shadow[name]\n self.shadow[name] = new_average.clone()\n\n def assign(self, model):\n \"\"\"Assign exponential moving average of parameter values to the\n respective parameters.\n Args:\n model (torch.nn.Module): Model to assign parameter values.\n \"\"\"\n for name, param in model.named_parameters():\n if param.requires_grad:\n assert name in self.shadow\n self.original[name] = param.data.clone()\n param.data = self.shadow[name]\n\n def resume(self, model):\n \"\"\"Restore original parameters to a model. That is, put back\n the values that were in each parameter at the last call to `assign`.\n Args:\n model (torch.nn.Module): Model to assign parameter values.\n \"\"\"\n for name, param in model.named_parameters():\n if param.requires_grad:\n assert name in self.shadow\n param.data = self.original[name]\n\n\nclass CheckpointSaver:\n \"\"\"Class to save and load model checkpoints.\n\n Save the best checkpoints as measured by a metric value passed into the\n `save` method. Overwrite checkpoints with better checkpoints once\n `max_checkpoints` have been saved.\n\n Args:\n save_dir (str): Directory to save checkpoints.\n max_checkpoints (int): Maximum number of checkpoints to keep before\n overwriting old ones.\n metric_name (str): Name of metric used to determine best model.\n maximize_metric (bool): If true, best checkpoint is that which maximizes\n the metric value passed in via `save`. Otherwise, best checkpoint\n minimizes the metric.\n log (logging.Logger): Optional logger for printing information.\n \"\"\"\n def __init__(self, save_dir, max_checkpoints, metric_name,\n maximize_metric=False, log=None):\n super(CheckpointSaver, self).__init__()\n\n self.save_dir = save_dir\n self.max_checkpoints = max_checkpoints\n self.metric_name = metric_name\n self.maximize_metric = maximize_metric\n self.best_val = None\n self.ckpt_paths = queue.PriorityQueue()\n self.log = log\n self._print(f\"Saver will {'max' if maximize_metric else 'min'}imize {metric_name}...\")\n\n def is_best(self, metric_val):\n \"\"\"Check whether `metric_val` is the best seen so far.\n\n Args:\n metric_val (float): Metric value to compare to prior checkpoints.\n \"\"\"\n if metric_val is None:\n # No metric reported\n return False\n\n if self.best_val is None:\n # No checkpoint saved yet\n return True\n\n return ((self.maximize_metric and self.best_val < metric_val)\n or (not self.maximize_metric and self.best_val > metric_val))\n\n def _print(self, message):\n \"\"\"Print a message if logging is enabled.\"\"\"\n if self.log is not None:\n self.log.info(message)\n\n def save(self, step, model_dict, metric_val, device):\n \"\"\"Save model parameters to disk.\n\n Args:\n step (int): Total number of examples seen during training so far.\n model (torch.nn.DataParallel): Model to save.\n metric_val (float): Determines whether checkpoint is best so far.\n device (torch.device): Device where model resides.\n \"\"\"\n\n checkpoint_path = os.path.join(self.save_dir,f'step_{step}')\n for name,model in model_dict.items():\n ckpt_dict = {\n 'model_name': model.__class__.__name__,\n 'model_state': model.cpu().state_dict(),\n 'step': step\n }\n\n model.to(device)\n torch.save(ckpt_dict, f\"{checkpoint_path}{name}.pth.tar\")\n self._print(f'Saved checkpoint: {checkpoint_path}')\n\n if self.is_best(metric_val):\n # Save the best model\n self.best_val = metric_val\n best_path = os.path.join(self.save_dir, 'best')\n for name in model_dict.keys():\n shutil.copy(f\"{checkpoint_path}{name}.pth.tar\", f\"{best_path}{name}.pth.tar\")\n\n self._print(f'New best checkpoint at step {step}...')\n\n # Add checkpoint path to priority queue (lowest priority removed first)\n if self.maximize_metric:\n priority_order = metric_val\n else:\n priority_order = -metric_val\n\n self.ckpt_paths.put((priority_order, checkpoint_path))\n\n # Remove a checkpoint if more than max_checkpoints have been saved\n if self.ckpt_paths.qsize() > self.max_checkpoints:\n _, worst_ckpt = self.ckpt_paths.get()\n try:\n for name in model_dict.keys():\n os.remove(f\"{worst_ckpt}{name}.pth.tar\")\n self._print(f'Removed checkpoint: {worst_ckpt}')\n except OSError:\n # Avoid crashing if checkpoint has been removed or protected\n pass\n\n\ndef load_model(model, checkpoint_path, gpu_ids, return_step=True):\n \"\"\"Load model parameters from disk.\n\n Args:\n model (torch.nn.DataParallel): Load parameters into this model.\n checkpoint_path (str): Path to checkpoint to load.\n gpu_ids (list): GPU IDs for DataParallel.\n return_step (bool): Also return the step at which checkpoint was saved.\n\n Returns:\n model (torch.nn.DataParallel): Model loaded from checkpoint.\n step (int): Step at which checkpoint was saved. Only if `return_step`.\n \"\"\"\n device = f\"cuda:{gpu_ids[0]}\" if gpu_ids else 'cpu'\n ckpt_dict = torch.load(checkpoint_path, map_location=device)\n\n # Build model, load parameters\n model.load_state_dict(ckpt_dict['model_state'])\n\n if return_step:\n step = ckpt_dict['step']\n return model, step\n\n return model\n\n\ndef get_available_devices() -> object:\n \"\"\"Get IDs of all available GPUs.\n\n Returns:\n device (torch.device): Main device (GPU 0 or CPU).\n gpu_ids (list): List of IDs of all GPUs that are available.\n \"\"\"\n gpu_ids = []\n if torch.cuda.is_available():\n gpu_ids += [gpu_id for gpu_id in range(torch.cuda.device_count())]\n device = torch.device(f'cuda:{gpu_ids[0]}')\n torch.cuda.set_device(device)\n else:\n device = torch.device('cpu')\n\n return device, gpu_ids\n\n\ndef get_save_dir(base_dir, name, type, id_max=100):\n \"\"\"Get a unique save directory by appending the smallest positive integer\n `id < id_max` that is not already taken (i.e., no dir exists with that id).\n\n Args:\n base_dir (str): Base directory in which to make save directories.\n name (str): Name to identify this training run. Need not be unique.\n training (bool): Save dir. is for training (determines subdirectory).\n id_max (int): Maximum ID number before raising an exception.\n\n Returns:\n save_dir (str): Path to a new directory with a unique name.\n \"\"\"\n for uid in range(1, id_max):\n subdir = type\n save_dir = os.path.join(base_dir, subdir, f'{name}-{uid:02d}')\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n return save_dir\n\n raise RuntimeError('Too many save directories created with the same name. \\\n Delete old save directories or use another name.')\n\n\ndef get_logger(log_dir, name):\n \"\"\"Get a `logging.Logger` instance that prints to the console\n and an auxiliary file.\n\n Args:\n log_dir (str): Directory in which to create the log file.\n name (str): Name to identify the logs.\n\n Returns:\n logger (logging.Logger): Logger instance for logging events.\n \"\"\"\n class StreamHandlerWithTQDM(logging.Handler):\n \"\"\"Let `logging` print without breaking `tqdm` progress bars.\n\n See Also:\n > https://stackoverflow.com/questions/38543506\n \"\"\"\n def emit(self, record):\n try:\n msg = self.format(record)\n tqdm.tqdm.write(msg)\n self.flush()\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n self.handleError(record)\n\n # Create logger\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n\n # Log everything (i.e., DEBUG level and above) to a file\n log_path = os.path.join(log_dir, 'log.txt')\n file_handler = logging.FileHandler(log_path)\n file_handler.setLevel(logging.DEBUG)\n\n # Log everything except DEBUG level (i.e., INFO level and above) to console\n console_handler = StreamHandlerWithTQDM()\n console_handler.setLevel(logging.INFO)\n\n # Create format for the logs\n file_formatter = logging.Formatter('[%(asctime)s] %(message)s',\n datefmt='%m.%d.%y %H:%M:%S')\n file_handler.setFormatter(file_formatter)\n console_formatter = logging.Formatter('[%(asctime)s] %(message)s',\n datefmt='%m.%d.%y %H:%M:%S')\n console_handler.setFormatter(console_formatter)\n\n # add the handlers to the logger\n logger.addHandler(file_handler)\n logger.addHandler(console_handler)\n\n return logger\n\n\ndef torch_from_json(path, dtype=torch.float32):\n \"\"\"Load a PyTorch Tensor from a JSON file.\n\n Args:\n path (str): Path to the JSON file to load.\n dtype (torch.dtype): Data type of loaded array.\n\n Returns:\n tensor (torch.Tensor): Tensor loaded from JSON file.\n \"\"\"\n with open(path, 'r') as fh:\n array = np.array(json.load(fh))\n\n tensor = torch.from_numpy(array).type(dtype)\n\n return tensor\n\n\n\nclass MetricsMeter:\n \"\"\"Keep track of model performance.\n \"\"\"\n def __init__(self,threshold=0.5):\n self.TP = 0\n self.FP = 0\n self.TN = 0\n self.FN= 0\n self.threshold=0.5\n self.prediction=np.array([1])\n self.label=np.array([1])\n\n def reset(self):\n \"\"\"Reset meter.\"\"\"\n self.__init__()\n\n def update(self, input,target ):\n \"\"\"Update meter with new result\n\n Args:\n input (torch.tensor, Batch_size*1): predicted probability tensor.\n target (torch.tensor, Batch_size*1): ground true, 1 represent positive\n\n \"\"\"\n predict=(input>self.threshold).int()\n self.TP+=(target[torch.where(predict==1)]==1).sum().item()\n self.FP += (target[torch.where(predict==1)]==0).sum().item()\n self.TN += (target[torch.where(predict==0)]==0).sum().item()\n self.FN += (target[torch.where(predict==0)]==1).sum().item()\n input=input.view(-1).numpy()\n target=target.view(-1).numpy()\n self.prediction=np.concatenate([self.prediction,input],axis=-1)\n self.label=np.concatenate([self.label,target],axis=-1)\n\n\n def return_metrics(self):\n recall=self.TP/(self.TP+self.FN+1e-30)\n precision=self.TP/(self.TP+self.FP+1e-30)\n specificity=self.TN/(self.TN+self.FP+1e-30)\n accuracy=(self.TP+self.TN)/(self.TP+self.FP+self.TN+self.FN+1e-30)\n F1=self.TP/(self.TP+0.5*(self.FP+self.FN)+1e-30)\n fpr,tpr,thresholds=roc_curve(self.label[1:],self.prediction[1:])\n AUC=auc(fpr,tpr)\n metrics_result = {'Accuracy': accuracy,\n \"Recall\": recall,\n \"Precision\": precision,\n \"Specificity\": specificity,\n \"F1\":F1,\n \"AUC\":AUC,\n \"fpr\":fpr,\n \"tpr\":tpr,\n \"thresholds\":thresholds\n }\n return metrics_result\n\n" ]
[ [ "torch.cuda.set_device", "torch.load", "sklearn.metrics.auc", "torch.cat", "sklearn.model_selection.train_test_split", "sklearn.metrics.roc_curve", "numpy.ones", "numpy.concatenate", "torch.from_numpy", "torch.cuda.is_available", "torch.where", "torch.device", "numpy.load", "torch.cuda.device_count", "numpy.array", "numpy.zeros", "torch.save" ] ]
Melykuti/COVID-19
[ "385e12574f5b8c40f540a743cda9e861bc0e0bd7" ]
[ "code/DEU.py" ]
[ "'''\nexec(open('DEU.py').read())\n15/3/2020-12/6/2021\n'''\n\nimport os, datetime\nimport numpy as np\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom importlib import reload\nimport utils\n\nallowed_values = \\\n ['Baden-Württemberg', 'Bayern', 'Berlin', 'Brandenburg', 'Bremen',\n 'Hamburg', 'Hessen', 'Mecklenburg-Vorpommern', 'Niedersachsen',\n 'Nordrhein-Westfalen', 'Rheinland-Pfalz', 'Saarland', 'Sachsen',\n 'Sachsen-Anhalt', 'Schleswig-Holstein', 'Thüringen',\n 'Deutschland',\n 'alle']\n\n### User input ###\n\n#selection = 'alle' # Choose one of the elements of allowed_values.\n#selection = allowed_values[0] # Alternatively, choose an element index from allowed_values.\nselection = 'Sachsen'\n#selection = 'Deutschland'\n\ncases = 'confirmed' # 'confirmed' or 'deaths' or 'confirmed_minus_deaths'\n\nwindow_length = -1 # from latest data point back into past if positive; if nonpositive, then it searches for optimum for model fitting (recommended)\nwindow_length_all = dict({bl: window_length for bl in allowed_values[:-1]})\n'''\n# You can select individual window lengths manually:\nwindow_length_all = dict({'Baden-Württemberg': 7, 'Bayern': window_length,\n 'Berlin': 5, 'Brandenburg': 5, 'Bremen': 15,\n 'Hamburg': 11, 'Hessen': 11, 'Mecklenburg-Vorpommern': 13,\n 'Niedersachsen': 12, 'Nordrhein-Westfalen': 15,\n 'Rheinland-Pfalz': 6, 'Saarland': window_length, 'Sachsen': 7,\n 'Sachsen-Anhalt': 6, 'Schleswig-Holstein': 8, 'Thüringen': 13,\n 'Deutschland': 13})\n'''\n\nsave_not_show = 0 # if 0, then shows the plot; if 1, then saves it; otherwise it does neither.\n# In the case of 'alle', 0 functions as -1.\n\nnormalise_by = 1e5 # report case numbers per this many people\nexp_or_lin = 'both' # Use 'exp' model (fitting linear model on logarithmic scale) or 'lin' model or 'both' for trying both and selecting the better.\nmax_display_length = 90 # in days; if positive, then it plots the most recent max_display_length days only\n#max_display_length = -1\nlang = 'de' # 'de' for German, anything else for English\n\n### End of user input ###\n\n\ndef open_data():\n '''\n Finding and opening your most recent data download if timestamp == None.\n Alternatively, specify a substring of requested timestamp to select which file to open.\n '''\n timestamp = None\n #timestamp = '20200427_14-37-31'\n #df=dict()\n lists = list()\n with os.scandir() as it:\n for entry in it:\n if (timestamp==None or timestamp in entry.name) and 'time_series_covid-19_DEU_Wikipedia_' in entry.name and entry.is_file():\n lists.append(entry.name)\n\n lists.sort()\n #print(lists)\n with open(lists[-1]) as t:\n return t.read()\n\n'''\ndef convert_months_to_nr(s: str) -> int:\n s = s.replace('\\n','')\n if s == 'Januar':\n return 1\n elif s == 'Februar':\n return 2\n elif s == 'März':\n return 3\n elif s == 'April':\n return 4\n elif s == 'Mai':\n return 5\n elif s == 'Juni':\n return 6\n elif s == 'Juli':\n return 7\n elif s == 'August':\n return 8\n elif s == 'September':\n return 9\n elif s == 'Oktober':\n return 10\n elif s == 'November':\n return 11\n elif s == 'Dezember':\n return 12\n else:\n print('ERROR at 2: Data format error, results are unreliable.')\n return -1\n'''\n\ndef convert_months_to_nr(s: str) -> int:\n for i in range(13):\n if ['blank', 'Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'][i] in s:\n return i\n print('ERROR at 2: Data format error, results are unreliable.')\n return -1\n\ndef convert_abbr_to_bl(s: str) -> str:\n i = ['BW', 'BY', 'BE', 'BB', 'HB', 'HH', 'HE', 'MV', 'NI', 'NW', 'RP', 'SL', 'SN', 'ST', 'SH', 'TH',\n 'Gesamt', 'DifferenzzumVortag'].index(s)\n return allowed_values[i]\n'''\ndef collect_dates(rows, table_no):\n # First 2 rows are the header: month and day.\n t = rows[0].find_all('th')\n months = []\n for j in range(1, len(t)-(table_no==0)):\n months += int(t[j]['colspan']) * [convert_months_to_nr(t[j].text)]\n #print(months)\n t = rows[1].find_all('th')\n days = []\n if table_no==0:\n for j in t[:-1]:\n days.append(j.text[:j.text.find('.')]) # cutting .\\n from end\n else:\n for j in t:\n days.append(j.text[:j.text.find('.')]) # cutting .\\n from end\n #print(days)\n ymd = list()\n for m, d in zip(months, days):\n ymd.append('2020-{0}-{1}'.format(m, d))\n dates = pd.to_datetime(ymd)\n return dates # pandas DatetimeIndex of dates\n\ndef collect_data(rows, table_no):\n dates = collect_dates(rows, table_no)\n cases_bl = dict()\n for i in range(2, len(rows)-2, 2): # runs from 2 by steps of 2 to 32 (inclusive)\n bundesland = rows[i].find_all('td')[2].find_all('a')[0].text\n #print(i, bundesland)\n cases_bl[bundesland] = list()\n # For the first table, leave out the last column (Erkr./100.000 Einw.)\n for j in range(3, len(rows[i].find_all('td'))-(table_no==0)):\n try:\n cases_bl[bundesland].append(int(rows[i].find_all('td')[j].text.replace('.','')))\n except:\n cases_bl[bundesland].append(0)\n\n bundeslaender = list()\n for bl in cases_bl:\n bundeslaender.append(pd.Series(cases_bl[bl], name=bl, index=dates))\n\n # Deutschland\n #print(rows[34].find_all('th')[0].find_all('a')[1].text)\n i = 34\n cases = []\n for j in range(1, len(rows[i].find_all('th'))-(table_no==0)):\n try:\n cases.append(int(rows[i].find_all('th')[j].text.replace('.','')))\n except:\n cases.append(0)\n #print(cases)\n s34 = pd.Series(cases, name = rows[i].find_all('th')[0].find_all('a')[1].text, index=dates)\n #print(s34)\n\n # Zunahme pro Tag\n #print(rows[35].find_all('th')[0].text)\n i = 35\n cases = []\n for j in range(1, len(rows[i].find_all('th'))-(table_no==0)):\n try:\n cases.append(int(rows[i].find_all('th')[j].text.replace('.','')))\n except:\n cases.append(0)\n #print(cases)\n s35 = pd.Series(cases, name = rows[i].find_all('th')[0].text, index=dates)\n #print(s35)\n\n #print(pd.concat(bundeslaender + [s34, s35], axis=1))\n return pd.concat(bundeslaender + [s34, s35], axis=1)\n'''\ndef extract_number(s):\n '''\n Maps a string with tailing text to an integer:\n 123.456 ^(f) -> 123456\n '''\n s = s.replace('\\n','').replace('.','').replace('-','0')\n for i in range(len(s)):\n if s[:i+1].isnumeric():\n t = s[:i+1]\n return int(t)\n\ndef collect_data_colwise(rows, shift_right=0):\n # Header\n firstrowcells = rows[0].find_all('th')\n col_names = list()\n #for t in range(1, len(firstrowcells)-2):\n for t in range(1+shift_right, len(firstrowcells)-3):\n col_names.append(convert_abbr_to_bl(firstrowcells[t].find('a').text))\n #for t in range(len(firstrowcells)-2, len(firstrowcells)):\n # Deutschland:\n col_names.append(convert_abbr_to_bl(firstrowcells[len(firstrowcells)-3].text.replace('\\n','')))\n # Diff.:\n col_names.append(firstrowcells[len(firstrowcells)-2].text.replace('\\n',' '))\n # Diff over week.:\n #col_names.append(firstrowcells[len(firstrowcells)-1].text.replace('\\n',''))\n\n # Data rows\n ymd = list()\n cases_date = dict()\n rows_list = list()\n row_counter = 0\n #for r in rows[1:-1]:\n for r in rows[2:-1]:\n #print(r.text)\n tds = r.find_all('td')\n # https://stackoverflow.com/a/1546251/9486169, we remove accidental multiple spaces from date:\n #print(tds[0].text)\n #day, month, year = tds[0].text.replace('\\n','').split(' ')\n #print(' '.join(tds[0].text.replace('\\n','').split()).split(' '))\n #day, month, year = ' '.join(tds[0].text.replace('\\n','').split()).split(' ')[:3]\n #day, month, year = tds[0].text.replace('\\n','').split()[:3] # until 1/4/2020\n #text_temp = tds[0].text.replace('\\n','')\n #text_temp = tds[shift_right].text.replace('\\n','')\n #text_temp = tds[shift_right - (row_counter%7 != 0)].text.replace('\\n','')\n text_temp = tds[shift_right - (row_counter%7 != 3)].text.replace('\\n','').replace('\\xa0', ' ')\n #print(text_temp[text_temp.find('♠')+1:])\n #day, month, year = text_temp[text_temp.find('♠')+1:].split()[:3] # on 12/4/2020\n day, month, year = text_temp.split()[:3] # on 12/6/2021\n year = year[:4]\n #print(day, month, year)\n ymd.append('{0}-{1}-{2}'.format(year, convert_months_to_nr(month), day.replace('.', '')))\n cases_date[ymd[-1]]=list()\n #for j in tds[1:]:\n for j in tds[1+shift_right - (row_counter%7 != 3) :-1]:\n # The character - is not the standard minus, it's a longer one so safer to do with\n # try & except.\n try:\n #cases_date[ymd[-1]].append(int(j.text.replace('\\n','').replace('.','').replace('-','0')))\n cases_date[ymd[-1]].append(extract_number(j.text))\n except:\n cases_date[ymd[-1]].append(0)\n rows_list.append(pd.Series(cases_date[ymd[-1]], index=col_names))\n row_counter += 1\n\n #print(col_names)\n #print(pd.concat(cases_date.values(), axis=0, columns=col_names))\n #return pd.concat(list(cases_date.values()), axis=0, columns=col_names)\n return pd.concat(rows_list, axis=1, keys=pd.to_datetime(ymd)).transpose()\n\ndef data_preparation_DEU(output):\n raw_html = open_data()\n\n soup = BeautifulSoup(raw_html, 'lxml')\n #print(soup.prettify())\n\n #tables = soup.find_all('table', {'class':'wikitable sortable mw-collapsible'}) # I expect two tables: 'Bestätigte Infektionsfälle (kumuliert)', 'Bestätigte Todesfälle (kumuliert)'\n tables = soup.find_all('table', {'class':'wikitable'}) # I expect six tables\n\n idx_Infektionsfaelle = 0\n idx_Todesfaelle = 2\n #if 'Elektronisch übermittelte Fälle (kumuliert)' not in tables[0].text or 'Bestätigte Todesfälle (kumuliert)' not in tables[2].text:\n #if 'Elektronisch übermittelte Fälle (kumuliert)' not in tables[0].text or 'Bestätigte Todesfälle (kumuliert)' not in tables[3].text:\n #if 'Daten über Infektionsfälle (kumuliert)' not in tables[0].text or 'Bestätigte Todesfälle (kumuliert)' not in tables[3].text:\n #if 'Infektionsfälle (kumuliert)' not in tables[idx_Infektionsfaelle].text or ('Bestätigte Todesfälle (kumuliert)' not in tables[idx_Todesfaelle].text and 'Bestätigte\\xa0Todesfälle\\xa0(kumuliert)' not in tables[idx_Todesfaelle].text):\n # print('ERROR at 0: Data format error, results are unreliable.')\n\n for i in [idx_Infektionsfaelle, idx_Todesfaelle]:\n rows = tables[i].find_all('tr')\n # or 'Februar' not in rows[0].text\n if (i==idx_Infektionsfaelle and ('Datum' not in rows[0].text or 'BW' not in rows[0].text)) or \\\n (i==idx_Todesfaelle and ('Datum' not in rows[0].text or 'BW' not in rows[0].text)):\n print('ERROR at 1: Data format error with table {}, results are unreliable.'.format(i))\n\n #dates = collect_dates(rows)\n #print(dates)\n if i==idx_Infektionsfaelle:\n #figures = collect_data(rows, i) # infections\n figures = collect_data_colwise(rows, 1) # infections\n #figures.loc[pd.to_datetime('2020-04-07'),'Berlin'] = 3845 # temporary hack but I updated Wikipedia table\n #figures.loc[pd.to_datetime('2020-03-20'),'Rheinland-Pfalz'] = 801\n #figures.loc[pd.to_datetime('2020-03-31'),'Sachsen-Anhalt'] = 680\n print(figures)\n else: # i==idx_Todesfaelle\n death_figures = collect_data_colwise(rows, 1) # deaths\n #print(death_figures)\n # Extend it to the size of cases and fill missing values with 0\n death_figures = pd.DataFrame(death_figures, index=figures.index).fillna(value=0).astype('int64')\n print(death_figures)\n\n if output == 'confirmed':\n figures_diff = pd.DataFrame(figures.iloc[:,:17])\n elif output == 'deaths':\n figures_diff = pd.DataFrame(death_figures.iloc[:,:17])\n elif output == 'confirmed_minus_deaths':\n figures_diff = pd.DataFrame(figures.iloc[:,:17] - death_figures.iloc[:,:17])\n #print(figures_diff)\n return figures_diff\n\n\nif __name__ == '__main__':\n pop_csv = 'DEU'\n figures_diff = data_preparation_DEU(cases)\n #figures_diff = figures_diff.iloc[:-1,:]\n if max_display_length > 0:\n figures_diff = figures_diff[-max_display_length:]\n\n utils.print_header(normalise_by, pop_csv)\n\n if selection != 'alle': # single run\n df_ts = figures_diff[selection]\n df_ts = utils.rm_early_zeros(df_ts)\n results, model = utils.process_geounit(df_ts, window_length, exp_or_lin)\n\n utils.print_results(selection, results.iloc[0, 0:8], normalise_by, pop_csv,\n results.iloc[0,8], results.iloc[0,9], 'normal', lang)\n\n if save_not_show in [0, 1]:\n utils.plotting(figures_diff[selection], model, save_not_show, selection, results.iloc[0,8],\n results.iloc[0,9], lang)\n\n else: # analysis of all federal states and complete Germany\n\n results_list = list()\n for selection in allowed_values[:-1]:\n print(selection)\n df_ts = figures_diff[selection]\n df_ts = utils.rm_early_zeros(df_ts)\n results, model = utils.process_geounit(df_ts, window_length, exp_or_lin)\n\n results = results.assign(selection=selection)\n results = results.set_index('selection')\n results_list.append(results)\n if save_not_show == 1:\n utils.plotting(figures_diff[selection], model, save_not_show, selection,\n results.iloc[0,8], results.iloc[0,9], lang)\n\n df_results = pd.concat(results_list)\n for selection in allowed_values[:-1]:\n if selection == 'Deutschland':\n print()\n if window_length_all[selection] > 0:\n utils.print_results(selection, df_results.loc[selection,:].iloc[0:8], normalise_by,\n pop_csv, window_length_all[selection],\n df_results.loc[selection,:].iloc[9], 'normal', lang)\n else:\n utils.print_results(selection, df_results.loc[selection,:].iloc[0:8], normalise_by,\n pop_csv, df_results.loc[selection,:].iloc[8],\n df_results.loc[selection,:].iloc[9], 'normal', lang)\n" ]
[ [ "pandas.concat", "pandas.to_datetime", "pandas.Series", "pandas.DataFrame" ] ]
fonnesbeck/ngcm_pandas_2016
[ "5a2a6aacbb850543c264e1f87eedc3955526b8c3" ]
[ "notebooks/solutions/nfs_replace.py" ]
[ "import pandas as pd\n\ndef read_desc(file_name):\n fname = \"../data/NationalFoodSurvey/{}\".format(file_name)\n return pd.read_csv(fname, sep=\"\\t\")\n\nfood_groups = read_desc(\"Ref_ food groups.txt\")\n\n# get the replacement dictionary\n# a mapping of key to value with which to replace it\nto_replace = food_groups.set_index('fdgp').to_dict()['fd gp description']\n\nfood_groups.fdgp.replace(to_replace)\n" ]
[ [ "pandas.read_csv" ] ]
bwprice/butterfly-wings
[ "18b138e7a907e372029b9c8e927bd06882bac964" ]
[ "butterfly/measurement.py" ]
[ "import numpy as np\nfrom joblib import Memory\n\nlocation = './cachedir'\nmemory = Memory(location, verbose=0)\n\n\[email protected]()\ndef main(points_interest, T_space, axes=None):\n ''' Calculates the length and draws the lines for length\n of the butterfly wings.\n\n Parameters\n ----------\n ax: array\n the array containing the 3 intermediary Axes.\n points_interest: dictionary \n dictionary containing the points of interest in the form [y, x],\n keyed with \"outer_pix_l\", \"inner_pix_l\", \"outer_pix_r\", \"inner_pix_r\", \n \"body_center\"\n T_space: float\n number of pixels between 2 ticks.\n\n Returns\n -------\n ax: ax\n an ax object\n dst_pix: dictionary\n dictionary containing measurements in pixels, keyed with\n \"dist_l\", \"dist_r\", \"dist_l_center\",\n \"dist_r_center\", \"dist_span\"\n dst_mm: tuple\n dictionary containing measurements in mm, keyed with\n the same keys as dst_pix\n\n '''\n\n # Extract points of interest\n pix_out_l, pix_out_r = np.array(points_interest[\"outer_pix_l\"]), np.array(points_interest[\"outer_pix_r\"])\n pix_in_l, pix_in_r = np.array(points_interest[\"inner_pix_l\"]), np.array(points_interest[\"inner_pix_r\"])\n body_center = np.array(points_interest[\"body_center\"])\n\n # Distance measurements between points of interest\n dist_r_pix = np.linalg.norm(pix_out_r - pix_in_r)\n dist_l_pix = np.linalg.norm(pix_out_l - pix_in_l)\n dist_r_center_pix = np.linalg.norm(pix_out_r - body_center)\n dist_l_center_pix = np.linalg.norm(pix_out_l - body_center)\n dist_span_pix = np.linalg.norm(pix_out_l - pix_out_r)\n\n # Converting to millimeters\n dist_l_mm = round(dist_l_pix / T_space, 2)\n dist_r_mm = round(dist_r_pix / T_space, 2)\n dist_l_center_mm = round(dist_l_center_pix / T_space, 2)\n dist_r_center_mm = round(dist_r_center_pix / T_space, 2)\n dist_span_mm = round(dist_span_pix / T_space, 2)\n\n # Do we want to round these?\n dist_l_pix = round(dist_l_pix, 2)\n dist_r_pix = round(dist_r_pix, 2)\n dist_l_center_pix = round(dist_l_center_pix, 2)\n dist_r_center_pix = round(dist_r_center_pix, 2)\n dist_span_pix = round(dist_span_pix, 2)\n\n dist_pix = {\n \"dist_l\": dist_l_pix,\n \"dist_r\": dist_r_pix,\n \"dist_l_center\": dist_l_center_pix,\n \"dist_r_center\": dist_r_center_pix,\n \"dist_span\": dist_span_pix\n }\n dist_mm = {\n \"dist_l\": dist_l_mm,\n \"dist_r\": dist_r_mm,\n \"dist_l_center\": dist_l_center_mm,\n \"dist_r_center\": dist_r_center_mm,\n \"dist_span\": dist_span_mm\n }\n\n if axes and axes[0]:\n textsize = 5\n if axes[3]:\n textsize = 3\n axes[0].plot([pix_out_l[1], pix_in_l[1]],\n [pix_out_l[0], pix_in_l[0]], color='r')\n axes[0].plot([pix_out_r[1], pix_in_r[1]],\n [pix_out_r[0], pix_in_r[0]], color='r')\n axes[0].text(int((pix_out_l[1] + pix_in_l[1]) / 2) + 50,\n int((pix_out_l[0] + pix_in_l[0]) / 2) - 50,\n 'left_wing = ' + str(round(dist_l_mm, 2)) + ' mm',\n size=textsize,\n color='r')\n axes[0].text(int((pix_out_r[1] + pix_in_r[1]) / 2) + 50,\n int((pix_out_r[0] + pix_in_r[0]) / 2) + 50,\n 'right_wing = ' + str(round(dist_r_mm, 2))\n + ' mm',\n size=textsize, color='r')\n\n axes[0].plot([pix_out_l[1], body_center[1]],\n [pix_out_l[0], body_center[0]], color='orange', linestyle='dotted')\n axes[0].plot([pix_out_r[1], body_center[1]],\n [pix_out_r[0], body_center[0]], color='orange', linestyle='dotted')\n axes[0].text(int((pix_out_l[1] + body_center[1]) / 2) + 50,\n int((pix_out_l[0] + body_center[0]) / 2) - 50,\n 'left_wing_center = ' + str(round(dist_l_center_mm, 2)) + ' mm',\n size=textsize,\n color='orange')\n axes[0].text(int((pix_out_r[1] + body_center[1]) / 2) + 50,\n int((pix_out_r[0] + body_center[0]) / 2) + 50,\n 'right_wing_center = ' + str(round(dist_r_center_mm, 2))\n + ' mm',\n size=textsize, color='orange')\n\n axes[0].plot([pix_out_l[1], pix_out_r[1]],\n [pix_out_l[0], pix_out_r[0]], color='orange', linestyle='dashed')\n axes[0].text(int((pix_out_l[1] + pix_out_r[1]) / 2) - 50,\n int((pix_out_l[0] + pix_out_r[0]) / 2) - 50,\n 'wing_span = ' + str(round(dist_span_mm, 2))\n + ' mm',\n size=textsize, color='orange')\n\n\n print(f'left_wing : {dist_mm[\"dist_l\"]} mm')\n print(f'right_wing : {dist_mm[\"dist_r\"]} mm')\n print(f'left_wing_center : {dist_mm[\"dist_l_center\"]} mm')\n print(f'right_wing_center : {dist_mm[\"dist_r_center\"]} mm')\n print(f'wing_span : {dist_mm[\"dist_span\"]} mm')\n\n return dist_pix, dist_mm\n" ]
[ [ "numpy.array", "numpy.linalg.norm" ] ]
trottomv/mymaze
[ "198720d18b78f4d713121e33d597314fed6d4874" ]
[ "app/solve.py" ]
[ "import networkx as nx\nimport numpy as np\nimport time\n\nclass Maze:\n MOVESARR = []\n SOLARR = []\n\n with open('txt/maze.txt', 'r') as f:\n lines = (line.rstrip(\"\\r\\n\") for line in f)\n maze = np.array([list(line) for line in lines])\n\n G = nx.Graph()\n\n def mazesolve():\n with open('txt/mazesolve.txt', 'r') as f:\n lines = (line.rstrip(\"\\r\\n\") for line in f)\n maze = np.array([list(line) for line in lines])\n mazesolve = np.asarray(maze)\n return mazesolve\n\n def solve():\n with open('txt/maze.txt', 'r') as f:\n lines = (line.rstrip(\"\\r\\n\") for line in f)\n maze = np.array([list(line) for line in lines])\n mazesolve = np.asarray(maze)\n\n G = nx.Graph()\n for y in range(len(maze)):\n for x in range(len(maze[y])):\n G.add_node((y,x))\n if y > 0:\n G.add_edge((y-1,x),(y,x))\n # G.add_edge((y,x-1),(y,x))\n if x > 0:\n G.add_edge((y,x-1),(y,x))\n # G.add_edge((y-1,x),(y,x))\n\n for y in range(len(maze)):\n for x in range(len(maze[y])):\n if maze[y][x] == 'X':\n G.remove_node((y,x))\n\n try:\n MOVESARR = []\n for point in nx.algorithms.astar_path(G,(1,0),(len(maze)-2,len(maze[0])-1)):\n MOVESARR.append(point)\n # Maze.TMPARR.append(point)\n mazesolve[point[0]][point[1]] = '+'\n if point == (1,0):\n mazesolve[point[0]][point[1]] = 'S'\n elif point == (len(maze)-2,len(maze[0])-1):\n mazesolve[point[0]][point[1]] = 'E'\n\n # Maze.SOLARR.append(Maze.TMPARR)\n Maze.SOLARR.append(MOVESARR)\n Maze.MOVESARR.append(MOVESARR)\n\n open(\"txt/mazesolve.txt\", \"w\").close()\n for i in range (len(mazesolve)):\n text_file = open(\"txt/mazesolve.txt\", \"a\")\n text_file.write(\"\".join(mazesolve[i])+ '\\n')\n text_file.close()\n\n return True\n\n except:\n return False\n\n def output():\n print(\"solving... (Teseo is running away from Minotaur)\")\n print(\"\")\n time.sleep(2)\n f = open(\"txt/mazesolve.txt\", \"r\")\n print(f.read())\n f.close\n\n print(\"Teseo is save in\", len(Maze.MOVESARR[0])-1, \"moves\")\n\n def nosoloutput():\n print(\"solving... (Teseo is running away from Minotaur)\")\n time.sleep(2)\n print(\"There is no solution for Teseo... sorry, try again!\")\n print(\"Try to generate a new maze\")\n\ndef main():\n if Maze.solve() is False:\n Maze.nosoloutput()\n else:\n Maze.output()\n\nif __name__==\"__main__\":\n main()\n" ]
[ [ "numpy.asarray" ] ]
theastropath/turbot
[ "c623cd9af73876efdd315f3d7dd09448a06d3331" ]
[ "src/turnips/plots.py" ]
[ "#!/usr/bin/env python3\n\nfrom collections import Counter\nimport io\nfrom typing import Iterable, Sequence\n\nimport matplotlib.pyplot as plt\n\nfrom turnips.meta import MetaModel\nfrom turnips.model import TRIPLE, SPIKE, DECAY, BUMP, Model, ModelEnum\nfrom turnips.multi import MultiModel\nfrom turnips.ttime import TimePeriod\nfrom turnips.markov import MARKOV\n\n\ndef plot_models_range(name: str,\n models: Sequence[Model],\n previous: ModelEnum,\n add_points: bool = False) -> None:\n '''\n Plot a fill_between for all models' low and high values using an\n alpha (transparency) equal to 1/num_models. Plot a regular line\n for all fixed prices.\n\n Shows ~probability of various prices based on your possible models.\n '''\n\n colors = {\n TRIPLE: 'orange',\n SPIKE: 'green',\n DECAY: 'red',\n BUMP: 'blue',\n }\n\n _fig, ax = plt.subplots()\n\n # cosmetics\n ax.set_title(f'Island {name}: current: !!ERROR!!; Last: {previous.name}')\n ax.set_ylabel('Turnip Price')\n ax.set_xticklabels(['Mon AM', 'Mon PM', 'Tue AM', 'Tue PM', 'Wed AM', 'Wed PM',\n 'Thu AM', 'Thu PM', 'Fri AM', 'Fri PM', 'Sat AM', 'Sat PM'])\n ax.xaxis.set_ticks(range(2, 14))\n plt.xticks(rotation=45)\n plt.grid(axis='both', which='both', ls='--')\n ax.set_ylim(0, 660)\n plt.tight_layout()\n\n if len(models) == 0:\n return\n\n a_model = models[0]\n\n continuous_priced_days = []\n continuous_priced_chunk = set()\n continuous_unpriced_days = []\n continuous_unpriced_chunk = set()\n for day in range(2, 14):\n # does this day have data?\n if a_model.timeline[TimePeriod(day)].price.is_atomic:\n # is tomorrow a valid day to have data?\n if day < 13:\n # does tomorrow have data?\n if a_model.timeline[TimePeriod(day + 1)].price.is_atomic:\n # build onto the chunk\n continuous_priced_chunk.update([day, day + 1])\n # chunk broken.\n else:\n continuous_priced_chunk.update([day])\n continuous_priced_days.append(list(continuous_priced_chunk))\n continuous_priced_chunk = set()\n else:\n # end of the week, finish the priced_days\n continuous_priced_days.append(list(continuous_priced_chunk))\n # today does not have data\n else:\n # is tomorrow a valid day to have data?\n if day < 13:\n # does it?\n if not a_model.timeline[TimePeriod(day + 1)].price.is_atomic:\n # build the chunk\n if day != 2:\n # add yesterday unless today is monday_am\n continuous_unpriced_chunk.update([day - 1, day, day + 1])\n else:\n continuous_unpriced_chunk.update([day, day + 1])\n # chunk broken\n else:\n if day != 2:\n continuous_unpriced_chunk.update([day - 1, day, day + 1])\n else:\n continuous_unpriced_chunk.update([day, day + 1])\n continuous_unpriced_days.append(list(sorted(continuous_unpriced_chunk, key=lambda x: x)))\n continuous_unpriced_chunk = set()\n else:\n # end of the week, finish the unpriced_days\n continuous_unpriced_days.append(list(continuous_unpriced_chunk))\n\n for chunk in continuous_priced_days:\n vals = [a_model.timeline[TimePeriod(day)].price.value for day in chunk]\n plt.plot(chunk, vals, c='black')\n\n model_counts = Counter(x.model_type for x in models)\n remaining_model_types = model_counts.keys()\n remaining_probability = sum(MARKOV[previous][rem_mod]\n for rem_mod in remaining_model_types)\n adjusted_priors = {model: MARKOV[previous][model] / remaining_probability\n for model in model_counts.keys()}\n\n for chunk in continuous_unpriced_days:\n if len(chunk) == 1:\n # if this is one day of unpriced data, connect it to the neighbors.\n value = chunk[0]\n chunk = [value - 1, value, value + 1]\n for model in models:\n low_vals = [model.timeline[TimePeriod(day)].price.lower for day in chunk]\n high_vals = [model.timeline[TimePeriod(day)].price.upper for day in chunk]\n\n if previous != ModelEnum.unknown:\n alpha = adjusted_priors[model.model_type] / model_counts[model.model_type]\n else:\n alpha = 1 / len(models)\n\n plt.fill_between(chunk, low_vals, high_vals, alpha=alpha, color=colors[model.model_type])\n\n if add_points:\n plt.scatter(chunk, low_vals, c='black', s=2)\n plt.scatter(chunk, high_vals, c='black', s=2)\n\n # cosmetics\n msummary = '+'.join(['{}_{{{}}}^{{{:.2f}}}'.format(t, l.name, adjusted_priors[l])\n for l, t in model_counts.items()])\n ax.set_title(f'Island {name}: ${len(models)}_{{total}}={msummary}$, Last: {previous.name}')\n\n\ndef plot_models_range_interactive(name: str,\n models: Sequence[Model],\n previous: ModelEnum,\n add_points: bool = False) -> None:\n '''\n Plot a fill_between for all models' low and high values using an\n alpha (transparency) equal to 1/num_models. Plot a regular line\n for all fixed prices.\n\n Shows ~probability of various prices based on your possible models.\n '''\n plot_models_range(name, models, previous, add_points)\n plt.show()\n\n\ndef plot_models_range_data(name: str,\n models: Sequence[Model],\n previous: ModelEnum,\n add_points: bool = False) -> None:\n '''\n Plot a fill_between for all models' low and high values using an\n alpha (transparency) equal to 1/num_models. Plot a regular line\n for all fixed prices.\n\n Shows ~probability of various prices based on your possible models.\n '''\n plot_models_range(name, models, previous, add_points)\n buff = io.BytesIO()\n plt.savefig(buff)\n return buff.getvalue()\n\n\ndef global_plot(island_models: Iterable[MultiModel]) -> None:\n '''Plot a histogram, per day, for all possible prices in the archipelago.\n\n This isn't exactly a probability curve since the histogram isn't scaled\n by the real probabilities.'''\n\n arch = MetaModel(100, island_models)\n\n hist = arch.histogram()\n\n num_ticks = len(range(2, 14))\n _fig, ax = plt.subplots(num_ticks, sharex=True)\n\n for i, (time, pricecounts) in enumerate(hist.items()):\n ax[i].hist(list(pricecounts.elements()), 50)\n ax[i].text(.8, .5, time,\n horizontalalignment='center',\n transform=ax[i].transAxes)\n\n ax[i].set_xlabel('Turnip Price')\n\n plt.show()\n" ]
[ [ "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.scatter", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.grid", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show" ] ]
amz-hjinfeng/ctpn-sagemaker
[ "576844b7762922a3fcf4a5097cee1ffd2c5ae07e" ]
[ "ctpn/text_detect.py" ]
[ "import os\nimport sys\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom lib.utils.timer import Timer\nfrom lib.fast_rcnn.config import cfg\nfrom lib.fast_rcnn.test import test_ctpn\nfrom lib.networks.factory import get_network\nfrom lib.text_connector.detectors import TextDetector\nfrom lib.text_connector.text_connect_cfg import Config as TextLineCfg\n\n\ndef resize_im(im, scale, max_scale=None):\n f = float(scale) / min(im.shape[0], im.shape[1])\n if max_scale != None and f * max(im.shape[0], im.shape[1]) > max_scale:\n f = float(max_scale) / max(im.shape[0], im.shape[1])\n return cv2.resize(im, None, None, fx=f, fy=f, interpolation=cv2.INTER_LINEAR), f\n\ndef load_tf_model():\n # load config file\n cfg.TEST.checkpoints_path = '/Users/hjinfeng/Documents/cigna/ctpn-sagemaker/ctpn/checkpoints'\n# for device in ['/device:gpu:1','/device:gpu:2']:\n# with tf.device(d)\n\n\n\n # init session\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0)\n config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)\n sess = tf.Session(config=config)\n\n # load network\n net = get_network(\"VGGnet_test\")\n\n # load model\n print('Loading network {:s}... '.format(\"VGGnet_test\"))\n saver = tf.train.Saver()\n try:\n print(cfg)\n ckpt = tf.train.get_checkpoint_state(cfg.TEST.checkpoints_path)\n print(ckpt)\n print('Restoring from {}...'.format(ckpt.model_checkpoint_path))\n saver.restore(sess, ckpt.model_checkpoint_path)\n print('done')\n except Exception as e:\n print(e)\n raise 'Check your pretrained {:s}'.format(ckpt.model_checkpoint_path)\n\n return sess, net\n\nsess, net = load_tf_model()\n\ndef ctpn(img):\n timer = Timer()\n timer.tic()\n\n img, scale = resize_im(img, scale=TextLineCfg.SCALE, max_scale=TextLineCfg.MAX_SCALE)\n scores, boxes = test_ctpn(sess, net, img)\n\n textdetector = TextDetector()\n boxes = textdetector.detect(boxes, scores[:, np.newaxis], img.shape[:2])\n timer.toc()\n print(\"\\n----------------------------------------------\")\n print(('Detection took {:.3f}s for '\n '{:d} object proposals').format(timer.total_time, boxes.shape[0]))\n\n return scores, boxes, img, scale\n\ndef draw_boxes(img, boxes, scale):\n box_id = 0\n img = img.copy()\n text_recs = np.zeros((len(boxes), 8), np.int)\n for box in boxes:\n if np.linalg.norm(box[0] - box[1]) < 5 or np.linalg.norm(box[3] - box[0]) < 5:\n continue\n\n if box[8] >= 0.8:\n color = (255, 0, 0) # red\n else:\n color = (0, 255, 0) # green\n\n cv2.line(img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), color, 2)\n cv2.line(img, (int(box[0]), int(box[1])), (int(box[4]), int(box[5])), color, 2)\n cv2.line(img, (int(box[6]), int(box[7])), (int(box[2]), int(box[3])), color, 2)\n cv2.line(img, (int(box[4]), int(box[5])), (int(box[6]), int(box[7])), color, 2)\n\n for i in range(8):\n text_recs[box_id, i] = box[i]\n\n box_id += 1\n\n img = cv2.resize(img, None, None, fx=1.0/scale, fy=1.0/scale, interpolation=cv2.INTER_LINEAR)\n return text_recs, img\n\ndef text_detect(img):\n scores, boxes, img, scale = ctpn(img)\n text_recs, img_drawed = draw_boxes(img, boxes, scale)\n return text_recs, img_drawed, img\n\n\n\ndef td(postImg):\n from lib.fast_rcnn.config import cfg_from_file\n cfg_from_file('/Users/hjinfeng/Documents/cigna/ctpn-sagemaker/ctpn/text.yml')\n text_recs, img_drawed, postImg = text_detect(postImg)\n return img_drawed\n" ]
[ [ "tensorflow.train.get_checkpoint_state", "numpy.linalg.norm", "tensorflow.ConfigProto", "tensorflow.GPUOptions", "tensorflow.Session", "tensorflow.train.Saver" ] ]
Pooya448/MultiGarmentNetwork
[ "81484ab1068d450d01f8148992126412ba4b4fe4" ]
[ "utils/smpl_paths.py" ]
[ "import os\nimport numpy as np\nfrom psbody.mesh import Mesh\nfrom os.path import join\nimport cPickle as pkl\nfrom lib.serialization import backwards_compatibility_replacements, load_model\nfrom utils.geometry import get_hres\nimport scipy.sparse as sp\n\n## Set your paths here\nSMPL_PATH = '/BS/RVH/work/data/smpl_models/neutral/basicModel_neutral_lbs_10_207_0_v1.0.0.pkl'\nsmpl_vt_ft_path = '/BS/bharat/work/MGN_final_release/assets/smpl_vt_ft.pkl'\n\nclass SmplPaths:\n def __init__(self, project_dir='', exp_name='', gender='neutral', garment=''):\n self.project_dir = project_dir\n # experiments name\n self.exp_name = exp_name\n self.gender = gender\n self.garment = garment\n\n def get_smpl_file(self):\n if self.gender == 'neutral':\n return SMPL_PATH\n\n else:\n raise(NotImplemented)\n\n return smpl_file\n\n def get_smpl(self):\n smpl_m = load_model(self.get_smpl_file())\n smpl_m.gender = self.gender\n return smpl_m\n\n def get_hres_smpl_model_data(self):\n\n dd = pkl.load(open(self.get_smpl_file()))\n backwards_compatibility_replacements(dd)\n\n hv, hf, mapping = get_hres(dd['v_template'], dd['f'])\n\n num_betas = dd['shapedirs'].shape[-1]\n J_reg = dd['J_regressor'].asformat('csr')\n\n model = {\n 'v_template': hv,\n 'weights': np.hstack([\n np.expand_dims(\n np.mean(\n mapping.dot(np.repeat(np.expand_dims(dd['weights'][:, i], -1), 3)).reshape(-1, 3)\n , axis=1),\n axis=-1)\n for i in range(24)\n ]),\n 'posedirs': mapping.dot(dd['posedirs'].reshape((-1, 207))).reshape(-1, 3, 207),\n 'shapedirs': mapping.dot(dd['shapedirs'].reshape((-1, num_betas))).reshape(-1, 3, num_betas),\n 'J_regressor': sp.csr_matrix((J_reg.data, J_reg.indices, J_reg.indptr), shape=(24, hv.shape[0])),\n 'kintree_table': dd['kintree_table'],\n 'bs_type': dd['bs_type'],\n 'bs_style': dd['bs_style'],\n 'J': dd['J'],\n 'f': hf,\n }\n\n return model\n\n def get_hres_smpl(self):\n smpl_m = load_model(self.get_hres_smpl_model_data())\n smpl_m.gender = self.gender\n return smpl_m\n\n @staticmethod\n def get_vt_ft():\n vt, ft = pkl.load(open(smpl_vt_ft_path))\n return vt, ft\n\n @staticmethod\n def get_vt_ft_hres():\n vt, ft = SmplPaths.get_vt_ft()\n vt, ft, _ = get_hres(np.hstack((vt, np.ones((vt.shape[0], 1)))), ft)\n return vt[:, :2], ft\n\nif __name__ == '__main__':\n dp = SmplPaths(gender='neutral')\n smpl_file = dp.get_smpl_file()\n\n print(smpl_file)\n" ]
[ [ "numpy.expand_dims", "scipy.sparse.csr_matrix", "numpy.ones" ] ]
renatoviolin/GAN-image-inpainting
[ "6ba7ccd4ae55b185ee89844e846d4c469f4fa65f" ]
[ "generative_inpainting/predict.py" ]
[ "import cv2\nimport numpy as np\nimport tensorflow as tf\nimport neuralgym as ng\n\nfrom .inpaint_model import InpaintCAModel\n\n\ncheckpoint_dir = 'generative_inpainting/models'\nFLAGS = ng.Config('generative_inpainting/inpaint.yml')\n\n\ndef run_fill(file_test, file_mask):\n model = InpaintCAModel()\n image = cv2.imread(file_test)\n mask = cv2.imread(file_mask)\n\n h, w, _ = image.shape\n grid = 8\n image = image[:h // grid * grid, :w // grid * grid, :]\n mask = mask[:h // grid * grid, :w // grid * grid, :]\n\n image = np.expand_dims(image, 0)\n mask = np.expand_dims(mask, 0)\n input_image = np.concatenate([image, mask], axis=2)\n\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.allow_growth = True\n with tf.Session(config=sess_config) as sess:\n input_image = tf.constant(input_image, dtype=tf.float32)\n output = model.build_server_graph(FLAGS, input_image)\n output = (output + 1.) * 127.5\n output = tf.reverse(output, [-1])\n output = tf.saturate_cast(output, tf.uint8)\n # load pretrained model\n vars_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n assign_ops = []\n for var in vars_list:\n vname = var.name\n from_name = vname\n var_value = tf.contrib.framework.load_variable(checkpoint_dir, from_name)\n assign_ops.append(tf.assign(var, var_value))\n sess.run(assign_ops)\n result = sess.run(output)\n tf.reset_default_graph()\n return result[0][:, :, ::-1]\n" ]
[ [ "tensorflow.reverse", "numpy.expand_dims", "tensorflow.constant", "tensorflow.get_collection", "tensorflow.assign", "numpy.concatenate", "tensorflow.ConfigProto", "tensorflow.reset_default_graph", "tensorflow.contrib.framework.load_variable", "tensorflow.Session", "tensorflow.saturate_cast" ] ]
GordonShinozaki/iust_deep_fuzz
[ "191e7bdf31840bd7d5052885029189bb6ffb262d" ]
[ "metadata_neural_fuzz_pdf_obj.py" ]
[ "\"\"\"\nPDF OBJ 9\n- New in version 9\n-- Create test data for format fuzzing (i.e p_t = 0.90) and prefix not update.\n-- Date: 1397-04-17\n- New in version 8\n-- Fuzzing back to generate_and_fuzz method.\n-- Perplexity and cross entropy add to metrics list.\n-- Use some Keras backend to reset model graph and state.\n-- Lets pdf_file_incremental_update_4.py call the generate_and_fuzz method.\n- New in version 7\n-- Use for bidirectional LSTM model, model=model9\n- New in version 6\n-- Train with 256 LSTM search, model=model_8\n-- Train on large dataset for first time!\n-New in version 5:\n-- Data generator fixed.\n-- Train on large dataset for first time!\n-New in version 4:\n-- Changing the data generator method for use with model.fit_generator()\n-New in version 3:\n-- Add support for training in large dataset with the help of python generators.\n-- Add callbacks to log most of training time events.\n-- File and directory now mange by code in appropriate manner for each train run.\n-- Add class FileFormatFuzz to do learn and fuzz process in one script.\n-- Note: The ability of training small dataset in memory with model.fit() method was include in version 3.\n\n\"\"\"\n\nfrom __future__ import print_function\n\n__version__ = '0.9.1'\n__author__ = 'Morteza'\n\nimport sys\nimport os\nimport datetime\nimport random\nimport numpy as np\n\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.optimizers import RMSprop, Adam\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, CSVLogger, LambdaCallback\nfrom keras.utils import plot_model\n\nimport pdf_object_preprocess as preprocess\nfrom config import learning_config\nimport deep_models\n\n\ndef cross_entropy(y_true, y_pred):\n \"\"\"\n Compute cross_entropy loss metric\n\n :param y_true:\n :param y_pred:\n :return:\n \"\"\"\n return K.categorical_crossentropy(y_true, y_pred)\n\n\ndef spars_cross_entropy(y_true, y_pred):\n return K.sparse_categorical_crossentropy(y_true, y_pred)\n\n\ndef perplexity(y_true, y_pred):\n \"\"\"\n Compute perplexity metric\n\n :param y_true:\n :param y_pred:\n :return:\n \"\"\"\n ce = K.categorical_crossentropy(y_true, y_pred)\n # pp = K.pow(np.e, ce) # Or 2?\n # pp = K.pow(2., ce) # Or np.e\n pp = K.exp(ce)\n # print('Perplexity value in perplexity function: ', K.eval(pp))\n return pp\n\n\nclass FileFormatFuzzer(object):\n \"\"\"\n Main class for learn and fuzz process\n \"\"\"\n def __init__(self, maxlen=85, step=1, batch_size=128):\n \"\"\"\n\n :param maxlen:\n :param step:\n :param batch_size:\n \"\"\"\n # os.chdir('./')\n\n # learning hyper-parameters\n self.maxlen = maxlen\n self.step = step\n self.batch_size = batch_size\n\n self.text_all = ''\n self.text_training = ''\n self.text_validation = ''\n self.text_test = ''\n\n self.chars = None\n self.char_indices = None\n self.indices_char = None\n\n # self.model = None\n K.reset_uids()\n K.clear_session()\n\n self.load_dataset()\n\n def define_model(self, input_dim, output_dim):\n \"\"\"\n Build the model: a single LSTM layer # We need to deep it # now is deep :)\n :param input_dim:\n :param output_dim:\n :return:\n \"\"\"\n model, model_name = deep_models.model_7(input_dim, output_dim)\n return model, model_name\n\n def load_dataset(self):\n \"\"\" Load all 3 part of each dataset and building dictionary index \"\"\"\n if learning_config['dataset_size'] == 'small':\n self.text_training = preprocess.load_from_file(learning_config['small_training_set_path'])\n self.text_validation = preprocess.load_from_file(learning_config['small_validation_set_path'])\n self.text_test = preprocess.load_from_file(learning_config['small_testing_set_path'])\n elif learning_config['dataset_size'] == 'medium':\n self.text_training = preprocess.load_from_file(learning_config['medium_training_set_path'])\n self.text_validation = preprocess.load_from_file(learning_config['medium_validation_set_path'])\n self.text_test = preprocess.load_from_file(learning_config['medium_testing_set_path'])\n elif learning_config['dataset_size'] == 'large':\n self.text_training = preprocess.load_from_file(learning_config['large_training_set_path'])\n self.text_validation = preprocess.load_from_file(learning_config['large_validation_set_path'])\n self.text_test = preprocess.load_from_file(learning_config['large_testing_set_path'])\n self.text_all = self.text_training + self.text_validation + self.text_test\n print('Total corpus length:', len(self.text_all))\n self.chars = sorted(list(set(self.text_all)))\n print('Total corpus chars:', len(self.chars))\n # print(chars)\n\n # Building dictionary index\n print('Building dictionary index ...')\n self.char_indices = dict((c, i) for i, c in enumerate(self.chars))\n # print(char_indices)\n self.indices_char = dict((i, c) for i, c in enumerate(self.chars))\n # print(indices_char)\n\n def generate_samples(self, text):\n \"\"\"Cut the text in semi-redundant sequences of maxlen characters\"\"\"\n sentences = [] # List of all sentence as input\n next_chars = [] # List of all next chars as labels\n for i in range(0, len(text) - self.maxlen, self.step): # arg2 why this?\n sentences.append(text[i: i + self.maxlen])\n # print(sentences)\n next_chars.append(text[i + self.maxlen])\n # print(next_chars)\n print('Number of semi sequences or samples:', len(sentences))\n return sentences, next_chars\n\n def data_generator(self, sentences, next_chars):\n \"\"\"\n Batch data generator for large dataset not fit completely in memory\n # Index j now increase Shuffle\n\n :param sentences:\n :param next_chars:\n :return:\n \"\"\"\n j = random.randint(0, len(sentences) - (self.batch_size+1))\n # print('Vectorization...')\n while True:\n # Fix generator :))\n x = np.zeros((self.batch_size, self.maxlen, len(self.chars)), dtype=np.bool)\n y = np.zeros((self.batch_size, len(self.chars)), dtype=np.bool)\n # j = random.randint(0, len(sentences) - (self.batch_size + 1))\n next_chars2 = next_chars[j: j + self.batch_size] ## F...:)\n for i, one_sample in enumerate(sentences[j: j + self.batch_size]):\n for t, char in enumerate(one_sample):\n x[i, t, self.char_indices[char]] = 1\n y[i, self.char_indices[next_chars2[i]]] = 1\n\n yield (x, y)\n # yield self.generate_single_batch(sentences, next_chars)\n j += self.batch_size\n if j > (len(sentences) - (self.batch_size+1)):\n j = random.randint(0, len(sentences) - (self.batch_size+1))\n\n def data_generator_validation(self, sentences, next_chars):\n \"\"\"\n Batch data generator for large dataset not fit completely in memory\n # Index j now increase sequentially (validation don't need to shuffle)\n\n :param sentences:\n :param next_chars:\n :return:\n \"\"\"\n j = 0\n # print('Vectorization...')\n while True:\n # Fix generator :))\n x = np.zeros((self.batch_size, self.maxlen, len(self.chars)), dtype=np.bool)\n y = np.zeros((self.batch_size, len(self.chars)), dtype=np.bool)\n # j = random.randint(0, len(sentences) - (self.batch_size + 1))\n next_chars2 = next_chars[j: j + self.batch_size] ## F...:)\n for i, one_sample in enumerate(sentences[j: j + self.batch_size]):\n for t, char in enumerate(one_sample):\n x[i, t, self.char_indices[char]] = 1\n y[i, self.char_indices[next_chars2[i]]] = 1\n\n yield (x, y)\n # yield self.generate_single_batch(sentences, next_chars)\n j += self.batch_size\n if j > (len(sentences) - (self.batch_size + 1)):\n j = 0\n\n def data_generator_in_memory(self, sentences, next_chars):\n \"\"\"All data generate for small dataset fit completely in memory\"\"\"\n x = np.zeros((len(sentences), self.maxlen, len(self.chars)), dtype=np.bool)\n y = np.zeros((len(sentences), len(self.chars)), dtype=np.bool)\n for i, one_sample in enumerate(sentences):\n for t, char in enumerate(one_sample):\n x[i, t, self.char_indices[char]] = 1\n y[i, self.char_indices[next_chars[i]]] = 1\n return x, y\n\n def train(self,\n epochs=1,\n trained_model=None,\n trained_model_name='trained_model_wn'):\n \"\"\"\n Create and train deep model\n\n :param epochs: Specify number of epoch for training.\n :param\n :\n :return: Nothing.\n \"\"\"\n # Start time of training\n dt = datetime.datetime.now().strftime('_date_%Y-%m-%d_%H-%M-%S_')\n\n print('Generate training samples ...')\n sentences_training, next_chars_training = self.generate_samples(self.text_training)\n print('Generate validations samples ...')\n sentences_validation, next_chars_validation = self.generate_samples(self.text_validation)\n\n # print(sentences_training[0] + '\\t' + next_chars_training[0])\n # print(sentences_training[1] + '\\t' + next_chars_training[1])\n # print(sentences_training[2] + '\\t' + next_chars_training[2])\n # print(sentences_training[3] + '\\t' + next_chars_training[3])\n # print(sentences_training[4] + '\\t' + next_chars_training[4])\n #\n # input()\n\n print('Build and compile model ...')\n model = None\n model_name = None\n if trained_model is None:\n model, model_name = self.define_model((self.maxlen, len(self.chars)), len(self.chars))\n else:\n model = trained_model\n model_name = trained_model_name\n optimizer = RMSprop(lr=0.01) # [0.001, 0.01, 0.02, 0.05, 0.1]\n optimizer = Adam(lr=0.001) # Reduce from 0.001 to 0.0001 for model_10\n model.compile(optimizer=optimizer,\n loss='categorical_crossentropy',\n # metrics=['accuracy']\n metrics=['accuracy', cross_entropy, perplexity])\n\n print(model_name, ' summary ...')\n model.summary()\n\n print(model_name, ' count_params ...')\n print(model.count_params())\n # input()\n\n print('Set #5 callback ...')\n # callback #1 EarlyStopping\n # monitor= 'val_loss' or monitor='loss'?\n model_early_stopping = EarlyStopping(monitor='loss', min_delta=0.01, patience=5, verbose=1, mode='auto')\n\n # callback #2 ModelCheckpoint\n # Create a directory for each training process to keep model checkpoint in .h5 format\n dir_name = './model_checkpoint/pdfs/' + model_name + dt + 'epochs_' + str(epochs) + '/'\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n file_name = dir_name + model_name + dt + 'epoch_{epoch:02d}_val_loss_{val_loss:.4f}.h5'\n model_checkpoint = ModelCheckpoint(file_name, verbose=1)\n\n # callback #3 TensorBoard\n dir_name = './logs_tensorboard/pdfs/' + model_name + dt + 'epochs_' + str(epochs) + '/'\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n model_tensorboard = TensorBoard(log_dir=dir_name, histogram_freq=0, batch_size=self.batch_size,\n write_graph=True, write_grads=False, write_images=True, embeddings_freq=0,\n embeddings_layer_names=None, embeddings_metadata=None)\n\n # callback #4 CSVLogger\n # Create a directory and an empty csv file within to save mode csv log.\n dir_name = './logs_csv/pdfs/' + model_name + dt + 'epochs_' + str(epochs) + '/'\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n file_name = dir_name + model_name + dt + '_epochs_' + str(epochs) + '_step_' + str(self.step) + '.csv'\n open(file_name, mode='a', newline='').close()\n model_csv_logger = CSVLogger(file_name, separator=',', append=False)\n\n # callback #5 LambdaCallback\n dir_name = './generated_results/pdfs/' + model_name + dt + 'epochs_' + str(epochs) + '/'\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n def on_epoch_end(epoch, logs):\n nonlocal model\n nonlocal epochs\n nonlocal model_name\n nonlocal dir_name\n print('Sampling model and save results ... ')\n self.generate_and_fuzz_new_samples(model=model,\n model_name=model_name,\n epochs=epochs,\n current_epoch=epoch,\n dir_name=dir_name\n )\n\n generate_and_fuzz_new_samples_callback = LambdaCallback(on_epoch_begin=None,\n on_epoch_end=on_epoch_end,\n on_batch_begin=None,\n on_batch_end=None,\n on_train_begin=None,\n on_train_end=None\n )\n\n if learning_config['dataset_size'] == 'very_small': # very_small\n print('Start training on small dataset ...')\n x, y = self.data_generator_in_memory(sentences_training, next_chars_training)\n model.fit(x, y,\n batch_size=self.batch_size,\n epochs=epochs,\n validation_split=0.2,\n shuffle=True,\n callbacks=[model_checkpoint,\n model_tensorboard,\n model_csv_logger,\n generate_and_fuzz_new_samples_callback]\n )\n else:\n print('Build training and validation data generators ...')\n training_data_generator = self.data_generator(sentences_training, next_chars_training)\n validation_data_generator = self.data_generator_validation(sentences_validation, next_chars_validation)\n\n # x, y = next(training_data_generator)\n # print(x)\n # print('+'*75)\n # print(y)\n # print('#'*50)\n # x, y = next(training_data_generator)\n # print(x)\n # print('+' * 75)\n # print(y)\n # print('#' * 50)\n\n # input()\n\n print('Start training on large dataset ...')\n model.fit_generator(generator=training_data_generator,\n # steps_per_epoch=200,\n steps_per_epoch=len(sentences_training) // self.batch_size, # 1000,\n validation_data=validation_data_generator,\n validation_steps=len(sentences_validation) // (self.batch_size*2), # 100,\n # validation_steps=10,\n use_multiprocessing=False,\n workers=1,\n epochs=epochs,\n shuffle=True,\n callbacks=[model_checkpoint,\n model_tensorboard,\n model_csv_logger,\n generate_and_fuzz_new_samples_callback]\n )\n\n # end of train method\n # --------------------------------------------------------------------\n\n def generate_and_fuzz_new_samples(self,\n model=None,\n model_name='model_1',\n epochs=1,\n current_epoch=1,\n dir_name=None):\n \"\"\"\n sampling the model and generate new object\n :param model: The model which is training.\n :param model_name: Name of model (base on hyperparameters config in deep_model.py file) e.g. [model_1, model_2,\n ...]\n :param epochs: Number of total epochs of training, e.g. 10,20,30,40,50 or 60\n :param current_epoch: Number of current epoch\n :param dir_name: root directory for this running.\n :return: Nothing\n \"\"\"\n\n # End time of current epoch\n dt = datetime.datetime.now().strftime('_date_%Y-%m-%d_%H-%M-%S')\n dir_name = dir_name + 'epoch_' + str(current_epoch) + dt + '/'\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n # Fuzzing hyper-parameters\n\n diversities = [i*0.10 for i in range(1, 20, 2)]\n diversities = [0.2, 0.5, 1.0, 1.2, 1.5, 1.8]\n diversities = [1.0] # for sou and for mou\n # diversities = [1.5]\n\n generated_obj_total = 30200 # [5, 10, 100, 1000, 3000] {1000-1100 for sou and 3000-3100 for muo}\n generated_obj_with_same_prefix = 20 # [1, 5, 10, 20, 40] {10 for sou and 20 for mou}\n generated_obj_max_allowed_len = random.randint(450, 550) # Choose max allowed len for object randomly\n exclude_from_fuzzing_set = {'s', 't', 'r', 'e', 'a', 'm', 'e', 'n', 'd', 'o', 'b', 'j'} # set(['s', 't', 'r', 'e', 'a', 'm'])\n\n # Learn and fuzz paper hyper-parameters\n t_fuzz = 0.90 # For comparision with p_fuzz where p_fuzz is a random number (if p_fuzz > t_fuzz)\n p_t = 0.90 # 0.9 and more for format fuzzing; 0.5 and less than 0.5 for data fuzzing. Now format fuzzing.\n\n # End of fuzzing hyper-parameters\n\n testset_objects_list = preprocess.get_list_of_object(self.text_test)\n testset_object_gt_maxlen_list = []\n for obj in testset_objects_list:\n if len(obj) > self.maxlen+len(' endobj'):\n testset_object_gt_maxlen_list.append(obj)\n print('len filtered test-set: ', len(testset_object_gt_maxlen_list))\n generated_total = ''\n for diversity in diversities:\n generated_total = ''\n for q in range(round(generated_obj_total/generated_obj_with_same_prefix)):\n\n obj_index = random.randint(0, len(testset_object_gt_maxlen_list) - 1)\n generated_obj_counter = 0\n generated_obj_len = 0\n generated = ''\n stop_condition = False\n endobj_attach_manually = False\n # print()\n print('-- Diversity:', diversity)\n\n obj_prefix = str(testset_object_gt_maxlen_list[obj_index])[0: self.maxlen]\n generated += obj_prefix\n # prob_vals = '1 ' * self.maxlen\n # learnt_grammar = obj_prefix\n\n print('--- Generating ts_text with seed:\\n \"' + obj_prefix + '\"')\n sys.stdout.write(generated)\n\n if generated.endswith('endobj'):\n generated_obj_counter += 1\n\n if generated_obj_counter > generated_obj_with_same_prefix:\n stop_condition = True\n\n while not stop_condition:\n x_pred = np.zeros((1, self.maxlen, len(self.chars)))\n for t, char in enumerate(obj_prefix):\n x_pred[0, t, self.char_indices[char]] = 1.\n\n preds = model.predict(x_pred, verbose=0)[0]\n next_index, prob, preds2 = self.sample(preds, diversity)\n next_char = self.indices_char[next_index]\n next_char_for_prefix = next_char\n\n ###### Fuzzing section we don't need it yet!\n if next_char not in exclude_from_fuzzing_set:\n p_fuzz = random.random()\n if p_fuzz > t_fuzz and preds2[next_index] > p_t:\n next_index = np.argmin(preds2)\n print(' FUZZ ', end='', flush=True)\n next_char = self.indices_char[next_index] # next_char updated.\n ###### End of fuzzing section\n\n obj_prefix = obj_prefix[1:] + next_char_for_prefix\n generated += next_char # next_char_for_prefix #\n generated_obj_len += 1\n\n if generated.endswith('endobj'):\n generated_obj_counter += 1\n generated_obj_len = 0\n elif (generated.endswith('endobj') is False) and \\\n (generated_obj_len > generated_obj_max_allowed_len):\n # Attach '\\nendobj\\n' manually, and reset obj_prefix\n generated += '\\nendobj\\n'\n generated_obj_counter += 1\n generated_obj_len = 0\n endobj_attach_manually = True\n\n if generated_obj_counter >= generated_obj_with_same_prefix: # Fix: Change > to >= (13970315)\n stop_condition = True\n elif endobj_attach_manually:\n # Reset prefix:\n # Here we need to modify obj_prefix because we manually change the generated_obj!\n # Below we add this new repair:\n\n # obj_prefix = obj_prefix[len('\\nendobj\\n'):] + '\\nendobj\\n'\n\n # Instead of modify obj_prefix we can reset prefix if we found that 'endobj' dose not generate\n # automatically. It seems to be better option, so we do this:\n obj_index = random.randint(0, len(testset_object_gt_maxlen_list) - 1)\n obj_prefix = str(testset_object_gt_maxlen_list[obj_index])[0: self.maxlen]\n generated += obj_prefix\n endobj_attach_manually = False\n\n sys.stdout.write(next_char)\n sys.stdout.flush()\n # print()\n generated_total += generated + '\\n'\n # save generated_result to file inside program\n\n file_name = model_name \\\n + '_diversity_' + repr(diversity) \\\n + '_epochs_' + repr(epochs) \\\n + '_step_' + repr(self.step) \\\n + '.txt'\n preprocess.save_to_file(dir_name + file_name, generated_total)\n # preprocess.save_to_file(dir_name + file_name + 'probabilities.txt', prob_vals)\n # preprocess.save_to_file(dir_name + file_name + 'learntgrammar.txt',learnt_grammar)\n print('Diversity %s save to file successfully.' % diversity)\n\n print('End of generation method.')\n print('Starting new epoch ...')\n return generated_total\n\n # Lower temperature will cause the model to make more likely,\n # but also more boring and conservative predictions.\n def sample(self, preds, temperature=1.0):\n \"\"\"\n Helper function to sample an index from a probability array\n :param preds:\n :param temperature:\n :return:\n \"\"\"\n\n # print('raw predictions = ', preds)\n preds = np.asarray(preds).astype('float64')\n\n preds = np.log(preds) / temperature\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n\n # Sampling with numpy functions:\n probas = np.random.multinomial(1, preds, 1)\n # print()\n # print('sanitize predictions = ', preds)\n return np.argmax(probas), probas, preds\n\n def no_sample(self):\n pass\n\n def sample_space(self):\n pass\n\n def save_model_plot(self, model, epochs):\n \"\"\"\n Save the model architecture plot.\n :param model:\n :param epochs:\n :return:\n \"\"\"\n dt = datetime.datetime.now().strftime('_%Y%m%d_%H%M%S_')\n # plot the model\n plot_model(model, to_file='./modelpic/date_' + dt + 'epochs_' + str(epochs) + '.png',\n show_shapes=True, show_layer_names=True)\n\n def load_model_and_generate(self, model_name='model_7', epochs=38):\n dt = datetime.datetime.now().strftime('_date_%Y-%m-%d_%H-%M-%S')\n dir_name = './generated_results/pdfs/' + model_name + dt + 'epochs_' + str(epochs) + '/'\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\n model = load_model('./model_checkpoint/best_models/'\n 'model_7_date_2018-05-14_21-44-21_epoch_38_val_loss_0.3300.h5',\n compile=False)\n optimizer = Adam(lr=0.001) # Reduce from 0.001 to 0.0001 just for model_10\n\n model.compile(optimizer=optimizer,\n loss='categorical_crossentropy',\n # metrics=['accuracy']\n metrics=['accuracy'])\n\n seq = self.generate_and_fuzz_new_samples(model=model,\n model_name=model_name,\n epochs=epochs,\n current_epoch=38,\n dir_name=dir_name)\n\n list_of_obj = preprocess.get_list_of_object(seq=seq, is_sort=False)\n return list_of_obj\n\n def get_model_summary(self):\n print('Get model summary ...')\n model, model_name = self.define_model((self.maxlen, len(self.chars)), len(self.chars))\n print(model_name, ' summary ...')\n model.summary()\n print(model_name, ' count_params ...')\n print(model.count_params())\n\n\ndef main(argv):\n \"\"\" The main function to call train() method\"\"\"\n epochs = 100\n fff = FileFormatFuzzer(maxlen=50, step=3, batch_size=256)\n # trained_model_dir = './model_checkpoint/best_models/'\n # trained_model_file_name = 'model_7_date_2018-05-14_21-44-21_epoch_65_val_loss_0.3335.h5'\n # trained_model_path = trained_model_dir + trained_model_file_name\n # trained_model = load_model(trained_model_path, compile=False)\n\n # Train deep model from first or continue training for previous trained model.\n # Trained model pass as argument.\n # fff.train(epochs=epochs,\n # trained_model=trained_model,\n # trained_model_name='model_7-1'\n # )\n # fff.get_model_summary()\n list_of_obj = fff.load_model_and_generate()\n print('Len list_of_obj', len(list_of_obj))\n dt = datetime.datetime.now().strftime('_%Y_%m_%d__%H_%M_%S_')\n print('Generation complete successfully', dt)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n" ]
[ [ "numpy.log", "numpy.asarray", "numpy.random.multinomial", "numpy.argmax", "numpy.argmin", "numpy.exp", "numpy.sum" ] ]
rbktech/netket
[ "847e120cad48f9c92d394e2078370e452f268a3d" ]
[ "netket/logging/json_log.py" ]
[ "# Copyright 2021 The NetKet 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\nimport json\nimport dataclasses\nimport orjson\n\nimport os\nfrom os import path as _path\nimport numpy as np\nimport jax\n\nfrom flax import serialization\n\nfrom jax.tree_util import tree_map\n\nfrom .runtime_log import RuntimeLog\n\n\ndef _exists_json(prefix):\n return _path.exists(prefix + \".log\") or _path.exists(prefix + \".mpack\")\n\n\ndef default(obj):\n if hasattr(obj, \"to_json\"):\n return obj.to_json()\n elif hasattr(obj, \"to_dict\"):\n return obj.to_dict()\n elif isinstance(obj, np.ndarray):\n if np.issubdtype(obj.dtype, np.complexfloating):\n return {\"real\": obj.real, \"imag\": obj.imag}\n else:\n if obj.ndim == 0:\n return obj.item()\n elif obj.ndim == 1:\n return obj.tolist()\n else:\n raise TypeError\n\n elif hasattr(obj, \"_device\"):\n return np.array(obj)\n elif isinstance(obj, complex):\n return {\"real\": obj.real, \"imag\": obj.imag}\n\n raise TypeError\n\n\nclass JsonLog(RuntimeLog):\n \"\"\"\n Json Logger, that can be passed with keyword argument `logger` to Monte\n Carlo drivers in order to serialize the outpit data of the simulation.\n\n If the model state is serialized, then it is serialized using the msgpack protocol of flax.\n For more information on how to de-serialize the output, see\n `here <https://flax.readthedocs.io/en/latest/flax.serialization.html>`_.\n The target of the serialization is the variational state itself.\n\n Data is serialized to json as several nested dictionaries. You can deserialize by simply calling\n :code:`json.load(open(filename))`.\n Logged expectation values will be captured inside histories objects, so they will have a\n subfield `iter` with the iterations at which that quantity has been computed, then `Mean` and\n others.\n Complex numbers are logged as dictionaries :code:`{'real':list, 'imag':list}`.\n \"\"\"\n\n def __init__(\n self,\n output_prefix: str,\n mode: str = \"write\",\n save_params_every: int = 50,\n write_every: int = 50,\n save_params: bool = True,\n ):\n \"\"\"\n Construct a Json Logger.\n\n Args:\n output_prefix: the name of the output files before the extension\n save_params_every: every how many iterations should machine parameters be flushed to file\n write_every: every how many iterations should data be flushed to file\n mode: Specify the behaviour in case the file already exists at this output_prefix. Options are\n - `[w]rite`: (default) overwrites file if it already exists;\n - `[a]ppend`: appends to the file if it exists, overwise creates a new file;\n - `[x]` or `fail`: fails if file already exists;\n save_params: bool flag indicating whever parameters should be serialized\n \"\"\"\n super().__init__()\n\n # Shorthands for mode\n if mode == \"w\":\n mode = \"write\"\n elif mode == \"a\":\n mode = \"append\"\n elif mode == \"x\":\n mode = \"fail\"\n\n if not ((mode == \"write\") or (mode == \"append\") or (mode == \"fail\")):\n raise ValueError(\n \"Mode not recognized: should be one of `[w]rite`, `[a]ppend` or `[x]`(fail).\"\n )\n\n file_exists = _exists_json(output_prefix)\n\n starting_json_content = {\"Output\": []}\n\n if file_exists and mode == \"append\":\n # if there is only the .mpacck file but not the json one, raise an error\n if not _path.exists(output_prefix + \".log\"):\n raise ValueError(\n \"History file does not exists, but wavefunction file does. Please change `output_prefix or set mode=`write`.\"\n )\n\n starting_json_content = json.load(open(output_prefix + \".log\"))\n\n elif file_exists and mode == \"fail\":\n raise ValueError(\n \"Output file already exists. Either delete it manually or change `output_prefix`.\"\n )\n\n dir_name = _path.dirname(output_prefix)\n if dir_name != \"\":\n os.makedirs(dir_name, exist_ok=True)\n\n self._prefix = output_prefix\n self._write_every = write_every\n self._save_params_every = save_params_every\n self._old_step = 0\n self._steps_notflushed_write = 0\n self._steps_notflushed_pars = 0\n self._save_params = save_params\n\n def __call__(self, step, item, variational_state):\n old_step = self._old_step\n super().__call__(step, item, variational_state)\n\n if (\n self._steps_notflushed_write % self._write_every == 0\n or step == old_step - 1\n ):\n self._flush_log()\n if (\n self._steps_notflushed_pars % self._save_params_every == 0\n or step == old_step - 1\n ):\n self._flush_params(variational_state)\n\n self._old_step = step\n self._steps_notflushed_write += 1\n self._steps_notflushed_pars += 1\n\n def _flush_log(self):\n with open(self._prefix + \".log\", \"wb\") as outfile:\n\n outfile.write(orjson.dumps(self.data, default=default))\n self._steps_notflushed_write = 0\n\n def _flush_params(self, variational_state):\n if not self._save_params:\n return\n\n binary_data = serialization.to_bytes(variational_state.variables)\n with open(self._prefix + \".mpack\", \"wb\") as outfile:\n outfile.write(binary_data)\n\n self._steps_notflushed_pars = 0\n\n def flush(self, variational_state):\n \"\"\"\n Writes to file the content of this logger.\n\n Args:\n variational_state: optionally also writes the parameters of the machine.\n \"\"\"\n self._flush_log()\n\n if variational_state is not None:\n self._flush_params(variational_state)\n" ]
[ [ "numpy.issubdtype", "numpy.array" ] ]
aframires/freesound-loop-annotator
[ "a24e0c23bfc671e41e8627150e7b9fcae5c8cb13" ]
[ "data_analysis/audiocommons_ffont/ac_utils/plotting.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn\nseaborn.set(style=\"dark\")\n\n\ndef plot_waveform(audio, sample_rate=44100, show=True, title=None):\n plt.figure()\n if title is not None:\n plt.title(title)\n time = np.linspace(0, len(audio)/sample_rate, num=len(audio))\n plt.plot(time, audio)\n if show:\n plt.show()\n\n\ndef plot_waveform_with_ticks(audio, ticks, sample_rate=44100, show=True, title=None):\n plt.figure()\n if title is not None:\n plt.title(title)\n for tick in ticks:\n plt.vlines(tick, 0, 1, label='tick', color='r')\n time = np.linspace(0, len(audio)/sample_rate, num=len(audio))\n plt.plot(time, audio)\n if show:\n plt.show()\n\n\ndef annotate_point_pair(ax, text, xy_start, xy_end, xycoords='data', text_offset=6, textx_offset=0, text_size=12, arrowprops=None):\n \"\"\"\n Taken from: http://stackoverflow.com/a/32522399\n Annotates two points by connecting them with an arrow.\n The annotation text is placed near the center of the arrow.\n \"\"\"\n\n if arrowprops is None:\n arrowprops = dict(arrowstyle= '<->', facecolor='black', linewidth=1.0)\n\n assert isinstance(text,str)\n\n xy_text = ((xy_start[0] + xy_end[0])/2. + textx_offset, (xy_start[1] + xy_end[1])/2.)\n arrow_vector = xy_end[0]-xy_start[0] + (xy_end[1] - xy_start[1]) * 1j\n arrow_angle = np.angle(arrow_vector)\n text_angle = arrow_angle - 0.5*np.pi\n\n ax.annotate(\n '', xy=xy_end, xycoords=xycoords,\n xytext=xy_start, textcoords=xycoords,\n arrowprops=arrowprops)\n\n label = ax.annotate(\n text,\n xy=xy_text,\n xycoords=xycoords,\n xytext=(text_offset * np.cos(text_angle), text_offset * np.sin(text_angle)),\n textcoords='offset points', size=text_size)\n\n return label" ]
[ [ "matplotlib.pyplot.vlines", "matplotlib.pyplot.title", "numpy.cos", "numpy.sin", "matplotlib.pyplot.plot", "numpy.angle", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
Komal-99/Hand_gesture_mouse-keyboard
[ "c96ea29f2e7907bf670283d5fe089ff1e4213fe3" ]
[ "mouse_gesture.py" ]
[ "\r\nimport cv2 as cv\r\nimport mediapipe as mp\r\nimport numpy as np\r\nimport time\r\nimport pyautogui as p\r\nimport keyboard\r\nimport tkinter as tk\r\nfrom pynput.mouse import Button, Controller\r\n\r\nmouse = Controller()\r\nmp_drawing = mp.solutions.drawing_utils\r\nmp_hands = mp.solutions.hands\r\nroot=tk.Tk()\r\nglobal screenRes\r\nscreenRes = (root.winfo_screenwidth(),\r\n root.winfo_screenheight()) \r\n\r\nVal4 = tk.IntVar()\r\nVal4.set(30)\r\nkando = Val4.get()/10\r\nfingerTipIds = [4, 8, 12, 16, 20]\r\ncap_device=0 \r\ndef draw_circle(image, x, y, roudness, color):\r\n cv.circle(image, (int(x), int(y)), roudness, color,\r\n thickness=5, lineType=cv.LINE_8, shift=0)\r\n\r\ndef calculate_distance(l1, l2):\r\n v = np.array([l1[0], l1[1]])-np.array([l2[0], l2[1]])\r\n distance = np.linalg.norm(v)\r\n return distance\r\n\r\ndef calculate_moving_average(landmark, ran, LiT): \r\n while len(LiT) < ran: \r\n LiT.append(landmark)\r\n LiT.append(landmark) \r\n if len(LiT) > ran: \r\n LiT.pop(0)\r\n return sum(LiT)/ran\r\ndef get_hand_label(index,hand,results):\r\n output =('Right 0.97', (1283, 827))\r\n for idx,classification in enumerate(results.multi_handedness):\r\n if classification.classification[0].index == index:\r\n # process results \r\n label=classification.classification[0].label\r\n score=classification.classification[0].score\r\n text='{} {}'.format(label,round(score,2))\r\n # extract coordinates\r\n coords=tuple(np.multiply(np.array((hand.landmark[mp_hands.HandLandmark.WRIST].x,hand.landmark[mp_hands.HandLandmark.WRIST].y)),[1536,864]).astype(int))\r\n output=text,coords\r\n return output\r\n\r\n\r\n\r\ndef main(cap_device, kando):\r\n dis = 0.7 \r\n preX, preY = 0, 0\r\n nowCli, preCli = 0, 0 \r\n norCli, prrCli = 0, 0 \r\n douCli = 0 \r\n i, k, h = 0, 0, 0\r\n LiTx, LiTy, list0x, list0y, list1x, list1y, list4x, list4y, list6x, list6y, list8x, list8y, list12x, list12y = [\r\n ], [], [], [], [], [], [], [], [], [], [], [], [], [] \r\n nowUgo = 1\r\n cap_width = 1280\r\n cap_height = 720\r\n start, c_start = float('inf'), float('inf')\r\n c_text = 0\r\n \r\n video = cv.VideoCapture(cap_device)\r\n cfps = int(video.get(cv.CAP_PROP_FPS))\r\n if cfps < 30:\r\n video.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)\r\n video.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)\r\n cfps = int(video.get(cv.CAP_PROP_FPS))\r\n ran = max(int(cfps/10), 1)\r\n hands = mp_hands.Hands(\r\n min_detection_confidence=0.8, \r\n min_tracking_confidence=0.8, \r\n max_num_hands=2\r\n )\r\n while video.isOpened():\r\n p_s = time.perf_counter()\r\n success, image = video.read()\r\n image = cv.cvtColor(cv.flip(image, 1), cv.COLOR_BGR2RGB)\r\n image.flags.writeable = False \r\n results = hands.process(image) \r\n\r\n image.flags.writeable = True \r\n image = cv.cvtColor(image, cv.COLOR_RGB2BGR)\r\n image_height, image_width, _ = image.shape\r\n landmarks_list = []\r\n if results.multi_hand_landmarks:\r\n hand_lands = results.multi_hand_landmarks[-1]\r\n for index, lm in enumerate(hand_lands.landmark):\r\n h, w, c = image.shape # Height, Width, Channels\r\n cx, cy = int(lm.x * w), int(lm.y * h)\r\n landmarks_list.append([index, cx, cy])\r\n\r\n # Drawing the Landmarks for only One Hand\r\n # Landmarks will be drawn for the Hand which was Detected First\r\n mp_drawing.draw_landmarks(image, hand_lands, mp_hands.HAND_CONNECTIONS)\r\n\r\n for num,hand_landmarks in enumerate(results.multi_hand_landmarks):\r\n \r\n mp_drawing.draw_landmarks(\r\n image, hand_landmarks, mp_hands.HAND_CONNECTIONS,mp_drawing.DrawingSpec(color=(121,22,76),thickness=2,circle_radius=4),mp_drawing.DrawingSpec(color=(250,44,250),thickness=2,circle_radius=2),)\r\n get_hand_label(num,hand_landmarks,results)# to detetct left or right hand\r\n \r\n #render left right detection \r\n if get_hand_label(num,hand_landmarks,results):\r\n text,coords=get_hand_label(num,hand_landmarks,results)\r\n cv.putText(image,text,coords,cv.FONT_HERSHEY_SIMPLEX,1,(255,0,255),2,cv.LINE_8)\r\n if(text[0]==\"R\"):\r\n\r\n landmark0 = [calculate_moving_average(hand_landmarks.landmark[0].x, ran, list0x), calculate_moving_average(\r\n hand_landmarks.landmark[0].y, ran, list0y)]\r\n landmark1 = [calculate_moving_average(hand_landmarks.landmark[1].x, ran, list1x), calculate_moving_average(\r\n hand_landmarks.landmark[1].y, ran, list1y)]\r\n landmark4 = [calculate_moving_average(hand_landmarks.landmark[4].x, ran, list4x), calculate_moving_average(\r\n hand_landmarks.landmark[4].y, ran, list4y)]\r\n landmark6 = [calculate_moving_average(hand_landmarks.landmark[6].x, ran, list6x), calculate_moving_average(\r\n hand_landmarks.landmark[6].y, ran, list6y)]\r\n landmark8 = [calculate_moving_average(hand_landmarks.landmark[8].x, ran, list8x), calculate_moving_average(\r\n hand_landmarks.landmark[8].y, ran, list8y)]\r\n landmark12 = [calculate_moving_average(hand_landmarks.landmark[12].x, ran, list12x), calculate_moving_average(\r\n hand_landmarks.landmark[12].y, ran, list12y)]\r\n\r\n absKij = calculate_distance(landmark0, landmark1)\r\n absUgo = calculate_distance(landmark8, landmark12) / absKij\r\n absCli = calculate_distance(landmark4, landmark6) / absKij\r\n\r\n posx, posy = mouse.position\r\n\r\n nowX = calculate_moving_average(\r\n hand_landmarks.landmark[8].x, ran, LiTx)\r\n nowY = calculate_moving_average(\r\n hand_landmarks.landmark[8].y, ran, LiTy)\r\n\r\n dx = kando * (nowX - preX) * image_width\r\n dy = kando * (nowY - preY) * image_height\r\n dx = dx+0.5\r\n dy = dy+0.5\r\n preX = nowX\r\n preY = nowY\r\n # print(dx, dy)\r\n if posx+dx < 0: \r\n dx = -posx\r\n elif posx+dx > screenRes[0]:\r\n dx = screenRes[0]-posx\r\n if posy+dy < 0:\r\n dy = -posy\r\n elif posy+dy > screenRes[1]:\r\n dy = screenRes[1]-posy\r\n\r\n \r\n if absCli < dis:\r\n nowCli = 1 # nowCli: 1:click 0:non click\r\n draw_circle(image, hand_landmarks.landmark[8].x * image_width,\r\n hand_landmarks.landmark[8].y * image_height, 20, (0, 250, 250))\r\n elif absCli >= dis:\r\n nowCli = 0\r\n if np.abs(dx) > 7 and np.abs(dy) > 7:\r\n k = 0 \r\n \r\n if nowCli == 1 and np.abs(dx) < 7 and np.abs(dy) < 7:\r\n if k == 0: \r\n start = time.perf_counter()\r\n k += 1\r\n end = time.perf_counter()\r\n if end-start > 1.5:\r\n norCli = 1\r\n draw_circle(image, hand_landmarks.landmark[8].x * image_width,\r\n hand_landmarks.landmark[8].y * image_height, 20, (0, 0, 250))\r\n else:\r\n norCli = 0\r\n \r\n # cursor\r\n if absUgo >= dis and nowUgo == 1:\r\n mouse.move(dx, dy)\r\n \r\n draw_circle(image, hand_landmarks.landmark[8].x * image_width,\r\n hand_landmarks.landmark[8].y * image_height, 8, (250, 0, 0))\r\n # left click\r\n if nowCli == 1 and nowCli != preCli:\r\n \r\n cv.putText(image, \"Left click\", (45, 365), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 3) \r\n cv.putText(image, \"For double left click do \", (33, 430),cv.FONT_HERSHEY_SIMPLEX, 1, (90, 233, 54), 3)\r\n cv.putText(image, \"left click twice in 0.5 sec\", (33, 465),cv.FONT_HERSHEY_SIMPLEX, 1, (90, 233, 54), 3)\r\n\r\n if h == 1: \r\n h = 0\r\n elif h == 0: \r\n \r\n mouse.press(Button.left)\r\n # print('Click')\r\n # left click release\r\n if nowCli == 0 and nowCli != preCli:\r\n mouse.release(Button.left)\r\n k = 0\r\n # print('Release')\r\n if douCli == 0: \r\n c_start = time.perf_counter()\r\n douCli += 1\r\n c_end = time.perf_counter()\r\n if 10*(c_end-c_start) > 5 and douCli == 1: \r\n mouse.click(Button.left, 2) # double click\r\n douCli = 0\r\n # right click\r\n if norCli == 1 and norCli != prrCli:\r\n # mouse.release(Button.left) \r\n \r\n cv.putText(image, \"Right Click\", (45, 375), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 3) \r\n mouse.press(Button.right)\r\n mouse.release(Button.right)\r\n h = 1 \r\n # print(\"right click\")\r\n # scroll\r\n if hand_landmarks.landmark[8].y-hand_landmarks.landmark[5].y > -0.06:\r\n mouse.scroll(0, -dy/50)\r\n \r\n cv.putText(image, \"Scroll\", (45, 375), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 3)\r\n \r\n draw_circle(image, hand_landmarks.landmark[8].x * image_width,\r\n hand_landmarks.landmark[8].y * image_height, 20, (0, 0, 0))\r\n nowUgo = 0\r\n else:\r\n nowUgo = 1\r\n\r\n preCli = nowCli\r\n prrCli = norCli\r\n if(text[0]==\"L\"):\r\n \r\n # Stores 1 if finger is Open and 0 if finger is closed\r\n fingers_open = []\r\n if len(landmarks_list) != 0:\r\n for tipId in fingerTipIds:\r\n if tipId == 4: # That is the thumb\r\n if landmarks_list[tipId][1] > landmarks_list[tipId - 1][1]:\r\n fingers_open.append(1)\r\n else:\r\n fingers_open.append(0)\r\n else:\r\n if landmarks_list[tipId][2] < landmarks_list[tipId - 2][2]:\r\n fingers_open.append(1)\r\n else:\r\n fingers_open.append(0)\r\n\r\n # Counts the Number of Fingers Open\r\n count_fingers_open = fingers_open.count(1)\r\n\r\n # If Hand Detected\r\n flag=\"\"\r\n if results.multi_hand_landmarks != None:\r\n \r\n if count_fingers_open == 1:\r\n \r\n cv.putText(image, \"left\", (45, 375), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 5)\r\n \r\n\r\n p.press('Left',presses=1)\r\n \r\n \r\n if count_fingers_open ==5:\r\n \r\n cv.putText(image, \"up\", (45, 375), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 5)\r\n p.press('Up',presses=1)\r\n \r\n\r\n if count_fingers_open == 2:\r\n \r\n cv.putText(image, \"right\", (45, 375), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 5)\r\n \r\n p.press('Right',presses=1)\r\n \r\n\r\n if count_fingers_open ==0:\r\n \r\n cv.putText(image, \"down\", (45, 375), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 5)\r\n p.press('Down',presses=1)\r\n \r\n \r\n \r\n p_e = time.perf_counter()\r\n fps = str(int(1/(float(p_e)-float(p_s))))\r\n cv.putText(image, \"FPS:\"+fps, (20, 80),\r\n cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3)\r\n \r\n cv.imshow(\"Hand gesture\",image)\r\n if (cv.waitKey(10) & 0xFF == ord('q')): \r\n break\r\n video.release()\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n main(cap_device, kando)\r\n\r\n" ]
[ [ "numpy.abs", "numpy.array", "numpy.linalg.norm" ] ]
quantumiracle/DQN_traffic_light_-control
[ "464c17ba25ebcb49f78d6cdcc96d7fe3764d7508" ]
[ "8.ddpg_for_grid/ddpg/models.py" ]
[ "import tensorflow as tf\nfrom common.models import get_network_builder\n\n\nclass Model(object):\n def __init__(self, name, network='mlp', **network_kwargs):\n self.name = name\n self.network_builder = get_network_builder(network)(**network_kwargs)\n\n @property\n def vars(self):\n return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name)\n\n @property\n def trainable_vars(self):\n return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.name)\n\n @property\n def perturbable_vars(self):\n return [var for var in self.trainable_vars if 'LayerNorm' not in var.name]\n\n\nclass Actor(Model):\n def __init__(self, nb_actions, name='actor', network='mlp', **network_kwargs):\n super().__init__(name=name, network=network, **network_kwargs)\n self.nb_actions = nb_actions\n print(self.nb_actions)\n #added\n self.hidden_layer1=400\n self.hidden_layer2=400\n self.hidden_layer3=600\n self.hidden_layer4=200\n\n def __call__(self, obs, reuse=False):\n with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE):\n x = self.network_builder(obs)\n # x = tf.layers.dense(x, self.nb_actions, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n # x = tf.nn.tanh(x)\n\n x = tf.layers.dense(x, self.hidden_layer1, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, self.hidden_layer2, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, self.hidden_layer3, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, self.hidden_layer4, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, self.nb_actions, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n '''\n in order to discrete the action, apply the trick of sharp sigmoid.\n with the following line: x<0 will be near 0, x>0 will be near 1\n then the discrete step in action choice wont affect too much of accuracy (with only small change of action value!)\n the key point of this step is to keep most part of discrete operation in the tensor graph, so as to be back propagated\n '''\n\n x = tf.nn.sigmoid(1000*x) # sigmoid ~ (0,1), tanh ~ (-1 , 1)\n\n return x\n\n\nclass Critic(Model):\n def __init__(self, name='critic', network='mlp', **network_kwargs):\n super().__init__(name=name, network=network, **network_kwargs)\n self.layer_norm = True\n\n #added\n self.hidden_layer1=400\n self.hidden_layer2=400\n self.hidden_layer3=600\n self.hidden_layer4=200\n\n\n def __call__(self, obs, action, reuse=False):\n with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE):\n x = tf.concat([obs, action], axis=-1) # this assumes observation and action can be concatenated\n x = self.network_builder(x)\n # x = tf.layers.dense(x, 1, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n\n x = tf.layers.dense(x, self.hidden_layer1, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, self.hidden_layer2, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, self.hidden_layer3, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, self.hidden_layer4, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n x = tf.nn.tanh(x)\n x = tf.layers.dense(x, 1, kernel_initializer=tf.random_uniform_initializer(minval=-3e-3, maxval=3e-3))\n\n return x\n\n @property\n def output_vars(self):\n output_vars = [var for var in self.trainable_vars if 'output' in var.name]\n return output_vars\n" ]
[ [ "tensorflow.concat", "tensorflow.nn.sigmoid", "tensorflow.random_uniform_initializer", "tensorflow.get_collection", "tensorflow.nn.tanh", "tensorflow.variable_scope" ] ]
BassyKuo/MicrosoftLearning-Azure-DP100
[ "c57230e4a98f55308f8f533b26df3da50a4a3ffb" ]
[ "diabetes_pipeline/train_diabetes.py" ]
[ "# Import libraries\nfrom azureml.core import Run\nimport argparse\nimport pandas as pd\nimport numpy as np\nimport joblib\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nimport matplotlib.pyplot as plt\n\n# Get parameters\nparser = argparse.ArgumentParser()\nparser.add_argument('--output_folder', type=str, dest='output_folder', default=\"diabetes_model\", help='output folder')\nargs = parser.parse_args()\noutput_folder = args.output_folder\n\n# Get the experiment run context\nrun = Run.get_context()\n\n# load the diabetes data (passed as an input dataset)\nprint(\"Loading Data...\")\ndiabetes = run.input_datasets['diabetes_train'].to_pandas_dataframe()\n\n# Separate features and labels\nX, y = diabetes[['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']].values, diabetes['Diabetic'].values\n\n# Split data into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)\n\n# Train adecision tree model\nprint('Training a decision tree model')\nmodel = DecisionTreeClassifier().fit(X_train, y_train)\n\n# calculate accuracy\ny_hat = model.predict(X_test)\nacc = np.average(y_hat == y_test)\nprint('Accuracy:', acc)\nrun.log('Accuracy', np.float(acc))\n\n# calculate AUC\ny_scores = model.predict_proba(X_test)\nauc = roc_auc_score(y_test,y_scores[:,1])\nprint('AUC: ' + str(auc))\nrun.log('AUC', np.float(auc))\n\n# plot ROC curve\nfpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1])\nfig = plt.figure(figsize=(6, 4))\n# Plot the diagonal 50% line\nplt.plot([0, 1], [0, 1], 'k--')\n# Plot the FPR and TPR achieved by our model\nplt.plot(fpr, tpr)\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC Curve')\nrun.log_image(name = \"ROC\", plot = fig)\nplt.show()\n\n# Save the trained model\nos.makedirs(output_folder, exist_ok=True)\noutput_path = output_folder + \"/model.pkl\"\njoblib.dump(value=model, filename=output_path)\n\nrun.complete()\n" ]
[ [ "sklearn.metrics.roc_auc_score", "matplotlib.pyplot.title", "sklearn.model_selection.train_test_split", "sklearn.metrics.roc_curve", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "sklearn.tree.DecisionTreeClassifier", "numpy.float", "matplotlib.pyplot.xlabel", "numpy.average", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
hikvisionresearch/opera
[ "0fb345a7ad0046c6fd674959c0ae19a65adeeacf" ]
[ "opera/models/dense_heads/petr_head.py" ]
[ "# Copyright (c) Hikvision Research Institute. All rights reserved.\nimport copy\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import (Linear, bias_init_with_prob, constant_init, normal_init,\n build_activation_layer)\nfrom mmcv.runner import force_fp32\nfrom mmdet.core import (bbox_cxcywh_to_xyxy, bbox_xyxy_to_cxcywh, multi_apply,\n reduce_mean)\nfrom mmdet.models.utils.transformer import inverse_sigmoid\nfrom mmdet.models.dense_heads import AnchorFreeHead\n\nfrom opera.core.bbox import build_assigner, build_sampler\nfrom opera.core.keypoint import (gaussian_radius, draw_umich_gaussian,\n weighted_neg_loss)\nfrom opera.models.utils import build_positional_encoding, build_transformer\nfrom ..builder import HEADS, build_loss\n\n\[email protected]_module()\nclass PETRHead(AnchorFreeHead):\n \"\"\"Implements the PETR transformer head.\n\n More details can be found in the `paper\n <https://arxiv.org/abs/2010.04159>`_ .\n\n Args:\n num_classes (int): Number of categories excluding the background.\n in_channels (int): Number of channels in the input feature map.\n num_query (int): Number of query in Transformer.\n num_kpt_fcs (int, optional): Number of fully-connected layers used in\n `FFN`, which is then used for the keypoint regression head. Default 2.\n transformer (obj:`mmcv.ConfigDict`|dict): Config for transformer.\n Default: None.\n sync_cls_avg_factor (bool): Whether to sync the avg_factor of\n all ranks. Default to False.\n positional_encoding (obj:`mmcv.ConfigDict`|dict):\n Config for position encoding.\n loss_cls (obj:`mmcv.ConfigDict`|dict): Config of the\n classification loss. Default `CrossEntropyLoss`.\n loss_kpt (obj:`mmcv.ConfigDict`|dict): Config of the\n regression loss. Default `L1Loss`.\n loss_oks (obj:`mmcv.ConfigDict`|dict): Config of the\n regression oks loss. Default `OKSLoss`.\n train_cfg (obj:`mmcv.ConfigDict`|dict): Training config of\n transformer head.\n test_cfg (obj:`mmcv.ConfigDict`|dict): Testing config of\n transformer head.\n init_cfg (dict or list[dict], optional): Initialization config dict.\n Default: None\n with_kpt_refine (bool): Whether to refine the reference points\n in the decoder. Defaults to False.\n as_two_stage (bool) : Whether to generate the proposal from\n the outputs of encoder.\n transformer (obj:`ConfigDict`): ConfigDict is used for building\n the Encoder and Decoder.\n \"\"\"\n\n def __init__(self,\n num_classes,\n in_channels,\n num_query=100,\n num_kpt_fcs=2,\n num_keypoints=17,\n transformer=None,\n sync_cls_avg_factor=True,\n positional_encoding=dict(\n type='SinePositionalEncoding',\n num_feats=128,\n normalize=True),\n loss_cls=dict(\n type='FocalLoss',\n use_sigmoid=True,\n gamma=2.0,\n alpha=0.25,\n loss_weight=2.0),\n loss_kpt=dict(type='L1Loss', loss_weight=70.0),\n loss_oks=dict(type='OKSLoss', loss_weight=2.0),\n loss_hm=dict(type='NegLoss', loss_weight=4.0),\n as_two_stage=True,\n with_kpt_refine=True,\n train_cfg=dict(\n assigner=dict(\n type='PoseHungarianAssigner',\n cls_cost=dict(type='FocalLossCost', weight=2.0),\n kpt_cost=dict(type='KptL1Cost', weight=70.0),\n oks_cost=dict(type='OksCost', weight=7.0))),\n loss_kpt_rpn=dict(type='mmdet.L1Loss', loss_weight=70.0),\n loss_kpt_refine=dict(type='mmdet.L1Loss', loss_weight=70.0),\n loss_oks_refine=dict(type='opera.OKSLoss', loss_weight=2.0),\n test_cfg=dict(max_per_img=100),\n init_cfg=None,\n **kwargs):\n # NOTE here use `AnchorFreeHead` instead of `TransformerHead`,\n # since it brings inconvenience when the initialization of\n # `AnchorFreeHead` is called.\n super(AnchorFreeHead, self).__init__(init_cfg)\n self.bg_cls_weight = 0\n self.sync_cls_avg_factor = sync_cls_avg_factor\n if train_cfg:\n assert 'assigner' in train_cfg, 'assigner should be provided '\\\n 'when train_cfg is set.'\n assigner = train_cfg['assigner']\n assert loss_cls['loss_weight'] == assigner['cls_cost']['weight'], \\\n 'The classification weight for loss and matcher should be' \\\n 'exactly the same.'\n assert loss_kpt['loss_weight'] == assigner['kpt_cost'][\n 'weight'], 'The regression L1 weight for loss and matcher ' \\\n 'should be exactly the same.'\n self.assigner = build_assigner(assigner)\n # DETR sampling=False, so use PseudoSampler\n sampler_cfg = dict(type='mmdet.PseudoSampler')\n self.sampler = build_sampler(sampler_cfg, context=self)\n self.num_query = num_query\n self.num_classes = num_classes\n self.in_channels = in_channels\n self.num_kpt_fcs = num_kpt_fcs\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n self.fp16_enabled = False\n self.as_two_stage = as_two_stage\n self.with_kpt_refine = with_kpt_refine\n self.num_keypoints = num_keypoints\n if self.as_two_stage:\n transformer['as_two_stage'] = self.as_two_stage\n self.loss_cls = build_loss(loss_cls)\n self.loss_kpt = build_loss(loss_kpt)\n self.loss_kpt_rpn = build_loss(loss_kpt_rpn)\n self.loss_kpt_refine = build_loss(loss_kpt_refine)\n self.loss_oks = build_loss(loss_oks)\n self.loss_oks_refine = build_loss(loss_oks_refine)\n self.loss_hm_weight = loss_hm['loss_weight']\n if self.loss_cls.use_sigmoid:\n self.cls_out_channels = num_classes\n else:\n self.cls_out_channels = num_classes + 1\n self.act_cfg = transformer.get('act_cfg',\n dict(type='ReLU', inplace=True))\n self.activate = build_activation_layer(self.act_cfg)\n self.positional_encoding = build_positional_encoding(\n positional_encoding)\n self.transformer = build_transformer(transformer)\n self.embed_dims = self.transformer.embed_dims\n assert 'num_feats' in positional_encoding\n num_feats = positional_encoding['num_feats']\n assert num_feats * 2 == self.embed_dims, 'embed_dims should' \\\n f' be exactly 2 times of num_feats. Found {self.embed_dims}' \\\n f' and {num_feats}.'\n self._init_layers()\n\n def _init_layers(self):\n \"\"\"Initialize classification branch and keypoint branch of head.\"\"\"\n\n fc_cls = Linear(self.embed_dims, self.cls_out_channels)\n\n kpt_branch = []\n kpt_branch.append(Linear(self.embed_dims, 512))\n kpt_branch.append(nn.ReLU())\n for _ in range(self.num_kpt_fcs):\n kpt_branch.append(Linear(512, 512))\n kpt_branch.append(nn.ReLU())\n kpt_branch.append(Linear(512, 2 * self.num_keypoints))\n kpt_branch = nn.Sequential(*kpt_branch)\n\n def _get_clones(module, N):\n return nn.ModuleList([copy.deepcopy(module) for i in range(N)])\n\n # last kpt_branch is used to generate proposal from\n # encode feature map when as_two_stage is True.\n num_pred = (self.transformer.decoder.num_layers + 1) if \\\n self.as_two_stage else self.transformer.decoder.num_layers\n\n if self.with_kpt_refine:\n self.cls_branches = _get_clones(fc_cls, num_pred)\n self.kpt_branches = _get_clones(kpt_branch, num_pred)\n else:\n self.cls_branches = nn.ModuleList(\n [fc_cls for _ in range(num_pred)])\n self.kpt_branches = nn.ModuleList(\n [kpt_branch for _ in range(num_pred)])\n\n self.query_embedding = nn.Embedding(self.num_query,\n self.embed_dims * 2)\n\n refine_kpt_branch = []\n for _ in range(self.num_kpt_fcs):\n refine_kpt_branch.append(Linear(self.embed_dims, self.embed_dims))\n refine_kpt_branch.append(nn.ReLU())\n refine_kpt_branch.append(Linear(self.embed_dims, 2))\n refine_kpt_branch = nn.Sequential(*refine_kpt_branch)\n if self.with_kpt_refine:\n num_pred = self.transformer.refine_decoder.num_layers\n self.refine_kpt_branches = _get_clones(refine_kpt_branch, num_pred)\n self.fc_hm = Linear(self.embed_dims, self.num_keypoints)\n\n def init_weights(self):\n \"\"\"Initialize weights of the PETR head.\"\"\"\n self.transformer.init_weights()\n if self.loss_cls.use_sigmoid:\n bias_init = bias_init_with_prob(0.01)\n for m in self.cls_branches:\n nn.init.constant_(m.bias, bias_init)\n for m in self.kpt_branches:\n constant_init(m[-1], 0, bias=0)\n # initialization of keypoint refinement branch\n if self.with_kpt_refine:\n for m in self.refine_kpt_branches:\n constant_init(m[-1], 0, bias=0)\n # initialize bias for heatmap prediction\n bias_init = bias_init_with_prob(0.1)\n normal_init(self.fc_hm, std=0.01, bias=bias_init)\n\n def forward(self, mlvl_feats, img_metas):\n \"\"\"Forward function.\n\n Args:\n mlvl_feats (tuple[Tensor]): Features from the upstream\n network, each is a 4D-tensor with shape\n (N, C, H, W).\n img_metas (list[dict]): List of image information.\n\n Returns:\n all_cls_scores (Tensor): Outputs from the classification head, \\\n shape [nb_dec, bs, num_query, cls_out_channels]. Note \\\n cls_out_channels should includes background.\n all_bbox_preds (Tensor): Sigmoid outputs from the regression \\\n head with normalized coordinate format (cx, cy, w, h). \\\n Shape [nb_dec, bs, num_query, 4].\n enc_outputs_class (Tensor): The score of each point on encode \\\n feature map, has shape (N, h*w, num_class). Only when \\\n as_two_stage is Ture it would be returned, otherwise \\\n `None` would be returned.\n enc_outputs_coord (Tensor): The proposal generate from the \\\n encode feature map, has shape (N, h*w, 4). Only when \\\n as_two_stage is Ture it would be returned, otherwise \\\n `None` would be returned.\n \"\"\"\n\n batch_size = mlvl_feats[0].size(0)\n input_img_h, input_img_w = img_metas[0]['batch_input_shape']\n img_masks = mlvl_feats[0].new_ones(\n (batch_size, input_img_h, input_img_w))\n for img_id in range(batch_size):\n img_h, img_w, _ = img_metas[img_id]['img_shape']\n img_masks[img_id, :img_h, :img_w] = 0\n\n mlvl_masks = []\n mlvl_positional_encodings = []\n for feat in mlvl_feats:\n mlvl_masks.append(\n F.interpolate(img_masks[None],\n size=feat.shape[-2:]).to(torch.bool).squeeze(0))\n mlvl_positional_encodings.append(\n self.positional_encoding(mlvl_masks[-1]))\n\n query_embeds = self.query_embedding.weight\n hs, init_reference, inter_references, \\\n enc_outputs_class, enc_outputs_kpt, hm_proto, memory = \\\n self.transformer(\n mlvl_feats,\n mlvl_masks,\n query_embeds,\n mlvl_positional_encodings,\n kpt_branches=self.kpt_branches if self.with_kpt_refine else None, # noqa:E501\n cls_branches=self.cls_branches if self.as_two_stage else None # noqa:E501\n )\n hs = hs.permute(0, 2, 1, 3)\n outputs_classes = []\n outputs_kpts = []\n\n for lvl in range(hs.shape[0]):\n if lvl == 0:\n reference = init_reference\n else:\n reference = inter_references[lvl - 1]\n reference = inverse_sigmoid(reference)\n outputs_class = self.cls_branches[lvl](hs[lvl])\n tmp_kpt = self.kpt_branches[lvl](hs[lvl])\n assert reference.shape[-1] == self.num_keypoints * 2\n tmp_kpt += reference\n outputs_kpt = tmp_kpt.sigmoid()\n outputs_classes.append(outputs_class)\n outputs_kpts.append(outputs_kpt)\n\n outputs_classes = torch.stack(outputs_classes)\n outputs_kpts = torch.stack(outputs_kpts)\n\n if hm_proto is not None:\n # get heatmap prediction (training phase)\n hm_memory, hm_mask = hm_proto\n hm_pred = self.fc_hm(hm_memory)\n hm_proto = (hm_pred.permute(0, 3, 1, 2), hm_mask)\n\n if self.as_two_stage:\n return outputs_classes, outputs_kpts, \\\n enc_outputs_class, enc_outputs_kpt.sigmoid(), \\\n hm_proto, memory, mlvl_masks\n else:\n return outputs_classes, outputs_coords, outputs_kpts, \\\n None, None, None, hm_proto\n\n def forward_refine(self, memory, mlvl_masks, refine_targets, losses,\n img_metas):\n \"\"\"Forward function.\n\n Args:\n mlvl_feats (tuple[Tensor]): Features from the upstream\n network, each is a 4D-tensor with shape\n (N, C, H, W).\n img_metas (list[dict]): List of image information.\n\n Returns:\n all_cls_scores (Tensor): Outputs from the classification head, \\\n shape [nb_dec, bs, num_query, cls_out_channels]. Note \\\n cls_out_channels should includes background.\n all_bbox_preds (Tensor): Sigmoid outputs from the regression \\\n head with normalized coordinate format (cx, cy, w, h). \\\n Shape [nb_dec, bs, num_query, 4].\n enc_outputs_class (Tensor): The score of each point on encode \\\n feature map, has shape (N, h*w, num_class). Only when \\\n as_two_stage is Ture it would be returned, otherwise \\\n `None` would be returned.\n enc_outputs_coord (Tensor): The proposal generate from the \\\n encode feature map, has shape (N, h*w, 4). Only when \\\n as_two_stage is Ture it would be returned, otherwise \\\n `None` would be returned.\n \"\"\"\n kpt_preds, kpt_targets, area_targets, kpt_weights = refine_targets\n pos_inds = kpt_weights.sum(-1) > 0\n if pos_inds.sum() == 0:\n pos_kpt_preds = torch.zeros_like(kpt_preds[:1])\n pos_img_inds = kpt_preds.new_zeros([1], dtype=torch.int64)\n else:\n pos_kpt_preds = kpt_preds[pos_inds]\n pos_img_inds = (pos_inds.nonzero() / self.num_query).squeeze(1).to(\n torch.int64)\n hs, init_reference, inter_references = self.transformer.forward_refine(\n mlvl_masks,\n memory,\n pos_kpt_preds.detach(),\n pos_img_inds,\n kpt_branches=self.refine_kpt_branches if self.with_kpt_refine else None, # noqa:E501\n )\n hs = hs.permute(0, 2, 1, 3)\n outputs_kpts = []\n\n for lvl in range(hs.shape[0]):\n if lvl == 0:\n reference = init_reference\n else:\n reference = inter_references[lvl - 1]\n reference = inverse_sigmoid(reference)\n tmp_kpt = self.refine_kpt_branches[lvl](hs[lvl])\n assert reference.shape[-1] == 2\n tmp_kpt += reference\n outputs_kpt = tmp_kpt.sigmoid()\n outputs_kpts.append(outputs_kpt)\n outputs_kpts = torch.stack(outputs_kpts)\n\n if not self.training:\n return outputs_kpts\n\n batch_size = mlvl_masks[0].size(0)\n factors = []\n for img_id in range(batch_size):\n img_h, img_w, _ = img_metas[img_id]['img_shape']\n factor = mlvl_masks[0].new_tensor(\n [img_w, img_h, img_w, img_h],\n dtype=torch.float32).unsqueeze(0).repeat(self.num_query, 1)\n factors.append(factor)\n factors = torch.cat(factors, 0)\n factors = factors[pos_inds][:, :2].repeat(1, kpt_preds.shape[-1] // 2)\n\n num_valid_kpt = torch.clamp(\n reduce_mean(kpt_weights.sum()), min=1).item()\n num_total_pos = kpt_weights.new_tensor([outputs_kpts.size(1)])\n num_total_pos = torch.clamp(reduce_mean(num_total_pos), min=1).item()\n pos_kpt_weights = kpt_weights[pos_inds]\n pos_kpt_targets = kpt_targets[pos_inds]\n pos_kpt_targets_scaled = pos_kpt_targets * factors\n pos_areas = area_targets[pos_inds]\n pos_valid = kpt_weights[pos_inds, 0::2]\n for i, kpt_refine_preds in enumerate(outputs_kpts):\n if pos_inds.sum() == 0:\n loss_kpt = loss_oks = kpt_refine_preds.sum() * 0\n losses[f'd{i}.loss_kpt_refine'] = loss_kpt\n losses[f'd{i}.loss_oks_refine'] = loss_oks\n continue\n # kpt L1 Loss\n pos_refine_preds = kpt_refine_preds.reshape(\n kpt_refine_preds.size(0), -1)\n loss_kpt = self.loss_kpt_refine(\n pos_refine_preds,\n pos_kpt_targets,\n pos_kpt_weights,\n avg_factor=num_valid_kpt)\n losses[f'd{i}.loss_kpt_refine'] = loss_kpt\n # kpt oks loss\n pos_refine_preds_scaled = pos_refine_preds * factors\n assert (pos_areas > 0).all()\n loss_oks = self.loss_oks_refine(\n pos_refine_preds_scaled,\n pos_kpt_targets_scaled,\n pos_valid,\n pos_areas,\n avg_factor=num_total_pos)\n losses[f'd{i}.loss_oks_refine'] = loss_oks\n return losses\n\n # over-write because img_metas are needed as inputs for bbox_head.\n def forward_train(self,\n x,\n img_metas,\n gt_bboxes,\n gt_labels=None,\n gt_keypoints=None,\n gt_areas=None,\n gt_bboxes_ignore=None,\n proposal_cfg=None,\n **kwargs):\n \"\"\"Forward function for training mode.\n\n Args:\n x (list[Tensor]): Features from backbone.\n img_metas (list[dict]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n gt_bboxes (Tensor): Ground truth bboxes of the image,\n shape (num_gts, 4).\n gt_labels (Tensor): Ground truth labels of each box,\n shape (num_gts,).\n gt_keypoints (Tensor): Ground truth keypoints of the image,\n shape (num_gts, K*3).\n gt_areas (Tensor): Ground truth mask areas of each box,\n shape (num_gts,).\n gt_bboxes_ignore (Tensor): Ground truth bboxes to be\n ignored, shape (num_ignored_gts, 4).\n proposal_cfg (mmcv.Config): Test / postprocessing configuration,\n if None, test_cfg would be used.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert proposal_cfg is None, '\"proposal_cfg\" must be None'\n outs = self(x, img_metas)\n memory, mlvl_masks = outs[-2:]\n outs = outs[:-2]\n if gt_labels is None:\n loss_inputs = outs + (gt_bboxes, gt_keypoints, gt_areas, img_metas)\n else:\n loss_inputs = outs + (gt_bboxes, gt_labels, gt_keypoints, gt_areas,\n img_metas)\n losses_and_targets = self.loss(\n *loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)\n losses, refine_targets = losses_and_targets\n # get pose refinement loss\n losses = self.forward_refine(memory, mlvl_masks, refine_targets,\n losses, img_metas)\n return losses\n\n @force_fp32(apply_to=('all_cls_scores', 'all_kpt_preds'))\n def loss(self,\n all_cls_scores,\n all_kpt_preds,\n enc_cls_scores,\n enc_kpt_preds,\n enc_hm_proto,\n gt_bboxes_list,\n gt_labels_list,\n gt_keypoints_list,\n gt_areas_list,\n img_metas,\n gt_bboxes_ignore=None):\n \"\"\"\"Loss function.\n\n Args:\n all_cls_scores (Tensor): Classification score of all\n decoder layers, has shape\n [nb_dec, bs, num_query, cls_out_channels].\n all_bbox_preds (Tensor): Sigmoid regression\n outputs of all decode layers. Each is a 4D-tensor with\n normalized coordinate format (cx, cy, w, h) and shape\n [nb_dec, bs, num_query, 4].\n enc_cls_scores (Tensor): Classification scores of\n points on encode feature map , has shape\n (N, h*w, num_classes). Only be passed when as_two_stage is\n True, otherwise is None.\n enc_kpt_preds (Tensor): Regression results of each points\n on the encode feature map, has shape (N, h*w, K*2). Only be\n passed when as_two_stage is True, otherwise is None.\n enc_feat_grids (Tensor): grid coordinates of each points\n on the encode feature map, has shape (N, h*w, 2). Only be\n passed when as_two_stage is True, otherwise is None.\n gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image\n with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels_list (list[Tensor]): Ground truth class indices for each\n image with shape (num_gts, ).\n gt_keypoints_list (list[Tensor]): Ground truth keypoints for each\n image with shape (num_gts, K*3) in [p^{1}_x, p^{1}_y, p^{1}_v,\n ..., p^{K}_x, p^{K}_y, p^{K}_v] format.\n gt_areas_list (list[Tensor]): Ground truth mask areas for each\n image with shape (num_gts, ).\n img_metas (list[dict]): List of image meta information.\n gt_bboxes_ignore (list[Tensor], optional): Bounding boxes\n which can be ignored for each image. Default None.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert gt_bboxes_ignore is None, \\\n f'{self.__class__.__name__} only supports ' \\\n f'for gt_bboxes_ignore setting to None.'\n\n num_dec_layers = len(all_cls_scores)\n all_gt_labels_list = [gt_labels_list for _ in range(num_dec_layers)]\n all_gt_keypoints_list = [\n gt_keypoints_list for _ in range(num_dec_layers)\n ]\n all_gt_areas_list = [gt_areas_list for _ in range(num_dec_layers)]\n img_metas_list = [img_metas for _ in range(num_dec_layers)]\n\n losses_cls, losses_kpt, losses_oks, kpt_preds_list, kpt_targets_list, \\\n area_targets_list, kpt_weights_list = multi_apply(\n self.loss_single, all_cls_scores, all_kpt_preds,\n all_gt_labels_list, all_gt_keypoints_list,\n all_gt_areas_list, img_metas_list)\n\n loss_dict = dict()\n # loss of proposal generated from encode feature map.\n if enc_cls_scores is not None:\n binary_labels_list = [\n torch.zeros_like(gt_labels_list[i])\n for i in range(len(img_metas))\n ]\n enc_loss_cls, enc_losses_kpt = \\\n self.loss_single_rpn(\n enc_cls_scores, enc_kpt_preds, binary_labels_list,\n gt_keypoints_list, gt_areas_list, img_metas)\n loss_dict['enc_loss_cls'] = enc_loss_cls\n loss_dict['enc_loss_kpt'] = enc_losses_kpt\n\n # loss from the last decoder layer\n loss_dict['loss_cls'] = losses_cls[-1]\n loss_dict['loss_kpt'] = losses_kpt[-1]\n loss_dict['loss_oks'] = losses_oks[-1]\n # loss from other decoder layers\n num_dec_layer = 0\n for loss_cls_i, loss_kpt_i, loss_oks_i in zip(\n losses_cls[:-1], losses_kpt[:-1], losses_oks[:-1]):\n loss_dict[f'd{num_dec_layer}.loss_cls'] = loss_cls_i\n loss_dict[f'd{num_dec_layer}.loss_kpt'] = loss_kpt_i\n loss_dict[f'd{num_dec_layer}.loss_oks'] = loss_oks_i\n num_dec_layer += 1\n\n # losses of heatmap generated from P3 feature map\n hm_pred, hm_mask = enc_hm_proto\n loss_hm = self.loss_heatmap(hm_pred, hm_mask, gt_keypoints_list,\n gt_labels_list, gt_bboxes_list)\n loss_dict['loss_hm'] = loss_hm\n\n return loss_dict, (kpt_preds_list[-1], kpt_targets_list[-1],\n area_targets_list[-1], kpt_weights_list[-1])\n\n def loss_heatmap(self, hm_pred, hm_mask, gt_keypoints, gt_labels,\n gt_bboxes):\n assert hm_pred.shape[-2:] == hm_mask.shape[-2:]\n num_img, _, h, w = hm_pred.size()\n # placeholder of heatmap target (Gaussian distribution)\n hm_target = hm_pred.new_zeros(hm_pred.shape)\n for i, (gt_label, gt_bbox, gt_keypoint) in enumerate(\n zip(gt_labels, gt_bboxes, gt_keypoints)):\n if gt_label.size(0) == 0:\n continue\n gt_keypoint = gt_keypoint.reshape(gt_keypoint.shape[0], -1,\n 3).clone()\n gt_keypoint[..., :2] /= 8\n assert gt_keypoint[..., 0].max() <= w # new coordinate system\n assert gt_keypoint[..., 1].max() <= h # new coordinate system\n gt_bbox /= 8\n gt_w = gt_bbox[:, 2] - gt_bbox[:, 0]\n gt_h = gt_bbox[:, 3] - gt_bbox[:, 1]\n for j in range(gt_label.size(0)):\n # get heatmap radius\n kp_radius = torch.clamp(\n torch.floor(\n gaussian_radius((gt_h[j], gt_w[j]), min_overlap=0.9)),\n min=0,\n max=3)\n for k in range(self.num_keypoints):\n if gt_keypoint[j, k, 2] > 0:\n gt_kp = gt_keypoint[j, k, :2]\n gt_kp_int = torch.floor(gt_kp)\n draw_umich_gaussian(hm_target[i, k], gt_kp_int,\n kp_radius)\n # compute heatmap loss\n hm_pred = torch.clamp(\n hm_pred.sigmoid_(), min=1e-4, max=1 - 1e-4) # refer to CenterNet\n loss_hm = weighted_neg_loss(hm_pred, hm_target, hm_mask.unsqueeze(1))\n return loss_hm * self.loss_hm_weight\n\n def loss_single(self,\n cls_scores,\n kpt_preds,\n gt_labels_list,\n gt_keypoints_list,\n gt_areas_list,\n img_metas):\n \"\"\"\"Loss function for outputs from a single decoder layer of a single\n feature level.\n\n Args:\n cls_scores (Tensor): Box score logits from a single decoder layer\n for all images. Shape [bs, num_query, cls_out_channels].\n bbox_preds (Tensor): Sigmoid outputs from a single decoder layer\n for all images, with normalized coordinate (cx, cy, w, h) and\n shape [bs, num_query, 4].\n kpt_preds (Tensor): Sigmoid outputs from a single decoder layer\n for all images, with normalized coordinate (x_{i}, y_{i}) and\n shape [bs, num_query, K*2].\n gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image\n with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels_list (list[Tensor]): Ground truth class indices for each\n image with shape (num_gts, ).\n gt_keypoints_list (list[Tensor]): Ground truth keypoints for each\n image with shape (num_gts, K*3) in [p^{1}_x, p^{1}_y, p^{1}_v,\n ..., p^{K}_x, p^{K}_y, p^{K}_v] format.\n gt_areas_list (list[Tensor]): Ground truth mask areas for each\n image with shape (num_gts, ).\n img_metas (list[dict]): List of image meta information.\n gt_bboxes_ignore_list (list[Tensor], optional): Bounding\n boxes which can be ignored for each image. Default None.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components for outputs from\n a single decoder layer.\n \"\"\"\n num_imgs = cls_scores.size(0)\n cls_scores_list = [cls_scores[i] for i in range(num_imgs)]\n kpt_preds_list = [kpt_preds[i] for i in range(num_imgs)]\n cls_reg_targets = self.get_targets(cls_scores_list, kpt_preds_list,\n gt_labels_list, gt_keypoints_list,\n gt_areas_list, img_metas)\n (labels_list, label_weights_list, kpt_targets_list, kpt_weights_list,\n area_targets_list, num_total_pos, num_total_neg) = cls_reg_targets\n labels = torch.cat(labels_list, 0)\n label_weights = torch.cat(label_weights_list, 0)\n kpt_targets = torch.cat(kpt_targets_list, 0)\n kpt_weights = torch.cat(kpt_weights_list, 0)\n area_targets = torch.cat(area_targets_list, 0)\n\n # classification loss\n cls_scores = cls_scores.reshape(-1, self.cls_out_channels)\n # construct weighted avg_factor to match with the official DETR repo\n cls_avg_factor = num_total_pos * 1.0 + \\\n num_total_neg * self.bg_cls_weight\n if self.sync_cls_avg_factor:\n cls_avg_factor = reduce_mean(\n cls_scores.new_tensor([cls_avg_factor]))\n cls_avg_factor = max(cls_avg_factor, 1)\n\n loss_cls = self.loss_cls(\n cls_scores, labels, label_weights, avg_factor=cls_avg_factor)\n\n # Compute the average number of gt boxes accross all gpus, for\n # normalization purposes\n num_total_pos = loss_cls.new_tensor([num_total_pos])\n num_total_pos = torch.clamp(reduce_mean(num_total_pos), min=1).item()\n\n # construct factors used for rescale bboxes\n factors = []\n for img_meta, kpt_pred in zip(img_metas, kpt_preds):\n img_h, img_w, _ = img_meta['img_shape']\n factor = kpt_pred.new_tensor([img_w, img_h, img_w,\n img_h]).unsqueeze(0).repeat(\n kpt_pred.size(0), 1)\n factors.append(factor)\n factors = torch.cat(factors, 0)\n\n # keypoint regression loss\n kpt_preds = kpt_preds.reshape(-1, kpt_preds.shape[-1])\n num_valid_kpt = torch.clamp(\n reduce_mean(kpt_weights.sum()), min=1).item()\n # assert num_valid_kpt == (kpt_targets>0).sum().item()\n loss_kpt = self.loss_kpt(\n kpt_preds, kpt_targets, kpt_weights, avg_factor=num_valid_kpt)\n\n # keypoint oks loss\n pos_inds = kpt_weights.sum(-1) > 0\n factors = factors[pos_inds][:, :2].repeat(1, kpt_preds.shape[-1] // 2)\n pos_kpt_preds = kpt_preds[pos_inds] * factors\n pos_kpt_targets = kpt_targets[pos_inds] * factors\n pos_areas = area_targets[pos_inds]\n pos_valid = kpt_weights[pos_inds, 0::2]\n if len(pos_areas) == 0:\n loss_oks = pos_kpt_preds.sum() * 0\n else:\n assert (pos_areas > 0).all()\n loss_oks = self.loss_oks(\n pos_kpt_preds,\n pos_kpt_targets,\n pos_valid,\n pos_areas,\n avg_factor=num_total_pos)\n\n return loss_cls, loss_kpt, loss_oks, kpt_preds, kpt_targets, \\\n area_targets, kpt_weights\n\n def get_targets(self,\n cls_scores_list,\n kpt_preds_list,\n gt_labels_list,\n gt_keypoints_list,\n gt_areas_list,\n img_metas):\n \"\"\"\"Compute regression and classification targets for a batch image.\n\n Outputs from a single decoder layer of a single feature level are used.\n\n Args:\n cls_scores_list (list[Tensor]): Box score logits from a single\n decoder layer for each image with shape [num_query,\n cls_out_channels].\n bbox_preds_list (list[Tensor]): Sigmoid outputs from a single\n decoder layer for each image, with normalized coordinate\n (cx, cy, w, h) and shape [num_query, 4].\n kpt_preds_list (list[Tensor]): Sigmoid outputs from a single\n decoder layer for each image, with normalized coordinate\n (x_{i}, y_{i}) and shape [num_query, K*2].\n gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image\n with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels_list (list[Tensor]): Ground truth class indices for each\n image with shape (num_gts, ).\n gt_keypoints_list (list[Tensor]): Ground truth keypoints for each\n image with shape (num_gts, K*3).\n gt_areas_list (list[Tensor]): Ground truth mask areas for each\n image with shape (num_gts, ).\n img_metas (list[dict]): List of image meta information.\n gt_bboxes_ignore_list (list[Tensor], optional): Bounding\n boxes which can be ignored for each image. Default None.\n\n Returns:\n tuple: a tuple containing the following targets.\n\n - labels_list (list[Tensor]): Labels for all images.\n - label_weights_list (list[Tensor]): Label weights for all \\\n images.\n - bbox_targets_list (list[Tensor]): BBox targets for all \\\n images.\n - bbox_weights_list (list[Tensor]): BBox weights for all \\\n images.\n - kpt_targets_list (list[Tensor]): Kpt targets for all \\\n images.\n - kpt_weights_list (list[Tensor]): Kpt weights for all \\\n images.\n - num_total_pos (int): Number of positive samples in all \\\n images.\n - num_total_neg (int): Number of negative samples in all \\\n images.\n \"\"\"\n (labels_list, label_weights_list, kpt_targets_list, kpt_weights_list,\n area_targets_list, pos_inds_list, neg_inds_list) = multi_apply(\n self._get_target_single, cls_scores_list, kpt_preds_list, \n gt_labels_list, gt_keypoints_list, gt_areas_list, img_metas)\n num_total_pos = sum((inds.numel() for inds in pos_inds_list))\n num_total_neg = sum((inds.numel() for inds in neg_inds_list))\n return (labels_list, label_weights_list, kpt_targets_list,\n kpt_weights_list, area_targets_list, num_total_pos,\n num_total_neg)\n\n def _get_target_single(self,\n cls_score,\n kpt_pred,\n gt_labels,\n gt_keypoints,\n gt_areas,\n img_meta):\n \"\"\"\"Compute regression and classification targets for one image.\n\n Outputs from a single decoder layer of a single feature level are used.\n\n Args:\n cls_score (Tensor): Box score logits from a single decoder layer\n for one image. Shape [num_query, cls_out_channels].\n bbox_pred (Tensor): Sigmoid outputs from a single decoder layer\n for one image, with normalized coordinate (cx, cy, w, h) and\n shape [num_query, 4].\n kpt_pred (Tensor): Sigmoid outputs from a single decoder layer\n for one image, with normalized coordinate (x_{i}, y_{i}) and\n shape [num_query, K*2].\n gt_bboxes (Tensor): Ground truth bboxes for one image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (Tensor): Ground truth class indices for one image\n with shape (num_gts, ).\n gt_keypoints (Tensor): Ground truth keypoints for one image with\n shape (num_gts, K*3) in [p^{1}_x, p^{1}_y, p^{1}_v, ..., \\\n p^{K}_x, p^{K}_y, p^{K}_v] format.\n gt_areas (Tensor): Ground truth mask areas for one image\n with shape (num_gts, ).\n img_meta (dict): Meta information for one image.\n gt_bboxes_ignore (Tensor, optional): Bounding boxes\n which can be ignored. Default None.\n\n Returns:\n tuple[Tensor]: a tuple containing the following for one image.\n\n - labels (Tensor): Labels of each image.\n - label_weights (Tensor]): Label weights of each image.\n - bbox_targets (Tensor): BBox targets of each image.\n - bbox_weights (Tensor): BBox weights of each image.\n - kpt_targets (Tensor): Keypoint targets of each image.\n - kpt_weights (Tensor): Keypoint weights of each image.\n - pos_inds (Tensor): Sampled positive indices for each image.\n - neg_inds (Tensor): Sampled negative indices for each image.\n \"\"\"\n\n num_bboxes = kpt_pred.size(0)\n # assigner and sampler\n assign_result = self.assigner.assign(cls_score, kpt_pred, gt_labels,\n gt_keypoints, gt_areas, img_meta)\n sampling_result = self.sampler.sample(assign_result, kpt_pred,\n gt_keypoints)\n pos_inds = sampling_result.pos_inds\n neg_inds = sampling_result.neg_inds\n\n # label targets\n labels = gt_labels.new_full((num_bboxes, ),\n self.num_classes,\n dtype=torch.long)\n labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds]\n label_weights = gt_labels.new_ones(num_bboxes)\n\n img_h, img_w, _ = img_meta['img_shape']\n\n # keypoint targets\n kpt_targets = torch.zeros_like(kpt_pred)\n kpt_weights = torch.zeros_like(kpt_pred)\n pos_gt_kpts = gt_keypoints[sampling_result.pos_assigned_gt_inds]\n pos_gt_kpts = pos_gt_kpts.reshape(pos_gt_kpts.shape[0],\n pos_gt_kpts.shape[-1] // 3, 3)\n valid_idx = pos_gt_kpts[:, :, 2] > 0\n pos_kpt_weights = kpt_weights[pos_inds].reshape(\n pos_gt_kpts.shape[0], kpt_weights.shape[-1] // 2, 2)\n pos_kpt_weights[valid_idx] = 1.0\n kpt_weights[pos_inds] = pos_kpt_weights.reshape(\n pos_kpt_weights.shape[0], kpt_pred.shape[-1])\n\n factor = kpt_pred.new_tensor([img_w, img_h]).unsqueeze(0)\n pos_gt_kpts_normalized = pos_gt_kpts[..., :2]\n pos_gt_kpts_normalized[..., 0] = pos_gt_kpts_normalized[..., 0] / \\\n factor[:, 0:1]\n pos_gt_kpts_normalized[..., 1] = pos_gt_kpts_normalized[..., 1] / \\\n factor[:, 1:2]\n kpt_targets[pos_inds] = pos_gt_kpts_normalized.reshape(\n pos_gt_kpts.shape[0], kpt_pred.shape[-1])\n\n area_targets = kpt_pred.new_zeros(\n kpt_pred.shape[0]) # get areas for calculating oks\n pos_gt_areas = gt_areas[sampling_result.pos_assigned_gt_inds]\n area_targets[pos_inds] = pos_gt_areas\n\n return (labels, label_weights, kpt_targets, kpt_weights,\n area_targets, pos_inds, neg_inds)\n\n def loss_single_rpn(self,\n cls_scores,\n kpt_preds,\n gt_labels_list,\n gt_keypoints_list,\n gt_areas_list,\n img_metas):\n \"\"\"\"Loss function for outputs from a single decoder layer of a single\n feature level.\n\n Args:\n cls_scores (Tensor): Box score logits from a single decoder layer\n for all images. Shape [bs, num_query, cls_out_channels].\n bbox_preds (Tensor): Sigmoid outputs from a single decoder layer\n for all images, with normalized coordinate (cx, cy, w, h) and\n shape [bs, num_query, 4].\n gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image\n with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels_list (list[Tensor]): Ground truth class indices for each\n image with shape (num_gts, ).\n img_metas (list[dict]): List of image meta information.\n gt_bboxes_ignore_list (list[Tensor], optional): Bounding\n boxes which can be ignored for each image. Default None.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components for outputs from\n a single decoder layer.\n \"\"\"\n num_imgs = cls_scores.size(0)\n cls_scores_list = [cls_scores[i] for i in range(num_imgs)]\n kpt_preds_list = [kpt_preds[i] for i in range(num_imgs)]\n cls_reg_targets = self.get_targets(cls_scores_list, kpt_preds_list,\n gt_labels_list, gt_keypoints_list,\n gt_areas_list, img_metas)\n (labels_list, label_weights_list, kpt_targets_list, kpt_weights_list,\n area_targets_list, num_total_pos, num_total_neg) = cls_reg_targets\n labels = torch.cat(labels_list, 0)\n label_weights = torch.cat(label_weights_list, 0)\n kpt_targets = torch.cat(kpt_targets_list, 0)\n kpt_weights = torch.cat(kpt_weights_list, 0)\n\n # classification loss\n cls_scores = cls_scores.reshape(-1, self.cls_out_channels)\n # construct weighted avg_factor to match with the official DETR repo\n cls_avg_factor = num_total_pos * 1.0 + \\\n num_total_neg * self.bg_cls_weight\n if self.sync_cls_avg_factor:\n cls_avg_factor = reduce_mean(\n cls_scores.new_tensor([cls_avg_factor]))\n cls_avg_factor = max(cls_avg_factor, 1)\n\n cls_avg_factor = max(cls_avg_factor, 1)\n loss_cls = self.loss_cls(\n cls_scores, labels, label_weights, avg_factor=cls_avg_factor)\n\n # Compute the average number of gt boxes accross all gpus, for\n # normalization purposes\n # num_total_pos = loss_cls.new_tensor([num_total_pos])\n # num_total_pos = torch.clamp(reduce_mean(num_total_pos), min=1).item()\n\n # keypoint regression loss\n kpt_preds = kpt_preds.reshape(-1, kpt_preds.shape[-1])\n num_valid_kpt = torch.clamp(\n reduce_mean(kpt_weights.sum()), min=1).item()\n # assert num_valid_kpt == (kpt_targets>0).sum().item()\n loss_kpt = self.loss_kpt_rpn(\n kpt_preds, kpt_targets, kpt_weights, avg_factor=num_valid_kpt)\n\n return loss_cls, loss_kpt\n\n @force_fp32(apply_to=('all_cls_scores', 'all_kpt_preds'))\n def get_bboxes(self,\n all_cls_scores,\n all_kpt_preds,\n enc_cls_scores,\n enc_kpt_preds,\n hm_proto,\n memory,\n mlvl_masks,\n img_metas,\n rescale=False):\n \"\"\"Transform network outputs for a batch into bbox predictions.\n\n Args:\n all_cls_scores (Tensor): Classification score of all\n decoder layers, has shape\n [nb_dec, bs, num_query, cls_out_channels].\n all_bbox_preds (Tensor): Sigmoid regression\n outputs of all decode layers. Each is a 4D-tensor with\n normalized coordinate format (cx, cy, w, h) and shape\n [nb_dec, bs, num_query, 4].\n all_kpt_preds (Tensor): Sigmoid regression\n outputs of all decode layers. Each is a 4D-tensor with\n normalized coordinate format (x_{i}, y_{i}) and shape\n [nb_dec, bs, num_query, K*2].\n enc_cls_scores (Tensor): Classification scores of\n points on encode feature map , has shape\n (N, h*w, num_classes). Only be passed when as_two_stage is\n True, otherwise is None.\n enc_bbox_preds (Tensor): Regression results of each points\n on the encode feature map, has shape (N, h*w, 4). Only be\n passed when as_two_stage is True, otherwise is None.\n img_metas (list[dict]): Meta information of each image.\n rescale (bool, optional): If True, return boxes in original\n image space. Defalut False.\n\n Returns:\n list[list[Tensor, Tensor]]: Each item in result_list is 2-tuple. \\\n The first item is an (n, 5) tensor, where the first 4 columns \\\n are bounding box positions (tl_x, tl_y, br_x, br_y) and the \\\n 5-th column is a score between 0 and 1. The second item is a \\\n (n,) tensor where each item is the predicted class label of \\\n the corresponding box.\n \"\"\"\n cls_scores = all_cls_scores[-1]\n kpt_preds = all_kpt_preds[-1]\n # cls_scores = enc_cls_scores\n # kpt_preds = enc_kpt_preds\n\n result_list = []\n for img_id in range(len(img_metas)):\n cls_score = cls_scores[img_id]\n kpt_pred = kpt_preds[img_id]\n img_shape = img_metas[img_id]['img_shape']\n scale_factor = img_metas[img_id]['scale_factor']\n # TODO: only support single image test\n # memory_i = memory[:, img_id, :]\n # mlvl_mask = mlvl_masks[img_id]\n proposals = self._get_bboxes_single(cls_score, kpt_pred,\n img_shape, scale_factor,\n memory, mlvl_masks, rescale)\n result_list.append(proposals)\n return result_list\n\n def _get_bboxes_single(self,\n cls_score,\n kpt_pred,\n img_shape,\n scale_factor,\n memory,\n mlvl_masks,\n rescale=False):\n \"\"\"Transform outputs from the last decoder layer into bbox predictions\n for each image.\n\n Args:\n cls_score (Tensor): Box score logits from the last decoder layer\n for each image. Shape [num_query, cls_out_channels].\n bbox_pred (Tensor): Sigmoid outputs from the last decoder layer\n for each image, with coordinate format (cx, cy, w, h) and\n shape [num_query, 4].\n kpt_pred (Tensor): Sigmoid outputs from the last decoder layer\n for each image, with coordinate format (x_{i}, y_{i}) and\n shape [num_query, K*2].\n img_shape (tuple[int]): Shape of input image, (height, width, 3).\n scale_factor (ndarray, optional): Scale factor of the image arange\n as (w_scale, h_scale, w_scale, h_scale).\n rescale (bool, optional): If True, return boxes in original image\n space. Default False.\n\n Returns:\n tuple[Tensor]: Results of detected bboxes and labels.\n\n - det_bboxes: Predicted bboxes with shape [num_query, 5], \\\n where the first 4 columns are bounding box positions \\\n (tl_x, tl_y, br_x, br_y) and the 5-th column are scores \\\n between 0 and 1.\n - det_labels: Predicted labels of the corresponding box with \\\n shape [num_query].\n \"\"\"\n assert len(cls_score) == len(kpt_pred)\n max_per_img = self.test_cfg.get('max_per_img', self.num_query)\n # exclude background\n if self.loss_cls.use_sigmoid:\n cls_score = cls_score.sigmoid()\n scores, indexs = cls_score.view(-1).topk(max_per_img)\n det_labels = indexs % self.num_classes\n bbox_index = indexs // self.num_classes\n kpt_pred = kpt_pred[bbox_index]\n else:\n scores, det_labels = F.softmax(cls_score, dim=-1)[..., :-1].max(-1)\n scores, bbox_index = scores.topk(max_per_img)\n kpt_pred = kpt_pred[bbox_index]\n det_labels = det_labels[bbox_index]\n\n # ----- results after pose decoder -----\n # det_kpts = kpt_pred.reshape(kpt_pred.size(0), -1, 2)\n\n # ----- results after joint decoder (default) -----\n # import time\n # start = time.time()\n refine_targets = (kpt_pred, None, None, torch.ones_like(kpt_pred))\n refine_outputs = self.forward_refine(memory, mlvl_masks,\n refine_targets, None, None)\n # end = time.time()\n # print(f'refine time: {end - start:.6f}')\n det_kpts = refine_outputs[-1]\n\n det_kpts[..., 0] = det_kpts[..., 0] * img_shape[1]\n det_kpts[..., 1] = det_kpts[..., 1] * img_shape[0]\n det_kpts[..., 0].clamp_(min=0, max=img_shape[1])\n det_kpts[..., 1].clamp_(min=0, max=img_shape[0])\n if rescale:\n det_kpts /= det_kpts.new_tensor(\n scale_factor[:2]).unsqueeze(0).unsqueeze(0)\n\n # use circumscribed rectangle box of keypoints as det bboxes\n x1 = det_kpts[..., 0].min(dim=1, keepdim=True)[0]\n y1 = det_kpts[..., 1].min(dim=1, keepdim=True)[0]\n x2 = det_kpts[..., 0].max(dim=1, keepdim=True)[0]\n y2 = det_kpts[..., 1].max(dim=1, keepdim=True)[0]\n det_bboxes = torch.cat([x1, y1, x2, y2], dim=1)\n det_bboxes = torch.cat((det_bboxes, scores.unsqueeze(1)), -1)\n\n det_kpts = torch.cat(\n (det_kpts, det_kpts.new_ones(det_kpts[..., :1].shape)), dim=2)\n\n return det_bboxes, det_labels, det_kpts\n \n def simple_test_bboxes(self, feats, img_metas, rescale=False):\n \"\"\"Test det bboxes without test-time augmentation.\n\n Args:\n feats (tuple[torch.Tensor]): Multi-level features from the\n upstream network, each is a 4D-tensor.\n img_metas (list[dict]): List of image information.\n rescale (bool, optional): Whether to rescale the results.\n Defaults to False.\n\n Returns:\n list[tuple[Tensor, Tensor]]: Each item in result_list is 2-tuple.\n The first item is ``bboxes`` with shape (n, 5),\n where 5 represent (tl_x, tl_y, br_x, br_y, score).\n The shape of the second tensor in the tuple is ``labels``\n with shape (n,)\n \"\"\"\n # forward of this head requires img_metas\n outs = self.forward(feats, img_metas)\n results_list = self.get_bboxes(*outs, img_metas, rescale=rescale)\n return results_list\n" ]
[ [ "torch.nn.Sequential", "torch.nn.functional.softmax", "torch.floor", "torch.cat", "torch.nn.init.constant_", "torch.zeros_like", "torch.nn.Embedding", "torch.nn.functional.interpolate", "torch.stack", "torch.nn.ReLU", "torch.ones_like" ] ]
varshini2305/orbitdeterminator
[ "b9c6bfb0553af3ee683da665cbb3764bd8bc5235" ]
[ "orbitdeterminator/kep_determination/ellipse_fit.py" ]
[ "\"\"\"Finds out the ellipse that best fits to a set of data points and calculates\n its keplerian elements.\n\"\"\"\n\nimport math\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.optimize import minimize\nfrom functools import partial\n\ndef __read_args():\n \"\"\"Reads command line arguments.\n\n Returns:\n object: Parsed arguments.\n \"\"\"\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--file', type=str, help='path to .csv file', default='orbit.csv')\n parser.add_argument('-u', '--units', type=str, help='units of distance (m or km)', default='km')\n return parser.parse_args()\n\n\ndef __cross_sum(data):\n \"\"\"Returns the normalized sum of the cross products between consecutive vectors.\n\n Args:\n data(nx3 numpy array): A matrix where each column represents the x,y,z coordinates of each position vector.\n\n Returns:\n float: The normalized sum of the cross products between consecutive vectors.\n \"\"\"\n\n cross_sum = 0\n for i in range(len(data)-1):\n v1 = data[i]\n v2 = data[i+1]\n cross_sum = cross_sum + np.cross(v1,v2)\n\n return cross_sum/np.linalg.norm(cross_sum)\n\n\ndef __plane_err(data,coeffs):\n \"\"\"Calculates the total squared error of the data wrt a plane.\n\n The data should be a list of points. coeffs is an array of\n 3 elements - the coefficients a,b,c in the plane equation\n ax+by+c = 0.\n\n Args:\n data(nx3 numpy array): A numpy array of points.\n coeffs(1x3 array): The coefficients of the plane ax+by+c=0.\n\n Returns:\n float: The total squared error wrt the plane defined by ax+by+cz = 0.\n \"\"\"\n\n a,b,c = coeffs\n return np.sum((a*data[:,0]+b*data[:,1]+c*data[:,2])**2)/(a**2+b**2+c**2)\n\n\ndef __project_to_plane(points,coeffs):\n \"\"\"Projects points onto a plane.\n\n Projects a list of points onto the plane ax+by+c=0,\n where a,b,c are elements of coeffs.\n\n Args:\n points(nx3 numpy array): A numpy array of points.\n coeffs(1x3 array): The coefficients of the plane ax+by+c=0.\n\n Returns:\n nx3 numpy array: A list of projected points.\n \"\"\"\n\n a,b,c = coeffs\n\n proj_mat = [[b**2+c**2, -a*b , -a*c ],\n [ -a*b ,a**2+c**2, -b*c ],\n [ -a*c , -b*c ,a**2+b**2]]\n\n return np.matmul(points,proj_mat)/(a**2+b**2+c**2)\n\n\ndef __conv_to_2D(points,x,y):\n \"\"\"Finds coordinates of points in a plane wrt a basis.\n\n Given a list of points in a plane, and a basis of the plane,\n this function returns the coordinates of those points\n wrt this basis.\n\n Args:\n points(numpy array): A numpy array of points.\n x(3x1 numpy array): One vector of the basis.\n y(3x1 numpy array): Another vector of the basis.\n\n Returns:\n nx2 numpy array: Coordinates of the points wrt the basis [x,y].\n \"\"\"\n\n mat = [x[0:2],y[0:2]]\n mat_inv = np.linalg.inv(mat)\n coords = np.matmul(points[:,0:2],mat_inv)\n\n return coords\n\ndef __cart_to_pol(points):\n \"\"\"Converts a list of cartesian coordinates into polar ones.\n\n Args:\n points(nx2 numpy array): The list of points in the format [x,y].\n\n Returns:\n nx2 numpy array: A list of polar coordinates in the format [radius,angle].\n \"\"\"\n\n pol = np.empty(points.shape)\n pol[:,0] = np.sqrt(points[:,0]**2+points[:,1]**2)\n pol[:,1] = np.arctan2(points[:,1],points[:,0])\n\n return pol\n\ndef __ellipse_err(polar_coords,params):\n \"\"\"Calculates the total squared error of the data wrt an ellipse.\n\n params is a 3 element array used to define an ellipse.\n It contains 3 elements a,e, and t0.\n\n a is the semi-major axis\n e is the eccentricity\n t0 is the angle of the major axis wrt the x-axis.\n\n These 3 elements define an ellipse with one focus at origin.\n Equation of the ellipse is r = a(1-e^2)/(1+ecos(t-t0))\n\n The function calculates r for every theta in the data.\n It then takes the square of the difference and sums it.\n\n Args:\n polar_coords(nx2 numpy array): A list of polar coordinates in the format [radius,angle].\n params(1x3 numpy array): The array [a,e,t0].\n\n Returns:\n float: The total squared error of the data wrt the ellipse.\n \"\"\"\n\n a,e,t0 = params\n dem = 1+e*np.cos(polar_coords[:,1]-t0)\n num = a*(1-e**2)\n r = np.divide(num,dem)\n err = np.sum((r - polar_coords[:,0])**2)\n return err\n\n\ndef __residuals(data,params,polar_coords,basis):\n \"\"\"Calculates the residuals after fitting the ellipse.\n\n Residuals are the difference between the fitted points and\n the actual points.\n\n res_x = fitted_x - initial_x\n res_y = fitted_y - initial_y\n res_z = fitted_z - initial_z\n\n where fitted_x,y,z is the closest point on the ellipse to initial_x,y,z.\n\n However, it is computationally expensive to find the true nearest point.\n So we take an approximation. We consider the point on the ellipse with\n the same true anomaly as the initial point to be the nearest point to it.\n Since the eccentricities of the orbits involved are small, this approximation\n holds.\n\n Args:\n data(nx3 numpy array): The list of original points.\n params(1x3 numpy array): The array [semi-major axis, eccentricity, argument of periapsis]\n of the fitted ellipse.\n polar_coords(nx2 numpy array): The list of 2D polar coordinates of the original points after\n projecting them onto the best-fit plane.\n basis(3x2 numpy array): The basis of the best-fit plane.\n\n Returns:\n nx3 numpy array: Returns the residuals\n \"\"\"\n\n a,e,t0 = params\n dem = 1+e*np.cos(polar_coords[:,1]-t0)\n num = a*(1-e**2)\n r = np.divide(num,dem)\n\n # convert to cartesian\n x_s = np.multiply(r,np.cos(polar_coords[:,1]))\n y_s = np.multiply(r,np.sin(polar_coords[:,1]))\n\n # convert to 3D\n filtered_coords = np.transpose(np.matmul(basis,[x_s,y_s]))\n\n residuals = filtered_coords - data\n\n return residuals\n\ndef __read_file(file_name):\n \"\"\"Reads a space separated csv file with 4 columns in the format t x y z.\n\n Args:\n file_name(string): the path to the file\n\n Returns:\n nx3 numpy array: A numpy array with the columns [x y z]. Note that the t coloumn is discarded.\n \"\"\"\n\n data = np.loadtxt(file_name,skiprows=1,usecols=(1,2,3))\n\n return data\n\ndef determine_kep(data):\n \"\"\"Determines keplerian elements that fit a set of points.\n\n Args:\n data(nx3 numpy array): A numpy array of points in the format [x y z].\n\n Returns:\n (kep,res) - The keplerian elements and the residuals as a tuple.\n kep: 1x6 numpy array\n res: nx3 numpy array\n\n For the keplerian elements:\n kep[0] - semi-major axis (in whatever units the data was provided in)\n kep[1] - eccentricity\n kep[2] - inclination (in degrees)\n kep[3] - argument of periapsis (in degrees)\n kep[4] - right ascension of ascending node (in degrees)\n kep[5] - true anomaly of the first row in the data (in degrees)\n\n For the residuals: (in whatever units the data was provided in)\n res[0] - residuals in x axis\n res[1] - residuals in y axis\n res[2] - residuals in z axis\n \"\"\"\n\n # try to fit a plane to the data first.\n\n # make a partial function of plane_err by supplying the data\n plane_err_data = partial(__plane_err,data)\n\n # plane is defined by ax+by+cz=0.\n p0 = __cross_sum(data) # make an initial guess\n\n # minimize the error\n p = minimize(plane_err_data,p0,method='nelder-mead',options={'maxiter':1000}).x\n p = p/np.linalg.norm(p) # normalize p\n\n # now p is the normal vector of the best-fit plane.\n\n # lan_vec is a vector along the line of intersection of the plane\n # and the x-y plane.\n lan_vec = np.cross([0,0,1],p)\n\n # if lan_vec is [0,0,0] it means that it is undefined and can take on\n # any value. So we set it to [1,0,0] so that the rest of the\n # calculation can proceed.\n if (np.array_equal(lan_vec,[0,0,0])):\n lan_vec = [1,0,0]\n\n # inclination is the angle between p and the z axis.\n inc = math.acos(np.clip(p[2]/np.linalg.norm(p),-1,1))\n # lan is the angle between the lan_vec and the x axis.\n lan = math.atan2(lan_vec[1],lan_vec[0])%(2*math.pi)\n\n # now we try to convert the problem into a 2D problem.\n\n # project all the points onto the plane.\n proj_data = __project_to_plane(data,p)\n\n # p_x and p_y are 2 orthogonal unit vectors on the plane.\n p_x,p_y = lan_vec, np.cross(p,lan_vec)\n p_x,p_y = p_x/np.linalg.norm(p_x), p_y/np.linalg.norm(p_y)\n\n # find coordinates of the points wrt the basis [p_x,p_y].\n coords_2D = __conv_to_2D(proj_data,p_x,p_y)\n\n # now try to fit an ellipse to these points.\n\n # convert them into polar coordinates\n polar_coords = __cart_to_pol(coords_2D)\n\n # make an initial guess for the parametres\n r_m = np.min(polar_coords[:,0])\n r_M = np.max(polar_coords[:,0])\n a0 = (r_m+r_M)/2\n e0 = (r_M-r_m)/(r_M+r_m)\n t00 = polar_coords[np.argmin(polar_coords[:,0]),1]\n\n params0 = [a0,e0,t00] # initial guess\n # make a partial function of ellipse_err with the data\n ellipse_err_data = partial(__ellipse_err,polar_coords)\n # minimize the error\n params = minimize(ellipse_err_data,params0,method='nelder-mead',options={'maxiter':1000}).x\n params[2] = params[2]%(2*math.pi) # bring argp between 0-360 degrees\n\n # calculate the true anomaly of the first entry in the dataset\n true_anom = (polar_coords[0][1]-params[2])%(2*math.pi)\n\n # calculation of residuals\n res = __residuals(data,params,polar_coords,np.column_stack((p_x,p_y)))\n\n kep = np.empty((6,1))\n kep[0] = params[0]\n kep[1] = params[1]\n kep[2] = math.degrees(inc)\n kep[3] = math.degrees(params[2])\n kep[4] = math.degrees(lan)\n kep[5] = math.degrees(true_anom)\n\n return kep,res\n\ndef __print_kep(kep,res,unit):\n \"\"\"Prints the keplerian elements and some information on residuals.\n\n Args:\n kep(1x6 numpy array): keplerian elements\n res(nx3 numpy array): residuals\n unit(string): units of distance used\n\n Returns:\n NIL\n \"\"\"\n\n # output the parameters\n print(\"Semi-major axis: \",kep[0][0],unit)\n print(\"Eccentricity: \",kep[1][0])\n print(\"Inclination: \",kep[2][0],\"deg\")\n print(\"Argument of periapsis: \",kep[3][0],\"deg\")\n print(\"Longitude of Ascending Node:\",kep[4][0],\"deg\")\n print(\"True Anomaly \",kep[5][0],\"deg\")\n\n # print data about residuals\n print()\n\n max_res = np.max(res,axis=0)\n min_res = np.min(res,axis=0)\n sum_res = np.sum(res,axis=0)\n avg_res = np.average(res,axis=0)\n std_res = np.std(res,axis=0)\n\n print(\"Printing data about residuals in each axis:\")\n print(\"Max: \",max_res)\n print(\"Min: \",min_res)\n print(\"Sum: \",sum_res)\n print(\"Average: \",avg_res)\n print(\"Standard Deviation:\",std_res)\n\ndef plot_kep(kep,data):\n \"\"\"Plots the original data and the orbit defined by the keplerian elements.\n\n Args:\n kep(1x6 numpy array): keplerian elements\n data(nx3 numpy array): original data\n\n Returns:\n nothing\n \"\"\"\n\n a = kep[0]\n e = kep[1]\n inc = math.radians(kep[2])\n t0 = math.radians(kep[3])\n lan = math.radians(kep[4])\n\n p_x = np.array([math.cos(lan), math.sin(lan), 0])\n p_y = np.array([-math.sin(lan)*math.cos(inc), math.cos(lan)*math.cos(inc), math.sin(inc)])\n\n # generate 1000 points on the ellipse\n theta = np.linspace(0,2*math.pi,1000)\n radii = a*(1-e**2)/(1+e*np.cos(theta-t0))\n\n # convert to cartesian\n x_s = np.multiply(radii,np.cos(theta))\n y_s = np.multiply(radii,np.sin(theta))\n\n # convert to 3D\n mat = np.column_stack((p_x,p_y))\n coords_3D = np.matmul(mat,[x_s,y_s])\n\n fig = plt.figure()\n ax = Axes3D(fig)\n ax.axis('equal')\n\n # plot\n ax.plot3D(coords_3D[0],coords_3D[1],coords_3D[2],c = 'red',label='Fitted Ellipse')\n ax.scatter3D(data[:,0],data[:,1],data[:,2],c='black',label='Initial Data')\n\n # The Pale Blue Dot\n ax.scatter3D(0,0,0,c='blue',depthshade=False,label='Earth')\n\n ax.can_zoom()\n ax.legend()\n plt.show()\n\nif __name__ == \"__main__\":\n args = __read_args()\n data = __read_file(args.file)\n kep, res = determine_kep(data)\n __print_kep(kep,res,args.units)\n plot_kep(kep,data)\n" ]
[ [ "numpy.sqrt", "numpy.linspace", "numpy.arctan2", "numpy.max", "numpy.argmin", "numpy.cross", "numpy.divide", "numpy.matmul", "numpy.sin", "numpy.std", "numpy.column_stack", "matplotlib.pyplot.figure", "numpy.min", "numpy.linalg.inv", "scipy.optimize.minimize", "matplotlib.pyplot.show", "numpy.sum", "numpy.array_equal", "numpy.linalg.norm", "numpy.empty", "numpy.cos", "numpy.average", "numpy.loadtxt" ] ]
InesPessoa/Capstone
[ "36dfd5941d638cbb75176b573645caff900dd4ee" ]
[ "code_1/model_with_autorization_code_regularized_amplitude.py" ]
[ "from features_creation import *\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.ensemble import AdaBoostClassifier\n\n\nif __name__ == \"__main__\":\n\n\n tresholds = [0, 20, 70]\n\n powers = [1, 2]\n\n for treshold in tresholds:\n for power in powers:\n df_train = pd.read_csv(\"resources/df_train.csv\", index_col=0)\n df_test = pd.read_csv(\"resources/df_test.csv\", index_col=0)\n\n target_name = \"ContrabandIndicator\"\n\n # drop duplicates\n is_duplicated = df_train.duplicated()\n df_train = df_train[is_duplicated == False]\n\n # divide dataset in features(X) and target(y)\n X_train = df_train.drop(columns=[target_name])\n y_train = df_train[target_name]\n\n X_test = df_test.drop(columns=[target_name])\n y_test = df_test[target_name]\n\n # target_encoding\n target = Target()\n y_train = target.target_encoding(y_train)\n\n y_test = target.target_encoding(y_test)\n\n features_cleaning = Pipeline(\n [('clean_text_sr', CleanText(\"StatuteReason\")),\n ('clean_text_irc', CleanText(\"InterventionReasonCode\")),\n ('clean_text_iln', CleanText(\"InterventionLocationName\")),\n ('clean_text_dn', CleanText(\"Department Name\")),\n ('clean_age', CleanAge(\"SubjectAge\")),\n ('set_others_statute_reason', SetOthers(feature_name=\"StatuteReason\", threshold=100)),\n ('set_others_InterventionReasonCode', SetOthers(feature_name=\"InterventionReasonCode\", threshold=100)),\n ('set_others_InterventionLocationName', SetOthers(feature_name=\"InterventionLocationName\", threshold=100)),\n ('set_others_dn', SetOthers(feature_name=\"Department Name\", threshold=100)),\n ('time_features', TimeFeatures(feature_name=\"InterventionDateTime\", month=False, weekday=False, hour=True)),\n ('per_iln', PercentageEncoder(feature_name=\"InterventionLocationName\")),\n ('per_sr', PercentageEncoder(feature_name=\"StatuteReason\")),\n ('boo_ri', BooleanEncoder(feature_name=\"ResidentIndicator\")),\n ('boo_tri', BooleanEncoder(feature_name=\"TownResidentIndicator\")),\n ('encode_sac', EncodeSACRegAmplitude(feature_name=\"SearchAuthorizationCode\", threshold=treshold, power=power)),\n ('per_irc', PercentageEncoder(feature_name=\"InterventionReasonCode\")),\n ('drop_columns', DropColumns(feature_names=[\n \"ReportingOfficerIdentificationID\",\n \"Department Name\",\n \"VehicleSearchedIndicator\",\n \"SubjectAge\",\n \"SubjectEthnicityCode\",\n \"SubjectRaceCode\",\n \"SubjectSexCode\"\n ]))\n ])\n\n\n X_train = features_cleaning.fit_transform(X_train, y_train)\n\n X_test = features_cleaning.transform(X_test)\n\n smote = SMOTE()\n\n X_train, y_train = smote.fit_resample(X_train, y_train)\n\n adc = AdaBoostClassifier(random_state=0)\n\n adc.fit(X_train, y_train)\n y_pred = adc.predict(X_test)\n\n\n #Model Performance\n score = classification_report(y_test, y_pred, labels=[0, 1])\n print(score)\n tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()\n cm = \"tn: \" + str(tn) + \"fp: \" + str(fp) + \"fn: \" + str(fn) + \"tp: \" + str(tp)\n print(cm)\n\n file = open(\"resources/final_model_with_sac_regularization_results_\" + str(treshold) + \"_\" + str(power) + \".txt\", 'w')\n file.write(str(score))\n file.write(\"\\n\")\n file.write(cm)\n file.close()\n\n df_test_with_prediction = copy.copy(df_test)\n df_test_with_prediction[\"prediction\"] = y_pred\n\n df_test_with_prediction.to_csv(\"resources/df_test_with_prediction_with_sac_regularization_\" + str(treshold) + \"_\" + str(power) + \".csv\")\n\n\n\n\n\n\n\n" ]
[ [ "sklearn.ensemble.AdaBoostClassifier", "sklearn.metrics.classification_report", "sklearn.metrics.confusion_matrix" ] ]
filipi/cleftTracker
[ "a79989308a2bdd0c3a10e21d9df185bfb82c0864" ]
[ "more_tests/tracker.py" ]
[ "#!/usr/bin/env python\n\n#https://docs.opencv.org/3.3.1/d7/d8b/tutorial_py_lucas_kanade.html\nimport numpy as np\nimport cv2\nimport sys\n\nfeature_params = dict( maxCorners = 100, #100, # params for ShiTomasi corner detection\n qualityLevel = 0.2, #0.3,,#0.2,\n minDistance = 7, #12, #7,\n blockSize = 7)# 7 ) #7 ) #12 )\nlk_params = dict( winSize = (50, 50),#(200,200) #(15,15), # Parameters for lucas kanade optical flow\n maxLevel = 2,\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 100, 0.03))\ncolor = np.random.randint(0,255,(100,3)) # Create some random colors\n#color = (0, 0, 255) \n#color_of = (0, 255, 0)\n\npause = False\nframeNumber = 0\n\ni = 0\nprogressArray = ['-', '\\\\', '|', '/' ]\n\nstructures = []\ncorners = np.ndarray([])\n\n#######################################################################################################\n\n#capFileName = '../obtaningData/basin_DNS.avi'\n#apFileName = '../obtaningData/simpson_1972_small.mpg'\n#capFileName = '../obtaningData/simpson_1972_fast.mpg'\n#capFileName = '../obtaningData/Simpson/frontSimpson.mpg'\ncapFileName = '../obtaningData/Neufeld/neufeld.mpg'\n#capFileName = '../obtaningData/lockExchangeSimpson_filipi_Re2445/test.mp4'\n#capFileName = '../frenteSimpson.mpg'\n#capFileName = '../obtaningData/Mariana/mariana.mp4'\n\n#######################################################################################################\n\n\ncap = cv2.VideoCapture(capFileName)\n# Take first frame and find corners in it\nfor i in range(0, 2):\n ret, old_frame = cap.read()\n\n\nret, old_frame = cap.read()\nmask = np.zeros_like(old_frame)\nmask = (255-mask)\nframe = old_frame\n\ncv2.imshow('frame', frame)\n\nold_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY) \np0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params) \n\nwhile(1):\n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n if k == 32:\n \n # (frameNumber)\n frameNumber = frameNumber + 1 \n \n #descomentar aqui para redescobrir os cantos\n #old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY) \n #p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params) \n \n old_gray_test = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY) \n p3 = cv2.goodFeaturesToTrack(old_gray_test, mask = None, **feature_params) \n \n \n frame_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)\n # calculate optical flow\n p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)\n #p1 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params) \n #print(p1)\n #print(p0) \n #break\n \n #print(p3)\n \n # Select good points\n good_new = p1[st==1]\n good_old = p0[st==1] \n corner_new = p3.reshape(-1,2) # esses novos cantos vao vir em numero diferente e nao da pra usar o \n # indice condicional st, mas precisa dar o reshpe para ficar um array\n # de uma posicao com um outro array dentro comos pontos e nao varios arrays\n # com os pontos\n print(corner_new.size)\n #print(good_old) \n #print(corner_new)\n #break\n \n # draw the tracks\n for k,(corner) in enumerate(corner_new):\n e,f = corner.ravel()\n frame2 = cv2.circle(old_frame,(e,f),5,color[k].tolist(),-1)\n cv2.imshow('frame2', frame2)\n \n for k,(new,old) in enumerate(zip(good_new,good_old)):\n a,b = new.ravel()\n c,d = old.ravel() \n \n #print(a)\n #quit()\n mask = cv2.line(mask, (a,b),(c,d), color[k].tolist(), 2)\n #mask = cv2.line(old_frame, (a,b),(c,d), color[k].tolist(), 5)\n frame = cv2.circle(old_frame,(a,b),5,color[k].tolist(),-1)\n \n \n \n #mask = cv2.line(mask, (a,b),(c,d), color_of, 5)\n #frame = cv2.circle(old_frame,(a,b),10,color,-1) \n \n #img = cv2.add(frame, mask)\n #mask = mask + frame\n mask = np.bitwise_and(mask, frame)#<<<<<<<<<<\n cv2.imshow('mask', mask)\n cv2.imshow('frame', frame)\n \n \n # Now update the previous frame and previous points\n old_gray = frame_gray.copy()\n p0 = good_new.reshape(-1,1,2)\n #break \n \n i = ( i + 1 ) % 4\n #print(progressArray[i]) \n sys.stdout.write('\\rprocessing frames...[{0}] - {1} {2} '.format(frameNumber, k, progressArray[i]))\n sys.stdout.flush()\n \n \n ret, old_frame = cap.read() \n structures.append(k)\n if old_frame is None:\n #print(frameNumber)\n break\n\ncv2.destroyAllWindows()\ncap.release()\n" ]
[ [ "numpy.bitwise_and", "numpy.zeros_like", "numpy.ndarray", "numpy.random.randint" ] ]
JTiger0431/bert-as-service
[ "4bd981cacdde706d51e5e8828a4a496ab62648bb" ]
[ "server/bert_serving/server/__init__.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Han Xiao <[email protected]> <https://hanxiao.github.io>\nimport multiprocessing\nimport os\nimport random\nimport sys\nimport threading\nimport time\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom itertools import chain\nfrom multiprocessing import Process\nfrom multiprocessing.pool import Pool\n\nimport numpy as np\nimport zmq\nimport zmq.decorators as zmqd\nfrom termcolor import colored\nfrom zmq.utils import jsonapi\n\nfrom .helper import *\nfrom .http import BertHTTPProxy\nfrom .zmq_decor import multi_socket\n\n__all__ = ['__version__', 'BertServer']\n__version__ = '1.8.9'\n\n_tf_ver_ = check_tf_version()\n\n\nclass ServerCmd:\n terminate = b'TERMINATION'\n show_config = b'SHOW_CONFIG'\n new_job = b'REGISTER'\n data_token = b'TOKENS'\n data_embed = b'EMBEDDINGS'\n\n @staticmethod\n def is_valid(cmd):\n return any(not k.startswith('__') and v == cmd for k, v in vars(ServerCmd).items())\n\n\nclass BertServer(threading.Thread):\n def __init__(self, args):\n super().__init__()\n self.logger = set_logger(colored('VENTILATOR', 'magenta'), args.verbose)\n\n self.model_dir = args.model_dir\n self.max_seq_len = args.max_seq_len\n self.num_worker = args.num_worker\n self.max_batch_size = args.max_batch_size\n self.num_concurrent_socket = max(8, args.num_worker * 2) # optimize concurrency for multi-clients\n self.port = args.port\n self.args = args\n self.status_args = {k: (v if k != 'pooling_strategy' else v.value) for k, v in sorted(vars(args).items())}\n self.status_static = {\n 'tensorflow_version': _tf_ver_,\n 'python_version': sys.version,\n 'server_version': __version__,\n 'pyzmq_version': zmq.pyzmq_version(),\n 'zmq_version': zmq.zmq_version(),\n 'server_start_time': str(datetime.now()),\n }\n self.processes = []\n self.logger.info('freeze, optimize and export graph, could take a while...')\n with Pool(processes=1) as pool:\n # optimize the graph, must be done in another process\n from .graph import optimize_graph\n self.graph_path, self.bert_config = pool.apply(optimize_graph, (self.args,))\n # from .graph import optimize_graph\n # self.graph_path = optimize_graph(self.args, self.logger)\n if self.graph_path:\n self.logger.info('optimized graph is stored at: %s' % self.graph_path)\n else:\n raise FileNotFoundError('graph optimization fails and returns empty result')\n self.is_ready = threading.Event()\n\n def __enter__(self):\n self.start()\n self.is_ready.wait()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\n def close(self):\n self.logger.info('shutting down...')\n self._send_close_signal()\n self.is_ready.clear()\n self.join()\n\n @zmqd.context()\n @zmqd.socket(zmq.PUSH)\n def _send_close_signal(self, _, frontend):\n frontend.connect('tcp://localhost:%d' % self.port)\n frontend.send_multipart([b'', ServerCmd.terminate, b'', b''])\n\n @staticmethod\n def shutdown(args):\n with zmq.Context() as ctx:\n ctx.setsockopt(zmq.LINGER, args.timeout)\n with ctx.socket(zmq.PUSH) as frontend:\n try:\n frontend.connect('tcp://%s:%d' % (args.ip, args.port))\n frontend.send_multipart([b'', ServerCmd.terminate, b'', b''])\n print('shutdown signal sent to %d' % args.port)\n except zmq.error.Again:\n raise TimeoutError(\n 'no response from the server (with \"timeout\"=%d ms), please check the following:'\n 'is the server still online? is the network broken? are \"port\" correct? ' % args.timeout)\n\n def run(self):\n self._run()\n\n @zmqd.context()\n @zmqd.socket(zmq.PULL)\n @zmqd.socket(zmq.PAIR)\n @multi_socket(zmq.PUSH, num_socket='num_concurrent_socket')\n def _run(self, _, frontend, sink, *backend_socks):\n\n def push_new_job(_job_id, _json_msg, _msg_len):\n # backend_socks[0] is always at the highest priority\n _sock = backend_socks[0] if _msg_len <= self.args.priority_batch_size else rand_backend_socket\n _sock.send_multipart([_job_id, _json_msg])\n\n # bind all sockets\n self.logger.info('bind all sockets')\n frontend.bind('tcp://*:%d' % self.port)\n addr_front2sink = auto_bind(sink)\n addr_backend_list = [auto_bind(b) for b in backend_socks]\n self.logger.info('open %d ventilator-worker sockets' % len(addr_backend_list))\n\n # start the sink process\n self.logger.info('start the sink')\n proc_sink = BertSink(self.args, addr_front2sink, self.bert_config)\n self.processes.append(proc_sink)\n proc_sink.start()\n addr_sink = sink.recv().decode('ascii')\n\n # start the backend processes\n device_map = self._get_device_map()\n for idx, device_id in enumerate(device_map):\n process = BertWorker(idx, self.args, addr_backend_list, addr_sink, device_id,\n self.graph_path, self.bert_config)\n self.processes.append(process)\n process.start()\n\n # start the http-service process\n if self.args.http_port:\n self.logger.info('start http proxy')\n proc_proxy = BertHTTPProxy(self.args)\n self.processes.append(proc_proxy)\n proc_proxy.start()\n\n rand_backend_socket = None\n server_status = ServerStatistic()\n\n for p in self.processes:\n p.is_ready.wait()\n\n self.is_ready.set()\n self.logger.info('all set, ready to serve request!')\n\n while True:\n try:\n request = frontend.recv_multipart()\n client, msg, req_id, msg_len = request\n except ValueError:\n self.logger.error('received a wrongly-formatted request (expected 4 frames, got %d)' % len(request))\n self.logger.error('\\n'.join('field %d: %s' % (idx, k) for idx, k in enumerate(request)), exc_info=True)\n else:\n server_status.update(request)\n if msg == ServerCmd.terminate:\n break\n elif msg == ServerCmd.show_config:\n self.logger.info('new config request\\treq id: %d\\tclient: %s' % (int(req_id), client))\n status_runtime = {'client': client.decode('ascii'),\n 'num_process': len(self.processes),\n 'ventilator -> worker': addr_backend_list,\n 'worker -> sink': addr_sink,\n 'ventilator <-> sink': addr_front2sink,\n 'server_current_time': str(datetime.now()),\n 'statistic': server_status.value,\n 'device_map': device_map,\n 'num_concurrent_socket': self.num_concurrent_socket}\n\n sink.send_multipart([client, msg, jsonapi.dumps({**status_runtime,\n **self.status_args,\n **self.status_static}), req_id])\n else:\n self.logger.info('new encode request\\treq id: %d\\tsize: %d\\tclient: %s' %\n (int(req_id), int(msg_len), client))\n # register a new job at sink\n sink.send_multipart([client, ServerCmd.new_job, msg_len, req_id])\n\n # renew the backend socket to prevent large job queueing up\n # [0] is reserved for high priority job\n # last used backennd shouldn't be selected either as it may be queued up already\n rand_backend_socket = random.choice([b for b in backend_socks[1:] if b != rand_backend_socket])\n\n # push a new job, note super large job will be pushed to one socket only,\n # leaving other sockets free\n job_id = client + b'#' + req_id\n if int(msg_len) > self.max_batch_size:\n seqs = jsonapi.loads(msg)\n job_gen = ((job_id + b'@%d' % i, seqs[i:(i + self.max_batch_size)]) for i in\n range(0, int(msg_len), self.max_batch_size))\n for partial_job_id, job in job_gen:\n push_new_job(partial_job_id, jsonapi.dumps(job), len(job))\n else:\n push_new_job(job_id, msg, int(msg_len))\n\n for p in self.processes:\n p.close()\n self.logger.info('terminated!')\n\n def _get_device_map(self):\n self.logger.info('get devices')\n run_on_gpu = False\n device_map = [-1] * self.num_worker\n if not self.args.cpu:\n try:\n import GPUtil\n num_all_gpu = len(GPUtil.getGPUs())\n avail_gpu = GPUtil.getAvailable(order='memory', limit=min(num_all_gpu, self.num_worker),\n maxMemory=0.9, maxLoad=0.9)\n num_avail_gpu = len(avail_gpu)\n\n if num_avail_gpu >= self.num_worker:\n run_on_gpu = True\n elif 0 < num_avail_gpu < self.num_worker:\n self.logger.warning('only %d out of %d GPU(s) is available/free, but \"-num_worker=%d\"' %\n (num_avail_gpu, num_all_gpu, self.num_worker))\n if not self.args.device_map:\n self.logger.warning('multiple workers will be allocated to one GPU, '\n 'may not scale well and may raise out-of-memory')\n else:\n self.logger.warning('workers will be allocated based on \"-device_map=%s\", '\n 'may not scale well and may raise out-of-memory' % self.args.device_map)\n run_on_gpu = True\n else:\n self.logger.warning('no GPU available, fall back to CPU')\n\n if run_on_gpu:\n device_map = ((self.args.device_map or avail_gpu) * self.num_worker)[: self.num_worker]\n except FileNotFoundError:\n self.logger.warning('nvidia-smi is missing, often means no gpu on this machine. '\n 'fall back to cpu!')\n self.logger.info('device map: \\n\\t\\t%s' % '\\n\\t\\t'.join(\n 'worker %2d -> %s' % (w_id, ('gpu %2d' % g_id) if g_id >= 0 else 'cpu') for w_id, g_id in\n enumerate(device_map)))\n return device_map\n\n\nclass BertSink(Process):\n def __init__(self, args, front_sink_addr, bert_config):\n super().__init__()\n self.port = args.port_out\n self.exit_flag = multiprocessing.Event()\n self.logger = set_logger(colored('SINK', 'green'), args.verbose)\n self.front_sink_addr = front_sink_addr\n self.verbose = args.verbose\n self.show_tokens_to_client = args.show_tokens_to_client\n self.max_seq_len = args.max_seq_len\n self.max_position_embeddings = bert_config.max_position_embeddings\n self.fixed_embed_length = args.fixed_embed_length\n self.is_ready = multiprocessing.Event()\n\n def close(self):\n self.logger.info('shutting down...')\n self.is_ready.clear()\n self.exit_flag.set()\n self.terminate()\n self.join()\n self.logger.info('terminated!')\n\n def run(self):\n self._run()\n\n @zmqd.socket(zmq.PULL)\n @zmqd.socket(zmq.PAIR)\n @zmqd.socket(zmq.PUB)\n def _run(self, receiver, frontend, sender):\n receiver_addr = auto_bind(receiver)\n frontend.connect(self.front_sink_addr)\n sender.bind('tcp://*:%d' % self.port)\n\n pending_jobs = defaultdict(lambda: SinkJob(self.max_seq_len, self.max_position_embeddings,\n self.show_tokens_to_client,\n self.fixed_embed_length)) # type: Dict[str, SinkJob]\n\n poller = zmq.Poller()\n poller.register(frontend, zmq.POLLIN)\n poller.register(receiver, zmq.POLLIN)\n\n # send worker receiver address back to frontend\n frontend.send(receiver_addr.encode('ascii'))\n\n # Windows does not support logger in MP environment, thus get a new logger\n # inside the process for better compability\n logger = set_logger(colored('SINK', 'green'), self.verbose)\n logger.info('ready')\n self.is_ready.set()\n\n while not self.exit_flag.is_set():\n socks = dict(poller.poll())\n if socks.get(receiver) == zmq.POLLIN:\n msg = receiver.recv_multipart()\n job_id = msg[0]\n # parsing job_id and partial_id\n job_info = job_id.split(b'@')\n job_id = job_info[0]\n partial_id = int(job_info[1]) if len(job_info) == 2 else 0\n\n if msg[3] == ServerCmd.data_embed:\n # parsing the ndarray\n arr_info, arr_val = jsonapi.loads(msg[1]), msg[2]\n x = np.frombuffer(memoryview(arr_val), dtype=arr_info['dtype']).reshape(arr_info['shape'])\n pending_jobs[job_id].add_embed(x, partial_id)\n elif msg[3] == ServerCmd.data_token:\n x = jsonapi.loads(msg[1])\n pending_jobs[job_id].add_token(x, partial_id)\n else:\n logger.error('received a wrongly-formatted request (expected 4 frames, got %d)' % len(msg))\n logger.error('\\n'.join('field %d: %s' % (idx, k) for idx, k in enumerate(msg)), exc_info=True)\n\n logger.info('collect %s %s (E:%d/T:%d/A:%d)' % (msg[3], job_id,\n pending_jobs[job_id].progress_embeds,\n pending_jobs[job_id].progress_tokens,\n pending_jobs[job_id].checksum))\n\n # check if there are finished jobs, then send it back to workers\n\n finished = [(k, v) for k, v in pending_jobs.items() if v.is_done]\n for job_info, tmp in finished:\n client_addr, req_id = job_info.split(b'#')\n x, x_info = tmp.result\n sender.send_multipart([client_addr, x_info, x, req_id])\n logger.info('send back\\tsize: %d\\tjob id: %s' % (tmp.checksum, job_info))\n # release the job\n tmp.clear()\n pending_jobs.pop(job_info)\n\n if socks.get(frontend) == zmq.POLLIN:\n client_addr, msg_type, msg_info, req_id = frontend.recv_multipart()\n if msg_type == ServerCmd.new_job:\n job_info = client_addr + b'#' + req_id\n # register a new job\n pending_jobs[job_info].checksum = int(msg_info)\n logger.info('job register\\tsize: %d\\tjob id: %s' % (int(msg_info), job_info))\n elif msg_type == ServerCmd.show_config:\n time.sleep(0.1) # dirty fix of slow-joiner: sleep so that client receiver can connect.\n logger.info('send config\\tclient %s' % client_addr)\n sender.send_multipart([client_addr, msg_info, req_id])\n\n\nclass SinkJob:\n def __init__(self, max_seq_len, max_position_embeddings, with_tokens, fixed_embed_length):\n self._pending_embeds = []\n self.tokens = []\n self.tokens_ids = []\n self.checksum = 0\n self.final_ndarray = None\n self.progress_tokens = 0\n self.progress_embeds = 0\n self.with_tokens = with_tokens\n self.max_seq_len_unset = max_seq_len is None\n self.max_position_embeddings = max_position_embeddings\n self.max_effective_len = 0\n self.fixed_embed_length = fixed_embed_length\n\n def clear(self):\n self._pending_embeds.clear()\n self.tokens_ids.clear()\n self.tokens.clear()\n del self.final_ndarray\n\n def _insert(self, data, pid, data_lst, idx_lst):\n lo = 0\n hi = len(idx_lst)\n while lo < hi:\n mid = (lo + hi) // 2\n if pid < idx_lst[mid]:\n hi = mid\n else:\n lo = mid + 1\n idx_lst.insert(lo, pid)\n data_lst.insert(lo, data)\n\n def add_embed(self, data, pid):\n def fill_data():\n self.final_ndarray[pid: (pid + data.shape[0]), 0:data.shape[1]] = data\n self.progress_embeds += progress\n if data.shape[1] > self.max_effective_len:\n self.max_effective_len = data.shape[1]\n\n progress = data.shape[0]\n if not self.checksum:\n self._pending_embeds.append((data, pid, progress))\n else:\n if self.final_ndarray is None:\n d_shape = list(data.shape[1:])\n if self.max_seq_len_unset and len(d_shape) > 1:\n # if not set max_seq_len, then we have no choice but set result ndarray to\n # [B, max_position_embeddings, dim] and truncate it at the end\n d_shape[0] = self.max_position_embeddings\n self.final_ndarray = np.zeros([self.checksum] + d_shape, dtype=data.dtype)\n fill_data()\n while self._pending_embeds:\n data, pid, progress = self._pending_embeds.pop()\n fill_data()\n\n def add_token(self, data, pid):\n progress = len(data)\n self._insert(data, pid, self.tokens, self.tokens_ids)\n self.progress_tokens += progress\n\n @property\n def is_done(self):\n if self.with_tokens:\n return self.checksum > 0 and self.checksum == self.progress_tokens and self.checksum == self.progress_embeds\n else:\n return self.checksum > 0 and self.checksum == self.progress_embeds\n\n @property\n def result(self):\n if self.max_seq_len_unset and not self.fixed_embed_length:\n x = np.ascontiguousarray(self.final_ndarray[:, 0:self.max_effective_len])\n else:\n x = self.final_ndarray\n x_info = {'dtype': str(x.dtype),\n 'shape': x.shape,\n 'tokens': list(chain.from_iterable(self.tokens)) if self.with_tokens else ''}\n\n x_info = jsonapi.dumps(x_info)\n return x, x_info\n\n\nclass BertWorker(Process):\n def __init__(self, id, args, worker_address_list, sink_address, device_id, graph_path, graph_config):\n super().__init__()\n self.worker_id = id\n self.device_id = device_id\n self.logger = set_logger(colored('WORKER-%d' % self.worker_id, 'yellow'), args.verbose)\n self.max_seq_len = args.max_seq_len\n self.mask_cls_sep = args.mask_cls_sep\n self.daemon = True\n self.exit_flag = multiprocessing.Event()\n self.worker_address = worker_address_list\n self.num_concurrent_socket = len(self.worker_address)\n self.sink_address = sink_address\n self.prefetch_size = args.prefetch_size if self.device_id > 0 else None # set to zero for CPU-worker\n self.gpu_memory_fraction = args.gpu_memory_fraction\n self.model_dir = args.model_dir\n self.verbose = args.verbose\n self.graph_path = graph_path\n self.bert_config = graph_config\n self.use_fp16 = args.fp16\n self.show_tokens_to_client = args.show_tokens_to_client\n self.is_ready = multiprocessing.Event()\n\n def close(self):\n self.logger.info('shutting down...')\n self.exit_flag.set()\n self.is_ready.clear()\n self.terminate()\n self.join()\n self.logger.info('terminated!')\n\n def get_estimator(self, tf):\n from tensorflow.python.estimator.estimator import Estimator\n from tensorflow.python.estimator.run_config import RunConfig\n from tensorflow.python.estimator.model_fn import EstimatorSpec\n\n def model_fn(features, labels, mode, params):\n with tf.gfile.GFile(self.graph_path, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n input_names = ['input_ids', 'input_mask', 'input_type_ids']\n\n output = tf.import_graph_def(graph_def,\n input_map={k + ':0': features[k] for k in input_names},\n return_elements=['final_encodes:0'])\n\n return EstimatorSpec(mode=mode, predictions={\n 'client_id': features['client_id'],\n 'encodes': output[0]\n })\n\n config = tf.ConfigProto(device_count={'GPU': 0 if self.device_id < 0 else 1})\n config.gpu_options.allow_growth = True\n config.gpu_options.per_process_gpu_memory_fraction = self.gpu_memory_fraction\n config.log_device_placement = False\n # session-wise XLA doesn't seem to work on tf 1.10\n # if args.xla:\n # config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1\n\n return Estimator(model_fn=model_fn, config=RunConfig(session_config=config))\n\n def run(self):\n self._run()\n\n @zmqd.socket(zmq.PUSH)\n @zmqd.socket(zmq.PUSH)\n @multi_socket(zmq.PULL, num_socket='num_concurrent_socket')\n def _run(self, sink_embed, sink_token, *receivers):\n # Windows does not support logger in MP environment, thus get a new logger\n # inside the process for better compatibility\n logger = set_logger(colored('WORKER-%d' % self.worker_id, 'yellow'), self.verbose)\n\n logger.info('use device %s, load graph from %s' %\n ('cpu' if self.device_id < 0 else ('gpu: %d' % self.device_id), self.graph_path))\n\n tf = import_tf(self.device_id, self.verbose, use_fp16=self.use_fp16)\n estimator = self.get_estimator(tf)\n\n for sock, addr in zip(receivers, self.worker_address):\n sock.connect(addr)\n\n sink_embed.connect(self.sink_address)\n sink_token.connect(self.sink_address)\n for r in estimator.predict(self.input_fn_builder(receivers, tf, sink_token), yield_single_examples=False):\n send_ndarray(sink_embed, r['client_id'], r['encodes'], ServerCmd.data_embed)\n logger.info('job done\\tsize: %s\\tclient: %s' % (r['encodes'].shape, r['client_id']))\n\n def input_fn_builder(self, socks, tf, sink):\n from .bert.extract_features import convert_lst_to_features\n from .bert.tokenization import FullTokenizer\n\n def gen():\n tokenizer = FullTokenizer(vocab_file=os.path.join(self.model_dir, 'vocab.txt'))\n # Windows does not support logger in MP environment, thus get a new logger\n # inside the process for better compatibility\n logger = set_logger(colored('WORKER-%d' % self.worker_id, 'yellow'), self.verbose)\n\n poller = zmq.Poller()\n for sock in socks:\n poller.register(sock, zmq.POLLIN)\n\n logger.info('ready and listening!')\n self.is_ready.set()\n\n while not self.exit_flag.is_set():\n events = dict(poller.poll())\n for sock_idx, sock in enumerate(socks):\n if sock in events:\n client_id, raw_msg = sock.recv_multipart()\n msg = jsonapi.loads(raw_msg)\n logger.info('new job\\tsocket: %d\\tsize: %d\\tclient: %s' % (sock_idx, len(msg), client_id))\n # check if msg is a list of list, if yes consider the input is already tokenized\n is_tokenized = all(isinstance(el, list) for el in msg)\n tmp_f = list(convert_lst_to_features(msg, self.max_seq_len,\n self.bert_config.max_position_embeddings,\n tokenizer, logger,\n is_tokenized, self.mask_cls_sep))\n if self.show_tokens_to_client:\n sink.send_multipart([client_id, jsonapi.dumps([f.tokens for f in tmp_f]),\n b'', ServerCmd.data_token])\n yield {\n 'client_id': client_id,\n 'input_ids': [f.input_ids for f in tmp_f],\n 'input_mask': [f.input_mask for f in tmp_f],\n 'input_type_ids': [f.input_type_ids for f in tmp_f]\n }\n\n def input_fn():\n return (tf.data.Dataset.from_generator(\n gen,\n output_types={'input_ids': tf.int32,\n 'input_mask': tf.int32,\n 'input_type_ids': tf.int32,\n 'client_id': tf.string},\n output_shapes={\n 'client_id': (),\n 'input_ids': (None, None),\n 'input_mask': (None, None),\n 'input_type_ids': (None, None)}).prefetch(self.prefetch_size))\n\n return input_fn\n\n\nclass ServerStatistic:\n def __init__(self):\n self._hist_client = defaultdict(int)\n self._hist_msg_len = defaultdict(int)\n self._client_last_active_time = defaultdict(float)\n self._num_data_req = 0\n self._num_sys_req = 0\n self._num_total_seq = 0\n self._last_req_time = time.perf_counter()\n self._last_two_req_interval = []\n self._num_last_two_req = 200\n\n def update(self, request):\n client, msg, req_id, msg_len = request\n self._hist_client[client] += 1\n if ServerCmd.is_valid(msg):\n self._num_sys_req += 1\n # do not count for system request, as they are mainly for heartbeats\n else:\n self._hist_msg_len[int(msg_len)] += 1\n self._num_total_seq += int(msg_len)\n self._num_data_req += 1\n tmp = time.perf_counter()\n self._client_last_active_time[client] = tmp\n if len(self._last_two_req_interval) < self._num_last_two_req:\n self._last_two_req_interval.append(tmp - self._last_req_time)\n else:\n self._last_two_req_interval.pop(0)\n self._last_req_time = tmp\n\n @property\n def value(self):\n def get_min_max_avg(name, stat):\n if len(stat) > 0:\n return {\n 'avg_%s' % name: sum(stat) / len(stat),\n 'min_%s' % name: min(stat),\n 'max_%s' % name: max(stat),\n 'num_min_%s' % name: sum(v == min(stat) for v in stat),\n 'num_max_%s' % name: sum(v == max(stat) for v in stat),\n }\n else:\n return {}\n\n def get_num_active_client(interval=180):\n # we count a client active when its last request is within 3 min.\n now = time.perf_counter()\n return sum(1 for v in self._client_last_active_time.values() if (now - v) < interval)\n\n parts = [{\n 'num_data_request': self._num_data_req,\n 'num_total_seq': self._num_total_seq,\n 'num_sys_request': self._num_sys_req,\n 'num_total_request': self._num_data_req + self._num_sys_req,\n 'num_total_client': len(self._hist_client),\n 'num_active_client': get_num_active_client()},\n get_min_max_avg('request_per_client', self._hist_client.values()),\n get_min_max_avg('size_per_request', self._hist_msg_len.keys()),\n get_min_max_avg('last_two_interval', self._last_two_req_interval),\n get_min_max_avg('request_per_second', [1. / v for v in self._last_two_req_interval]),\n ]\n\n return {k: v for d in parts for k, v in d.items()}\n" ]
[ [ "numpy.ascontiguousarray", "tensorflow.python.estimator.run_config.RunConfig", "numpy.zeros", "tensorflow.python.estimator.model_fn.EstimatorSpec" ] ]
jangenoe/InteractieveCursus
[ "8348c4f64f0c2a2ddca915814897483ff551b782" ]
[ "ToegepasteAnalogeElektronica/cursus.py" ]
[ "import matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom matplotlib import patches\nimport scipy.signal as signal\n#import pandas as pd # nakijken of nog nodig\nimport numpy as np\nfrom PySpice.Probe.Plot import plot\nfrom PySpice.Spice.Parser import SpiceParser\nfrom PySpice.Spice.Netlist import Circuit\nfrom PySpice.Unit import *\nimport schemdraw as schem\nimport schemdraw.elements as e\nfrom ipywidgets import interact,FloatSlider\nusewidgets=True;\n \ndef spicelisting(filename):\n with open(filename) as f:\n for line in f:\n print(line.strip())\n print()\n \n\ndef freqs_resp(ba_array,Dmin=1,Dmax=5,lowDB=-100, Npts = 1024,fsize=(6,4),legend=[],Printcoef=True,SaveGraf=False,grafname=\"c2.svg\"):\n \"\"\"\n b = ndarray of numerator coefficients\n a = ndarray of denominator coefficents\n Dmin = start frequency as 10**Dmin\n Dmax = stop frequency as 10**Dmax\n lowDB = lowest transfer function amplitude (in DB)\n Npts = number of points to plot; defult is 1024\n fsize = figure size; defult is (6,4) inches\n \"\"\"\n f = np.logspace(Dmin,Dmax,Npts)\n fig, ax = plt.subplots(2,1 ,sharex=True,figsize=fsize)\n index=0\n for ba in ba_array:\n if Printcoef:\n ib=len(ba[0])-1\n print(\"Veelterm coefficienten teller: M=\",ib)\n for bb in ba[0]:\n print (\"b[\",ib,\"] =\",bb)\n ib-=1\n ia=len(ba[1])-1\n print(\"Veelterm coefficienten noemer: N=\", ia)\n for aa in ba[1]:\n print (\"a[\",ia,\"] =\",aa)\n ia-=1\n w,H = signal.freqs(ba[0],ba[1],2*np.pi*f)\n if legend==[]:\n ax[0].semilogx(f,20*np.log10(np.abs(H)))\n else:\n ax[0].semilogx(f,20*np.log10(np.abs(H)),label=legend[index])\n index+=1\n ax[1].semilogx(f,np.angle(H)/np.pi*180)\n ax[0].set_ylabel('Gain (dB)')\n ax[0].set_title('Frequency Response - Magnitude')\n ax[0].grid()\n ax[0].set_xlim([10**Dmin,10**Dmax]);\n ax[0].set_ylim([lowDB,5]);\n if not(legend==[]):\n ax[0].legend()\n ax[1].set_xlabel('Frequency (Hz)')\n ax[1].set_ylabel('Phase (graden)')\n ax[1].set_title('Frequency Response - Phase')\n ax[1].set_xlim([10**Dmin,10**Dmax]);\n ax[1].set_yticks([-180,-90,0,90,180])\n ax[1].grid();\n if SaveGraf:\n plt.savefig(grafname)\n plt.show();\ndef polen_nullen(z,p,circelarray,fsize=(6,6),Printcoef=True):\n if Printcoef:\n ib=1\n print(\"Lijst der nullen: M=\", len(z))\n for bb in z:\n print (\"z[\",ib,\"] =\",bb)\n ib+=1\n ia=1\n print(\"Lijst der polen: N=\", len(p))\n for aa in p:\n print (\"p[\",ia,\"] =\",aa)\n ia+=1\n fig, ax = plt.subplots(1,1, figsize=fsize)\n for circel in circelarray:\n ax.add_patch(patches.Ellipse((0,2*np.pi*circel[2]), width=4*np.pi*circel[0], height=4*np.pi*circel[1], fill=False, color='black', ls='dashed'))\n t1 = plt.plot(z.real, z.imag, 'go', ms=10)\n plt.setp( t1, markersize=5.0, markeredgewidth=1.5, markeredgecolor='k', markerfacecolor='g')\n t2 = plt.plot(p.real, p.imag, 'rx', ms=10)\n plt.setp( t2, markersize=5.0, markeredgewidth=1.5, markeredgecolor='r', markerfacecolor='r')\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n plt.show();" ]
[ [ "scipy.signal.freqs", "matplotlib.patches.Ellipse", "numpy.abs", "numpy.logspace", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.setp", "numpy.angle", "matplotlib.pyplot.show" ] ]
EfratShimron/sigpy
[ "d140abf0fe7268851aec3be74d238a5ba8d2dd28" ]
[ "sigpy/linop.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"This module contains an abstraction class Linop for linear operators,\nand provides commonly used linear operators, including signal transforms\nsuch as FFT, NUFFT, and wavelet, and array manipulation operators,\nsuch as reshape, transpose, and resize.\n\"\"\"\nimport numpy as np\n\nfrom sigpy import backend, block, fourier, util, interp, conv, wavelet\n\n\ndef _check_shape_positive(shape):\n\n if not all(s > 0 for s in shape):\n raise ValueError(\n 'Shapes must be positive, got {shape}'.format(shape=shape))\n\n\nclass Linop(object):\n \"\"\"Abstraction for linear operator.\n\n Linop can be called or multiplied to an array to\n perform a linear operation.\n Given a Linop A, and an appropriately shaped input x, the following are\n both valid operations to compute x -> A(x):\n\n >>> y = A * x\n >>> y = A(x)\n\n Its adjoint linear operator can be obtained using the .H attribute.\n Linops can be scaled, added, subtracted, stacked and composed.\n Here are some example of valid operations on Linop A, Linop B,\n and a scalar a:\n\n >>> A.H\n >>> a * A + B\n >>> a * A * B\n\n Args:\n oshape: Output shape.\n ishape: Input shape.\n repr_str (string or None): default: class name.\n\n Attributes:\n oshape: output shape.\n ishape: input shape.\n H: adjoint linear operator.\n\n \"\"\"\n def __init__(self, oshape, ishape, repr_str=None):\n self.oshape = list(oshape)\n self.ishape = list(ishape)\n\n _check_shape_positive(oshape)\n _check_shape_positive(ishape)\n\n if repr_str is None:\n self.repr_str = self.__class__.__name__\n else:\n self.repr_str = repr_str\n\n def _check_domain(self, input):\n for i1, i2 in zip(input.shape, self.ishape):\n if i2 != -1 and i1 != i2:\n raise ValueError(\n 'input shape mismatch for {s}, got {input_shape}'.format(\n s=self, input_shape=input.shape))\n\n def _check_codomain(self, output):\n for o1, o2 in zip(output.shape, self.oshape):\n if o2 != -1 and o1 != o2:\n raise ValueError(\n 'output shape mismatch for {s}, got {output_shape}'.format(\n s=self, output_shape=output.shape))\n\n def _apply(self, input):\n raise NotImplementedError\n\n def apply(self, input):\n \"\"\"Apply linear operation on input.\n\n This function checks for the input/output shapes,\n and calls the internal user-defined _apply() method.\n\n Args:\n input (array): input array of shape `ishape`.\n\n Returns:\n array: output array of shape `oshape`.\n\n \"\"\"\n self._check_domain(input)\n with backend.get_device(input):\n output = self._apply(input)\n\n self._check_codomain(output)\n return output\n\n def _adjoint_linop(self):\n raise NotImplementedError\n\n @property\n def H(self):\n r\"\"\"Return adjoint linear operator.\n\n An adjoint linear operator :math:`A^H` for\n a linear operator :math:`A` is defined as:\n\n .. math:\n \\left< A x, y \\right> = \\left< x, A^H, y \\right>\n\n Returns:\n Linop: adjoint linear operator.\n\n \"\"\"\n return self._adjoint_linop()\n\n def __call__(self, input):\n return self.__mul__(input)\n\n def __mul__(self, input):\n if isinstance(input, Linop):\n return Compose([self, input])\n elif np.isscalar(input):\n M = Multiply(self.ishape, input)\n return Compose([self, M])\n elif isinstance(input, backend.get_array_module(input).ndarray):\n return self.apply(input)\n\n return NotImplemented\n\n def __rmul__(self, input):\n if np.isscalar(input):\n M = Multiply(self.oshape, input)\n return Compose([M, self])\n\n return NotImplemented\n\n def __add__(self, input):\n if isinstance(input, Linop):\n return Add([self, input])\n else:\n raise NotImplementedError\n\n def __neg__(self):\n\n return -1 * self\n\n def __sub__(self, input):\n return self.__add__(-input)\n\n def __repr__(self):\n return '<{oshape}x{ishape}> {repr_str} Linop>'.format(\n oshape=self.oshape, ishape=self.ishape, repr_str=self.repr_str)\n\n\nclass Identity(Linop):\n \"\"\"Identity linear operator.\n\n Args:\n shape (tuple of ints): Input shape\n\n \"\"\"\n\n def __init__(self, shape):\n super().__init__(shape, shape)\n\n def _apply(self, input):\n return input\n\n def _adjoint_linop(self):\n return self\n\n\nclass ToDevice(Linop):\n \"\"\"Move input between devices.\n\n Args:\n shape (tuple of ints): Input/output shape.\n odevice (Device): Output device\n idevice (Device): Input device\n \"\"\"\n\n def __init__(self, shape, odevice, idevice):\n self.odevice = odevice\n self.idevice = idevice\n\n super().__init__(shape, shape)\n\n def _apply(self, input):\n return backend.to_device(input, self.odevice)\n\n def _adjoint_linop(self):\n return ToDevice(self.ishape, self.idevice, self.odevice)\n\n\nclass AllReduce(Linop):\n \"\"\"Performs all reduce between MPI ranks.\n\n Args:\n shape (tuple of ints): Input/output shape.\n comm (Communicator): Communicator.\n\n \"\"\"\n\n def __init__(self, shape, comm, in_place=False):\n self.comm = comm\n self.in_place = in_place\n\n super().__init__(shape, shape)\n\n def _apply(self, input):\n with backend.get_device(input):\n if self.in_place:\n output = input\n else:\n output = input.copy()\n\n self.comm.allreduce(output)\n return output\n\n def _adjoint_linop(self):\n return AllReduceAdjoint(self.ishape, self.comm, in_place=self.in_place)\n\n\nclass AllReduceAdjoint(Linop):\n \"\"\"All reduce adjoint operator. Equivalant to identity.\n\n Args:\n shape (tuple of ints): Input/output shape.\n comm (Communicator): Communicator.\n\n \"\"\"\n\n def __init__(self, shape, comm, in_place=False):\n self.comm = comm\n self.in_place = in_place\n\n super().__init__(shape, shape)\n\n def _apply(self, input):\n return input\n\n def _adjoint_linop(self):\n return AllReduce(self.ishape, self.comm, in_place=self.in_place)\n\n\nclass Conj(Linop):\n \"\"\"Complex conjugate of linear operator.\n\n Args:\n A (Linop): Input linear operator.\n\n \"\"\"\n\n def __init__(self, A):\n self.A = A\n\n super().__init__(A.oshape, A.ishape, repr_str=A.repr_str)\n\n def _apply(self, input):\n device = backend.get_device(input)\n with device:\n input = device.xp.conj(input)\n\n output = self.A(input)\n\n device = backend.get_device(output)\n with device:\n return device.xp.conj(output)\n\n def _adjoint_linop(self):\n return Conj(self.A.H)\n\n\nclass Add(Linop):\n \"\"\"Addition of linear operators.\n\n ishape, and oshape must match.\n\n Args:\n linops (list of Linops): Input linear operators.\n\n Returns:\n Linop: linops[0] + linops[1] + ... + linops[n - 1]\n\n \"\"\"\n\n def __init__(self, linops):\n _check_linops_same_ishape(linops)\n _check_linops_same_oshape(linops)\n\n self.linops = linops\n oshape = linops[0].oshape\n ishape = linops[0].ishape\n\n super().__init__(\n oshape, ishape,\n repr_str=' + '.join([linop.repr_str for linop in linops]))\n\n def _apply(self, input):\n output = 0\n with backend.get_device(output):\n for linop in self.linops:\n output += linop(input)\n\n return output\n\n def _adjoint_linop(self):\n return Add([linop.H for linop in self.linops])\n\n\ndef _check_compose_linops(linops):\n for linop1, linop2 in zip(linops[:-1], linops[1:]):\n if (linop1.ishape != linop2.oshape):\n raise ValueError('cannot compose {linop1} and {linop2}.'.format(\n linop1=linop1, linop2=linop2))\n\n\ndef _combine_compose_linops(linops):\n combined_linops = []\n for linop in linops:\n if isinstance(linop, Compose):\n combined_linops += linop.linops\n else:\n combined_linops.append(linop)\n\n return combined_linops\n\n\nclass Compose(Linop):\n \"\"\"Composition of linear operators.\n\n Args:\n linops (list of Linops): Linear operators to be composed.\n\n Returns:\n Linop: linops[0] * linops[1] * ... * linops[n - 1]\n\n \"\"\"\n\n def __init__(self, linops):\n _check_compose_linops(linops)\n self.linops = _combine_compose_linops(linops)\n\n super().__init__(\n self.linops[0].oshape, self.linops[-1].ishape,\n repr_str=' * '.join([linop.repr_str for linop in linops]))\n\n def _apply(self, input):\n output = input\n for linop in self.linops[::-1]:\n output = linop(output)\n\n return output\n\n def _adjoint_linop(self):\n return Compose([linop.H for linop in self.linops[::-1]])\n\n\ndef _check_linops_same_ishape(linops):\n for linop in linops:\n if (linop.ishape != linops[0].ishape):\n raise ValueError(\n 'Linops must have the same ishape, got {linops}.'.format(\n linops=linops))\n\n\ndef _check_linops_same_oshape(linops):\n for linop in linops:\n if (linop.oshape != linops[0].oshape):\n raise ValueError(\n 'Linops must have the same oshape, got {linops}.'.format(\n linops=linops))\n\n\ndef _hstack_params(shapes, axis):\n if axis is None:\n return _hstack_params([[util.prod(shape)] for shape in shapes], 0)\n\n ishape = list(shapes[0])\n ndim = len(ishape)\n idx = shapes[0][axis]\n indices = []\n\n for shape in shapes[1:]:\n if len(shape) != ndim:\n raise Exception(\n 'Shapes must have the same lengths to concatenate.')\n\n for i in range(ndim):\n if i == axis:\n ishape[i] += shape[i]\n indices.append(idx)\n idx += shape[i]\n elif shape[i] != ishape[i]:\n raise RuntimeError(\n 'Shapes not along axis must be the same to concatenate.')\n\n return ishape, indices\n\n\nclass Hstack(Linop):\n \"\"\"Horizontally stack linear operators.\n\n Creates a Linop that splits the input, applies Linops independently,\n and sums outputs.\n In matrix form, this is equivalant to given matrices {A1, ..., An},\n returns [A1, ..., An].\n\n Args:\n linops (list of Linops): list of linops with the same output shape.\n axis (int or None): If None, inputs are vectorized and concatenated.\n Otherwise, inputs are stacked along axis.\n\n \"\"\"\n\n def __init__(self, linops, axis=None):\n self.nops = len(linops)\n _check_linops_same_oshape(linops)\n\n self.linops = linops\n self.axis = axis\n\n ishape, self.indices = _hstack_params(\n [linop.ishape for linop in self.linops], axis)\n oshape = self.linops[0].oshape\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n output = 0\n with device:\n for n, linop in enumerate(self.linops):\n if n == 0:\n start = 0\n else:\n start = self.indices[n - 1]\n\n if n == self.nops - 1:\n end = None\n else:\n end = self.indices[n]\n\n if self.axis is None:\n output += linop(input[start:end].reshape(linop.ishape))\n else:\n ndim = len(linop.ishape)\n axis = self.axis % ndim\n\n slc = tuple([slice(None)] * axis + [slice(start, end)] +\n [slice(None)] * (ndim - axis - 1))\n\n output += linop(input[slc])\n\n return output\n\n def _adjoint_linop(self):\n return Vstack([op.H for op in self.linops], axis=self.axis)\n\n\ndef _vstack_params(shapes, axis):\n if axis is None:\n return _vstack_params([[util.prod(shape)] for shape in shapes], 0)\n\n oshape = list(shapes[0])\n ndim = len(oshape)\n idx = shapes[0][axis]\n indices = []\n\n for shape in shapes[1:]:\n if len(shape) != ndim:\n raise Exception(\n 'Shapes must have the same lengths to concatenate.')\n\n for i in range(ndim):\n if i == axis:\n oshape[i] += shape[i]\n indices.append(idx)\n idx += shape[i]\n elif shape[i] != oshape[i]:\n raise Exception(\n 'Shapes not along axis must be the same to concatenate.')\n\n return oshape, indices\n\n\nclass Vstack(Linop):\n \"\"\"Vertically stack linear operators.\n\n Creates a Linop that applies linops independently,\n and concatenates outputs.\n In matrix form, this is equivalant to given matrices {A1, ..., An},\n returns [A1.T, ..., An.T].T.\n\n Args:\n linops (list of Linops): list of linops with the same input shape.\n axis (int or None): If None, outputs are vectorized and concatenated.\n\n \"\"\"\n\n def __init__(self, linops, axis=None):\n self.nops = len(linops)\n _check_linops_same_ishape(linops)\n\n self.axis = axis\n self.linops = linops\n\n oshape, self.indices = _vstack_params(\n [linop.oshape for linop in self.linops], axis)\n ishape = self.linops[0].ishape\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n xp = device.xp\n with device:\n output = xp.empty(self.oshape, dtype=input.dtype)\n for n, linop in enumerate(self.linops):\n if n == 0:\n start = 0\n else:\n start = self.indices[n - 1]\n\n if n == self.nops - 1:\n end = None\n else:\n end = self.indices[n]\n\n if self.axis is None:\n output[start:end] = linop(input).ravel()\n else:\n ndim = len(linop.oshape)\n axis = self.axis % ndim\n slc = tuple([slice(None)] * axis + [slice(start, end)] +\n [slice(None)] * (ndim - axis - 1))\n output[slc] = linop(input)\n\n return output\n\n def _adjoint_linop(self):\n\n return Hstack([op.H for op in self.linops], axis=self.axis)\n\n\nclass Diag(Linop):\n \"\"\"Diagonally stack linear operators.\n\n Create a Linop that splits input, applies linops independently,\n and concatenates outputs.\n In matrix form, given matrices {A1, ..., An}, returns diag([A1, ..., An]).\n\n Args:\n linops (list of Linops): list of linops with the same input and\n output shape.\n axis (int or None): If None, inputs/outputs are vectorized\n and concatenated.\n\n \"\"\"\n\n def __init__(self, linops, axis=None):\n self.nops = len(linops)\n\n self.linops = linops\n self.axis = axis\n ishape, self.iindices = _hstack_params(\n [linop.ishape for linop in self.linops], axis)\n oshape, self.oindices = _vstack_params(\n [linop.oshape for linop in self.linops], axis)\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n xp = device.xp\n with device:\n output = xp.empty(self.oshape, dtype=input.dtype)\n for n, linop in enumerate(self.linops):\n if n == 0:\n istart = 0\n ostart = 0\n else:\n istart = self.iindices[n - 1]\n ostart = self.oindices[n - 1]\n\n if n == self.nops - 1:\n iend = None\n oend = None\n else:\n iend = self.iindices[n]\n oend = self.oindices[n]\n\n if self.axis is None:\n output[ostart:oend] = linop(\n input[istart:iend].reshape(linop.ishape)).ravel()\n else:\n ndim = len(linop.oshape)\n axis = self.axis % ndim\n oslc = tuple([slice(None)] * axis + [slice(ostart, oend)] +\n [slice(None)] * (ndim - axis - 1))\n\n ndim = len(linop.ishape)\n axis = self.axis % ndim\n islc = tuple([slice(None)] * axis + [slice(istart, iend)] +\n [slice(None)] * (ndim - axis - 1))\n\n output[oslc] = linop(input[islc])\n\n return output\n\n def _adjoint_linop(self):\n return Diag([op.H for op in self.linops], axis=self.axis)\n\n\nclass Reshape(Linop):\n \"\"\"Reshape input to given output shape.\n\n Args:\n oshape (tuple of ints): Output shape.\n ishape (tuple of ints): Input shape.\n\n \"\"\"\n\n def __init__(self, oshape, ishape):\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return input.reshape(self.oshape)\n\n def _adjoint_linop(self):\n return Reshape(self.ishape, self.oshape)\n\n\nclass Transpose(Linop):\n \"\"\"Tranpose input with the given axes.\n\n Args:\n ishape (tuple of ints): Input shape.\n axes (None or tuple of ints): Axes to transpose input.\n\n \"\"\"\n\n def __init__(self, ishape, axes=None):\n self.axes = axes\n if axes is None:\n self.iaxes = None\n oshape = ishape[::-1]\n else:\n self.iaxes = np.argsort(axes)\n oshape = [ishape[a] for a in axes]\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return input.transpose(self.axes)\n\n def _adjoint_linop(self):\n\n if self.axes is None:\n iaxes = None\n oshape = self.ishape[::-1]\n else:\n iaxes = np.argsort(self.axes)\n oshape = [self.ishape[a] for a in self.axes]\n\n return Transpose(oshape, axes=iaxes)\n\n\nclass FFT(Linop):\n \"\"\"FFT linear operator.\n\n Args:\n ishape (tuple of int): Input shape\n axes (None or tuple of int): Axes to perform FFT.\n If None, applies on all axes.\n center (bool): Toggle center FFT.\n\n \"\"\"\n\n def __init__(self, shape, axes=None, center=True):\n\n self.axes = axes\n self.center = center\n\n super().__init__(shape, shape)\n\n def _apply(self, input):\n return fourier.fft(input, axes=self.axes, center=self.center)\n\n def _adjoint_linop(self):\n return IFFT(self.ishape, axes=self.axes, center=self.center)\n\n\nclass IFFT(Linop):\n \"\"\"IFFT linear operator.\n\n Args:\n ishape (tuple of int): Input shape\n axes (None or tuple of int): Axes to perform FFT.\n If None, applies on all axes.\n center (bool): Toggle center FFT.\n\n \"\"\"\n\n def __init__(self, shape, axes=None, center=True):\n\n self.axes = axes\n self.center = center\n\n super().__init__(shape, shape)\n\n def _apply(self, input):\n return fourier.ifft(input, axes=self.axes, center=self.center)\n\n def _adjoint_linop(self):\n return FFT(self.ishape, axes=self.axes, center=self.center)\n\n\ndef _get_matmul_oshape(ishape, mshape, adjoint):\n ishape_exp, mshape_exp = util._expand_shapes(ishape, mshape)\n if adjoint:\n mshape_exp[-1], mshape_exp[-2] = mshape_exp[-2], mshape_exp[-1]\n\n oshape = []\n for i, m in zip(ishape_exp[:-2], mshape_exp[:-2]):\n if not (i == m or i == 1 or m == 1):\n raise ValueError('Invalid shapes: {ishape}, {mshape}.'.format(\n ishape=ishape, mshape=mshape))\n\n oshape.append(max(i, m))\n\n if mshape_exp[-1] != ishape_exp[-2]:\n raise ValueError('Invalid shapes: {ishape}, {mshape}.'.format(\n ishape=ishape, mshape=mshape))\n\n oshape += [mshape_exp[-2], ishape_exp[-1]]\n\n return oshape\n\n\ndef _get_matmul_adjoint_sum_axes(oshape, ishape, mshape):\n ishape_exp, mshape_exp = util._expand_shapes(ishape, mshape)\n max_ndim = max(len(ishape), len(mshape))\n sum_axes = []\n for i, m, o, d in zip(\n ishape_exp[:-2], mshape_exp[:-2], oshape[:-2],\n range(max_ndim - 2)):\n if (i == 1 and (m != 1 or o != 1)):\n sum_axes.append(d)\n\n return sum_axes\n\n\nclass MatMul(Linop):\n \"\"\"Matrix multiplication.\n\n Args:\n ishape (tuple of ints): Input shape.\n It must be able to broadcast with mat.shape.\n mat (array): Matrix of shape [..., m, n]\n adjoint (bool): Toggle adjoint.\n If True, performs conj(mat).swapaxes(-1, -2)\n before performing matrix multiplication.\n\n \"\"\"\n\n def __init__(self, ishape, mat, adjoint=False):\n self.mat = mat\n self.adjoint = adjoint\n\n oshape = _get_matmul_oshape(ishape, mat.shape, adjoint)\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n xp = device.xp\n mat = backend.to_device(self.mat, device)\n with device:\n if self.adjoint:\n mat = xp.conj(mat).swapaxes(-1, -2)\n\n return xp.matmul(mat, input)\n\n def _adjoint_linop(self):\n sum_axes = _get_matmul_adjoint_sum_axes(\n self.oshape, self.ishape, self.mat.shape)\n\n M = MatMul(self.oshape, self.mat, adjoint=not self.adjoint)\n S = Sum(M.oshape, sum_axes)\n R = Reshape(self.ishape, S.oshape)\n return R * S * M\n\n\ndef _get_right_matmul_oshape(ishape, mshape, adjoint):\n ishape_exp, mshape_exp = util._expand_shapes(ishape, mshape)\n if adjoint:\n mshape_exp[-1], mshape_exp[-2] = mshape_exp[-2], mshape_exp[-1]\n\n max_ndim = max(len(ishape), len(mshape))\n oshape = []\n for i, m, d in zip(ishape_exp[:-2], mshape_exp[:-2], range(max_ndim - 2)):\n if not (i == m or i == 1 or m == 1):\n raise ValueError('Invalid shapes: {ishape}, {mshape}.'.format(\n ishape=ishape, mshape=mshape))\n\n oshape.append(max(i, m))\n\n if ishape_exp[-1] != mshape_exp[-2]:\n raise ValueError('Invalid shapes: {ishape}, {mshape}.'.format(\n ishape=ishape, mshape=mshape))\n\n oshape += [ishape_exp[-2], mshape_exp[-1]]\n\n return oshape\n\n\nclass RightMatMul(Linop):\n \"\"\"Matrix multiplication on the right.\n\n Args:\n ishape (tuple of ints): Input shape.\n It must be able to broadcast with mat.shape.\n mat (array): Matrix of shape [..., m, n]\n adjoint (bool): Toggle adjoint.\n If True, performs conj(mat).swapaxes(-1, -2)\n before performing matrix multiplication.\n\n \"\"\"\n\n def __init__(self, ishape, mat, adjoint=False):\n self.mat = mat\n self.adjoint = adjoint\n\n oshape = _get_right_matmul_oshape(ishape, mat.shape, adjoint)\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n xp = device.xp\n mat = backend.to_device(self.mat, device)\n with device:\n if self.adjoint:\n mat = xp.conj(mat).swapaxes(-1, -2)\n\n return xp.matmul(input, mat)\n\n def _adjoint_linop(self):\n sum_axes = _get_matmul_adjoint_sum_axes(\n self.oshape, self.ishape, self.mat.shape)\n\n M = RightMatMul(self.oshape, self.mat, adjoint=not self.adjoint)\n S = Sum(M.oshape, sum_axes)\n R = Reshape(self.ishape, S.oshape)\n return R * S * M\n\n\ndef _get_multiply_oshape(ishape, mshape):\n ishape_exp, mshape_exp = util._expand_shapes(ishape, mshape)\n max_ndim = max(len(ishape), len(mshape))\n oshape = []\n for i, m, d in zip(ishape_exp, mshape_exp, range(max_ndim)):\n if not (i == m or i == 1 or m == 1):\n raise ValueError('Invalid shapes: {ishape}, {mshape}.'.format(\n ishape=ishape, mshape=mshape))\n\n oshape.append(max(i, m))\n\n return oshape\n\n\ndef _get_multiply_adjoint_sum_axes(oshape, ishape, mshape):\n ishape_exp, mshape_exp = util._expand_shapes(ishape, mshape)\n max_ndim = max(len(ishape), len(mshape))\n sum_axes = []\n for i, m, o, d in zip(ishape_exp, mshape_exp, oshape, range(max_ndim)):\n if (i == 1 and (m != 1 or o != 1)):\n sum_axes.append(d)\n\n return sum_axes\n\n\nclass Multiply(Linop):\n \"\"\"Multiplication linear operator.\n\n Args:\n ishape (tuple of ints): Input shape.\n mult (array): Array to multiply.\n\n \"\"\"\n\n def __init__(self, ishape, mult, conj=False):\n self.mult = mult\n self.conj = conj\n if np.isscalar(mult):\n self.mshape = [1]\n else:\n self.mshape = mult.shape\n\n oshape = _get_multiply_oshape(ishape, self.mshape)\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n xp = device.xp\n\n with device:\n if np.isscalar(self.mult):\n if self.mult == 1:\n return input\n\n mult = self.mult\n if self.conj:\n mult = mult.conjugate()\n\n else:\n mult = backend.to_device(self.mult, device)\n if mult.dtype != input.dtype:\n mult = mult.astype(input.dtype)\n\n if self.conj:\n mult = xp.conj(mult)\n\n return input * mult\n\n def _adjoint_linop(self):\n sum_axes = _get_multiply_adjoint_sum_axes(\n self.oshape, self.ishape, self.mshape)\n\n M = Multiply(self.oshape, self.mult, conj=not self.conj)\n S = Sum(M.oshape, sum_axes)\n R = Reshape(self.ishape, S.oshape)\n return R * S * M\n\n\nclass Interpolate(Linop):\n \"\"\"Interpolation linear operator.\n\n Args:\n ishape (tuple of ints): Input shape = batch_shape + grd_shape\n coord (array): Coordinates, values from - nx / 2 to nx / 2 - 1.\n ndim can only be 1, 2 or 3, of shape pts_shape + [ndim]\n width (float): Width of interp. kernel in grid size.\n kernel (array): Look-up kernel of kernel K, from K[0] to K[width].\n scale (float): Scaling of coordinates.\n shift (float): Shifting of coordinates.\n\n \"\"\"\n\n def __init__(self, ishape, coord, width, kernel):\n ndim = coord.shape[-1]\n oshape = list(ishape[:-ndim]) + list(coord.shape[:-1])\n\n self.coord = coord\n self.width = width\n self.kernel = kernel\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n\n device = backend.get_device(input)\n coord = backend.to_device(self.coord, device)\n kernel = backend.to_device(self.kernel, device)\n\n with device:\n return interp.interpolate(input, self.width, kernel, coord)\n\n def _adjoint_linop(self):\n return Gridding(self.ishape, self.coord, self.width, self.kernel)\n\n\nclass Gridding(Linop):\n \"\"\"Gridding linear operator.\n\n Args:\n oshape (tuple of ints): Output shape = batch_shape + pts_shape\n ishape (tuple of ints): Input shape = batch_shape + grd_shape\n coord (array): Coordinates, values from - nx / 2 to nx / 2 - 1.\n ndim can only be 1, 2 or 3. of shape pts_shape + [ndim]\n width (float): Width of interp. kernel in grid size\n kernel (array): Llook-up kernel of kernel K, from K[0] to K[width]\n scale (float): Scaling of coordinates.\n shift (float): Shifting of coordinates.\n\n \"\"\"\n\n def __init__(self, oshape, coord, width, kernel):\n ndim = coord.shape[-1]\n ishape = list(oshape[:-ndim]) + list(coord.shape[:-1])\n\n self.coord = coord\n self.width = width\n self.kernel = kernel\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n coord = backend.to_device(self.coord, device)\n kernel = backend.to_device(self.kernel, device)\n\n with device:\n return interp.gridding(\n input, self.oshape, self.width, kernel, coord)\n\n def _adjoint_linop(self):\n return Interpolate(self.oshape, self.coord, self.width, self.kernel)\n\n\nclass Resize(Linop):\n \"\"\"Resize linear operator.\n\n Args:\n oshape (tuple of int): Output shape.\n ishape (tuple of int): Input shape\n \"\"\"\n\n def __init__(self, oshape, ishape, ishift=None, oshift=None):\n self.ishift = ishift\n self.oshift = oshift\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n\n return util.resize(input, self.oshape,\n ishift=self.ishift, oshift=self.oshift)\n\n def _adjoint_linop(self):\n\n return Resize(self.ishape, self.oshape,\n ishift=self.oshift, oshift=self.ishift)\n\n\nclass Flip(Linop):\n \"\"\"Flip linear operator.\n\n Args:\n shape (tuple of int): Input shape\n \"\"\"\n\n def __init__(self, shape, axes=None):\n self.axes = axes\n\n super().__init__(shape, shape)\n\n def _apply(self, input):\n return util.flip(input, self.axes)\n\n def _adjoint_linop(self):\n return self\n\n\nclass Downsample(Linop):\n \"\"\"Downsampling linear operator.\n\n Args:\n ishape (tuple of ints): Input shape.\n factor (tuple of ints): Downsampling factor.\n shift (None of tuple of ints): Shifts before down-sampling.\n \"\"\"\n\n def __init__(self, ishape, factors, shift=None):\n self.factors = factors\n\n if shift is None:\n shift = [0] * len(ishape)\n\n self.shift = shift\n oshape = [((i - s + f - 1) // f)\n for i, f, s in zip(ishape, factors, shift)]\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return util.downsample(input, self.factors, shift=self.shift)\n\n def _adjoint_linop(self):\n return Upsample(self.ishape, self.factors, shift=self.shift)\n\n\nclass Upsample(Linop):\n \"\"\"Upsampling linear operator.\n\n Args:\n ishape (tuple of ints): Input shape.\n factor (tuple of ints): Upsampling factor.\n shift (None of tuple of ints): Shifts before up-sampling.\n\n \"\"\"\n\n def __init__(self, oshape, factors, shift=None):\n self.factors = factors\n\n if shift is None:\n shift = [0] * len(oshape)\n\n self.shift = shift\n ishape = [((i - s + f - 1) // f)\n for i, f, s in zip(oshape, factors, shift)]\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return util.upsample(input, self.oshape,\n self.factors, shift=self.shift)\n\n def _adjoint_linop(self):\n return Downsample(self.oshape, self.factors, shift=self.shift)\n\n\nclass Circshift(Linop):\n \"\"\"Circular shift linear operator.\n\n Args:\n shape (tuple of ints): Input/output shape.\n shift (tuple of ints): Shifts.\n axes (None or tuple of ints): Axes to perform circular shift.\n\n \"\"\"\n\n def __init__(self, shape, shift, axes=None):\n\n self.axes = axes\n self.shift = shift\n self.ishift = [-s for s in self.shift]\n\n super().__init__(shape, shape)\n\n def _apply(self, input):\n return util.circshift(input, self.shift, self.axes)\n\n def _adjoint_linop(self):\n return Circshift(self.ishape, [-s for s in self.shift], axes=self.axes)\n\n\nclass Wavelet(Linop):\n \"\"\"Wavelet transform linear operator.\n\n Currently only has CPU implementation. GPU inputs will be copied to CPU,\n and back to compute on CPU.\n\n Args:\n ishape (tuple of int): Input shape.\n axes (None or tuple of int): Axes to perform wavelet transform.\n wave_name (str): Wavelet name.\n level (None or int): Number of wavelet levels.\n \"\"\"\n\n def __init__(self, ishape, axes=None, wave_name='db4', level=None):\n self.wave_name = wave_name\n self.axes = axes\n self.level = level\n oshape, _ = wavelet.get_wavelet_shape(ishape, wave_name, axes, level)\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return wavelet.fwt(\n input, wave_name=self.wave_name, axes=self.axes, level=self.level)\n\n def _adjoint_linop(self):\n return InverseWavelet(\n self.ishape,\n axes=self.axes,\n wave_name=self.wave_name,\n level=self.level)\n\n\nclass InverseWavelet(Linop):\n \"\"\"Inverse wavelet transform linear operator.\n\n Currently only has CPU implementation. GPU inputs will be copied to CPU,\n and back to compute on CPU.\n\n Args:\n oshape (tuple of int): Output shape.\n axes (None or tuple of int): Axes to perform wavelet transform.\n wave_name (str): Wavelet name.\n level (None or int): Number of wavelet levels.\n \"\"\"\n\n def __init__(self, oshape, axes=None, wave_name='db4', level=None):\n self.wave_name = wave_name\n self.axes = axes\n self.level = level\n ishape, self.coeff_slices = wavelet.get_wavelet_shape(\n oshape, wave_name, axes, level)\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return wavelet.iwt(\n input, self.oshape, self.coeff_slices,\n wave_name=self.wave_name, axes=self.axes, level=self.level)\n\n def _adjoint_linop(self):\n return Wavelet(self.oshape, axes=self.axes,\n wave_name=self.wave_name, level=self.level)\n\n\nclass Sum(Linop):\n \"\"\"Sum linear operator. Accumulate axes by summing.\n\n Args:\n ishape (tuple of ints): Input shape.\n axes (tuple of ints): Axes to sum over.\n \"\"\"\n\n def __init__(self, ishape, axes):\n self.axes = tuple(i % len(ishape) for i in axes)\n oshape = [ishape[i] for i in range(len(ishape)) if i not in self.axes]\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n device = backend.get_device(input)\n xp = device.xp\n with device:\n return xp.sum(input, axis=self.axes)\n\n def _adjoint_linop(self):\n\n return Tile(self.ishape, self.axes)\n\n\nclass Tile(Linop):\n \"\"\"Tile linear operator.\n\n Args:\n oshape (tuple of ints): Output shape.\n axes (tuple of ints): Axes to tile.\n\n \"\"\"\n\n def __init__(self, oshape, axes):\n\n self.axes = tuple(a % len(oshape) for a in axes)\n ishape = [oshape[d] for d in range(len(oshape)) if d not in self.axes]\n self.expanded_ishape = []\n self.reps = []\n for d in range(len(oshape)):\n if d in self.axes:\n self.expanded_ishape.append(1)\n self.reps.append(oshape[d])\n else:\n self.expanded_ishape.append(oshape[d])\n self.reps.append(1)\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n\n device = backend.get_device(input)\n xp = device.xp\n with device:\n return xp.tile(input.reshape(self.expanded_ishape), self.reps)\n\n def _adjoint_linop(self):\n\n return Sum(self.oshape, self.axes)\n\n\nclass ArrayToBlocks(Linop):\n \"\"\"Extract blocks from an array in a sliding window manner.\n\n Args:\n ishape (array): input array of shape [..., N_1, ..., N_D]\n blk_shape (tuple): block shape of length D, with D <= 4.\n blk_strides (tuple): block strides of length D.\n\n See Also:\n :func:`sigpy.block.array_to_blocks`\n\n \"\"\"\n\n def __init__(self, ishape, blk_shape, blk_strides):\n self.blk_shape = blk_shape\n self.blk_strides = blk_strides\n D = len(blk_shape)\n num_blks = [(i - b + s) // s for i, b,\n s in zip(ishape[-D:], blk_shape, blk_strides)]\n oshape = num_blks + list(blk_shape)\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return block.array_to_blocks(input, self.blk_shape, self.blk_strides)\n\n def _adjoint_linop(self):\n return BlocksToArray(self.ishape, self.blk_shape, self.blk_strides)\n\n\nclass BlocksToArray(Linop):\n \"\"\"Accumulate blocks into an array in a sliding window manner.\n\n Args:\n oshape (tuple): output shape.\n blk_shape (tuple): block shape of length D.\n blk_strides (tuple): block strides of length D.\n\n Returns:\n array: array of shape oshape.\n\n \"\"\"\n def __init__(self, oshape, blk_shape, blk_strides):\n self.blk_shape = blk_shape\n self.blk_strides = blk_strides\n D = len(blk_shape)\n num_blks = [(i - b + s) // s for i, b,\n s in zip(oshape[-D:], blk_shape, blk_strides)]\n ishape = num_blks + list(blk_shape)\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return block.blocks_to_array(\n input, self.oshape, self.blk_shape, self.blk_strides)\n\n def _adjoint_linop(self):\n return ArrayToBlocks(self.oshape, self.blk_shape, self.blk_strides)\n\n\ndef Gradient(ishape, axes=None):\n import warnings\n\n warnings.warn('Gradient Linop is renamed to FiniteDifference, '\n 'Please switch to use FiniteDifference.',\n category=DeprecationWarning)\n\n return FiniteDifference(ishape, axes=axes)\n\n\ndef FiniteDifference(ishape, axes=None):\n \"\"\"Linear operator that computes finite difference gradient.\n\n Args:\n ishape (tuple of ints): Input shape.\n\n \"\"\"\n I = Identity(ishape)\n axes = util._normalize_axes(axes, len(ishape))\n ndim = len(ishape)\n linops = []\n for i in axes:\n D = I - Circshift(ishape, [0] * i + [1] + [0] * (ndim - i - 1))\n R = Reshape([1] + list(ishape), ishape)\n linops.append(R * D)\n\n G = Vstack(linops, axis=0)\n\n return G\n\n\nclass NUFFT(Linop):\n \"\"\"NUFFT linear operator.\n\n Args:\n ishape (tuple of int): Input shape.\n coord (array): Coordinates, with values [-ishape / 2, ishape / 2]\n oversamp (float): Oversampling factor.\n width (float): Kernel width.\n n (int): Kernel sampling number.\n\n \"\"\"\n def __init__(self, ishape, coord, oversamp=1.25, width=4.0, n=128):\n self.coord = coord\n self.oversamp = oversamp\n self.width = width\n self.n = n\n\n ndim = coord.shape[-1]\n\n oshape = list(ishape[:-ndim]) + list(coord.shape[:-1])\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n\n return fourier.nufft(\n input,\n self.coord,\n oversamp=self.oversamp,\n width=self.width,\n n=self.n)\n\n def _adjoint_linop(self):\n\n return NUFFTAdjoint(self.ishape, self.coord,\n oversamp=self.oversamp, width=self.width, n=self.n)\n\n\nclass NUFFTAdjoint(Linop):\n \"\"\"NUFFT adjoint linear operator.\n\n Args:\n oshape (tuple of int): Output shape\n coord (array): Coordinates, with values [-ishape / 2, ishape / 2]\n oversamp (float): Oversampling factor.\n width (float): Kernel width.\n n (int): Kernel sampling number.\n\n \"\"\"\n def __init__(self, oshape, coord, oversamp=1.25, width=4.0, n=128):\n self.coord = coord\n self.oversamp = oversamp\n self.width = width\n self.n = n\n\n ndim = coord.shape[-1]\n\n ishape = list(oshape[:-ndim]) + list(coord.shape[:-1])\n\n super().__init__(oshape, ishape)\n\n def _apply(self, input):\n return fourier.nufft_adjoint(\n input,\n self.coord,\n self.oshape,\n oversamp=self.oversamp,\n width=self.width,\n n=self.n)\n\n def _adjoint_linop(self):\n\n return NUFFT(self.oshape, self.coord,\n oversamp=self.oversamp, width=self.width, n=self.n)\n\n\nclass ConvolveData(Linop):\n r\"\"\"Convolution operator for data arrays.\n\n Args:\n data_shape (tuple of ints): data array shape:\n :math:`[\\ldots, m_1, \\ldots, m_D]` if multi_channel is False,\n :math:`[\\ldots, c_i, m_1, \\ldots, m_D]` otherwise.\n filt (array): filter array of shape:\n :math:`[n_1, \\ldots, n_D]` if multi_channel is False\n :math:`[c_o, c_i, n_1, \\ldots, n_D]` otherwise.\n mode (str): {'full', 'valid'}.\n strides (None or tuple of ints): convolution strides of length D.\n multi_channel (bool): specify if input/output has multiple channels.\n\n \"\"\"\n def __init__(self, data_shape, filt, mode='full', strides=None,\n multi_channel=False):\n self.filt = filt\n self.mode = mode\n self.strides = strides\n self.multi_channel = multi_channel\n\n D, b, B, m, n, s, c_i, c_o, p = conv._get_convolve_params(\n data_shape, filt.shape,\n mode, strides, multi_channel)\n\n if multi_channel:\n output_shape = b + (c_o, ) + p\n else:\n output_shape = b + p\n\n super().__init__(output_shape, data_shape)\n\n def _apply(self, input):\n return conv.convolve(input, self.filt, mode=self.mode,\n strides=self.strides,\n multi_channel=self.multi_channel)\n\n def _adjoint_linop(self):\n return ConvolveDataAdjoint(\n self.ishape, self.filt,\n mode=self.mode, strides=self.strides,\n multi_channel=self.multi_channel)\n\n\nclass ConvolveDataAdjoint(Linop):\n r\"\"\"Adjoint convolution operator for data arrays.\n\n Args:\n data_shape (tuple of ints): data array shape:\n :math:`[\\ldots, m_1, \\ldots, m_D]` if multi_channel is False,\n :math:`[\\ldots, c_i, m_1, \\ldots, m_D]` otherwise.\n filt (array): filter array of shape:\n :math:`[n_1, \\ldots, n_D]` if multi_channel is False\n :math:`[c_o, c_i, n_1, \\ldots, n_D]` otherwise.\n mode (str): {'full', 'valid'}.\n strides (None or tuple of ints): convolution strides of length D.\n multi_channel (bool): specify if input/output has multiple channels.\n\n \"\"\"\n def __init__(self, data_shape, filt,\n mode='full', strides=None, multi_channel=False):\n self.filt = filt\n self.mode = mode\n self.strides = strides\n self.multi_channel = multi_channel\n\n D, b, B, m, n, s, c_i, c_o, p = conv._get_convolve_params(\n data_shape, filt.shape,\n mode, strides, multi_channel)\n\n if multi_channel:\n output_shape = b + (c_o, ) + p\n else:\n output_shape = b + p\n\n super().__init__(data_shape, output_shape)\n\n def _apply(self, input):\n return conv.convolve_data_adjoint(\n input, self.filt, self.oshape,\n mode=self.mode,\n strides=self.strides,\n multi_channel=self.multi_channel)\n\n def _adjoint_linop(self):\n return ConvolveData(self.oshape, self.filt,\n mode=self.mode, strides=self.strides,\n multi_channel=self.multi_channel)\n\n\nclass ConvolveFilter(Linop):\n r\"\"\"Convolution operator for filter arrays.\n\n Args:\n filt_shape (tuple of ints): filter array shape:\n :math:`[n_1, \\ldots, n_D]` if multi_channel is False\n :math:`[c_o, c_i, n_1, \\ldots, n_D]` otherwise.\n data (array): data array of shape:\n :math:`[\\ldots, m_1, \\ldots, m_D]` if multi_channel is False,\n :math:`[\\ldots, c_i, m_1, \\ldots, m_D]` otherwise.\n mode (str): {'full', 'valid'}.\n strides (None or tuple of ints): convolution strides of length D.\n multi_channel (bool): specify if input/output has multiple channels.\n\n \"\"\"\n def __init__(self, filt_shape, data,\n mode='full', strides=None,\n multi_channel=False):\n self.data = data\n self.mode = mode\n self.strides = strides\n self.multi_channel = multi_channel\n\n D, b, B, m, n, s, c_i, c_o, p = conv._get_convolve_params(\n data.shape, filt_shape,\n mode, strides, multi_channel)\n\n if multi_channel:\n output_shape = b + (c_o, ) + p\n else:\n output_shape = b + p\n\n super().__init__(output_shape, filt_shape)\n\n def _apply(self, input):\n data = backend.to_device(self.data, backend.get_device(input))\n return conv.convolve(data, input,\n mode=self.mode, strides=self.strides,\n multi_channel=self.multi_channel)\n\n def _adjoint_linop(self):\n return ConvolveFilterAdjoint(\n self.ishape, self.data,\n mode=self.mode, strides=self.strides,\n multi_channel=self.multi_channel)\n\n\nclass ConvolveFilterAdjoint(Linop):\n r\"\"\"Adjoint convolution operator for filter arrays.\n\n Args:\n filt_shape (tuple of ints): filter array shape:\n :math:`[n_1, \\ldots, n_D]` if multi_channel is False\n :math:`[c_o, c_i, n_1, \\ldots, n_D]` otherwise.\n data (array): data array of shape:\n :math:`[\\ldots, m_1, \\ldots, m_D]` if multi_channel is False,\n :math:`[\\ldots, c_i, m_1, \\ldots, m_D]` otherwise.\n mode (str): {'full', 'valid'}.\n strides (None or tuple of ints): convolution strides of length D.\n multi_channel (bool): specify if input/output has multiple channels.\n\n \"\"\"\n def __init__(self, filt_shape, data,\n mode='full', strides=None,\n multi_channel=False):\n self.data = data\n self.mode = mode\n self.strides = strides\n self.multi_channel = multi_channel\n\n D, b, B, m, n, s, c_i, c_o, p = conv._get_convolve_params(\n data.shape, filt_shape,\n mode, strides, multi_channel)\n\n if multi_channel:\n output_shape = b + (c_o, ) + p\n else:\n output_shape = b + p\n\n super().__init__(filt_shape, output_shape)\n\n def _apply(self, input):\n return conv.convolve_filter_adjoint(\n input, self.data, self.oshape,\n mode=self.mode, strides=self.strides,\n multi_channel=self.multi_channel)\n\n def _adjoint_linop(self):\n return ConvolveFilter(self.oshape, self.data,\n mode=self.mode, strides=self.strides,\n multi_channel=self.multi_channel)\n" ]
[ [ "numpy.argsort", "numpy.isscalar" ] ]
Easonyesheng/BrainMRIProcess
[ "d58f8edbb3591a8bb506187778a275b18e76ca0b" ]
[ "De_bone.py" ]
[ "'''\nget rid of skull\n 1. use the original DICOM pixel array -- make the highest to 0\n 2. use conditional dilation\n'''\n\nimport cv2\nimport numpy as np \nfrom Imread import DicomIn \nfrom DilateAndErosion import *\nfrom PIL import Image,ImageQt\nimport time\n\n\nTempPath='/Users/zhangyesheng/Desktop/temp/ConDSkull/'\n\n\n'''\noutput : img - 0 & 255\n'''\ndef OpenSk(SE,img):\n Img_ER = ErosionGet(img, SE) \n none, Img_ER = cv2.threshold(Img_ER,0,255,cv2.THRESH_BINARY)\n Img_ER_DR = DilationGet(Img_ER, SE)\n none, Img_ER_DR = cv2.threshold(Img_ER_DR,0,255,cv2.THRESH_BINARY)\n\n \n name = TempPath+'Open.jpg'\n cv2.imwrite(name,Img_ER_DR)\n Im_show = cv2.imread(name,-1) \n \n return Im_show\n\n'''\nConditional Dialate\ninput : img & line's position\noutput : img_R\n'''\ndef ConDia_Sk(img,lineP,TempPath='/Users/zhangyesheng/Desktop/temp/ConDSkull/'):\n \n w,h = img.shape\n path = TempPath\n cv2.imwrite(path+'Ori.jpg',img*255)\n # cv2.imwrite(path+'Ori.jpg',img*255)\n img = img.astype(np.int)\n img_line = np.zeros([w,h],dtype='int')\n img_line[:,lineP] = 1\n \n \n temp = np.zeros([w,h],dtype='int')\n SE = np.ones([3,3],dtype='bool')\n c = 0\n img_grayt = img.astype(np.bool)\n # print(img_grayt.dtype)\n \n # img_graytl = img_grayt*255\n a = 0\n b = 0\n while(True):\n print(c)\n img_line = DilationGet(img_line,SE)\n temp = img_line.copy()\n # print(temp.dtype)\n # temp = temp.astype(np.int)\n # img_line = img_line.astype(np.bool)\n img_line = img_line & img_grayt # 0 & 1\n img_line = img_line.astype(np.int)\n # print(img_line.dtype)\n img_l = img_line*255\n \n cv2.imwrite(path+str(c)+'.jpg',img_l)\n c+=1\n # print((temp == img_line).all())\n res = temp == img_line\n a = np.sum(res == False)\n if (a == b):\n break\n b = a\n \n return img_line.astype(np.int)\n\n\n'''\nUse the different value of skull in MRI to de-skull\ninput : DICOM array\noutput : image array\n'''\ndef DSk_DICOM(array):\n Max = array.max()\n\n index_min = np.argwhere(array < 300)\n index_max = np.argwhere(array > Max-100)\n # print('Min: ',Min)\n # print('index shape: ',index.shape)\n num, temp = index_min.shape\n for i in range(num):\n array[index_min[i,0],index_min[i,1]] = 0\n\n num, temp = index_max.shape\n for i in range(num):\n array[index_max[i,0],index_max[i,1]] = 0\n\n\n array = (array/array.max())*255\n return array\n\n\n'''\nCombined Method\ninput : DICOM array\noutput : image array : [0,255]\n'''\ndef DSK_DI_Morpho(array):\n\n t = str(time.time())[-1]\n\n Max = array.max()\n\n index_min = np.argwhere(array < 300)\n index_max = np.argwhere(array > Max-100)\n # print('Min: ',Min)\n # print('index shape: ',index.shape)\n num, temp = index_min.shape\n for i in range(num):\n array[index_min[i,0],index_min[i,1]] = 0\n\n num, temp = index_max.shape\n for i in range(num):\n array[index_max[i,0],index_max[i,1]] = 0\n\n\n array = (array/array.max())*255\n\n \n # Threshod\n Mask = np.where(array>21,1,0)\n w, h = Mask.shape\n\n for i in range(h):\n if (array[:,i]>0).any():\n lineP = i\n break\n \n Mask = ConDia_Sk(Mask, lineP, )\n Mask_ = (Mask*255)\n cv2.imwrite(TempPath+'Mask.jpg',Mask_)\n array = array - Mask_\n cv2.imwrite('/Users/zhangyesheng/Desktop/医学信息学/Project/temp/de_sk'+t+'.jpg',array) # Skull deminished\n # Open\n img = cv2.imread('/Users/zhangyesheng/Desktop/医学信息学/Project/temp/de_sk'+t+'.jpg',-1)\n Mask2 = np.where(img>21,1,0) * 255\n '''\n The SE size need to change accroding to differrent images\n '''\n SE = np.ones([11,11],dtype='bool') \n Mask2 = OpenSk(SE, Mask2)\n cv2.imwrite('/Users/zhangyesheng/Desktop/医学信息学/Project/temp/mask'+t+'.jpg',Mask2)\n Mask3 = cv2.imread('/Users/zhangyesheng/Desktop/医学信息学/Project/temp/mask'+t+'.jpg',-1)\n array = array * (Mask3).astype('int')\n\n array = (array/array.max())*255 # get rid of small dots \n\n return array\n\n\n\n\n\n\nDICOMPath = '/Users/zhangyesheng/Desktop/医学信息学/BrainMRIProcess/Dicom_Seg/brain_013.dcm'\n\n\nif __name__ == \"__main__\":\n info, PixelArray = DicomIn(DICOMPath)\n array_no_skull = DSk_DICOM(PixelArray)\n # array_no_skull = DSK_DI_Morpho(PixelArray)\n # cv2.imwrite('/Users/zhangyesheng/Desktop/医学信息学/Project/temp/de_sk_fin'+t+'.jpg',array_no_skull)\n Ima = Image.fromarray(array_no_skull)\n Ima.show() \n # img = cv2.imread('/Users/zhangyesheng/Desktop/医学信息学/Project/temp/de_sk1.jpg',-1)\n # Mask2 = np.where(img>21,1,0) * 255\n # SE = np.ones([5,5],dtype='bool')\n # Mask2 = OpenSk(SE, Mask2)\n \n # cv2.imwrite('/Users/zhangyesheng/Desktop/医学信息学/Project/temp/mask.jpg',Mask2)\n # Ima = Image.fromarray(Mask2)\n # Ima.show()\n\n\n" ]
[ [ "numpy.argwhere", "numpy.ones", "numpy.where", "numpy.zeros", "numpy.sum" ] ]
hoon0528/testpage
[ "08b5d5b18678fbd8c7526849c7dec69c09ccd230" ]
[ "tutorials/nengo/newsome_model.py" ]
[ "import nengo\nimport numpy as np\nfrom nengo.dists import Uniform\n\n\n# following are required for computing \n# the conditioned avg response\ncond_colour = []\ncond_motion = []\n\n\n#Monkey A inputs\nclass Experiment(object):\n def __init__(self, seed=None, interval=0.75, delay=0.75, blk_length=36):\n self.rng = np.random.RandomState(seed=seed)\n self.interval = interval\n self.delay = delay\n self.blk_interval = blk_length * (interval + delay)\n self.col_index = None\n self.mot_index = None\n self.cont_index = None\n self.colour = 0\n self.motion = 0\n self.context = self.rng.choice([2,-2])\n \n def context_in(self, t): \n index = int(t / self.blk_interval) % 2\n if self.cont_index != index:\n self.context *= -1\n self.cont_index = index\n return self.context \n\n def colour_in(self, t):\n index = int(t / self.interval) % 6 \n if self.col_index != index:\n if self.colour != 0:\n self.colour = 0\n else:\n self.colour = self.rng.choice([0.06,0.18,0.50,-0.06,-0.18,-0.50])\n cond_colour.append(self.colour)\n self.col_index = index\n return self.colour \n \n def motion_in(self, t):\n index = int(t / self.interval) % 6 \n if self.mot_index != index:\n if self.motion != 0:\n self.motion = 0\n else:\n self.motion = self.rng.choice([0.05,0.15,0.50,-0.05,-0.15,-0.50])\n cond_motion.append(self.motion)\n self.mot_index = index\n return self.motion \n \n def correct_ans(self, t):\n if self.context == -2:\n if self.colour == 0:\n ans = 0\n elif self.colour>0:\n ans = 1\n else:\n ans = -1\n else:\n if self.motion == 0:\n ans = 0\n elif self.motion>0:\n ans = 1\n else:\n ans = -1 \n return ans\n\n\nseed=31 \nmodel = nengo.Network(seed=seed) #This seed could also be different\nwith model:\n exp = Experiment(seed=seed)\n \n stim_colour = nengo.Node(exp.colour_in)\n stim_motion = nengo.Node(exp.motion_in)\n stim_context = nengo.Node(exp.context_in)\n\n \n pfc = nengo.Ensemble(n_neurons=1000, dimensions=4, \n radius=2, max_rates=Uniform(20, 120))\n \n thresh = nengo.Ensemble(n_neurons=200, dimensions=1, radius=1, \n intercepts=Uniform(0.2, 1),\n max_rates=Uniform(20,120))\n \n tau = 0.2\n nengo.Connection(stim_colour, pfc[0], synapse=tau) \n nengo.Connection(stim_motion, pfc[1], synapse=tau) \n nengo.Connection(stim_context, pfc[2], synapse=tau)\n \n #multiplicative gating \n def response(x):\n colour, motion, context, choice = x\n choice = 1*((2-context)*colour + (2+context)*motion) # mem effect: +.75*choice\n return 0, 0, 0, choice\n \n nengo.Connection(pfc, pfc, synapse=0.1, function=response)\n nengo.Connection(pfc[3], thresh)\n \n corr_ans = nengo.Node(exp.correct_ans, size_out=1)\n" ]
[ [ "numpy.random.RandomState" ] ]
Bobobert/RL_notebooks
[ "408430acca96d223a95210ca0b33297d6188ce95" ]
[ "A2Cv02/a2c_atari.py" ]
[ "from A2C import Agent, Learner, envMaker, config, ray\nfrom A2C.nets import AC_AtariHalf\nfrom A2C.functions import seeder, trainSync, graphResults\nfrom A2C.functions import NCPUS, expDir, saveConfig, Saver\nfrom torch.utils.tensorboard import SummaryWriter\nfrom math import ceil\n\nEXP = \"a2c\"\nNAME = \"Seaquest-v0\"\n\nenvmake = envMaker(NAME)\nconfig[\"envName\"] = NAME\nconfig[\"nActions\"] = 6\nconfig[\"atari\"] = True\nconfig[\"nAgents\"] = NCPUS - 1\nconfig[\"hidden\"] = 256\nconfig[\"n-step\"] = 5\nconfig[\"learningRate\"] = 5e-4\nconfig[\"cPolicyLoss\"] = 1.0\nconfig[\"cValueLoss\"] = 0.2\nconfig[\"entropyLoss\"] = 0.01\nconfig[\"nTest\"] = ceil(28/(NCPUS - 1))\nconfig[\"episodes_train\"] = 10**5\nFREQ_TEST = 10**3\nconfig[\"freq_test\"] = FREQ_TEST\n\npath, tbpath = expDir(EXP,NAME)\nsaveConfig(config, path)\nseeder(8088)\nwriter = SummaryWriter(tbpath)\nsaver = Saver(path)\nnet = AC_AtariHalf\n\nif __name__ == \"__main__\":\n # INIT RAY\n Agent = ray.remote(Agent)\n Learner = ray.remote(Learner)\n\n ray.init(num_cpus=NCPUS - 1)\n agents = [Agent.remote(envmake, net, config, \n seedTrain = i, \n seedTest = (i + 1)*(NCPUS + 1)) \n for i in range(NCPUS - 1)]\n learner = Learner.remote(net, config)\n # Train ActorCritic\n average_return, var_return = trainSync(agents, learner, config, saver = saver, writer = writer)\n # Save results\n graphResults(average_return, var_return, FREQ_TEST, mod = EXP, save = path)\n saver.saveAll()\n # Close tent\n ray.shutdown()\n writer.close()\n" ]
[ [ "torch.utils.tensorboard.SummaryWriter" ] ]
yuqiao1120/eightPuzzle
[ "f8a353756810ed832f9e15513f9dbd5ad895cd47" ]
[ "PK/ai7.py" ]
[ "# -*- coding: utf-8 -*-\n# @Time : 2020/10/9 16:48\n# @Author : Breeze\n# @Email : [email protected]\n# 初始状态\nimport numpy as np\n\n\"\"\"\n 由于 0 是空格,因此我们在考虑状态的逆序对问题的时候,就不需要考虑 0 对逆序对数量的影响。\n 也就是说我们只需要考虑:把整个3*3矩阵去掉 0 之后写成一个序列,这个序列逆序对的数量,以及两个状态的逆序对奇偶性是否相同。\n 如果两个状态的奇偶性相同,则这两个状态的奇偶性相互可达;否则相互不可达。\n\n 其次,我们再考虑移动数字对逆序对奇偶性的影响。由于 0 并不参与逆序对的统计,因此将 0 左右移动,写成的序列并不变,并不影响逆序对的数量。\n 而将 0 上下移动的时候,相当于有一个数字被后移或前移了 2 位。如abcdefg八个数中,将c后移 2 位,得到序列abdecfg.\n 显然,逆序对可能发生改变的部分只有cde三个数字。\n 根据线性代数的知识,我们可以知道,两个相邻数字进行一次交换,逆序对的奇偶性改变;\n 而上述操作可以视为c分别于d e对调一次,逆序对的奇偶性改变了两次,和原来相比相当于没有改变。\n\n 因此,用归纳法我们可以证明:只要两个状态的序列逆序对奇偶性相同,他们就一定互相可达;否则一定互相不可达,因为交换 0 并不影响逆序对的奇偶性。\n\"\"\"\n\n# 目标状态 值-位置表\ngoal_dic = {\n 1: (0, 0), 2: (0, 1), 3: (0, 2),\n 4: (1, 0), 5: (1, 1), 6: (1, 2),\n 7: (2, 0), 8: (2, 1), 0: (2, 2)\n}\n# 启发值列表\nactiValue = []\n\n\n# 输出状态\ndef PrintState(state):\n for i in state: print(i)\n\n\n# 复制状态\ndef CopyState(state):\n s = []\n for i in state: s.append(i[:])\n return s\n\n\n# 获取空格的位置\ndef GetSpace(state):\n for y in range(len(state)):\n for x in range(len(state[y])):\n if state[y][x] == 0: return y, x\n\n\n# 获取空格上移后的状态,不改变原状态\ndef MoveUp(state):\n s = CopyState(state)\n y, x = GetSpace(s)\n s[y][x], s[y - 1][x] = s[y - 1][x], s[y][x]\n return s\n\n\n# 获取空格下移后的状态,不改变原状态\ndef MoveDown(state):\n s = CopyState(state)\n y, x = GetSpace(s)\n s[y][x], s[y + 1][x] = s[y + 1][x], s[y][x]\n return s\n\n\n# 获取空格左移后的状态,不改变原状态\ndef MoveLeft(state):\n s = CopyState(state)\n y, x = GetSpace(s)\n s[y][x], s[y][x - 1] = s[y][x - 1], s[y][x]\n return s\n\n\n# 获取空格右移后的状态,不改变原状态\ndef MoveRight(state):\n s = CopyState(state)\n y, x = GetSpace(s)\n s[y][x], s[y][x + 1] = s[y][x + 1], s[y][x]\n return s\n\n\n# 获取两个状态之间的启发距离\ndef GetDistance(src, dest):\n dic, d = goal_dic, 0\n for i in range(len(src)):\n for j in range(len(src[i])):\n pos = dic[src[i][j]]\n y, x = pos[0], pos[1]\n d += abs(y - i) + abs(x - j)\n return d\n\n\n# 获取指定状态下的操作\ndef GetActions(state):\n acts = []\n y, x = GetSpace(state)\n if x > 0: acts.append(MoveLeft)\n if y > 0: acts.append(MoveUp)\n if x < len(state[0]) - 1: acts.append(MoveRight)\n if y < len(state[0]) - 1: acts.append(MoveDown)\n return acts\n\n\n# 用于统一操作序列的函数\ndef Start(state):\n return\n\n\n# 边缘队列中的节点类\nclass Node:\n state = None # 状态\n value = -1 # 启发值\n step = 0 # 初始状态到当前状态的距离(步数)\n action = Start # 到达此节点所进行的操作\n parent = None, # 父节点\n\n # 用状态和步数构造节点对象\n def __init__(self, state, step, action, parent):\n self.state = state\n self.step = step\n self.action = action\n self.parent = parent\n # 计算估计距离\n self.value = GetDistance(state, goal_state) + step\n\n\n# 获取拥有最小启发值的元素索引\ndef GetMinIndex(queue):\n index = 0\n for i in range(len(queue)):\n node = queue[i]\n if node.value < queue[index].value:\n index = i\n return index\n\n\n# 将状态转换为整数\ndef toInt(state):\n value = 0\n for i in state:\n for j in i:\n value = value * 10 + j\n return value\n\n\n# A*算法寻找初始状态到目标状态的路径\ndef AStar(init, goal):\n # 边缘队列初始已有源状态节点\n queue = [Node(init, 0, Start, None)]\n visit = {} # 访问过的状态表\n count = 0 # 循环次数\n # 队列没有元素则查找失败\n while queue:\n # 获取拥有最小估计距离的节点索引\n index = GetMinIndex(queue)\n node = queue[index]\n visit[toInt(node.state)] = True\n count += 1\n if node.state == goal:\n return node, count\n del queue[index]\n # 扩展当前节点\n for act in GetActions(node.state):\n # 获取此操作下到达的状态节点并将其加入边缘队列中\n near = Node(act(node.state), node.step + 1, act, node)\n\n if toInt(near.state) not in visit:\n queue.append(near)\n\n return None, count\n\n\n# 将链表倒序,返回链头和链尾\ndef reverse(node):\n if node.parent is None:\n return node, node\n head, rear = reverse(node.parent)\n rear.parent, node.parent = node, None\n return head, node\n\n\ndef InversionNum(lst):\n # 改写归并排序,在归并排序中,每当R部分元素先于L部分元素插入原列表时,逆序对数要加L剩余元素数\n if len(lst) == 1:\n return lst, 0\n else:\n n = len(lst) // 2\n lst1, count1 = InversionNum(lst[0:n])\n lst2, count2 = InversionNum(lst[n:len(lst)])\n lst, count = Count(lst1, lst2, 0)\n return lst, count1 + count2 + count\n\n\ndef Count(lst1, lst2, count):\n i = 0\n j = 0\n res = []\n while i < len(lst1) and j < len(lst2):\n if lst1[i] <= lst2[j]:\n res.append(lst1[i])\n i += 1\n else:\n res.append(lst2[j])\n count += len(lst1) - i # 当右半部分的元素先于左半部分元素进入有序列表时,逆序对数量增加左半部分剩余的元素数\n j += 1\n res += lst1[i:]\n res += lst2[j:]\n return res, count\n\n\ndef ai(initState, goalState, swap, step):\n global goal_state\n global init_state\n init_state = initState\n goal_state = goalState\n print(init_state, goal_state)\n init_ = list(np.array(init_state).reshape(9).tolist())\n goal_ = list(np.array(goal_state).reshape(9).tolist())\n init_.remove(0)\n goal_.remove(0)\n _, init_IN = InversionNum(init_)\n _, goal_IN = InversionNum(goal_)\n if init_IN % 2 != goal_IN % 2:\n print(\"无解\")\n print(\"进入强制交换\")\n temp = list(np.array(init_state).reshape(9).tolist())\n t = temp[swap[0]]\n temp[swap[0]] = temp[swap[1]]\n temp[swap[1]] = t\n print(\"After being swapped:\", temp)\n ti = [i for i in temp]\n ti.remove(0)\n _, temp_IN = InversionNum(ti)\n print(\"(ai)temp_IN:\", temp_IN)\n if temp_IN % 2 != goal_IN % 2:\n print(\"强制交换后无解,进入手动交换\")\n init_state = list(np.array(temp).reshape(3, 3).tolist())\n res, swapped = func(init_state, goal_state)\n return res, swapped\n print(\"搜索中:\")\n init_state = list(np.array(temp).reshape(3, 3).tolist())\n node, count = AStar(init_state, goal_state)\n if node is None:\n print(\"无法从初始状态到达目标状态!\")\n else:\n print(\"搜索成功,循环次数:\", count)\n node, rear = reverse(node)\n count = 0\n steps = []\n first = 1\n while node:\n # 启发值包括从起点到此节点的距离\n\n if first:\n first = 0\n node = node.parent\n count += 1\n continue\n print(\"第\", count, \"步:\", node.action.__name__, \"启发值为:\", count, \"+\", node.value - count)\n PrintState(node.state)\n steps.append(node.action.__name__)\n node = node.parent\n count += 1\n return steps, swap\n else:\n node, count = AStar(init_state, goal_state)\n if node is None:\n print(\"无法从初始状态到达目标状态!\")\n else:\n print(\"搜索成功,循环次数:\", count)\n node, rear = reverse(node)\n count = 0\n steps = []\n first = 1\n while node:\n # 启发值包括从起点到此节点的距离\n if first:\n first = 0\n node = node.parent\n count += 1\n continue\n print(\"第\", count, \"步:\", node.action.__name__, \"启发值为:\", count, \"+\", node.value - count)\n PrintState(node.state)\n steps.append(node.action.__name__)\n count += 1\n if step == count and swap[0] != swap[1]: # count就是步数\n init_state = sswap(swap, node)\n res, swapped = func(init_state, goal_state)\n return steps + res, swapped\n node = node.parent\n\n return steps, swap\n\n\ndef sswap(swap, node):\n # 将node.State平展为一维后,由swap数组来交换顺序得到新的序列,从头执行ai()\n print(node.state)\n state = np.array(node.state).reshape(9)\n a = state[swap[0]]\n b = state[swap[1]]\n state[swap[0]] = b\n state[swap[1]] = a\n state = list(np.array(state).reshape(3, 3).tolist())\n print(\"After being swapped: \")\n print(state)\n return state\n\n\ndef _main():\n #\n step = 19\n swap = [3, 2]\n #\n global goal_state\n global init_state\n init_state = [\n [2, 3, 5],\n [8, 4, 7],\n [6, 0, 1]\n ]\n # 目标状态\n goal_state = [\n [1, 2, 3],\n [0, 4, 5],\n [6, 7, 8]\n ]\n init_ = list(np.array(init_state).reshape(9).tolist())\n goal_ = list(np.array(goal_state).reshape(9).tolist())\n # goal_ = goal_.remove(0)\n init_.remove(0)\n goal_.remove(0)\n print(init_, goal_)\n _, init_IN = InversionNum(init_)\n _, goal_IN = InversionNum(goal_)\n print(init_IN, goal_IN)\n if init_IN % 2 != goal_IN % 2:\n print(\"无解\")\n print(\"进入强制交换\")\n temp = list(np.array(init_state).reshape(9).tolist())\n t = temp[swap[0]]\n temp[swap[0]] = temp[swap[1]]\n temp[swap[1]] = t\n print(\"After being swapped:\", temp)\n ti = [i for i in temp]\n ti.remove(0)\n _, temp_IN = InversionNum(ti)\n print(\"temp_IN:\", temp_IN)\n if temp_IN % 2 != goal_IN % 2:\n print(\"强制交换后无解,进入手动交换\")\n init_state = list(np.array(temp).reshape(3, 3).tolist())\n res = func(init_state, goal_state)\n return res\n node, count = AStar(init_state, goal_state)\n if node is None:\n print(\"无法从初始状态到达目标状态!\")\n else:\n print(\"搜索成功,循环次数:\", count)\n node, rear = reverse(node)\n count = 0\n steps = []\n first = 1\n while node:\n # 启发值包括从起点到此节点的距离\n\n if first:\n first = 0\n node = node.parent\n count += 1\n continue\n print(\"第\", count, \"步:\", node.action.__name__, \"启发值为:\", count, \"+\", node.value - count)\n PrintState(node.state)\n steps.append(node.action.__name__)\n count += 1\n if step == count: # count就是步数\n init_state = sswap(swap, node)\n res = func(init_state, goal_state)\n return steps + res\n node = node.parent\n\n\ndef func(init_state, goal_state):\n init_ = list(np.array(init_state).reshape(9).tolist())\n goal_ = list(np.array(goal_state).reshape(9).tolist())\n init_.remove(0)\n goal_.remove(0)\n print(init_, goal_)\n _, init_IN = InversionNum(init_)\n _, goal_IN = InversionNum(goal_)\n print(init_IN, goal_IN)\n if init_IN % 2 != goal_IN % 2:\n print(\"正在交换:\")\n init_state, swapped = finestSwap(init_state)\n print(\"After being swapped BY HAND\")\n print(init_state)\n else:\n swapped = [-1, -1]\n node, count = AStar(init_state, goal_state)\n if node is None:\n print(\"无法从初始状态到达目标状态!\")\n else:\n print(\"搜索成功,循环次数:\", count)\n node, rear = reverse(node)\n count = 0\n steps = []\n first = 1\n while node:\n # 启发值包括从起点到此节点的距离\n\n if first:\n first = 0\n node = node.parent\n count += 1\n continue\n print(\"第\", count, \"步:\", node.action.__name__, \"启发值为:\", count, \"+\", node.value - count)\n PrintState(node.state)\n steps.append(node.action.__name__)\n node = node.parent\n count += 1\n return steps, swapped\n\n\ndef finestSwap(state):\n \"\"\"\n\n :param state:3*3 无解状态数组\n :return: 3*3 根据启发值选取最优\n \"\"\"\n init_ = list(np.array(state).reshape(9).tolist())\n toswap = []\n cur = 0\n while cur < 8:\n if init_[cur] != 0 and init_[cur + 1] != 0:\n toswap.append([cur, cur + 1])\n cur += 1\n # print(toswap)\n swappedState = []\n for item in toswap:\n temp = [i for i in init_]\n t = temp[item[0]]\n temp[item[0]] = temp[item[1]]\n temp[item[1]] = t\n swappedState.append(list(np.array(temp).reshape(3, 3).tolist()))\n # print(swappedState)\n distances = []\n for swapped in swappedState:\n distances.append(GetDistance(swapped, goal_state))\n res = swappedState[distances.index(min(distances))]\n return res, toswap[distances.index(min(distances))]\n\n\nif __name__ == '__main__':\n # mmap = dict(zip(['MoveUp', 'MoveLeft', 'MoveDown', 'MoveRight'], ['w', 'a', 's', 'd']))\n # res = [mmap[i] for i in _main()]\n # print(res)\n print(InversionNum([3, 7, 5, 6, 4, 8, 2, 1]))\n" ]
[ [ "numpy.array" ] ]
PeterJaq/optical_film_toolbox
[ "0e2d2bfa5f1f93d405a2f25ee50e51771be777a5" ]
[ "old_research/model/policy_gridient_softmax.py" ]
[ "import numpy as np\r\nimport tensorflow as tf\r\n\r\n# reproducible\r\nnp.random.seed(1)\r\ntf.set_random_seed(1)\r\n\r\n\r\nclass PolicyGradient:\r\n def __init__(\r\n self,\r\n n_actions,\r\n n_features,\r\n learning_rate=0.01,\r\n reward_decay=0.95,\r\n output_graph=False,\r\n ):\r\n self.n_actions = n_actions\r\n self.n_features = n_features\r\n self.lr = learning_rate\r\n self.gamma = reward_decay\r\n\r\n self.ep_obs, self.ep_as, self.ep_rs = [], [], []\r\n\r\n self._build_net()\r\n\r\n self.sess = tf.Session()\r\n\r\n if output_graph:\r\n # $ tensorboard --logdir=logs\r\n # http://0.0.0.0:6006/\r\n # tf.train.SummaryWriter soon be deprecated, use following\r\n tf.summary.FileWriter(\"logs/\", self.sess.graph)\r\n\r\n self.sess.run(tf.global_variables_initializer())\r\n\r\n def _build_net(self):\r\n with tf.name_scope('inputs'):\r\n self.tf_obs = tf.placeholder(tf.float32, [None, self.n_features], name=\"observations\")\r\n self.tf_acts = tf.placeholder(tf.int32, [None, ], name=\"actions_num\")\r\n self.tf_vt = tf.placeholder(tf.float32, [None, ], name=\"actions_value\")\r\n # fc1\r\n layer = tf.layers.dense(\r\n inputs=self.tf_obs,\r\n units=8,\r\n activation=tf.nn.tanh, # tanh activation\r\n kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.3),\r\n bias_initializer=tf.constant_initializer(0.1),\r\n name='fc1'\r\n )\r\n # fc2\r\n all_act = tf.layers.dense(\r\n inputs=layer,\r\n units=self.n_actions,\r\n activation=None,\r\n kernel_initializer=tf.random_normal_initializer(mean=0, stddev=0.3),\r\n bias_initializer=tf.constant_initializer(0.1),\r\n name='fc2'\r\n )\r\n\r\n self.all_act_prob = tf.nn.softmax(all_act, name='act_prob') # use softmax to convert to probability\r\n\r\n with tf.name_scope('loss'):\r\n # to maximize total reward (log_p * R) is to minimize -(log_p * R), and the tf only have minimize(loss)\r\n neg_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=all_act, labels=self.tf_acts) # this is negative log of chosen action\r\n # or in this way:\r\n # neg_log_prob = tf.reduce_sum(-tf.log(self.all_act_prob)*tf.one_hot(self.tf_acts, self.n_actions), axis=1)\r\n loss = tf.reduce_mean(neg_log_prob * self.tf_vt) # reward guided loss\r\n\r\n with tf.name_scope('train'):\r\n self.train_op = tf.train.AdamOptimizer(self.lr).minimize(loss)\r\n\r\n def choose_action(self, observation):\r\n prob_weights = self.sess.run(self.all_act_prob, feed_dict={self.tf_obs: observation[np.newaxis, :]})\r\n action = np.random.choice(range(prob_weights.shape[1]), p=prob_weights.ravel()) # select action w.r.t the actions prob\r\n return action\r\n\r\n def store_transition(self, s, a, r):\r\n self.ep_obs.append(s)\r\n self.ep_as.append(a)\r\n self.ep_rs.append(r)\r\n\r\n def learn(self):\r\n # discount and normalize episode reward\r\n discounted_ep_rs_norm = self._discount_and_norm_rewards()\r\n\r\n # train on episode\r\n self.sess.run(self.train_op, feed_dict={\r\n self.tf_obs: np.vstack(self.ep_obs), # shape=[None, n_obs]\r\n self.tf_acts: np.array(self.ep_as), # shape=[None, ]\r\n self.tf_vt: discounted_ep_rs_norm, # shape=[None, ]\r\n })\r\n\r\n self.ep_obs, self.ep_as, self.ep_rs = [], [], [] # empty episode data\r\n return discounted_ep_rs_norm\r\n\r\n def _discount_and_norm_rewards(self):\r\n # discount episode rewards\r\n discounted_ep_rs = np.zeros_like(self.ep_rs)\r\n running_add = 0\r\n for t in reversed(range(0, len(self.ep_rs))):\r\n running_add = running_add * self.gamma + self.ep_rs[t]\r\n discounted_ep_rs[t] = running_add\r\n\r\n # normalize episode rewards\r\n discounted_ep_rs -= np.mean(discounted_ep_rs)\r\n discounted_ep_rs /= np.std(discounted_ep_rs)\r\n return discounted_ep_rs" ]
[ [ "numpy.array", "tensorflow.nn.softmax", "tensorflow.summary.FileWriter", "numpy.random.seed", "tensorflow.reduce_mean", "tensorflow.placeholder", "tensorflow.constant_initializer", "tensorflow.global_variables_initializer", "numpy.std", "numpy.zeros_like", "numpy.mean", "tensorflow.Session", "tensorflow.name_scope", "tensorflow.set_random_seed", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.train.AdamOptimizer", "tensorflow.random_normal_initializer", "numpy.vstack" ] ]
aniruddhak1998/pytorch_RVAE
[ "b60a1d7d4453f76331e4b8460406558c92ea6b18" ]
[ "train.py" ]
[ "import argparse\nimport os\n\nimport numpy as np\nimport torch as t\nfrom torch.optim import Adam\n\nfrom utils.batch_loader import BatchLoader\nfrom utils.parameters import Parameters\nfrom model.rvae import RVAE\n\nif __name__ == \"__main__\":\n\n if not os.path.exists('data/word_embeddings.npy'):\n raise FileNotFoundError(\"word embeddings file was't found\")\n\n parser = argparse.ArgumentParser(description='RVAE')\n parser.add_argument('--num-iterations', type=int, default=120000, metavar='NI',\n help='num iterations (default: 120000)')\n parser.add_argument('--batch-size', type=int, default=32, metavar='BS',\n help='batch size (default: 32)')\n parser.add_argument('--use-cuda', type=bool, default=True, metavar='CUDA',\n help='use cuda (default: True)')\n parser.add_argument('--learning-rate', type=float, default=0.00005, metavar='LR',\n help='learning rate (default: 0.00005)')\n parser.add_argument('--dropout', type=float, default=0.3, metavar='DR',\n help='dropout (default: 0.3)')\n parser.add_argument('--use-trained', type=bool, default=False, metavar='UT',\n help='load pretrained model (default: False)')\n parser.add_argument('--ce-result', default='', metavar='CE',\n help='ce result path (default: '')')\n parser.add_argument('--kld-result', default='', metavar='KLD',\n help='ce result path (default: '')')\n\n args = parser.parse_args()\n\n batch_loader = BatchLoader('')\n parameters = Parameters(batch_loader.max_word_len,\n batch_loader.max_seq_len,\n batch_loader.words_vocab_size,\n batch_loader.chars_vocab_size)\n\n rvae = RVAE(parameters)\n if args.use_trained:\n rvae.load_state_dict(t.load('trained_RVAE'))\n if args.use_cuda:\n rvae = rvae.cuda()\n\n optimizer = Adam(rvae.learnable_parameters(), args.learning_rate)\n\n train_step = rvae.trainer(optimizer, batch_loader)\n validate = rvae.validater(batch_loader)\n\n ce_result = []\n kld_result = []\n\n for iteration in range(args.num_iterations):\n\n cross_entropy, kld, coef = train_step(iteration, args.batch_size, args.use_cuda, args.dropout)\n\n if iteration % 5 == 0:\n print('\\n')\n print('------------TRAIN-------------')\n print('----------ITERATION-----------')\n print(iteration)\n print('--------CROSS-ENTROPY---------')\n print(cross_entropy.data.cpu().numpy())\n print('-------------KLD--------------')\n print(kld.data.cpu().numpy())\n print('-----------KLD-coef-----------')\n print(coef)\n print('------------------------------')\n\n if iteration % 10 == 0:\n cross_entropy, kld = validate(args.batch_size, args.use_cuda)\n\n cross_entropy = cross_entropy.data.cpu().numpy()\n kld = kld.data.cpu().numpy()\n\n print('\\n')\n print('------------VALID-------------')\n print('--------CROSS-ENTROPY---------')\n print(cross_entropy)\n print('-------------KLD--------------')\n print(kld)\n print('------------------------------')\n\n ce_result += [cross_entropy]\n kld_result += [kld]\n\n if iteration % 20 == 0:\n seed = np.random.normal(size=[1, parameters.latent_variable_size])\n\n sample = rvae.sample(batch_loader, 50, seed, args.use_cuda)\n\n print('\\n')\n print('------------SAMPLE------------')\n print('------------------------------')\n print(sample)\n print('------------------------------')\n\n t.save(rvae.state_dict(), 'trained_RVAE')\n\n np.save('ce_result_{}.npy'.format(args.ce_result), np.array(ce_result))\n np.save('kld_result_npy_{}'.format(args.kld_result), np.array(kld_result))\n" ]
[ [ "numpy.random.normal", "numpy.array", "torch.load" ] ]
biosustain/AnalyticsTools
[ "11eca81f0a504766cb68d4f77b688b41bd258650" ]
[ "tests/test_data/MFA_sampling/generate_visualization_test_data.py" ]
[ "# generate test_data\n# Last date : 27.05.2021\n# By : Matthias Mattanovich ([email protected])\n# This script is intended to generate sample data and save them into the\n# test_data file. The saved objects will then be used to test the\n# MFA_visualization functions using unit testing.\nimport pickle\nimport pandas as pd\nimport pathlib\nimport cobra\nfrom BFAIR.mfa.INCA import INCA_reimport\nfrom BFAIR.mfa.sampling import (\n replace_biomass_rxn_name,\n add_constraints,\n bound_relaxation,\n)\nfrom BFAIR.mfa.visualization import (\n reshape_fluxes_escher,\n sampled_fluxes_minrange,\n show_reactions,\n get_subsytem_reactions,\n show_subsystems,\n)\n\ncurrent_dir = str(pathlib.Path(__file__).parent.absolute())\n\npd.set_option(\"mode.chained_assignment\", None)\n# Use pickle to save python variables\nfilehandler = open(\"visualization_test_data.obj\", \"wb\")\n\n# prepare input data\nmodel = cobra.io.load_json_model(\n current_dir + \"/../MFA_modelInputsData/iJO1366.json\")\nfilename = current_dir + \"/../MFA_modelInputsData/TestFile.mat\"\nsimulation_info = pd.read_csv(\n current_dir + \"/../MFA_modelInputsData/experimentalMS_data_I.csv\")\nsimulation_id = \"WTEColi_113C80_U13C20_01\"\nreimport_data = INCA_reimport()\n(\n fittedData,\n fittedFluxes,\n fittedFragments,\n fittedMeasuredFluxes,\n fittedMeasuredFragments,\n fittedMeasuredFluxResiduals,\n fittedMeasuredFragmentResiduals,\n simulationParameters,\n) = reimport_data.reimport(filename, simulation_info, simulation_id)\nfittedFluxes = replace_biomass_rxn_name(\n fittedFluxes,\n biomass_string='Biomass',\n biomass_rxn_name='BIOMASS_Ec_iJO1366_core_53p95M'\n)\nmodel = add_constraints(model, fittedFluxes)\nbound_relaxation(\n model,\n fittedFluxes,\n destructive=True,\n fluxes_to_ignore=['BIOMASS_Ec_iJO1366_core_53p95M']\n)\nsolution = model.optimize()\n# Sample the relaxed model\nrelaxed_sampled_fluxes = cobra.sampling.sample(model, n=100)\n\n# Generate comparison data\nfluxes_relaxed = reshape_fluxes_escher(solution)\nrelaxed_fluxes_sampling = reshape_fluxes_escher(relaxed_sampled_fluxes)\nreduced_relaxed_sampled_fluxes = sampled_fluxes_minrange(\n relaxed_sampled_fluxes, min_val=-1, max_val=1)\nreactions, subsystems = get_subsytem_reactions(model, 14)\nreactions_indeces = show_reactions(reactions)\nsubsystems_indices = show_subsystems(model)\n\npickle.dump(\n [\n solution,\n relaxed_sampled_fluxes,\n fluxes_relaxed,\n relaxed_fluxes_sampling,\n reduced_relaxed_sampled_fluxes,\n reactions,\n subsystems,\n reactions_indeces,\n subsystems_indices,\n ],\n filehandler,\n)\n\nfilehandler.close()\n" ]
[ [ "pandas.set_option", "pandas.read_csv" ] ]
edding/socal-2019-nlp-complete
[ "d3b5c2d57da06b6682dd6aeec3d4070bf9c1f257" ]
[ "tf_models/utils.py" ]
[ "from typing import Any, List, BinaryIO\nimport os\nimport pickle\nimport logging\nfrom typing import Tuple\n\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.layers import Dense, Input, Dropout\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom tensorflow.keras.callbacks import History\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n\nlogging.getLogger().setLevel(logging.INFO)\n\n\ndef build_mlp_model(\n input_dim: int, layers: List[int], output_dim: int, dropout_rate: float = 0\n) -> Model:\n \"\"\"Return a MLP model with given parameter settings\"\"\"\n # Input layer\n X = Input(shape=(input_dim,))\n\n # Hidden layer(s)\n H = X\n for layer in layers:\n H = Dense(layer, activation=\"relu\")(H)\n if dropout_rate > 0:\n H = Dropout(rate=dropout_rate)(H)\n\n # Output layer\n activation_func = \"softmax\" if output_dim > 1 else \"sigmoid\"\n\n Y = Dense(output_dim, activation=activation_func)(H)\n return Model(inputs=X, outputs=Y)\n\n\ndef train(\n training_corpus: str, pos_label: str = \"\", root: str = \"\"\n) -> Tuple[Model, History, TfidfVectorizer]:\n \"\"\"\n Train a MLP model on given `training_corpus`. For simple demo purpose, I didn't expose parameters for\n the model for tuning here. Feel free to play with these parameters and build a larger corpus for better model.\n \"\"\"\n # Load data from corpus file\n df = pd.read_csv(os.path.join(root, training_corpus))\n train_text, train_label = df[\"text\"], df[\"label\"]\n\n tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2))\n train_x = tfidf_vectorizer.fit_transform(train_text)\n train_y = train_label.apply(lambda x: 1 if x == pos_label else 0)\n\n print(train_y)\n\n input_dim = len(tfidf_vectorizer.vocabulary_)\n\n # Build a mlp model for binary classification\n mlp_model = build_mlp_model(\n input_dim=input_dim, layers=[10], output_dim=1, dropout_rate=0.2\n )\n\n print(mlp_model.summary())\n\n mlp_model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"acc\"])\n\n CPK_PATH = os.path.join(root, \"model_cpk.hdf5\") # path to store checkpoint\n model_cpk_hook = ModelCheckpoint(\n CPK_PATH, monitor=\"acc\", save_best_only=True # Only keep the best model\n )\n\n history = mlp_model.fit(train_x, train_y, epochs=100, callbacks=[model_cpk_hook])\n\n mlp_model.load_weights(CPK_PATH)\n os.remove(CPK_PATH)\n\n return mlp_model, history, tfidf_vectorizer\n\n\ndef plot_history(his: History, metrics: List[str]):\n \"\"\"\n Given a history object returned from `fit` and the name of metrics,\n plot the curve of metrics against number of epochs.\n \"\"\"\n for metric in metrics:\n plt.plot(his.history[metric], label=metric)\n plt.legend()\n\n\ndef save_model(\n model: Model, vectorizer, name: str, root: str = \"\"\n) -> Tuple[str, str, str]:\n \"\"\"Save the trained model (structure, weights) and vectorizer to files.\"\"\"\n json_file, h5_file, vec_file = (\n os.path.join(root, \"{}.{}\".format(name, ext)) for ext in (\"json\", \"h5\", \"pkl\")\n )\n\n with open(json_file, \"w\") as fp:\n fp.write(model.to_json())\n model.save_weights(h5_file)\n\n with open(vec_file, \"wb\") as bfp: # type: BinaryIO\n pickle.dump(vectorizer, bfp)\n\n logging.info(\"Model is being written to {}\".format(root + \"/\"))\n\n return json_file, h5_file, vec_file\n\n\ndef load_model(name: str, root: str = \"\") -> Tuple[Model, Any]:\n \"\"\"Load the trained model (structure, weights) and vectorizer from files.\"\"\"\n json_file, h5_file, vec_file = (\n os.path.join(root, \"{}.{}\".format(name, ext)) for ext in (\"json\", \"h5\", \"pkl\")\n )\n\n with open(json_file) as fp:\n model = model_from_json(fp.read()) # type: Model\n model.load_weights(h5_file)\n\n with open(vec_file, \"rb\") as bfp: # type: BinaryIO\n vectorizer = pickle.load(bfp)\n\n logging.info(\"Model loaded from {}\".format(root + \"/\"))\n\n return model, vectorizer\n" ]
[ [ "matplotlib.pyplot.legend", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.keras.models.Model", "tensorflow.keras.layers.Dense", "matplotlib.pyplot.plot", "tensorflow.keras.layers.Dropout", "sklearn.feature_extraction.text.TfidfVectorizer", "tensorflow.keras.layers.Input" ] ]
Querela/trump-biden-linguistic-style-analysis
[ "71d18fd42fecce652445db29b0344514d53b2529" ]
[ "process_tweets_nlp_counters.py" ]
[ "from collections import Counter\nfrom warnings import simplefilter\n\nimport pandas as pd\nfrom tqdm import tqdm\n\nsimplefilter(action=\"ignore\", category=FutureWarning)\ntqdm.pandas()\n\nFN_TWEETS_IN = \"data/Tweets_R_TrumpBiden_out.xlsx\"\nFN_TWEETS_OUT = \"data/Tweets_R_TrumpBiden_counters.xlsx\"\n\n\ndef count_neighbors(dfp):\n npairs = [\n tuple(w.split(\"+\"))\n for row in dfp[\"words_neighbors\"]\n for w in str(row).strip().split(\" \")\n if row\n ]\n cnt = Counter(npairs)\n\n dfpc = pd.DataFrame(\n [\n (n, left, right)\n for (left, right), n in sorted(\n cnt.items(), key=lambda x: x[1], reverse=True\n )\n ],\n columns=[\"amount\", \"left\", \"right\"],\n )\n return dfpc\n\n\ndef count_words_in_column(dfp, colname):\n if colname not in dfp.columns:\n return None\n\n words = [w for row in dfp[colname] for w in str(row).strip().split(\" \") if row]\n cnt = Counter(words)\n if \"nan\" in cnt:\n del cnt[\"nan\"]\n\n dfpc = pd.DataFrame(\n [\n (n, word)\n for word, n in sorted(cnt.items(), key=lambda x: x[1], reverse=True)\n ],\n columns=[\"amount\", \"word\"],\n )\n return dfpc\n\n\ndef run():\n # load CSV data\n df: pd.DataFrame = pd.read_excel(FN_TWEETS_IN)\n writer = pd.ExcelWriter(FN_TWEETS_OUT, engine=\"xlsxwriter\")\n\n for person in (\"Trump\", \"Biden\"):\n dfp = df[df[\"Who\"] == person]\n\n # neighbors\n dfpc = count_neighbors(dfp)\n dfpc.to_excel(writer, index=False, sheet_name=f\"{person} Neighbors (counted)\")\n\n for pos in (\n \"verb\",\n \"adjective\",\n \"proper_noun\",\n \"noun\",\n \"pronoun\",\n \"adverb\",\n \"stop\",\n ):\n colname = f\"text_{pos}\"\n dfppc = count_words_in_column(dfp, colname)\n if dfppc is not None:\n dfppc.to_excel(writer, index=False, sheet_name=f\"{person} Word ({pos})\")\n\n writer.save()\n\n\nif __name__ == \"__main__\":\n run()" ]
[ [ "pandas.read_excel", "pandas.ExcelWriter" ] ]
Knowledge-Precipitation-Tribe/Deep-Learning
[ "7fdb9c3553af44c890c85702330244adbbcb418d" ]
[ "code/nn/model/DataReader.py" ]
[ "# -*- coding: utf-8 -*-#\n'''\n# Name: DataLoader\n# Description: \n# Author: super\n# Date: 2020/11/25\n'''\nimport numpy as np\nfrom pathlib import Path\n\nfrom model.Initialize import *\n\nclass DataReader(object):\n def __init__(self, train_file, test_file):\n self.train_file_name = train_file\n self.test_file_name = test_file\n self.num_train = 0 # num of training examples\n self.num_test = 0 # num of test examples\n self.num_validation = 0 # num of validation examples\n self.num_feature = 0 # num of features\n self.num_category = 0 # num of categories\n self.XTrain = None # training feature set\n self.YTrain = None # training label set\n self.XTest = None # test feature set\n self.YTest = None # test label set\n self.XTrainRaw = None # training feature set before normalization\n self.YTrainRaw = None # training label set before normalization\n self.XTestRaw = None # test feature set before normalization\n self.YTestRaw = None # test label set before normalization\n self.XDev = None # validation feature set\n self.YDev = None # validation lable set\n\n # read data from file\n def ReadData(self):\n train_file = Path(self.train_file_name)\n if train_file.exists():\n data = np.load(self.train_file_name)\n self.XTrainRaw = data[\"data\"]\n self.YTrainRaw = data[\"label\"]\n assert(self.XTrainRaw.shape[0] == self.YTrainRaw.shape[0])\n self.num_train = self.XTrainRaw.shape[0]\n self.num_feature = self.XTrainRaw.shape[1]\n self.num_category = len(np.unique(self.YTrainRaw))\n # this is for if no normalize requirment\n self.XTrain = self.XTrainRaw\n self.YTrain = self.YTrainRaw\n else:\n raise Exception(\"Cannot find train file!!!\")\n #end if\n\n test_file = Path(self.test_file_name)\n if test_file.exists():\n data = np.load(self.test_file_name)\n self.XTestRaw = data[\"data\"]\n self.YTestRaw = data[\"label\"]\n assert(self.XTestRaw.shape[0] == self.YTestRaw.shape[0])\n self.num_test = self.XTestRaw.shape[0]\n # this is for if no normalize requirment\n self.XTest = self.XTestRaw\n self.YTest = self.YTestRaw\n # in case there has no validation set created\n self.XDev = self.XTest\n self.YDev = self.YTest\n else:\n raise Exception(\"Cannot find test file!!!\")\n #end if\n\n # merge train/test data first, normalize, then split again\n def NormalizeX(self):\n '''\n 要将训练集和测试集合并到一起,共同进行归一化操作,防止训练集和测试集得到的归一化值尺度不一样\n :return:\n '''\n x_merge = np.vstack((self.XTrainRaw, self.XTestRaw))\n x_merge_norm = self.__NormalizeX(x_merge)\n train_count = self.XTrainRaw.shape[0]\n self.XTrain = x_merge_norm[0:train_count,:]\n self.XTest = x_merge_norm[train_count:,:]\n\n def __NormalizeX(self, raw_data):\n temp_X = np.zeros_like(raw_data)\n self.X_norm = np.zeros((2, self.num_feature))\n # 按行归一化,即所有样本的同一特征值分别做归一化\n for i in range(self.num_feature):\n # get one feature from all examples\n x = raw_data[:, i]\n max_value = np.max(x)\n min_value = np.min(x)\n # min value\n self.X_norm[0,i] = min_value\n # range value\n self.X_norm[1,i] = max_value - min_value\n x_new = (x - self.X_norm[0,i]) / self.X_norm[1,i]\n temp_X[:, i] = x_new\n # end for\n return temp_X\n\n def NormalizeY(self, nettype, base=0):\n '''\n 要判断网络类型,回归的话要做归一化处理。二分类要做0,1编码,多分类要做one-hot编码\n :param nettype:\n :param base:\n :return:\n '''\n if nettype == NetType.Fitting:\n y_merge = np.vstack((self.YTrainRaw, self.YTestRaw))\n y_merge_norm = self.__NormalizeY(y_merge)\n train_count = self.YTrainRaw.shape[0]\n self.YTrain = y_merge_norm[0:train_count,:]\n self.YTest = y_merge_norm[train_count:,:]\n elif nettype == NetType.BinaryClassifier:\n self.YTrain = self.__ToZeroOne(self.YTrainRaw, base)\n self.YTest = self.__ToZeroOne(self.YTestRaw, base)\n elif nettype == NetType.MultipleClassifier:\n self.YTrain = self.__ToOneHot(self.YTrainRaw, base)\n self.YTest = self.__ToOneHot(self.YTestRaw, base)\n\n def __NormalizeY(self, raw_data):\n assert(raw_data.shape[1] == 1)\n self.Y_norm = np.zeros((2,1))\n max_value = np.max(raw_data)\n min_value = np.min(raw_data)\n # min value\n self.Y_norm[0, 0] = min_value\n # range value\n self.Y_norm[1, 0] = max_value - min_value\n y_new = (raw_data - min_value) / self.Y_norm[1, 0]\n return y_new\n\n def DeNormalizeY(self, predict_data):\n '''\n 逆归一化\n :param predict_data:\n :return:\n '''\n real_value = predict_data * self.Y_norm[1,0] + self.Y_norm[0,0]\n return real_value\n\n def __ToOneHot(self, Y, base=0):\n count = Y.shape[0]\n temp_Y = np.zeros((count, self.num_category))\n for i in range(count):\n n = (int)(Y[i,0])\n temp_Y[i,n-base] = 1\n return temp_Y\n\n # for binary classifier\n # if use tanh function, need to set negative_value = -1\n def __ToZeroOne(Y, positive_label=1, negative_label=0, positiva_value=1, negative_value=0):\n temp_Y = np.zeros_like(Y)\n for i in range():\n if Y[i,0] == negative_label: # 负类的标签设为0\n temp_Y[i,0] = negative_value\n elif Y[i,0] == positive_label: # 正类的标签设为1\n temp_Y[i,0] = positiva_value\n # end if\n # end for\n return temp_Y\n\n # normalize data by specified range and min_value\n def NormalizePredicateData(self, X_predicate):\n X_new = np.zeros(X_predicate.shape)\n n_feature = X_predicate.shape[0]\n for i in range(n_feature):\n x = X_predicate[i,:]\n X_new[i,:] = (x-self.X_norm[0,i])/self.X_norm[1,i]\n return X_new\n\n # need explicitly call this function to generate validation set\n def GenerateValidationSet(self, k = 10):\n '''\n 获取验证集函数\n :param k:\n :return:\n '''\n self.num_validation = (int)(self.num_train / k)\n self.num_train = self.num_train - self.num_validation\n # validation set\n self.XDev = self.XTrain[0:self.num_validation]\n self.YDev = self.YTrain[0:self.num_validation]\n # train set\n self.XTrain = self.XTrain[self.num_validation:]\n self.YTrain = self.YTrain[self.num_validation:]\n\n def GetValidationSet(self):\n return self.XDev, self.YDev\n\n def GetTestSet(self):\n return self.XTest, self.YTest\n\n # 获得批样本数据\n def GetBatchTrainSamples(self, batch_size, iteration):\n '''\n 根据batch_size和iteration的方式获取类似minibatch的数据。\n :param batch_size:\n :param iteration:\n :return:\n '''\n start = iteration * batch_size\n end = start + batch_size\n batch_X = self.XTrain[start:end,:]\n batch_Y = self.YTrain[start:end,:]\n return batch_X, batch_Y\n\n # permutation only affect along the first axis, so we need transpose the array first\n # see the comment of this class to understand the data format\n #\n # >>> arr = np.arange(9).reshape((3, 3))\n # >>> np.random.permutation(arr)\n # array([[6, 7, 8],\n # [0, 1, 2],\n # [3, 4, 5]])\n # only affect the first axis\n # see the comment of this class to understand the data format\n # 打乱数据内容\n def Shuffle(self):\n seed = np.random.randint(0,100)\n np.random.seed(seed)\n XP = np.random.permutation(self.XTrain)\n np.random.seed(seed)\n YP = np.random.permutation(self.YTrain)\n self.XTrain = XP\n self.YTrain = YP" ]
[ [ "numpy.random.seed", "numpy.min", "numpy.unique", "numpy.max", "numpy.random.permutation", "numpy.zeros_like", "numpy.load", "numpy.zeros", "numpy.vstack", "numpy.random.randint" ] ]
Dagu9/Reinforcement-learning-SGD
[ "a689fa1177cd34f32dd4d30a5a6140fb721855bf" ]
[ "usersimulator/ConfusionModel.py" ]
[ "###############################################################################\n# PyDial: Multi-domain Statistical Spoken Dialogue System Software\n###############################################################################\n#\n# Copyright 2015 - 2019\n# Cambridge University Engineering Department Dialogue Systems Group\n#\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\n'''\nConfusionModel.py - handcrafted SemI error creator \n===================================================\n\nCopyright CUED Dialogue Systems Group 2015 - 2017\n\n.. seealso:: CUED Imports/Dependencies: \n\n import :mod:`utils.DiaAct` |.|\n import :mod:`ontology.Ontology` |.|\n import :mod:`utils.Settings` |.|\n import :mod:`utils.ContextLogger`\n\n************************\n\n''' \n\n__author__ = \"cued_dialogue_systems_group\"\nimport copy\n\nfrom utils import Settings\nfrom utils import DiaAct\nfrom ontology import Ontology\nfrom utils import ContextLogger\nimport numpy as np\nlogger = ContextLogger.getLogger('')\n\n\nclass EMConfusionModel(object):\n '''Base class for EMRandomConfusionModel. \n\n .. Note:: \n Used through derived class only. \n '''\n def create_wrong_hyp(self, a_u):\n '''Create a wrong hypothesis for a_u\n\n :param a_u: of :class:`DiaAct`\n :type a_u: instance\n :returns: (instance) of :class:`DiaAct` - modified input act\n '''\n confact_is_same = True\n num_attempts = 0\n max_num_attempts = 25\n conf_act = None\n while confact_is_same and num_attempts < max_num_attempts:\n conf_act = self.confuse_hyp(a_u)\n confact_is_same = (conf_act == a_u)\n if conf_act.act == 'bye':\n confact_is_same = True # hack to avoid the system finishing the dialogue after a bye confusion\n num_attempts += 1\n\n if num_attempts == max_num_attempts:\n logger.warning(\"Confused act same after %d attempts: return null() instead.\" % max_num_attempts)\n #return DiaAct.DiaAct('null()')\n return a_u\n\n return conf_act\n\n\nclass EMRandomConfusionModel(EMConfusionModel):\n '''Derived class from :class:`EMConfusionModel`.\n\n :param None:\n '''\n\n def __init__(self, domainString):\n self.domainString = domainString\n\n self.CONFUSE_TYPE = 0.2\n self.CONFUSE_SLOT = 0.3\n self.CONFUSE_VALUE = 0.5\n self.newUserActs = ['hello',\n 'thankyou',\n 'ack',\n 'bye',\n 'inform',\n 'request',\n 'reqalts',\n 'reqmore',\n 'confirm',\n 'affirm',\n 'negate',\n 'deny',\n 'repeat',\n 'null']\n self.nNewUserActs = len(self.newUserActs)\n\n def confuse_hyp(self, a_u):\n '''Randomly confuse the act type, slot or value.\n\n :param a_u: of :class:`DiaAct`\n :type a_u: instance\n :returns: (instance) of :class:`DiaAct` - modified input act\n '''\n wHyp = copy.deepcopy(a_u)\n\n # Identify if this diaact type takes 0, 1, or 2 arguments\n nSlotVal = wHyp.getDiaItemFormat()\n\n # Make a choice to confuse the type, slot or value\n choice = Settings.random.choice([0, 1, 2], p=[self.CONFUSE_TYPE, self.CONFUSE_SLOT, self.CONFUSE_VALUE])\n choice = min(choice, nSlotVal)\n\n if choice == 0:\n wHyp = self._confuse_type(wHyp)\n elif choice == 1:\n wHyp = self._confuse_slot(wHyp)\n elif choice == 2:\n wHyp = self._confuse_value(wHyp)\n else:\n logger.error('Invalid choice ' + str(choice))\n\n return wHyp\n\n def _confuse_dia_act_type(self, oldtype):\n '''\n Randomly select a dialogue act type different from oldtype.\n '''\n acttypeset = copy.copy(self.newUserActs)\n acttypeset.remove(oldtype)\n return Settings.random.choice(acttypeset)\n\n def _confuse_slot_name(self, old_name):\n '''\n Randomly select a slot name that is different from the given old_name\n '''\n slots = Ontology.global_ontology.get_requestable_slots(self.domainString)\n if old_name in slots:\n slots.remove(old_name)\n # if old_name not in slots:\n # logger.error('Slot \"%s\" is not found in ontology.' % old_name)\n\n return Settings.random.choice(slots)\n\n def _get_confused_value_for_slot(self, slot, old_val):\n '''\n Randomly select a slot value for the given slot s different from old_val.\n '''\n return Ontology.global_ontology.getRandomValueForSlot(self.domainString, slot=slot, notthese=[old_val])\n\n def _confuse_type(self, hyp):\n '''\n Create a wrong hypothesis, where the dialogue act type is different.\n '''\n hyp.items = []\n hyp.act = self._confuse_dia_act_type(hyp.act)\n item_format = DiaAct.actTypeToItemFormat[hyp.act]\n if item_format == 0:\n return hyp\n elif item_format == 1:\n new_slot_name = Ontology.global_ontology.get_random_slot_name(self.domainString)\n hyp.append(new_slot_name, None)\n elif item_format == 2:\n new_slot_name = Ontology.global_ontology.get_random_slot_name(self.domainString)\n assert new_slot_name is not None\n new_slot_val = Ontology.global_ontology.getRandomValueForSlot(self.domainString, slot=new_slot_name)\n hyp.append(new_slot_name, new_slot_val)\n # TODO: If item_format is 3, it doesn't confuse slot-values.\n # This might be a bug in the original implementation.\n return hyp\n\n def _confuse_slot(self, hyp):\n '''\n Create a wrong hypothesis, where the slot names are different.\n '''\n for dip in hyp.items:\n # If the slot is empty, just break\n if dip.slot is None:\n break\n\n slot = dip.slot\n if slot == 'more':\n break\n\n dip.slot = self._confuse_slot_name(slot)\n if dip.val is not None:\n dip.val = Ontology.global_ontology.getRandomValueForSlot(self.domainString, slot=dip.slot)\n\n return hyp\n\n def _confuse_value(self, a_u):\n '''\n Create a wrong hypothesis, where one slot value is different.\n '''\n rand = Settings.random.randint(len(a_u.items))\n a_u_i = a_u.items[rand]\n\n if a_u_i.slot is not None and a_u_i.val is not None:\n a_u.items[rand].val = self._get_confused_value_for_slot(a_u_i.slot, a_u_i.val)\n\n return a_u\n\nclass EMLevenshteinConfusionModel(EMConfusionModel):\n '''Derived class from :class:`EMConfusionModel`.\n\n :param None:\n '''\n\n def __init__(self, domainString):\n self.domainString = domainString\n\n self.CONFUSE_TYPE = 0.2\n self.CONFUSE_SLOT = 0.3\n self.CONFUSE_VALUE = 0.5\n self.len_confusion_list = 6\n self.newUserActs = ['hello',\n 'thankyou',\n 'ack',\n 'bye',\n 'inform',\n 'request',\n 'reqalts',\n 'reqmore',\n 'confirm',\n 'affirm',\n 'negate',\n 'deny',\n 'repeat',\n 'null']\n self.nNewUserActs = len(self.newUserActs)\n self.type_confusions = self.get_confusion_distributions(self.newUserActs, offset=0.15)\n self.slot_confusions = self.get_confusion_distributions(Ontology.global_ontology.get_requestable_slots(self.domainString), offset=0.15)\n for slot in self.slot_confusions:\n if 'name' in self.slot_confusions[slot]['wlist']:\n itemindices = np.where(self.slot_confusions[slot]['wlist']=='name')\n self.slot_confusions[slot]['wlist'] = np.delete(self.slot_confusions[slot]['wlist'],itemindices[0])\n self.slot_confusions[slot]['dist'] = np.delete(self.slot_confusions[slot]['dist'],itemindices[0])\n self.slot_confusions[slot]['dist'] = self.slot_confusions[slot]['dist']/np.sum(self.slot_confusions[slot]['dist'])\n \n self.slot_value_confusions = {}\n for slot in Ontology.global_ontology.get_system_requestable_slots(self.domainString) + [unicode('name')]:\n self.slot_value_confusions[slot] = self.get_confusion_distributions(\n Ontology.global_ontology.get_informable_slot_values(self.domainString, slot) + [unicode('dontcare')], offset=0.15)\n\n def get_confusion_distributions(self, word_list, offset=0.15):\n '''\n\n :param word_list: The list of words to be confused\n :param offset: Distribution softening factor, the largest the softer the distribution will be\n :return: dictionary\n '''\n wlist = list(word_list)\n Settings.random.shuffle(wlist)\n distributions = {}\n distances = [[self.levenshteinDistance(w1,w2) for w1 in wlist] for w2 in wlist]\n for i in range(len(wlist)):\n word = wlist[i]\n distributions[word] = {}\n sorted_indexes = np.argsort(distances[i])[1:self.len_confusion_list+1]\n sorted_wordlist = np.array(wlist)[sorted_indexes]\n distribution = np.array(distances[i])[sorted_indexes]\n distribution = 1./distribution\n distribution /= sum(distribution)\n distribution += offset\n distribution /= sum(distribution)\n distributions[word]['wlist'] = sorted_wordlist\n distributions[word]['dist'] = distribution\n return distributions\n\n def confuse_hyp(self, a_u):\n '''Randomly confuse the act type, slot or value.\n\n :param a_u: of :class:`DiaAct`\n :type a_u: instance\n :returns: (instance) of :class:`DiaAct` - modified input act\n '''\n wHyp = copy.deepcopy(a_u)\n\n # Identify if this diaact type takes 0, 1, or 2 arguments\n nSlotVal = wHyp.getDiaItemFormat()\n\n # Make a choice to confuse the type, slot or value\n choice = Settings.random.choice([0, 1, 2], p=[self.CONFUSE_TYPE, self.CONFUSE_SLOT, self.CONFUSE_VALUE])\n choice = min(choice, nSlotVal)\n\n if choice == 0:\n wHyp = self._confuse_type(wHyp)\n elif choice == 1:\n wHyp = self._confuse_slot(wHyp)\n elif choice == 2:\n wHyp = self._confuse_value(wHyp)\n else:\n logger.error('Invalid choice ' + str(choice))\n\n return wHyp\n\n def _confuse_dia_act_type(self, oldtype):\n '''\n Select a dialogue act type different from oldtype.\n '''\n return Settings.random.choice(self.type_confusions[oldtype]['wlist'], p=self.type_confusions[oldtype]['dist'])\n\n\n def _confuse_slot_name(self, old_name):\n '''\n Randomly select a slot name that is different from the given old_name\n '''\n return Settings.random.choice(self.slot_confusions[old_name]['wlist'], p=self.slot_confusions[old_name]['dist'])\n\n def _get_confused_value_for_slot(self, slot, old_val):\n '''\n Randomly select a slot value for the given slot s different from old_val.\n '''\n if slot not in self.slot_value_confusions.keys():\n return Ontology.global_ontology.getRandomValueForSlot(self.domainString, slot=slot, notthese=[old_val])\n elif old_val not in self.slot_value_confusions[slot]:\n return Ontology.global_ontology.getRandomValueForSlot(self.domainString, slot=slot, notthese=[old_val])\n else:\n return Settings.random.choice(self.slot_value_confusions[slot][old_val]['wlist'], p=self.slot_value_confusions[slot][old_val]['dist'])\n\n def _confuse_type(self, hyp):\n '''\n Create a wrong hypothesis, where the dialogue act type is different.\n '''\n hyp.items = []\n hyp.act = self._confuse_dia_act_type(hyp.act)\n item_format = DiaAct.actTypeToItemFormat[hyp.act]\n if item_format == 0:\n return hyp\n elif item_format == 1:\n new_slot_name = Ontology.global_ontology.get_random_slot_name(self.domainString)\n hyp.append(new_slot_name, None)\n elif item_format == 2:\n new_slot_name = Ontology.global_ontology.get_random_slot_name(self.domainString)\n assert new_slot_name is not None\n new_slot_val = Ontology.global_ontology.getRandomValueForSlot(self.domainString, slot=new_slot_name)\n hyp.append(new_slot_name, new_slot_val)\n # TODO: If item_format is 3, it doesn't confuse slot-values.\n # This might be a bug in the original implementation.\n return hyp\n\n def _confuse_slot(self, hyp):\n '''\n Create a wrong hypothesis, where the slot names are different.\n '''\n for dip in hyp.items:\n # If the slot is empty, just break\n if dip.slot is None:\n break\n\n slot = dip.slot\n if slot == 'more' or slot == 'type':\n break\n\n dip.slot = self._confuse_slot_name(slot)\n if dip.val is not None:\n dip.val = Ontology.global_ontology.getRandomValueForSlot(self.domainString, slot=dip.slot)\n\n return hyp\n\n def _confuse_value(self, a_u):\n '''\n Create a wrong hypothesis, where one slot value is different.\n '''\n rand = Settings.random.randint(len(a_u.items))\n a_u_i = a_u.items[rand]\n\n if a_u_i.slot is not None and a_u_i.val is not None and a_u_i.slot != 'type':\n a_u.items[rand].val = self._get_confused_value_for_slot(a_u_i.slot, a_u_i.val)\n\n return a_u\n\n def levenshteinDistance(self, s1, s2):\n if len(s1) > len(s2):\n s1, s2 = s2, s1\n\n distances = range(len(s1) + 1)\n for i2, c2 in enumerate(s2):\n distances_ = [i2 + 1]\n for i1, c1 in enumerate(s1):\n if c1 == c2:\n distances_.append(distances[i1])\n else:\n distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1])))\n distances = distances_\n return distances[-1]\n\n#END OF FILE\n" ]
[ [ "numpy.delete", "numpy.argsort", "numpy.array", "numpy.where", "numpy.sum" ] ]
lseventeen/PHTrans
[ "6152758bce653b723c5c1cc9a5ec203046bc6f88" ]
[ "PHTrans/phtrans/inference/metrics.py" ]
[ "import glob\r\nimport os\r\nimport SimpleITK as sitk\r\nimport numpy as np\r\nfrom batchgenerators.utilities.file_and_folder_operations import *\r\nfrom nnunet.utilities.task_name_id_conversion import convert_id_to_task_name\r\nfrom batchgenerators.utilities.file_and_folder_operations import join, isdir\r\nfrom medpy import metric\r\nfrom nnunet.paths import nnUNet_raw_data\r\nimport pandas as pd\r\n\r\n\r\ndef calculate_metric_percase(pred, gt):\r\n pred[pred > 0] = 1\r\n gt[gt > 0] = 1\r\n if pred.sum() > 0 and gt.sum() > 0:\r\n dice = metric.binary.dc(pred, gt)\r\n hd95 = metric.binary.hd95(pred, gt)\r\n return dice, hd95\r\n elif pred.sum() > 0 and gt.sum() == 0:\r\n return 1, 0\r\n else:\r\n return 0, 0\r\n\r\n\r\ndef read_nii(path):\r\n return sitk.GetArrayFromImage(sitk.ReadImage(path))\r\n\r\n\r\ndef get_dice_hd95(pre_path, experiment_id, task_id):\r\n task = convert_id_to_task_name(task_id)\r\n label_path = join(nnUNet_raw_data, task)\r\n predict_list = sorted(glob.glob(os.path.join(pre_path, '*nii.gz')))\r\n label_list = sorted(\r\n glob.glob(os.path.join(label_path, 'labelsTs', '*nii.gz')))\r\n\r\n print(\"loading success...\")\r\n dataset = load_json(join(label_path, 'dataset.json'))\r\n metric_list = 0.0\r\n for predict, label in zip(predict_list, label_list):\r\n case = predict.split('/')[-1]\r\n print(case)\r\n predict, label, = read_nii(predict), read_nii(label)\r\n metric_i = []\r\n for i in dataset['evaluationClass']:\r\n metric_i.append(calculate_metric_percase(predict == i, label == i))\r\n metric_list += np.array(metric_i)\r\n print('case %s mean_dice %f mean_hd95 %f' %\r\n (case, np.mean(metric_i, axis=0)[0], np.mean(metric_i, axis=0)[1]))\r\n metric_list = metric_list / len(predict_list)\r\n clm = [\"DSC\", \"HD\", \"Aotra\", \"Gallbladder\", \"Kidnery(L)\", \"Kidnery(R)\", \"Liver\", \"Pancreas\",\r\n \"Spleen\", \"Stomach\"] if task_id == 17 else [\"DSC\", \"HD\", \"RV\", \"MLV\", \"LVC\"]\r\n for i in range(len(dataset['evaluationClass'])):\r\n print('Mean class %s mean_dice %f mean_hd95 %f' %\r\n (clm[i+2], metric_list[i][0], metric_list[i][1]))\r\n performance = np.mean(metric_list, axis=0)[0]\r\n mean_hd95 = np.mean(metric_list, axis=0)[1]\r\n print('Testing performance in best val model: mean_dice : %f mean_hd95 : %f' % (\r\n performance, mean_hd95))\r\n\r\n idx = experiment_id\r\n data = np.hstack((performance*100, mean_hd95,\r\n metric_list[:, 0]*100)).reshape(1, len(dataset['evaluationClass'])+2)\r\n df = pd.DataFrame(data, index=[idx], columns=clm)\r\n df.to_csv(join(pre_path, f\"{experiment_id}_result.cvs\"))\r\n\r\n df.to_excel(\r\n join(pre_path, f\"{experiment_id}_result.xlsx\"), sheet_name='Synapse')\r\n\r\n\r\nif __name__ == '__main__':\r\n pre_path = \"/home/lwt/code/nnUNet_trained_models/nnUNet/3d_fullres/Task017_AbdominalOrganSegmentation/PHTransTrainer__nnUNetPlansv2.1/fold_0/phtrans_220410_211502/validation_raw_postprocessed\"\r\n experiment_id = \"phtrans_220410_211502\"\r\n get_dice_hd95(pre_path, experiment_id, 17)\r\n" ]
[ [ "numpy.hstack", "numpy.array", "numpy.mean", "pandas.DataFrame" ] ]
akshay9/DDPG-Continous-Control
[ "fcd7c031613a5d0f03cd1cf8d2bb807922a53989" ]
[ "model.py" ]
[ "import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndef hidden_init(layer):\n fan_in = layer.weight.data.size()[0]\n lim = 1. / np.sqrt(fan_in)\n return (-lim, lim)\n\nclass Actor(nn.Module):\n \"\"\"Actor (Policy) Model.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fc1_units=400, fc2_units=300):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fc1_units (int): Number of nodes in first hidden layer\n fc2_units (int): Number of nodes in second hidden layer\n \"\"\"\n super(Actor, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fc1 = nn.Linear(state_size, fc1_units)\n self.batch_norm = nn.BatchNorm1d(fc1_units) # Use batch normalization \n self.fc2 = nn.Linear(fc1_units, fc2_units)\n self.fc3 = nn.Linear(fc2_units, action_size)\n self.reset_parameters()\n\n def reset_parameters(self):\n self.fc1.weight.data.uniform_(*hidden_init(self.fc1))\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\n self.fc3.weight.data.uniform_(-3e-3, 3e-3)\n\n def forward(self, state):\n \"\"\"Build an actor (policy) network that maps states -> actions.\"\"\"\n x = self.batch_norm(self.fc1(state))\n x = F.relu(x)\n x = F.relu(self.fc2(x))\n return F.tanh(self.fc3(x))\n\n\nclass Critic(nn.Module):\n \"\"\"Critic (Value) Model.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fcs1_units=400, fc2_units=300):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fcs1_units (int): Number of nodes in the first hidden layer\n fc2_units (int): Number of nodes in the second hidden layer\n \"\"\"\n super(Critic, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fcs1 = nn.Linear(state_size, fcs1_units)\n self.batch_norm = nn.BatchNorm1d(fcs1_units) # Use batch normalization \n self.fc2 = nn.Linear(fcs1_units+action_size, fc2_units)\n self.fc3 = nn.Linear(fc2_units, 1)\n self.reset_parameters()\n\n def reset_parameters(self):\n self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1))\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\n self.fc3.weight.data.uniform_(-3e-3, 3e-3)\n\n def forward(self, state, action):\n \"\"\"Build a critic (value) network that maps (state, action) pairs -> Q-values.\"\"\"\n xs = self.batch_norm(self.fcs1(state))\n x = F.relu(xs)\n x = torch.cat((xs, action), dim=1)\n x = F.relu(self.fc2(x))\n return self.fc3(x)\n" ]
[ [ "torch.nn.BatchNorm1d", "numpy.sqrt", "torch.cat", "torch.manual_seed", "torch.nn.Linear", "torch.nn.functional.relu" ] ]
mihaipx/SHIPcal
[ "45d108c82ca845546ef854c4624ac2d4f981cf0a" ]
[ "General_modules/func_General.py" ]
[ "\r\n#Miguel Frasquet\r\n\r\nimport numpy as np\r\nimport math\r\n#from matplotlib import pyplot as plt\r\n\r\ndef bar_MPa(pres):\r\n pres=pres/10\r\n return pres\r\ndef MPa_bar(pres):\r\n pres=pres*10\r\n return pres\r\ndef C_K(temp):\r\n temp=temp+273\r\n return temp\r\ndef K_C(temp):\r\n temp=temp-273\r\n return temp\r\n \r\ndef check_overwrite(data,reg,rebaja,num_loops,n_coll_loop,type_integration,almVolumen,correccionDNI,FS):\r\n flag_n_coll_loop=False;flag_rebaja=False;flag_num_loops=False;flag_type_integration=False;flag_almVolumen=False;flag_correccionDNI=False;flag_FS=False\r\n if data.at[reg,'rebaja']==rebaja:\r\n pass\r\n else:\r\n flag_rebaja=True\r\n if data.at[reg,'num_loops'] == num_loops: \r\n pass\r\n else:\r\n flag_num_loops=True\r\n if data.at[reg,'n_coll_loop'] == n_coll_loop:\r\n pass\r\n else:\r\n flag_n_coll_loop=True\r\n if data.at[reg,'type_integration'] == type_integration:\r\n pass\r\n else:\r\n flag_type_integration=True\r\n if data.at[reg,'almVolumen'] == almVolumen:\r\n pass\r\n else:\r\n flag_almVolumen=True\r\n if data.at[reg,'correccionDNI'] == correccionDNI:\r\n pass\r\n else:\r\n flag_correccionDNI=True\r\n if data.at[reg,'FS'] == FS:\r\n pass\r\n else:\r\n flag_FS=True\r\n \r\n flagOverwrite=[flag_rebaja,flag_num_loops,flag_n_coll_loop,flag_type_integration,flag_almVolumen,flag_correccionDNI,flag_FS] \r\n return flagOverwrite\r\n \r\n\r\ndef calc_hour_year(mes,dia,hora): #This function calculates what is the correspondign hour of the year for an specific date and time.\r\n mes_days=(31,28,31,30,31,30,31,31,30,31,30,31)\r\n \r\n num_days=0 #Initializate the variables\r\n cont_mes=mes-1\r\n if mes<=12: #Check that the month input is reliable\r\n while (cont_mes >0):\r\n cont_mes=cont_mes-1 #Counts backwards from the introduced month to the first month in the year(January)\r\n num_days=num_days+mes_days[cont_mes] #Adds all the days in the months previous to the introduced one\r\n if dia<=mes_days[mes-1]: #Checks that the introduced dau number is smaller than the number of days in that month\r\n num_days=num_days+dia #Adds the quantity of days passed so far in the introduced month\r\n else:\r\n raise ValueError('Day should be <=days_month') \r\n else:\r\n raise ValueError('Month should be <=12')\r\n \r\n if hora<=24: #Checks that the hour number is less than 24\r\n hour_year=(num_days-1)*24+hora #Minus the 24 h of the current day, and adds the hours that have passed in the current day #Calculates the current year hour\r\n else:\r\n raise ValueError('Hour should be <=24')\r\n #The minimum output hour year is 1\r\n return hour_year\r\n\r\n \r\n \r\ndef DemandData(file_demand,mes_ini_sim,dia_ini_sim,hora_ini_sim,mes_fin_sim,dia_fin_sim,hora_fin_sim): #Returns the only the entries of the demand vector (consumtpion for every hour along the year) that corresponds to the hours between the the starting and ending hours of the simulation\r\n \r\n# Demand = np.loadtxt(file_demand, delimiter=\",\")\r\n Demand=np.array(file_demand)\r\n \r\n hour_year_ini=calc_hour_year(mes_ini_sim,dia_ini_sim,hora_ini_sim)\r\n hour_year_fin=calc_hour_year(mes_fin_sim,dia_fin_sim,hora_fin_sim)\r\n \r\n if hour_year_ini <= hour_year_fin:\r\n sim_steps=hour_year_fin-hour_year_ini\r\n else:\r\n raise ValueError('End time is smaller than start time') \r\n\r\n\r\n #Bucle de simulacion\r\n Demand_sim=np.zeros (sim_steps)\r\n step_sim=np.zeros (sim_steps)\r\n \r\n \r\n step=0\r\n for step in range(0,sim_steps):\r\n step_sim[step]=step\r\n Demand_sim[step]=Demand[hour_year_ini+step-1]\r\n \r\n step+=1\r\n \r\n# if plot_Demand==1:\r\n# fig = plt.figure()\r\n# fig.suptitle('Demand', fontsize=14, fontweight='bold')\r\n# ax2 = fig.add_subplot(111) \r\n# ax2 .plot(step_sim, Demand_sim,'.-',color = 'b',label=\"Demand_sim\")\r\n# \r\n# ax2.set_xlabel('simulation')\r\n# ax2.set_ylabel('kWh')\r\n# plt.legend(bbox_to_anchor=(1.05, 1), loc=1, borderaxespad=0.)\r\n \r\n return Demand_sim\r\n\r\ndef annualConsumpFromSHIPcal(activeHoursArray,activeDaysWeekArray,activeMonthsArray,annualConsumptionkWh):\r\n #Una vez tengo los arrays lo convierto en horario\r\n findes_array=[3,0,3,2,3,2,3,3,2,3,2,3] #Vector findes es 28-el numero de días de cada mes, suponemos 28=4 semanas\r\n \r\n #Vectores día de la semana combinados con el vector diario\r\n lunes_array=list(np.array(activeHoursArray)*activeDaysWeekArray[0])\r\n martes_array=list(np.array(activeHoursArray)*activeDaysWeekArray[1])\r\n miercoles_array=list(np.array(activeHoursArray)*activeDaysWeekArray[2])\r\n jueves_array=list(np.array(activeHoursArray)*activeDaysWeekArray[3])\r\n viernes_array=list(np.array(activeHoursArray)*activeDaysWeekArray[4])\r\n sabado_array=list(np.array(activeHoursArray)*activeDaysWeekArray[5])\r\n domingo_array=list(np.array(activeHoursArray)*activeDaysWeekArray[6])\r\n \r\n #Vector semana\r\n semana_array=lunes_array+martes_array+miercoles_array+jueves_array+viernes_array+sabado_array+domingo_array\r\n \r\n #Vector mes\r\n Enero_array=list(np.array(4*semana_array+lunes_array*findes_array[0])*activeMonthsArray[0])\r\n Febrero_array=list(np.array(4*semana_array+lunes_array*findes_array[1])*activeMonthsArray[1])\r\n Marzo_array=list(np.array(4*semana_array+lunes_array*findes_array[2])*activeMonthsArray[2])\r\n Abril_array=list(np.array(4*semana_array+lunes_array*findes_array[3])*activeMonthsArray[3])\r\n Mayo_array=list(np.array(4*semana_array+lunes_array*findes_array[4])*activeMonthsArray[4])\r\n Junio_array=list(np.array(4*semana_array+lunes_array*findes_array[5])*activeMonthsArray[5])\r\n Julio_array=list(np.array(4*semana_array+lunes_array*findes_array[6])*activeMonthsArray[6])\r\n Agosto_array=list(np.array(4*semana_array+lunes_array*findes_array[7])*activeMonthsArray[7])\r\n Septiembre_array=list(np.array(4*semana_array+lunes_array*findes_array[8])*activeMonthsArray[8])\r\n Octubre_array=list(np.array(4*semana_array+lunes_array*findes_array[9])*activeMonthsArray[9])\r\n Noviembre_array=list(np.array(4*semana_array+lunes_array*findes_array[10])*activeMonthsArray[10])\r\n Diciembre_array=list(np.array(4*semana_array+lunes_array*findes_array[11])*activeMonthsArray[11])\r\n \r\n #vector anual\r\n anual_array=Enero_array+Febrero_array+Marzo_array+Abril_array+Mayo_array+Junio_array+Julio_array+Agosto_array+Septiembre_array+Octubre_array+Noviembre_array+Diciembre_array\r\n \r\n #Consumo anual horario (potencia asumida constante durante toda la hora)\r\n if np.sum(anual_array)==0:\r\n consumo_anual_horario=0\r\n else:\r\n consumo_medio_diario=annualConsumptionkWh/np.sum(anual_array) #kW cada hora\r\n consumo_anual_horario=np.array(anual_array)*consumo_medio_diario #Consumo que debe de ser metido en la base de datos\r\n return consumo_anual_horario\r\n \r\ndef waterFromGrid(T_in_C_AR_mes):\r\n \r\n T_in_C_AR=np.zeros(8760)\r\n for ii in range(0,8760):\r\n if (ii<=744-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[0]\r\n if (ii>744-1) and (ii<=1416-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[1]\r\n if (ii>1416-1) and (ii<=2160-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[2] \r\n if (ii>2160-1) and (ii<=2880-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[3] \r\n if (ii>2880-1) and (ii<=3624-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[4] \r\n if (ii>3624-1) and (ii<=4344-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[5] \r\n if (ii>4344-1) and (ii<=5088-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[6] \r\n if (ii>5088-1) and (ii<=5832-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[7] \r\n if (ii>5832-1) and (ii<=6552-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[8]\r\n if (ii>6552-1) and (ii<=7296-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[9]\r\n if (ii>7296-1) and (ii<=8016-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[10]\r\n if (ii>8016-1):\r\n T_in_C_AR[ii]=T_in_C_AR_mes[11] \r\n \r\n return (T_in_C_AR)\r\n\r\n\r\ndef waterFromGrid_trim(T_in_C_AR,mes_ini_sim,dia_ini_sim,hora_ini_sim,mes_fin_sim,dia_fin_sim,hora_fin_sim):\r\n \r\n hour_year_ini=calc_hour_year(mes_ini_sim,dia_ini_sim,hora_ini_sim)#Calls a function within this same script yo calculate the corresponding hout in the year for the day/month/hour of start and end\r\n hour_year_fin=calc_hour_year(mes_fin_sim,dia_fin_sim,hora_fin_sim)\r\n \r\n if hour_year_ini <= hour_year_fin: #Checks that the starting hour is before than the enfing hour\r\n sim_steps=hour_year_fin-hour_year_ini #Stablishes the number of steps as the hours between the starting and ending hours\r\n else:\r\n raise ValueError('End time is smaller than start time') \r\n \r\n T_in_C_AR_trim=np.zeros (sim_steps)\r\n \r\n step=0\r\n for step in range(0,sim_steps):\r\n T_in_C_AR_trim[step]=T_in_C_AR[hour_year_ini+step-1]\r\n step+=1\r\n \r\n return (T_in_C_AR_trim) \r\n \r\n\r\ndef waterFromGrid_v2(T_in_C_AR_mes):\r\n days_in_the_month=[31,28,31,30,31,30,31,31,30,31,30,31] #days_in_the_month[month_number]=how many days are in the month number \"month_number\"\r\n T_in_C_AR=[] #Creates an empty list where I'll store the temperatures per hour along the year.\r\n for month in range(12): #For eacho month\r\n T_in_C_AR+=[T_in_C_AR_mes[month]]*(days_in_the_month[month]*24) #Append the average temperature from the grid number_of_days_in_the_month*24 times\r\n return(np.array(T_in_C_AR)) #Returns the list transformed to an array.\r\n\r\ndef waterFromGrid_v3(file_meteo, sender='CIMAV'):\r\n if sender=='CIMAV':\r\n Tamb = np.loadtxt(file_meteo, delimiter=\"\\t\", skiprows=4)[:,7]#Reads the temperature of the weather. The TMYs are a bit different.\r\n elif sender=='SHIPcal':\r\n from simforms.models import Locations, MeteoData\r\n meteo_data = MeteoData.objects.filter(location=Locations.objects.get(pk=file_meteo))\r\n Tamb = meteo_data.order_by('hour_year_sim').values_list('temp',flat=True)\r\n else:\r\n Tamb = np.loadtxt(file_meteo, delimiter=\"\\t\")[:,9]#Reads the temperature of the weather\r\n TambAverage=np.mean(Tamb) #Computes the year average\r\n TambMax=np.amax(Tamb) #Computes the maximum temperature\r\n \r\n offset = 3 #A defined offset of 3 °C\r\n ratio = 0.22 + 0.0056*(TambAverage - 6.67)\r\n lag = 1.67 - 0.56*(TambAverage - 6.67)\r\n#The offset, lag, and ratio values were obtained by fitting data compiled by Abrams and Shedd [8], the FloridaSolar Energy Center [9], and Sandia National Labs\r\n \r\n T_in_C_AR=[] #It is easier to work with this array as a list first to print 24 times the mean value of the water temperature for every day\r\n \r\n for day in range(365):\r\n #The hourly year array is built by the temperature calculated for the day printed 24 times for each day\r\n T_in_C_AR+=[(TambAverage+offset)+ratio*(TambMax/2)*np.sin(np.radians(-90+(day-15-lag)*360/365))]*24 #This was taken from TRNSYS documentation.\r\n \r\n return np.array(T_in_C_AR)\r\n\r\ndef thermalOil(T): #Function to derive the properties of thermal oil from the Thermal oil DB\r\n T=T-273 #To transform K to C\r\n if T==0:\r\n T=0.001\r\n else:\r\n pass\r\n #Density kg/m3\r\n rho=-0.6388*T+885.61\r\n #Specific Heat kJ/kgK\r\n Cp=0.0038*T+1.8074\r\n #Thermal conductivity W/mK\r\n k=-9e-5*T+.1376\r\n #Dinamic viscosity #kg/m*s\r\n Dv=(23428.38511*T**(-1.89020))*1e-3\r\n #Kinematic viscosity m2/s\r\n Kv=(19563.70818*T**-1.80379)*1e-6\r\n #Thermal Diffusivity m2/s\r\n thermalDiff=8.20353*np.exp(-0.00135*T)*1e-8\r\n #PrantNumber\r\n Prant=177506.92794*T**(-1.68808)\r\n return(rho,Cp,k,Dv,Kv,thermalDiff,Prant)\r\n \r\n \r\ndef moltenSalt(T): #Function to derive the properties of molten Salts from Solar Salt SQM\r\n \r\n T=T-273 #To transform K to C\r\n if T==0:\r\n T=0.001\r\n else:\r\n pass\r\n \r\n #Density kg/m3\r\n rho=-0.636*T+2090\r\n #Specific Heat kJ/kgK\r\n Cp=max(1.6,0.000172*T+1.44)\r\n #Thermal conductivity W/mK\r\n k=1.89e-4*T+.441\r\n #Dinamic viscosity #kg/m*s\r\n try:\r\n Dv=0.0231*math.exp(-6.17e-3*T)\r\n except:\r\n Dv=0.001 #To avoid errors when iteration process explores high boundaries\r\n\r\n\r\n return(rho,Cp,k,Dv)\r\n \r\n\r\n \r\n\r\ndef reportOutputOffline(reportsVar):\r\n print(\"\")\r\n print(\"////////////////// Results from SHIPcal v.\"+reportsVar['version']+\" ///////////////////\")\r\n print(\"Location: \"+reportsVar['location']+\" (\"+str(round(reportsVar['DNI_anual_irradiation'],2))+\" kWh with ModfDNI: \"+str(reportsVar['mofDNI'])+\")\")\r\n print(\"Solar plant: \"+str(int(reportsVar['Area_total']*1.5))+\" m2 with \"+str(reportsVar['n_coll_loop'])+\" collectors per loop, in \"+str(reportsVar['num_loops'])+\" loops\")\r\n print(\"Storage: \"+str(int(reportsVar['energyStored']))+\" kWh\")\r\n print(\"Integration scheme: \"+reportsVar['type_integration'])\r\n print(\"/// SOLAR PRODUCTION:\")\r\n print(\"Energy demand of the industry \"+str(round(reportsVar['Demand_anual'],2))+\" kWh\")\r\n print(\"Gross solar production: \"+str(round(reportsVar['Production_max'],2))+\" kWh with ModfProd: \"+str(reportsVar['mofProd'])+\" (\"+str(int(reportsVar['solar_fraction_max']))+\" %)\")\r\n print(\"Net solar production: \"+str(round(reportsVar['Production_lim'],2))+\" kWh with ModfProd: \"+str(reportsVar['mofProd'])+\" (\"+str(int(reportsVar['solar_fraction_lim']))+\" %)\")\r\n print(\"Utilization ratio: \"+str(round(reportsVar['Utilitation_ratio'],2))+\" %\")\r\n print(\"/// FINANCE:\")\r\n print(\"Investment: \"+str(int(reportsVar['Selling_price']))+\" $\")\r\n print(\"Savings 1st year: \"+str(int(reportsVar['Energy_savingsList'][1]))+\" $ with ModfInv: \"+str(reportsVar['mofINV'])+\"\")\r\n print(\"Payback period: \"+str(int(reportsVar['AmortYear']))+\" years\")" ]
[ [ "numpy.amax", "numpy.radians", "numpy.mean", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.loadtxt" ] ]
FrancescoFarinola/Anemia-Web-App
[ "4c33331fc985b6c645293837d3a9578621558470" ]
[ "model.py" ]
[ "import pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import GradientBoostingClassifier\nimport cv2\nimport pickle\n\n\ndef predizione():\n scaler = StandardScaler() # scaler per normalizzare i dati\n data = pd.read_csv(\n \"train/unico_smote.csv\") # lettura da csv dei dati della congiuntiva delle istanze di train\n Xc = data.iloc[:, :-1].values # assegno a Xc le features correlate della congiuntiva\n Yc = data.iloc[:, -1].values # assegno a Yc i target\n scaler.fit(Xc) # normalizzo le features\n # MODELLO\n classifier = GradientBoostingClassifier(loss='deviance',criterion='mse') # LMT\n classifier.fit(Xc, Yc) # train del modello\n pickle.dump(classifier, open('model.pkl', 'wb'))\n return \"\"\n\n\npredizione()\n\ndef extract_conjunctiva(st1):\n image1 = cv2.imread(st1)\n g, r, astar, c = 0, 0, 0, 0\n data = []\n lab_image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2LAB)\n for i in range(image1.shape[0]):\n for j in range(image1.shape[1]):\n if image1[i, j, 0] < 254:\n if image1[i, j, 1] < 254:\n if image1[i, j, 2] < 254:\n g += image1[i, j, 1]\n r += image1[i, j, 2]\n astar += lab_image1[i, j, 1]\n c += 1\n data.append(round(astar / c - 128, 2))\n data.append(round((r / c) - (g / c), 2))\n return data\n\ndef extract_nailbed(st2):\n image2 = cv2.imread(st2)\n b, astar, bstar, c = 0, 0, 0, 0\n data = []\n lab_image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2LAB)\n for i in range(image2.shape[0]):\n for j in range(image2.shape[1]):\n if image2[i, j, 0] < 254:\n if image2[i, j, 1] < 254:\n if image2[i, j, 2] < 254:\n b += image2[i, j, 0]\n astar += lab_image2[i, j, 1]\n bstar += lab_image2[i, j, 2]\n c += 1\n\n data.append(round(b / c, 2))\n data.append(round(astar / c - 128, 2))\n data.append(round(bstar / c - 128, 2))\n return data\n\ndef extract_fingertip(st3):\n video1 = cv2.VideoCapture(st3)\n ret = True\n bsum, bstarsum = 0, 0\n data = []\n i = 0\n while ret and i < 10:\n ret, frame = video1.read()\n if ret:\n b, bstar, c = 0, 0, 0\n lab_image = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)\n for k in range(frame.shape[0]):\n for j in range(frame.shape[1]):\n b = b + frame[k, j, 0]\n bstar = bstar + lab_image[k, j, 2]\n c = c + 1\n b = b/c\n bstar = bstar/c\n bsum = bsum + b\n bstarsum = bstarsum + bstar\n i = i + 1\n data.append(round(bsum/i, 2))\n data.append(round(bstarsum/i-128, 2))\n return data\n\n" ]
[ [ "sklearn.preprocessing.StandardScaler", "pandas.read_csv", "sklearn.ensemble.GradientBoostingClassifier" ] ]
eschnett/asdf-cxx
[ "0d0fd304e32145c666abd6845999a5d659e49aa9" ]
[ "asdf-demo-external-python.py" ]
[ "#! /usr/bin/env python\n\nfrom __future__ import print_function\nimport numpy as np\n\nfrom asdf import *\n\n\n\ndef write_external():\n print(\"Writing external file...\")\n\n # The actual dataset\n alpha = ndarray.create_int64(\n np.array([1, 2, 3], np.int64), block_format_t_inline_array,\n compression_t_none, 0, np.array([]), [3])\n # A local reference\n beta = reference.create_from_path(\"\", [\"group\", \"alpha\", \"data\"])\n\n grp = group.create(\n {\"alpha\": entry.create_from_ndarray(\"alpha\", alpha, \"\"),\n \"beta\": entry.create_from_reference(\"beta\", beta, \"\")})\n\n project = asdf.create_from_group({}, grp)\n project.write(\"external.asdf\")\n\n\n\ndef write_metadata():\n print(\"Writing metadata file...\")\n\n # A remote reference\n gamma = reference.create_from_path(\"external.asdf\",\n [\"group\", \"alpha\", \"data\"])\n # A local reference\n delta = reference.create_from_path(\"\", [\"group\", \"gamma\", \"reference\"])\n # A remote reference to a local reference\n epsilon = reference.create_from_path(\"external.asdf\",\n [\"group\", \"beta\", \"reference\"])\n\n grp = group.create(\n {\"gamma\": entry.create_from_reference(\"gamma\", gamma, \"\"),\n \"delta\": entry.create_from_reference(\"delta\", delta, \"\"),\n \"epsilon\": entry.create_from_reference(\"epsilon\", epsilon, \"\")})\n\n project = asdf.create_from_group({}, grp)\n project.write(\"metadata.asdf\")\n\n\n\ndef read_metadata():\n print(\"Reading metadata file...\")\n\n project = asdf.read(\"metadata.asdf\")\n grp = project.get_group()\n\n gamma = grp.get_entries()[\"gamma\"].get_reference()\n print(\"gamma: <\" + gamma.get_target() + \">\")\n rs_node = gamma.resolve()\n arr = ndarray.read(rs_node)\n print(\"gamma': [ndarray] \" + str(arr.get_data_vector_int64()))\n\n delta = grp.get_entries()[\"delta\"].get_reference()\n print(\"delta: <\" + delta.get_target() + \">\")\n rs_node = delta.resolve()\n ref = reference.create_from_reader_state_node(rs_node)\n print(\"delta': [reference] \" + ref.get_target())\n rs_node1 = ref.resolve()\n arr = ndarray.read(rs_node1)\n print(\"delta'': [ndarray] \" + str(arr.get_data_vector_int64()))\n \n epsilon = grp.get_entries()[\"epsilon\"].get_reference()\n print(\"epsilon: <\" + epsilon.get_target() + \">\")\n rs_node = epsilon.resolve()\n ref = reference.create_from_reader_state_node(rs_node)\n print(\"epsilon': [reference] \" + ref.get_target())\n rs_node1 = ref.resolve()\n arr = ndarray.read(rs_node1)\n print(\"epsilon'': [ndarray] \" + str(arr.get_data_vector_int64()))\n\n\n\nprint(\"asdf-demo-external-python:\")\nprint(\" Create a simple ASDF file with external references from Python\")\n\nwrite_external()\nwrite_metadata()\nread_metadata()\n\nprint(\"Done.\")\n" ]
[ [ "numpy.array" ] ]
trondkr/xESMF
[ "27952e1ab2f1b7b23c443953b9d1e079376efb08" ]
[ "xesmf/tests/test_backend.py" ]
[ "import os\nimport numpy as np\nimport ESMF\nimport xesmf as xe\nfrom xesmf.backend import (warn_f_contiguous, warn_lat_range,\n esmf_grid, add_corner, esmf_locstream,\n esmf_regrid_build, esmf_regrid_apply,\n esmf_regrid_finalize)\nfrom xesmf.smm import read_weights, apply_weights\n\nfrom numpy.testing import assert_equal, assert_almost_equal\nimport pytest\n\n# We use pure numpy arrays to test backend\n# xarray DataSet is only used at the very beginning as a quick way to make data\ncoord_names = ['lon', 'lat', 'lon_b', 'lat_b']\n\nds_in = xe.util.grid_global(20, 12)\nlon_in, lat_in, lon_b_in, lat_b_in = [ds_in[name].values\n for name in coord_names]\n\nds_out = xe.util.grid_global(15, 9)\nlon_out, lat_out, lon_b_out, lat_b_out = [ds_out[name].values\n for name in coord_names]\n\n# shortcut to test a single grid\nlon, lat, lon_b, lat_b = [lon_in, lat_in, lon_b_in, lat_b_in]\n\n# input test data\nds_in['data'] = xe.data.wave_smooth(ds_in['lon'], ds_in['lat'])\ndata_in = ds_in['data'].values\n\n# reference output data, calculated analytically\nds_out['data_ref'] = xe.data.wave_smooth(ds_out['lon'], ds_out['lat'])\ndata_ref = ds_out['data_ref'].values\n\n# 4D data to test broadcasting, increasing linearly with time and lev\nds_in.coords['time'] = np.arange(1, 11)\nds_in.coords['lev'] = np.arange(1, 51)\nds_in['data4D'] = ds_in['time'] * ds_in['lev'] * ds_in['data']\ndata4D_in = ds_in['data4D'].values\n\n\ndef test_warn_f_on_array():\n a = np.zeros([2, 2], order='C')\n with pytest.warns(UserWarning):\n warn_f_contiguous(a)\n\n\ndef test_warn_f_on_grid():\n # should throw a warning if not passing transpose\n with pytest.warns(UserWarning):\n esmf_grid(lon, lat)\n\n\ndef test_warn_lat_range():\n # latitude goes to -100 (invalid value)\n ds_temp = xe.util.grid_2d(-180, 180, 10, -100, 90, 5)\n with pytest.warns(UserWarning):\n warn_lat_range(ds_temp['lat'].values)\n with pytest.warns(UserWarning):\n warn_lat_range(ds_temp['lat_b'].values)\n\n\ndef test_esmf_grid_with_corner():\n\n # only center coordinate, no corners\n # remember to pass transpose (F-ordered) to backend\n grid = esmf_grid(lon.T, lat.T)\n\n # make sure coordinate values agree\n assert_equal(grid.coords[0][0], lon.T)\n assert_equal(grid.coords[0][1], lat.T)\n\n # make sure meta data agree\n assert not grid.has_corners # no corner yet!\n assert grid.staggerloc == [True, False, False, False]\n assert grid.coord_sys is ESMF.CoordSys.SPH_DEG\n assert grid.rank == 2\n assert_equal(grid.size[0], lon.T.shape)\n assert_equal(grid.upper_bounds[0], lon.T.shape)\n assert_equal(grid.lower_bounds[0], np.array([0, 0]))\n\n # now add corner information\n add_corner(grid, lon_b.T, lat_b.T)\n\n # coordinate values\n assert_equal(grid.coords[3][0], lon_b.T)\n assert_equal(grid.coords[3][1], lat_b.T)\n\n # metadata\n assert grid.has_corners # should have corner now\n assert grid.staggerloc == [True, False, False, True]\n assert_equal(grid.size[3], lon_b.T.shape)\n assert_equal(grid.upper_bounds[3], lon_b.T.shape)\n assert_equal(grid.lower_bounds[3], np.array([0, 0]))\n\n\ndef test_esmf_build_bilinear():\n\n grid_in = esmf_grid(lon_in.T, lat_in.T)\n grid_out = esmf_grid(lon_out.T, lat_out.T)\n\n regrid = esmf_regrid_build(grid_in, grid_out, 'bilinear')\n assert regrid.unmapped_action is ESMF.UnmappedAction.IGNORE\n assert regrid.regrid_method is ESMF.RegridMethod.BILINEAR\n\n # they should share the same memory\n regrid.srcfield.grid is grid_in\n regrid.dstfield.grid is grid_out\n\n esmf_regrid_finalize(regrid)\n\n\ndef test_esmf_extrapolation():\n\n grid_in = esmf_grid(lon_in.T, lat_in.T)\n grid_out = esmf_grid(lon_out.T, lat_out.T)\n\n regrid = esmf_regrid_build(grid_in, grid_out, 'bilinear')\n data_out_esmpy = esmf_regrid_apply(regrid, data_in.T).T\n # without extrapolation, the first and last lines/columns = 0\n assert data_out_esmpy[0, 0] == 0\n\n regrid = esmf_regrid_build(grid_in, grid_out, 'bilinear', extrap='inverse_dist', extrap_num_pnts=3, extrap_exp=1)\n data_out_esmpy = esmf_regrid_apply(regrid, data_in.T).T\n # the 3 closest points in data_in are 2.010, 2.005, and 1.992. The result should be roughly equal to 2.0\n assert np.round(data_out_esmpy[0, 0], 1) == 2.0\n\n\ndef test_regrid():\n\n # use conservative regridding as an example,\n # since it is the most well-tested studied one in papers\n\n # TODO: possible to break this long test into smaller tests?\n # not easy due to strong dependencies.\n\n grid_in = esmf_grid(lon_in.T, lat_in.T)\n grid_out = esmf_grid(lon_out.T, lat_out.T)\n\n # no corner info yet, should not be able to use conservative\n with pytest.raises(ValueError):\n esmf_regrid_build(grid_in, grid_out, 'conservative')\n\n # now add corners\n add_corner(grid_in, lon_b_in.T, lat_b_in.T)\n add_corner(grid_out, lon_b_out.T, lat_b_out.T)\n\n # also write to file for scipy regridding\n filename = 'test_weights.nc'\n if os.path.exists(filename):\n os.remove(filename)\n regrid = esmf_regrid_build(grid_in, grid_out, 'conservative',\n filename=filename)\n assert regrid.regrid_method is ESMF.RegridMethod.CONSERVE\n\n # apply regridding using ESMPy's native method\n data_out_esmpy = esmf_regrid_apply(regrid, data_in.T).T\n\n rel_err = (data_out_esmpy - data_ref)/data_ref # relative error\n assert np.max(np.abs(rel_err)) < 0.05\n\n # apply regridding using scipy\n weights = read_weights(filename, lon_in.size, lon_out.size)\n shape_in = lon_in.shape\n shape_out = lon_out.shape\n data_out_scipy = apply_weights(weights, data_in, shape_in, shape_out)\n\n # must be exactly the same as esmpy's result!\n # TODO: this fails once but I cannot replicate it.\n # Maybe assert_equal is too strict for scipy vs esmpy comparision\n assert_equal(data_out_scipy, data_out_esmpy)\n\n # finally, test broadcasting with scipy\n # TODO: need to test broadcasting with ESMPy backend?\n # We only use Scipy in frontend, and ESMPy is just for backend benchmark\n # However, it is useful to compare performance and show scipy is 3x faster\n data4D_out = apply_weights(weights, data4D_in, shape_in, shape_out)\n\n # data over broadcasting dimensions should agree\n assert_almost_equal(data4D_in.mean(axis=(2, 3)),\n data4D_out.mean(axis=(2, 3)),\n decimal=10)\n\n # clean-up\n esmf_regrid_finalize(regrid)\n os.remove(filename)\n\n\ndef test_regrid_periodic_wrong():\n\n # not using periodic grid\n grid_in = esmf_grid(lon_in.T, lat_in.T)\n grid_out = esmf_grid(lon_out.T, lat_out.T)\n\n assert grid_in.num_peri_dims == 0\n assert grid_in.periodic_dim is None\n\n regrid = esmf_regrid_build(grid_in, grid_out, 'bilinear')\n data_out_esmpy = esmf_regrid_apply(regrid, data_in.T).T\n\n rel_err = (data_out_esmpy - data_ref)/data_ref # relative error\n assert np.max(np.abs(rel_err)) == 1.0 # some data will be missing\n\n # clean-up\n esmf_regrid_finalize(regrid)\n\n\ndef test_regrid_periodic_correct():\n\n # only need to specific periodic for input grid\n grid_in = esmf_grid(lon_in.T, lat_in.T, periodic=True)\n grid_out = esmf_grid(lon_out.T, lat_out.T)\n\n assert grid_in.num_peri_dims == 1\n assert grid_in.periodic_dim == 0 # the first axis, longitude\n\n regrid = esmf_regrid_build(grid_in, grid_out, 'bilinear')\n data_out_esmpy = esmf_regrid_apply(regrid, data_in.T).T\n\n rel_err = (data_out_esmpy - data_ref)/data_ref # relative error\n assert np.max(np.abs(rel_err)) < 0.065\n # clean-up\n esmf_regrid_finalize(regrid)\n\n\ndef test_esmf_locstream():\n lon = np.arange(5)\n lat = np.arange(5)\n\n ls = esmf_locstream(lon, lat)\n assert isinstance(ls, ESMF.LocStream)\n\n lon2d, lat2d = np.meshgrid(lon, lat)\n with pytest.raises(ValueError):\n ls = esmf_locstream(lon2d, lat2d)\n with pytest.raises(ValueError):\n ls = esmf_locstream(lon, lat2d)\n with pytest.raises(ValueError):\n ls = esmf_locstream(lon2d, lat)\n" ]
[ [ "numpy.testing.assert_equal", "numpy.abs", "numpy.meshgrid", "numpy.arange", "numpy.round", "numpy.array", "numpy.zeros" ] ]
Floou/python-adv
[ "9e2c518ab48eb4e9744c405470525f8931702525" ]
[ "210222/step_3.py" ]
[ "from random import randint\nfrom time import perf_counter\n\nimport numpy as np\nfrom random import randint\nfrom time import perf_counter\n\nimport numpy as np\n\nnums = [randint(1, 1000) for _ in range(10 ** 5)]\n\nnums_by_7 = [num for num in nums]\nstart = perf_counter()\nprint(sum(nums_by_7), perf_counter() - start)\n\nnums_by_7_np = np.array([num for num in nums]).astype('int64')\nstart = perf_counter()\nprint(sum(nums_by_7_np), perf_counter() - start)\n# _sum = nums_by_7_np[0] # int32\n# _sum += nums_by_7_np[1] # int32\n# _sum += nums_by_7_np[2] # int32\nstart = perf_counter()\nprint(nums_by_7_np.sum(), perf_counter() - start)\n\nprint(nums_by_7_np.mean(), sum(nums_by_7) / len(nums_by_7))\nprint(nums_by_7_np.std())\nprint(nums_by_7_np.min())\nprint(nums_by_7_np.max())\nprint(nums_by_7_np.size, nums_by_7_np.shape)\n\n" ]
[ [ "numpy.array" ] ]
mrwu-mac/DIFNet
[ "a952d7c92b7577bed4767d97400ce470e95116b6" ]
[ "models/transformer/attention.py" ]
[ "import numpy as np\nimport torch\nfrom torch import nn\nfrom models.containers import Module\n\nfrom middle import TensorRecorder\n\nrecorder = TensorRecorder()\n\n\nclass ScaledDotProductAttention(nn.Module):\n '''\n Scaled dot-product attention\n '''\n\n def __init__(self, d_model, d_k, d_v, h, dropout=.1, comment=None):\n '''\n :param d_model: Output dimensionality of the model\n :param d_k: Dimensionality of queries and keys\n :param d_v: Dimensionality of values\n :param h: Number of heads\n '''\n super(ScaledDotProductAttention, self).__init__()\n self.fc_q = nn.Linear(d_model, h * d_k)\n self.fc_k = nn.Linear(d_model, h * d_k)\n self.fc_v = nn.Linear(d_model, h * d_v)\n self.fc_o = nn.Linear(h * d_v, d_model)\n self.dropout = nn.Dropout(dropout)\n\n self.d_model = d_model\n self.d_k = d_k\n self.d_v = d_v\n self.h = h\n\n self.init_weights()\n\n self.comment = comment\n\n def init_weights(self):\n nn.init.xavier_uniform_(self.fc_q.weight)\n nn.init.xavier_uniform_(self.fc_k.weight)\n nn.init.xavier_uniform_(self.fc_v.weight)\n nn.init.xavier_uniform_(self.fc_o.weight)\n nn.init.constant_(self.fc_q.bias, 0)\n nn.init.constant_(self.fc_k.bias, 0)\n nn.init.constant_(self.fc_v.bias, 0)\n nn.init.constant_(self.fc_o.bias, 0)\n\n def forward(self, queries, keys, values, attention_mask=None, attention_weights=None):\n '''\n Computes\n :param queries: Queries (b_s, nq, d_model)\n :param keys: Keys (b_s, nk, d_model)\n :param values: Values (b_s, nk, d_model)\n :param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.\n :param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).\n :return:\n '''\n\n b_s, nq = queries.shape[:2]\n nk = keys.shape[1]\n q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2, 1, 3) # (b_s, h, nq, d_k)\n k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1) # (b_s, h, d_k, nk)\n v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2, 1, 3) # (b_s, h, nk, d_v)\n att = torch.matmul(q, k) / np.sqrt(self.d_k) # (b_s, h, nq, nk)\n if attention_weights is not None:\n att = att * attention_weights\n if attention_mask is not None:\n att = att.masked_fill(attention_mask, -np.inf)\n att = torch.softmax(att, -1)\n att = self.dropout(att)\n # recorder.record(att,comment=self.comment)\n out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s, nq, self.h * self.d_v) # (b_s, nq, h*d_v)\n out = self.fc_o(out) # (b_s, nq, d_model)\n return out\n\n\nclass ScaledDotProductAttentionMemory(nn.Module):\n '''\n Scaled dot-product attention with memory\n '''\n\n def __init__(self, d_model, d_k, d_v, h, m):\n '''\n :param d_model: Output dimensionality of the model\n :param d_k: Dimensionality of queries and keys\n :param d_v: Dimensionality of values\n :param h: Number of heads\n :param m: Number of memory slots\n '''\n super(ScaledDotProductAttentionMemory, self).__init__()\n self.fc_q = nn.Linear(d_model, h * d_k)\n self.fc_k = nn.Linear(d_model, h * d_k)\n self.fc_v = nn.Linear(d_model, h * d_v)\n self.fc_o = nn.Linear(h * d_v, d_model)\n self.m_k = nn.Parameter(torch.FloatTensor(1, m, h * d_k))\n self.m_v = nn.Parameter(torch.FloatTensor(1, m, h * d_v))\n\n self.d_model = d_model\n self.d_k = d_k\n self.d_v = d_v\n self.h = h\n self.m = m\n\n self.init_weights()\n\n def init_weights(self):\n nn.init.xavier_uniform_(self.fc_q.weight)\n nn.init.xavier_uniform_(self.fc_k.weight)\n nn.init.xavier_uniform_(self.fc_v.weight)\n nn.init.xavier_uniform_(self.fc_o.weight)\n nn.init.normal_(self.m_k, 0, 1 / self.d_k)\n nn.init.normal_(self.m_v, 0, 1 / self.m)\n nn.init.constant_(self.fc_q.bias, 0)\n nn.init.constant_(self.fc_k.bias, 0)\n nn.init.constant_(self.fc_v.bias, 0)\n nn.init.constant_(self.fc_o.bias, 0)\n\n def forward(self, queries, keys, values, attention_mask=None, attention_weights=None):\n '''\n Computes\n :param queries: Queries (b_s, nq, d_model)\n :param keys: Keys (b_s, nk, d_model)\n :param values: Values (b_s, nk, d_model)\n :param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.\n :param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).\n :return:\n '''\n b_s, nq = queries.shape[:2]\n nk = keys.shape[1]\n\n m_k = np.sqrt(self.d_k) * self.m_k.expand(b_s, self.m, self.h * self.d_k)\n m_v = np.sqrt(self.m) * self.m_v.expand(b_s, self.m, self.h * self.d_v)\n\n q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2, 1, 3) # (b_s, h, nq, d_k)\n k = torch.cat([self.fc_k(keys), m_k], 1).view(b_s, nk + self.m, self.h, self.d_k).permute(0, 2, 3, 1) # (b_s, h, d_k, nk)\n v = torch.cat([self.fc_v(values), m_v], 1).view(b_s, nk + self.m, self.h, self.d_v).permute(0, 2, 1, 3) # (b_s, h, nk, d_v)\n\n att = torch.matmul(q, k) / np.sqrt(self.d_k) # (b_s, h, nq, nk)\n if attention_weights is not None:\n att = torch.cat([att[:, :, :, :nk] * attention_weights, att[:, :, :, nk:]], -1)\n if attention_mask is not None:\n att[:, :, :, :nk] = att[:, :, :, :nk].masked_fill(attention_mask, -np.inf)\n att = torch.softmax(att, -1)\n out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s, nq, self.h * self.d_v) # (b_s, nq, h*d_v)\n out = self.fc_o(out) # (b_s, nq, d_model)\n return out\n\n\nclass MultiHeadAttention(Module):\n '''\n Multi-head attention layer with Dropout and Layer Normalization.\n '''\n\n def __init__(self, d_model, d_k, d_v, h, dropout=.1, identity_map_reordering=False, can_be_stateful=False,\n attention_module=None, attention_module_kwargs=None, comment=None):\n super(MultiHeadAttention, self).__init__()\n self.identity_map_reordering = identity_map_reordering\n self.attention = ScaledDotProductAttention(d_model=d_model, d_k=d_k, d_v=d_v, h=h, comment=comment)\n self.dropout = nn.Dropout(p=dropout)\n self.layer_norm = nn.LayerNorm(d_model)\n\n self.can_be_stateful = can_be_stateful\n if self.can_be_stateful:\n self.register_state('running_keys', torch.zeros((0, d_model)))\n self.register_state('running_values', torch.zeros((0, d_model)))\n\n def forward(self, queries, keys, values, attention_mask=None, attention_weights=None):\n if self.can_be_stateful and self._is_stateful:\n self.running_keys = torch.cat([self.running_keys, keys], 1)\n keys = self.running_keys\n\n self.running_values = torch.cat([self.running_values, values], 1)\n values = self.running_values\n\n if self.identity_map_reordering:\n q_norm = self.layer_norm(queries)\n k_norm = self.layer_norm(keys)\n v_norm = self.layer_norm(values)\n out = self.attention(q_norm, k_norm, v_norm, attention_mask, attention_weights)\n out = queries + self.dropout(torch.relu(out))\n else:\n out = self.attention(queries, keys, values, attention_mask, attention_weights)\n out = self.dropout(out)\n out = self.layer_norm(queries + out)\n return out\n" ]
[ [ "torch.nn.Dropout", "torch.softmax", "numpy.sqrt", "torch.cat", "torch.nn.init.constant_", "torch.zeros", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.matmul", "torch.relu", "torch.nn.init.normal_", "torch.FloatTensor", "torch.nn.init.xavier_uniform_" ] ]
cameronaaron/conversationai-moderator-reddit
[ "1c6528485aa3dc031d880210efdbbd5951ff0734" ]
[ "perspective_reddit_bot/compute_bot_metrics_test.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"compute_bot_metrics tests\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\n\nimport numpy as np\nimport pandas as pd\n\nimport compute_bot_metrics\n\n\nclass ComputeBotMetricsTest(unittest.TestCase):\n\n def test_process_modactions_frame(self):\n raw_df = pd.DataFrame({\n 'removed': [True, False, np.NaN],\n 'rule:hitox': ['report', 'noop', 'report'],\n 'rule:medtox': ['noop', 'noop', 'rule-not-triggered'],\n })\n cleaned_df = compute_bot_metrics.process_modactions_frame(raw_df)\n # Should drop the last row due to nan in removed.\n self.assertEqual(2, len(cleaned_df))\n # Should convert rule columns to booleans.\n self.assertEqual([True, False], list(cleaned_df['rule:hitox']))\n self.assertEqual([False, False], list(cleaned_df['rule:medtox']))\n\n def test_compute_rule_metrics(self):\n df = pd.DataFrame({\n 'removed': [True, True, False, False],\n 'rule:hitox': [True, False, False, False],\n 'rule:medtox': [True, True, True, True],\n })\n metrics = compute_bot_metrics.compute_rule_metrics(df)\n expected_df = pd.DataFrame({\n 'rule': ['hitox', 'medtox', '~overall~'],\n 'precision': [1.0, 0.5, 0.5],\n 'recall': [0.5, 1.0, 1.0],\n 'flags': [1, 4, 4],\n }, columns=['rule', 'precision', 'recall', 'flags'])\n pd.testing.assert_frame_equal(expected_df, metrics)\n\n def test_compute_pr_table(self):\n df = pd.DataFrame({\n 'removed': [True, True, False, False],\n 'score:tox': [1.0, 0.5, 0.6, 0.0],\n })\n pr_table = compute_bot_metrics.compute_pr_table(df, 'score:tox', 10)\n expected_df = pd.DataFrame({\n 'precision': [0.6666666666666666, 0.5, 1.0],\n 'recall': [1.0, 0.5, 0.5],\n 'threshold': [0.5, 0.6, 1.0],\n }, columns=['precision', 'recall', 'threshold'])\n pd.testing.assert_frame_equal(expected_df, pr_table)\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "pandas.testing.assert_frame_equal", "pandas.DataFrame" ] ]
datadesk/census-data-aggregator
[ "a6eadcb65652b1fa1107087d5f413064e5cff9d6" ]
[ "census_data_aggregator/__init__.py" ]
[ "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport math\nimport numpy\nimport warnings\nfrom .exceptions import DataError, SamplingPercentageWarning\n\n\ndef approximate_sum(*pairs):\n \"\"\"\n Sum estimates from the U.S. Census Bureau and approximate the combined margin of error.\n\n Follows the U.S. Census Bureau's `official guidelines`_ for how to calculate a new margin of error\n when totaling multiple values. Useful for aggregating census categories and geographies.\n\n Args:\n *pairs (list): An open-ended set of paired lists, each expected to provide an\n estimate followed by its margin of error.\n\n Returns:\n A two-item tuple with the summed total followed by the approximated margin of error.\n\n (19866960, 5437.757350231803)\n\n Examples:\n Combining the under-five male population with under-five female population\n to calculate a grand total of children under five.\n\n >>> males_under_5, males_under_5_moe = 10154024, 3778\n >>> females_under_5, females_under_5_moe = 9712936, 3911\n >>> approximate_sum(\n (males_under_5, males_under_5_moe),\n (females_under_5, females_under_5_moe)\n )\n 19866960, 5437.757350231803\n\n .. _official guidelines:\n https://www.documentcloud.org/documents/6162551-20180418-MOE.html\n \"\"\"\n # According to the Census Bureau, when approximating a sum use only the largest zero estimate margin of error, once\n # https://www.documentcloud.org/documents/6162551-20180418-MOE.html#document/p52\n zeros = [p for p in pairs if p[0] == 0]\n # So if there are zeros...\n if len(zeros) > 1:\n # ... weed them out\n max_zero_margin = max([p[1] for p in zeros])\n not_zero_margins = [p[1] for p in pairs if p[0] != 0]\n margins = [max_zero_margin] + not_zero_margins\n # If not, just keep all the input margins\n else:\n margins = [p[1] for p in pairs]\n\n # Calculate the margin using the bureau's official formula\n margin_of_error = math.sqrt(sum([m**2 for m in margins]))\n\n # Calculate the total\n total = sum([p[0] for p in pairs])\n\n # Return the results\n return total, margin_of_error\n\n\ndef approximate_median(range_list, design_factor=1, sampling_percentage=None):\n \"\"\"\n Estimate a median and approximate the margin of error.\n\n Follows the U.S. Census Bureau's `official guidelines`_ for estimation using a design factor.\n Useful for generating medians for measures like household income and age when aggregating census geographies.\n\n Args:\n range_list (list): A list of dictionaries that divide the full range of data values into continuous categories.\n Each dictionary should have three keys:\n * min (int): The minimum value of the range\n * max (int): The maximum value of the range\n * n (int): The number of people, households or other unit in the range\n The minimum value in the first range and the maximum value in the last range\n can be tailored to the dataset by using the \"jam values\" provided in\n the `American Community Survey's technical documentation`_.\n design_factor (float, optional): A statistical input used to tailor the standard error to the\n variance of the dataset. This is only needed for data coming from public use microdata sample,\n also known as PUMS. You do not need to provide this input if you are approximating\n data from the American Community Survey. The design factor for each PUMS\n dataset is provided as part of `the bureau's reference material`_.\n sampling_percentage (float, optional): A statistical input used to correct for variance linked to\n the size of the survey's population sample. This value submitted should be the percentage of\n * One-year PUMS: 1\n * One-year ACS: 2.5\n * Three-year ACS: 7.5\n * Five-year ACS: 12.5\n If you do not provide this input, a margin of error will not be returned.\n\n Returns:\n A two-item tuple with the median followed by the approximated margin of error.\n\n (42211.096153846156, 10153.200960954948)\n\n Examples:\n Estimating the median for a range of household incomes.\n\n >>> household_income_2013_acs5 = [\n dict(min=2499, max=9999, n=186),\n dict(min=10000, max=14999, n=78),\n dict(min=15000, max=19999, n=98),\n dict(min=20000, max=24999, n=287),\n dict(min=25000, max=29999, n=142),\n dict(min=30000, max=34999, n=90),\n dict(min=35000, max=39999, n=107),\n dict(min=40000, max=44999, n=104),\n dict(min=45000, max=49999, n=178),\n dict(min=50000, max=59999, n=106),\n dict(min=60000, max=74999, n=177),\n dict(min=75000, max=99999, n=262),\n dict(min=100000, max=124999, n=77),\n dict(min=125000, max=149999, n=100),\n dict(min=150000, max=199999, n=58),\n dict(min=200000, max=250001, n=18)\n ]\n\n >>> approximate_median(household_income_2013_acs5, sampling_percentage=5*2.5)\n (42211.096153846156, 4706.522752733644)\n\n ... _official guidelines:\n https://www.documentcloud.org/documents/6165603-2013-2017AccuracyPUMS.html#document/p18\n ... _American Community Survey's technical documentation\n https://www.documentcloud.org/documents/6165752-2017-SummaryFile-Tech-Doc.html#document/p20/a508561\n ... _the bureau's reference material:\n https://www.census.gov/programs-surveys/acs/technical-documentation/pums/documentation.html\n \"\"\"\n # Sort the list\n range_list.sort(key=lambda x: x['min'])\n\n # For each range calculate its min and max value along the universe's scale\n cumulative_n = 0\n for range_ in range_list:\n range_['n_min'] = cumulative_n\n cumulative_n += range_['n']\n range_['n_max'] = cumulative_n\n\n # What is the total number of observations in the universe?\n n = sum([d['n'] for d in range_list])\n\n # What is the estimated midpoint of the n?\n n_midpoint = n / 2.0\n\n # Now use those to determine which group contains the midpoint.\n n_midpoint_range = next(d for d in range_list if n_midpoint >= d['n_min'] and n_midpoint <= d['n_max'])\n\n # How many households in the midrange are needed to reach the midpoint?\n n_midrange_gap = n_midpoint - n_midpoint_range['n_min']\n\n # What is the proportion of the group that would be needed to get the midpoint?\n n_midrange_gap_percent = n_midrange_gap / n_midpoint_range['n']\n\n # Apply this proportion to the width of the midrange\n n_midrange_gap_adjusted = (n_midpoint_range['max'] - n_midpoint_range['min']) * n_midrange_gap_percent\n\n # Estimate the median\n estimated_median = n_midpoint_range['min'] + n_midrange_gap_adjusted\n\n # If there's no sampling percentage, we can't calculate a margin of error\n if not sampling_percentage:\n # Let's throw a warning, but still return the median\n warnings.warn(\"\", SamplingPercentageWarning)\n return estimated_median, None\n\n # Get the standard error for this dataset\n standard_error = (design_factor * math.sqrt(((100 - sampling_percentage) / (n * sampling_percentage)) * (50**2))) / 100\n\n # Use the standard error to calculate the p values\n p_lower = .5 - standard_error\n p_upper = .5 + standard_error\n\n # Estimate the p_lower and p_upper n values\n p_lower_n = n * p_lower\n p_upper_n = n * p_upper\n\n # Find the ranges the p values fall within\n try:\n p_lower_range_i, p_lower_range = next(\n (i, d) for i, d in enumerate(range_list)\n if p_lower_n >= d['n_min'] and p_lower_n <= d['n_max']\n )\n except StopIteration:\n raise DataError(f\"The n's lower p value {p_lower_n} does not fall within a data range.\")\n\n try:\n p_upper_range_i, p_upper_range = next(\n (i, d) for i, d in enumerate(range_list)\n if p_upper_n >= d['n_min'] and p_upper_n <= d['n_max']\n )\n except StopIteration:\n raise DataError(f\"The n's upper p value {p_upper_n} does not fall within a data range.\")\n\n # Use these values to estimate the lower bound of the confidence interval\n p_lower_a1 = p_lower_range['min']\n try:\n p_lower_a2 = range_list[p_lower_range_i + 1]['min']\n except IndexError:\n p_lower_a2 = p_lower_range['max']\n p_lower_c1 = p_lower_range['n_min'] / n\n try:\n p_lower_c2 = range_list[p_lower_range_i + 1]['n_min'] / n\n except IndexError:\n p_lower_c2 = p_lower_range['n_max'] / n\n lower_bound = ((p_lower - p_lower_c1) / (p_lower_c2 - p_lower_c1)) * (p_lower_a2 - p_lower_a1) + p_lower_a1\n\n # Same for the upper bound\n p_upper_a1 = p_upper_range['min']\n try:\n p_upper_a2 = range_list[p_upper_range_i + 1]['min']\n except IndexError:\n p_upper_a2 = p_upper_range['max']\n p_upper_c1 = p_upper_range['n_min'] / n\n try:\n p_upper_c2 = range_list[p_upper_range_i + 1]['n_min'] / n\n except IndexError:\n p_upper_c2 = p_upper_range['n_max'] / n\n upper_bound = ((p_upper - p_upper_c1) / (p_upper_c2 - p_upper_c1)) * (p_upper_a2 - p_upper_a1) + p_upper_a1\n\n # Calculate the standard error of the median\n standard_error_median = 0.5 * (upper_bound - lower_bound)\n\n # Calculate the margin of error at the 90% confidence level\n margin_of_error = 1.645 * standard_error_median\n\n # Return the result\n return estimated_median, margin_of_error\n\n\ndef approximate_proportion(numerator_pair, denominator_pair):\n \"\"\"\n Calculate an estimate's proportion of another estimate and approximate the margin of error.\n\n Follows the U.S. Census Bureau's `official guidelines`_.\n\n Intended for case where the numerator is a subset of the denominator.\n The `approximate_ratio` method should be used in cases where the\n denominator is larger.\n\n Args:\n numerator (list): a two-item sequence with a U.S. Census\n bureau estimate and its margin of error.\n\n denominator (list): a two-item sequence with a U.S. Census\n bureau estimate and its margin of error.\n\n Returns:\n A two-item sequence containing with the proportion followed by its estimated\n margin of error.\n\n (0.322, 0.008)\n\n Examples:\n The percentage of single women in suburban Virginia.\n\n >>> approximate_proportion((203119, 5070), (690746, 831))\n (0.322, 0.008)\n\n ... _official guidelines:\n https://www.documentcloud.org/documents/6177941-Acs-General-Handbook-2018-ch08.html#document/p5\n \"\"\"\n # Pull out the values\n numerator_estimate, numerator_moe = numerator_pair\n denominator_estimate, denominator_moe = denominator_pair\n\n # Approximate the proportion\n proportion_estimate = numerator_estimate / denominator_estimate\n\n # Approximate the margin of error\n squared_proportion_moe = numerator_moe**2 - (proportion_estimate**2 * denominator_moe**2)\n # Ensure it is greater than zero\n if squared_proportion_moe < 0:\n raise DataError(\n \"The margin of error is less than zero. Census experts advise using the approximate_ratio method instead.\"\n )\n proportion_moe = (1.0 / denominator_estimate) * math.sqrt(squared_proportion_moe)\n\n # Return the result\n return proportion_estimate, proportion_moe\n\n\ndef approximate_ratio(numerator_pair, denominator_pair):\n \"\"\"\n Calculate the ratio between two estimates and approximate its margin of error.\n\n Follows the U.S. Census Bureau's `official guidelines`_.\n\n Args:\n numerator (list): a two-item sequence with a U.S. Census\n bureau estimate and its margin of error.\n\n denominator (list): a two-item sequence with a U.S. Census\n bureau estimate and its margin of error.\n\n Returns:\n A two-item sequence containing the ratio and its approximated margin of error.\n\n (0.9869791666666666, 0.07170047425884142)\n\n Examples:\n >>> approximate_ratio((226840, 5556), (203119, 5070))\n (1.117, 0.039)\n\n ... _official guidelines:\n https://www.documentcloud.org/documents/6177941-Acs-General-Handbook-2018-ch08.html#document/p7\n \"\"\"\n # Pull out the values\n numerator_estimate, numerator_moe = numerator_pair\n denominator_estimate, denominator_moe = denominator_pair\n\n # Approximate the ratio\n ratio_estimate = numerator_estimate / denominator_estimate\n\n # Approximate the margin of error\n squared_ratio_moe = numerator_moe**2 + (ratio_estimate**2 * denominator_moe**2)\n ratio_moe = (1.0 / denominator_estimate) * math.sqrt(squared_ratio_moe)\n\n # Return the result\n return ratio_estimate, ratio_moe\n\n\ndef approximate_product(pair_one, pair_two):\n \"\"\"\n Calculates the product of two estimates and approximates its margin of error.\n\n Follows the U.S. Census Bureau's `official guidelines`_.\n\n Args:\n pair_one (list): a two-item sequence with a U.S. Census\n bureau estimate and its margin of error.\n\n pair_two (list): a two-item sequence with a U.S. Census\n bureau estimate and its margin of error.\n\n Returns:\n A two-item sequence containing the estimate and its approximate margin of error.\n\n (61393366, 202289)\n\n Examples:\n >>> approximate_product((74506512, 228238), (0.824, 0.001))\n (61393366, 202289)\n\n ... _official guidelines:\n https://www.documentcloud.org/documents/6177941-Acs-General-Handbook-2018-ch08.html#document/p8\n \"\"\"\n # Pull out the values\n estimate_one, moe_one = pair_one\n estimate_two, moe_two = pair_two\n\n # Approximate the product\n product_estimate = estimate_one * estimate_two\n\n # Approximate the margin of error\n squared_product_moe = (estimate_one**2 * moe_two**2) + (estimate_two**2 * moe_one**2)\n product_moe = math.sqrt(squared_product_moe)\n\n # Return the results\n return product_estimate, product_moe\n\n\ndef approximate_percentchange(pair_old, pair_new):\n \"\"\"\n Calculates the percent change between two estimates and approximates its margin of error.\n\n Multiplies results by 100.\n\n Follows the U.S. Census Bureau's `official guidelines`_.\n\n Args:\n pair_old (list): a two-item sequence with an earlier U.S. Census\n bureau estimate and its margin of error.\n\n pair_new (list): a two-item sequence with a later U.S. Census\n bureau estimate and its margin of error.\n\n Returns:\n A two-item sequence containing the estimate and its approximate margin of error.\n\n (61393366, 202289)\n\n Examples:\n The change of percentage of single women in suburban Virginia,\n taken from the bureau's official example as well as data `gathered elsewhere`_.\n\n >>> approximate_percentchange((135173, 3860), (139301, 4047))\n (3.0538643072211165, 4.198069852261231)\n\n ... _official guidelines:\n https://www.documentcloud.org/documents/6177941-Acs-General-Handbook-2018-ch08.html#document/p8\n ... _gathered elsewhere:\n https://www.fairfaxcounty.gov/demographics/sites/demographics/files/assets/acs/acs2017.pdf\n \"\"\"\n # Pull out the values\n estimate_old, moe_old = pair_old\n estimate_new, moe_new = pair_new\n\n # Approximate the percent change\n percent_change_estimate = ((estimate_new - estimate_old) / estimate_old) * 100\n\n # Approximate the margin of error\n percent_change_as_ratio = approximate_ratio(pair_new, pair_old)\n decimal_change_moe = percent_change_as_ratio[1]\n percent_change_moe = 100 * decimal_change_moe\n\n # Return the results\n return percent_change_estimate, percent_change_moe\n\n\ndef approximate_mean(range_list, simulations=50, pareto=False):\n \"\"\"\n Estimate a mean and approximate the margin of error.\n\n The Census Bureau guidelines do not provide instructions for\n approximating a mean using data from the ACS.\n\n Instead, we implement our own simulation-based approach.\n\n Due to the stochastic nature of the simulation approach, you will need to set\n a seed before running this function to ensure replicability.\n\n Note that this function expects you to submit a lower bound for the smallest\n bin and an upper bound for the largest bin. This is often not available for\n ACS datasets like income. We recommend experimenting with different\n lower and upper bounds to assess its effect on the resulting mean.\n\n Args:\n range_list (list): A list of dictionaries that divide the full range of data values into continuous categories.\n Each dictionary should have four keys:\n * min (int): The minimum value of the range\n * max (int): The maximum value of the range\n * n (int): The number of people, households or other units in the range\n * moe (float): The margin of error for n\n simulations (int): number of simulations to run, used to estimate margin of error. Defaults to 50.\n pareto (logical): Set True to use the Pareto distribution to simulate values in upper bin.\n Set False to assume a uniform distribution. Pareto is often appropriate for income. Defaults to False.\n\n Returns:\n A two-item tuple with the mean followed by the approximated margin of error.\n\n (774578.4565215431, 128.94103705296743)\n\n Examples:\n Estimating the mean for a range of household incomes.\n\n >>> income = [\n dict(min=0, max=9999, n=7942251, moe=17662),\n dict(min=10000, max=14999, n=5768114, moe=16409),\n dict(min=15000, max=19999, n=5727180, moe=16801),\n dict(min=20000, max=24999, n=5910725, moe=17864),\n dict(min=25000, max=29999, n=5619002, moe=16113),\n dict(min=30000, max=34999, n=5711286, moe=15891),\n dict(min=35000, max=39999, n=5332778, moe=16488),\n dict(min=40000, max=44999, n=5354520, moe=15415),\n dict(min=45000, max=49999, n=4725195, moe=16890),\n dict(min=50000, max=59999, n=9181800, moe=20965),\n dict(min=60000, max=74999, n=11818514, moe=30723),\n dict(min=75000, max=99999, n=14636046, moe=49159),\n dict(min=100000, max=124999, n=10273788, moe=47842),\n dict(min=125000, max=149999, n=6428069, moe=37952),\n dict(min=150000, max=199999, n=6931136, moe=37236),\n dict(min=200000, max=1000000, n=7465517, moe=42206)\n ]\n >>> approximate_mean(income)\n (98045.44530685373, 194.54892406267754)\n >>> approximate_mean(income, pareto=True)\n (60364.96525340687, 58.60735554621351)\n \"\"\"\n # Sort the list\n range_list.sort(key=lambda x: x['min'])\n\n if pareto: # need shape parameter if using Pareto distribution\n nb1 = range_list[-2]['n'] # number in second to last bin\n nb = range_list[-1]['n'] # number in last bin\n lb1 = range_list[-2]['min'] # lower bound of second to last bin\n lb = range_list[-1]['min'] # lower bound of last bin\n alpha_hat = (numpy.log(nb1 + nb) - numpy.log(nb)) / (numpy.log(lb) - numpy.log(lb1)) # shape parameter for Pareto\n\n simulation_results = []\n for i in range(simulations):\n simulated_values = []\n simulated_n = []\n # loop through every bin except the last one\n for range_ in range_list[:-1]:\n se = range_['moe'] / 1.645 # convert moe to se\n nn = round(numpy.random.normal(range_['n'], se)) # use moe to introduce randomness into number in bin\n nn = int(nn) # clean it up\n simulated_values.append(numpy.random.uniform(range_['min'], range_['max'], size=(1, nn)).sum()) # draw random values within the bin, assume uniform\n simulated_n.append(nn)\n # a special case to handle the last bin\n if pareto:\n last = range_list[-1]\n se = last['moe'] / 1.645 # convert moe to se\n nn = round(numpy.random.normal(last['n'], se)) # use moe to introduce randomness into number in bin\n nn = int(nn) # clean it up\n simulated_values.append(numpy.random.pareto(a=alpha_hat, size=(1, nn)).sum()) # draw random values within the bin, assume uniform\n simulated_n.append(nn)\n # use uniform otherwise\n else:\n last = range_list[-1]\n se = last['moe'] / 1.645 # convert moe to se\n nn = round(numpy.random.normal(last['n'], se)) # use moe to introduce randomness into number in bin\n nn = int(nn) # clean it up\n simulated_values.append(numpy.random.uniform(last['min'], last['max'], size=(1, nn)).sum()) # draw random values within the bin, assume uniform\n simulated_n.append(nn)\n simulation_results.append(sum(simulated_values) / sum(simulated_n)) # calculate mean for replicate\n\n estimated_mean = numpy.mean(simulation_results) # calculate overall mean\n moe_right = numpy.quantile(simulation_results, 0.95) - estimated_mean # go from confidence interval to margin of error\n moe_left = estimated_mean - numpy.quantile(simulation_results, 0.05) # go from confidence interval to margin of error\n margin_of_error = max(moe_left, moe_right) # if asymmetrical take bigger one, conservative\n\n # Return the result\n return estimated_mean, margin_of_error\n" ]
[ [ "numpy.log", "numpy.random.pareto", "numpy.quantile", "numpy.random.normal", "numpy.mean", "numpy.random.uniform" ] ]
valley-joker/zvt
[ "7147725c6350adda54b95c3c40f5e70ce459e08a" ]
[ "zvt/recorders/joinquant/meta/stock_trade_day_recorder.py" ]
[ "# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom jqdatapy.api import get_trade_days\n\nfrom zvt.contract.api import df_to_db\nfrom zvt.contract.recorder import TimeSeriesDataRecorder\nfrom zvt.domain import StockTradeDay, Stock\nfrom zvt.utils.time_utils import to_time_str\n\n\nclass StockTradeDayRecorder(TimeSeriesDataRecorder):\n entity_provider = 'joinquant'\n entity_schema = Stock\n\n provider = 'joinquant'\n data_schema = StockTradeDay\n\n def __init__(self, entity_type='stock', exchanges=['sh', 'sz'], entity_ids=None, codes=None, day_data=False,\n batch_size=10, force_update=False, sleeping_time=5, default_size=2000, real_time=False,\n fix_duplicate_way='add', start_timestamp=None, end_timestamp=None, close_hour=0, close_minute=0,\n entity_filters=None) -> None:\n super().__init__(entity_type, exchanges, entity_ids, ['000001'], day_data, batch_size, force_update,\n sleeping_time, default_size, real_time, fix_duplicate_way, start_timestamp, end_timestamp,\n close_hour, close_minute, entity_filters)\n\n def record(self, entity, start, end, size, timestamps):\n df = pd.DataFrame()\n dates = get_trade_days(date=to_time_str(start))\n dates = dates.iloc[:, 0]\n self.logger.info(f'add dates:{dates}')\n df['timestamp'] = pd.to_datetime(dates)\n df['id'] = [to_time_str(date) for date in dates]\n df['entity_id'] = 'stock_sz_000001'\n\n df_to_db(df=df, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update)\n\n\nif __name__ == '__main__':\n r = StockTradeDayRecorder()\n r.run()\n# the __all__ is generated\n__all__ = ['StockTradeDayRecorder']\n" ]
[ [ "pandas.to_datetime", "pandas.DataFrame" ] ]
MithellScott/Dyse-Robotics
[ "625787f97845c4cd883617b3cc32c2419dd88a73" ]
[ "src/dyse-robots/arman_control/scripts/Arm.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom Transformer import Transformer\nfrom mpl_toolkits.mplot3d import Axes3D\n\nclass Arm:\n\tdef __init__(self, init_joint_poses=None, motor_spin=[1,1,-1,-1,1], restrictions=None, default_joint_angles=[90, 135, 45, 0, 90]):\n\t\tif init_joint_poses is None:\n\t\t\t# values are approximations for development purposes\n\t\t\tself.init_joint_poses = np.array([[0, 0, 2, np.pi/2, 0, 0],\n\t\t\t\t\t\t\t\t\t\t\t [11.5, 0, 0, 0, 0, np.pi],\n\t\t\t\t\t\t\t\t\t\t\t [0, -5.75, 0, 0, 0, 3 * np.pi / 4],\n\t\t\t\t\t\t\t\t\t\t\t [-6, -3.5, 0, np.pi, -np.pi/2, 0]\n\t\t\t\t\t\t\t\t\t\t\t ]) \n\t\telse:\n\t\t\tself.init_joint_poses = init_joint_poses\n\t\t\t\n\t\t# evironment dimensions\n\t\tself.envDim = 3\n\t\t# number of joints\n\t\tself.nJoints = len(self.init_joint_poses) + 1\n\t\t\n\t\t# an empty set of transformers\n\t\tself.autobots = []\n\t\t\n\t\tself.spin = motor_spin\n\t\t\n\t\t# initialize state constraints and objects\n\t\tself.j_rstr = np.zeros((self.nJoints, 2))\n\t\tself.poseActual = np.zeros((self.nJoints))\n\t\tself.joint_poses = np.zeros((self.nJoints, self.envDim))\n\t\t\n\t\tself.set_restrictions(restrictions)\n\t\tself.adjust_joints(default_joint_angles)\n\t\t\n\t\t# update kinematics\n\t\tself.forward_IK()\n\t\t\n\tdef build_transformers(self):\n\t\t# the base joint is defined as the world origin\n\t\tself.autobots = []\n\t\tprev_tf = None\n\t\tfor i,joint in enumerate(self.init_joint_poses):\n\t\t\ttrns = Transformer(0.0, 0.0, np.radians(self.poseActual[i]) * self.spin[i], 'temp', protocol=['psi']) \n\t\t\ttranslationActual = trns.transform(joint[:3], inverse=True)\n\t\t\ttf = Transformer(joint[3], joint[4], joint[5] + np.radians(self.poseActual[i]) * self.spin[i], f'Joint{i+1}',translation=translationActual, parent=prev_tf)\n\t\t\tif not prev_tf is None:\n\t\t\t\tself.autobots[-1].child = tf\n\t\t\tself.autobots.append(tf)\n\t\t\tprev_tf = tf\n\t\t\n\tdef set_restrictions(self, restrictions):\n\t\tif restrictions is None:\n\t\t\t# default Arman joint restrictions\n\t\t\tassert 5 == self.nJoints, 'set_restrictions requested: failed, number of joints is not 5(default)'\n\t\t\tself.j_rstr = np.array([[0, 180],[45, 135],[0, 135],[0, 135],[0, 180]])\n\t\telse:\n\t\t\tassert len(restrictions) == self.nJoints, f'set_restrictions requested: failed, restrictions set length {len(restrictions)} != {self.nJoints}'\n\t\t\tself.j_rstr = restrictions\n\t\n\tdef forward_IK(self):\n\t\t# update the transformers\n\t\tself.build_transformers()\n\t\t# Calculate the new joint poses.\n\t\t# Passing [0.0,0.0,0.0] to transform\n\t\t# will return the origin of that frame \n\t\t# in parent coords.\n\t\tfor i in range(self.nJoints-1, 0, -1):\n\t\t\ttf = self.autobots[i-1]\n\t\t\tpoint = np.array([0.0, 0.0, 0.0])\n\t\t\twhile not tf is None:\n\t\t\t\tpoint = tf.transform(point, inverse=True)\n\t\t\t\ttf = tf.parent\n\t\t\tself.joint_poses[i] = point\n\t\t\t\n\tdef adjust_joints(self, adjustments):\n\t\tassert len(adjustments) == self.nJoints, f'Angle adjustment requested: joint angle set shape mismatch {np.array(adjustments).shape} -> {self.nJoints}'\n\t\t# make sure no angle adjustments contradict valid configurations\n\t\tfor i,joint in enumerate(self.poseActual):\n\t\t\tself.poseActual[i] = max(self.j_rstr[i][0], min(joint + adjustments[i], self.j_rstr[i][1]))\n\t\tself.forward_IK()\n\t\t\n\tdef set_joints(self, poses):\n\t\tassert len(poses) == self.nJoints, f'Angle set requested: joint angle set shape mismatch {np.array(pose).shape} -> {self.nJoints}'\n\t\t# make sure no angle adjustments contradict valid configurations\n\t\tfor i in range(self.nJoints):\n\t\t\tself.poseActual[i] = max(self.j_rstr[i][0], min(poses[i], self.j_rstr[i][1]))\n\t\tself.forward_IK()\n\nclass Renderer:\n\tdef __init__(self):\n\t\tself.verbose = True\n\t\tself.visualize = True\n\n\tdef draw(self, joint_poses):\n\t\tax = plt.subplot(111, projection='3d')\n\t\tax.axes.set_xlim3d(left=-20, right=20) \n\t\tax.axes.set_xlabel('X')\n\t\tax.axes.set_ylim3d(bottom=-20, top=20) \n\t\tax.axes.set_ylabel('Y')\n\t\tax.axes.set_zlim3d(bottom=0, top=40) \n\t\torigins = [[0],[0],[0]]\n\t\tfor pose in joint_poses:\n\t\t\torigins[0].append(pose[0])\n\t\t\torigins[1].append(pose[1])\n\t\t\torigins[2].append(pose[2])\n\t\t\tax.scatter(pose[0], pose[1], pose[2], color='r', marker='x')\n\t\tax.plot(origins[0], origins[1], origins[2], color='c', alpha=0.6)\n\t\tplt.show()\n" ]
[ [ "numpy.radians", "matplotlib.pyplot.subplot", "numpy.array", "numpy.zeros", "matplotlib.pyplot.show" ] ]
houseofleft/Processing
[ "13e65c9ef5918c153ed83dcb44c4b53277f8bdd6" ]
[ "visuals/2021-python/outline_delaunay.py" ]
[ "import shades\nfrom random import randint\nfrom scipy.spatial import Delaunay\n\ncanvas = shades.Canvas(1000, 1000)\nink = shades.NoiseGradient(\n noise_fields=[shades.NoiseField(scale=0.002) for i in range(3)],\n color=(100,150,200)\n)\n\npoints = [(randint(50, canvas.width-50), randint(50, canvas.height-50)) for i in range(2000)]\n# plus some edge points to make sure the whole canvas is coloured\npoints += [(randint(50, canvas.width-50), 50) for i in range(10)]\npoints += [(50, randint(50, canvas.height-50)) for i in range(10)]\npoints += [(randint(50, canvas.width-50), canvas.height-50) for i in range(10)]\npoints += [(canvas.width-50, randint(50, canvas.height-50)) for i in range(10)]\npoints += [(50, 50), (50, canvas.height-50), (canvas.width-50, 50), (canvas.width-50, canvas.height-50)]\n\n# drawing triangles between points\nfor tri in Delaunay(points).simplices:\n ink.triangle_outline(\n canvas,\n points[tri[0]],\n points[tri[1]],\n points[tri[2]],\n 1\n )\n\ncanvas.show()\n" ]
[ [ "scipy.spatial.Delaunay" ] ]
evcu/meta-dataset
[ "bca9dd3964c908b607e8ff64628d5f1afa43386c" ]
[ "meta_dataset/analysis/select_best_model.py" ]
[ "# coding=utf-8\n# Copyright 2019 The Meta-Dataset Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python2, python3\nr\"\"\"A script for choosing the best variant of a model automatically.\n\nIt takes as input the root directory of all experiments, and a list of names of\ndirectories in that root, each storing the data of an experiment with multiple\nvariants accross which we want to select the best. Each experiment directory\nshould contain a directoy named 'summaries' that hosts subdirectories for the\ndifferent runs with each one containing event files. These event files are read\nto figure out which is best in terms of mean validation accuracy, and at which\nstep of that run this best value occurs in.\n\nFor each of the experiment directories provided, the output information is saved\nin a 'best.pklz' file in that directory. This file contains a dict with keys\n'best_variant', 'best_valid_acc', and 'best_update_num' where the name of the\nvariant is simply the name of the sub-directory corresponding to that variant.\n\nExample directory structure (after the script is ran):\nRoot contains: 'Exp1', 'Exp2'.\n Exp1 contains: 'checkpoints', 'summaries', and best.pklz\n summaries contains: '1', '2', '3', ..., '20'\n '1' contains event files\n '2' contains event files\n ...\n '20' contains event files\n\nSample command:\n# pylint: disable=line-too-long\npython -m meta_dataset.analysis.select_best_model \\\n --alsologtostderr \\\n --all_experiments_root=<experiments_root> \\\n --experiment_dir_basenames=baseline_imagenet_icml2019_1/3602170,baselinefinetune_imagenet_icml2019_1/3581340\n# pylint: enable=line-too-long\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport numpy as np\nfrom six.moves import range\nfrom six.moves import zip\nimport six.moves.cPickle as pkl\nimport tensorflow as tf\n\nFLAGS = tf.flags.FLAGS\n\ntf.flags.DEFINE_string(\n 'all_experiments_root',\n '',\n 'The overall experiments directory root.')\n\ntf.flags.DEFINE_string(\n 'experiment_dir_basenames', ''\n 'baseline_imagenet_icml2019_1/3602170,'\n 'baselinefinetune_imagenet_icml2019_1/3581340',\n 'A comma-separated list of directory basenames. Adding each basename as a '\n 'suffix to FLAGS.all_experiments_root forms a path that stores the data of '\n 'an experiment with multiple variants accross which we want to select the '\n 'best. Each such path is expected to host a directory named \"summaries\" '\n 'that contains subdirectories for the different runs with each such '\n 'subdirectory containing event files.')\n\n# TODO(etriantafillou): This assumes the variants to omit are the same for all\n# experiments that model selection will be ran for which doesn't make much\n# sense. Maybe just remove this altogether?\ntf.flags.DEFINE_string(\n 'restrict_to_variants', '', 'A comma-separated list of '\n 'variants to restrict to for model selection. This is '\n 'useful for example for finding the best out of all '\n 'variants that use a specific embedding or image size.')\n\ntf.flags.DEFINE_string(\n 'restrict_to_variants_by_range', '', 'A comma-separated list of '\n 'two integers that represent the start and end range (both inclusive) '\n 'of variant ids to restrict to.')\n\ntf.flags.DEFINE_string(\n 'description', 'best', 'The description for the output. The output will '\n 'then be named as description.pklz and description.txt. For example, this '\n 'can be used to reflect that some variants were omitted.')\n\n# The following two flags assume that the parameters of the experiments have\n# been logged (they attempt to read from them). If this is not the case, the\n# restrict_to_variants flag should be used instead.\ntf.flags.DEFINE_string(\n 'restrict_to_architectures', '', 'The comma-separated names of the '\n 'embedding networks to restrict to for model selection.')\n\ntf.flags.DEFINE_enum(\n 'restrict_to_pretrained_source', '', ['', 'scratch', 'imagenet'],\n 'The name of a pretrained_source to '\n 'restrict to for model selection.')\n\n\ndef get_value_from_pkl(pickle_file, param_name):\n \"\"\"Gets the value associated with param_name in the given pickle file.\"\"\"\n if tf.gfile.Exists(pickle_file):\n with tf.gfile.Open(pickle_file, 'rb') as f:\n params = pkl.load(f)\n if param_name not in params:\n tf.logging.info('The dict in {} does not have the key {}'.format(\n pickle_file, param_name))\n return None\n else:\n return params[param_name]\n else:\n tf.logging.info('The file {} does not exist'.format(pickle_file))\n return None\n\n\ndef get_paths_to_events(root_dir,\n restrict_to_architectures,\n restrict_to_pretrained_source,\n restrict_to_variants=None):\n \"\"\"Returns a dict that maps each variant name to its event file.\n\n The name of the variant is the basename of the directory where it's stored.\n Assumes the following directory organization root_dir contains a sub-directory\n for every variant where event files can be found.\n\n There may be more than one event file for each variant, e.g. a new one will be\n created upon restarting an experiment that was pre-empted. So later event\n files contain the summaries for larger values of 'step'. We need all of them\n for determining the global 'best'.\n\n Args:\n root_dir: A str. The root directory of experiments of all models variants.\n restrict_to_architectures: A list of names of architectures to restrict to\n when choosing the best variant.\n restrict_to_pretrained_source: A string. The pretrained_source to restrict\n to when choosing the best variant.\n restrict_to_variants: Optionally, a set of variant names to restrict to.\n \"\"\"\n params_dir = os.path.join(root_dir, 'params')\n summary_dir = os.path.join(root_dir, 'summaries')\n\n def get_variant_architecture(name):\n \"\"\"Get the architecture of the given variant if it's recorded, o/w None.\"\"\"\n variant_params_dir = os.path.join(params_dir, name)\n variant_params_file = os.path.join(variant_params_dir, 'params.pkl')\n return get_value_from_pkl(variant_params_file,\n '_gin.LearnerConfig.embedding_network')\n\n def get_variant_pretrained_source(name):\n variant_params_dir = os.path.join(params_dir, name)\n variant_params_file = os.path.join(variant_params_dir, 'params.pkl')\n return get_value_from_pkl(variant_params_file,\n '_gin.LearnerConfig.pretrained_source')\n\n def keep_variant(name):\n \"\"\"Determine if the variant in directory name should be considered.\"\"\"\n value_error_msg = (\n 'Requested to restrict to an architecture or '\n 'pretrained_source but the given experiment does not '\n 'have its params recorded. Looked in: {}'.format(params_dir))\n\n if restrict_to_architectures:\n architecture = get_variant_architecture(name)\n if architecture is None:\n raise ValueError(value_error_msg)\n valid_architecture = (not restrict_to_architectures or\n architecture in restrict_to_architectures)\n\n if restrict_to_pretrained_source:\n pretrained_source = get_variant_pretrained_source(name)\n if pretrained_source is None:\n raise ValueError(value_error_msg)\n valid_pretrained_source = (\n not restrict_to_pretrained_source or\n pretrained_source == restrict_to_pretrained_source)\n\n valid_variant_name = True\n if restrict_to_variants is not None:\n valid_variant_name = name in restrict_to_variants\n\n return (valid_architecture and valid_pretrained_source and\n valid_variant_name)\n\n variant_names = [\n fname for fname in tf.gfile.ListDirectory(summary_dir)\n if tf.gfile.IsDirectory(os.path.join(summary_dir, fname))\n ]\n\n # Further filter variant names based on the given restrictions.\n variant_names = [name for name in variant_names if keep_variant(name)]\n\n if not variant_names:\n raise ValueError('Found no subdirectories in {}. Was expecting a '\n 'subdirectory per variant.'.format(summary_dir))\n variant_paths = [\n os.path.join(summary_dir, variant_dir) for variant_dir in variant_names\n ]\n\n event_paths = {}\n for variant_path, variant_name in zip(variant_paths, variant_names):\n event_filenames = [\n f_name for f_name in tf.gfile.ListDirectory(variant_path)\n if f_name.startswith('events.out.tfevents')\n ]\n\n if len(event_filenames) < 1:\n tf.logging.warn('Skipping empty variant {}.'.format(variant_path))\n tf.logging.info('Was expecting at least one event file '\n 'in directory {}. Instead, found {}.'.format(\n variant_path, len(event_filenames)))\n continue\n event_paths[variant_name] = [\n os.path.join(variant_path, event_filename)\n for event_filename in event_filenames\n ]\n\n tf.logging.info('Found event files for variants: {}'.format(\n list(event_paths.keys())))\n return event_paths\n\n\ndef extract_best_from_event_file(event_path):\n \"\"\"Returns the best accuracy and the step it occurs in in the given events.\n\n This searches the summaries written in a given event file, which may be only a\n subset of the total summaries of a run, since the summaries of a run are\n sometimes split into multiple event files.\n\n Args:\n event_path: A string. The path to an event file.\n \"\"\"\n steps, valid_accs = [], []\n for event in tf.train.summary_iterator(event_path):\n step = event.step\n for value in event.summary.value:\n if value.tag == 'mean valid acc':\n steps.append(step)\n valid_accs.append(value.simple_value)\n argmax_ind = np.argmax(valid_accs)\n best_acc = valid_accs[argmax_ind]\n best_step = steps[argmax_ind]\n return best_acc, best_step\n\n\ndef extract_best_from_variant(event_paths):\n \"\"\"Returns the best accuracy and the step it occurs in for the given run.\n\n Args:\n event_paths: A list of strings. The event files of the given run.\n \"\"\"\n best_acc = -1\n for event_path in event_paths:\n best_acc_, best_step_ = extract_best_from_event_file(event_path)\n if best_acc_ > best_acc:\n best_acc = best_acc_\n best_step = best_step_\n return best_acc, best_step\n\n\ndef main(argv):\n del argv\n experiment_paths = [\n os.path.join(FLAGS.all_experiments_root, basename)\n for basename in FLAGS.experiment_dir_basenames.split(',')\n ]\n # Perform model selection for each provided experiment root.\n for root_experiment_dir in experiment_paths:\n stars_string = '**************************************\\n'\n architecture_string = ''\n if FLAGS.restrict_to_architectures:\n architecture_string = ' out of the {} variants'.format(\n FLAGS.restrict_to_architectures)\n tf.logging.info('{}Selecting the best variant for: {}{}.{}'.format(\n stars_string, root_experiment_dir, architecture_string, stars_string))\n\n if FLAGS.restrict_to_variants_by_range and FLAGS.restrict_to_variants:\n raise ValueError('Please provide only one of '\n 'FLAGS.restrict_to_variants_by_range and '\n 'FLAGS.restrict_to_variants, not both.')\n\n restrict_to_variants = None\n if FLAGS.restrict_to_variants_by_range:\n start, end = FLAGS.restrict_to_variants_by_range.split(',')\n start, end = int(start), int(end)\n restrict_to_variants = set(\n [str(variant_id) for variant_id in range(start, end + 1)])\n if FLAGS.restrict_to_variants:\n restrict_to_variants = set(FLAGS.restrict_to_variants.split(','))\n\n restrict_to_architectures = []\n if FLAGS.restrict_to_architectures:\n restrict_to_architectures = FLAGS.restrict_to_architectures.split(',')\n\n event_paths = get_paths_to_events(\n root_experiment_dir,\n restrict_to_architectures,\n FLAGS.restrict_to_pretrained_source,\n restrict_to_variants=restrict_to_variants)\n # Read the event file of each variant to find the highest mean validation\n # accuracy reached with it.\n best_variant = ''\n best_valid_acc = -1\n best_step = -1\n for variant_name, event_path in event_paths.items():\n best_valid_acc_, best_step_ = extract_best_from_variant(event_path)\n if best_valid_acc_ > best_valid_acc:\n best_variant = variant_name\n best_valid_acc = best_valid_acc_\n best_step = best_step_\n\n output_dict = {\n 'best_variant': best_variant,\n 'best_valid_acc': best_valid_acc,\n 'best_update_num': best_step\n }\n\n # Create a more informative description if necessary.\n description = FLAGS.description\n if FLAGS.restrict_to_architectures and FLAGS.description == 'best':\n description += '_{}'.format(FLAGS.restrict_to_architectures)\n\n if (FLAGS.restrict_to_pretrained_source and FLAGS.description == 'best'):\n if FLAGS.restrict_to_pretrained_source == 'scratch':\n description += '_trained_from_scratch'\n else:\n description += '_pretrained_on_{}'.format(\n FLAGS.restrict_to_pretrained_source)\n\n output_path_pklz = os.path.join(root_experiment_dir,\n '{}.pklz'.format(description))\n with tf.gfile.Open(output_path_pklz, 'wb') as f:\n pkl.dump(output_dict, f, protocol=pkl.HIGHEST_PROTOCOL)\n\n # Also write this info as a .txt file for easier reading.\n output_path_txt = os.path.join(root_experiment_dir,\n '{}.txt'.format(description))\n with tf.gfile.Open(output_path_txt, 'w') as f:\n f.write(\n 'best_variant: {}\\nbest_valid_acc: {}\\nbest_update_num: {}\\n'.format(\n best_variant, best_valid_acc, best_step))\n tf.logging.info(\n 'Best variant: {}. Best valid acc: {}. Best update num: {}. '\n 'Just wrote this info to {} and {}'.format(best_variant, best_valid_acc,\n best_step, output_path_pklz,\n output_path_txt))\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run(main)\n" ]
[ [ "tensorflow.gfile.ListDirectory", "tensorflow.gfile.Open", "tensorflow.flags.DEFINE_string", "tensorflow.gfile.Exists", "numpy.argmax", "tensorflow.train.summary_iterator", "tensorflow.logging.set_verbosity", "tensorflow.flags.DEFINE_enum", "tensorflow.app.run" ] ]
jdye64/cudf
[ "a02f888badcd9cf7f81a0e32605f51d51085311f" ]
[ "python/cudf/cudf/core/column/timedelta.py" ]
[ "# Copyright (c) 2020-2021, NVIDIA CORPORATION.\n\nfrom __future__ import annotations\n\nimport datetime as dt\nfrom numbers import Number\nfrom typing import Any, Sequence, Tuple, Union, cast\n\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\n\nimport cudf\nfrom cudf import _lib as libcudf\nfrom cudf._typing import (\n BinaryOperand,\n DatetimeLikeScalar,\n Dtype,\n DtypeObj,\n ScalarLike,\n)\nfrom cudf.core.buffer import Buffer\nfrom cudf.core.column import ColumnBase, column, string\nfrom cudf.core.column.datetime import _numpy_to_pandas_conversion\nfrom cudf.utils.dtypes import is_scalar, np_to_pa_dtype\nfrom cudf.utils.utils import _fillna_natwise\n\n_dtype_to_format_conversion = {\n \"timedelta64[ns]\": \"%D days %H:%M:%S\",\n \"timedelta64[us]\": \"%D days %H:%M:%S\",\n \"timedelta64[ms]\": \"%D days %H:%M:%S\",\n \"timedelta64[s]\": \"%D days %H:%M:%S\",\n}\n\n\nclass TimeDeltaColumn(column.ColumnBase):\n \"\"\"\n Parameters\n ----------\n data : Buffer\n The Timedelta values\n dtype : np.dtype\n The data type\n size : int\n Size of memory allocation.\n mask : Buffer; optional\n The validity mask\n offset : int\n Data offset\n null_count : int, optional\n The number of null values.\n If None, it is calculated automatically.\n \"\"\"\n\n def __init__(\n self,\n data: Buffer,\n dtype: Dtype,\n size: int = None, # TODO: make non-optional\n mask: Buffer = None,\n offset: int = 0,\n null_count: int = None,\n ):\n dtype = cudf.dtype(dtype)\n\n if data.size % dtype.itemsize:\n raise ValueError(\"Buffer size must be divisible by element size\")\n if size is None:\n size = data.size // dtype.itemsize\n size = size - offset\n super().__init__(\n data,\n size=size,\n dtype=dtype,\n mask=mask,\n offset=offset,\n null_count=null_count,\n )\n\n if not (self.dtype.type is np.timedelta64):\n raise TypeError(f\"{self.dtype} is not a supported duration type\")\n\n self._time_unit, _ = np.datetime_data(self.dtype)\n\n def __contains__(self, item: DatetimeLikeScalar) -> bool:\n try:\n item = np.timedelta64(item, self._time_unit)\n except ValueError:\n # If item cannot be converted to duration type\n # np.timedelta64 raises ValueError, hence `item`\n # cannot exist in `self`.\n return False\n return item.view(\"int64\") in self.as_numerical\n\n @property\n def values(self):\n \"\"\"\n Return a CuPy representation of the TimeDeltaColumn.\n \"\"\"\n raise NotImplementedError(\n \"TimeDelta Arrays is not yet implemented in cudf\"\n )\n\n def to_arrow(self) -> pa.Array:\n mask = None\n if self.nullable:\n mask = pa.py_buffer(self.mask_array_view.copy_to_host())\n data = pa.py_buffer(self.as_numerical.data_array_view.copy_to_host())\n pa_dtype = np_to_pa_dtype(self.dtype)\n return pa.Array.from_buffers(\n type=pa_dtype,\n length=len(self),\n buffers=[mask, data],\n null_count=self.null_count,\n )\n\n def to_pandas(\n self, index=None, nullable: bool = False, **kwargs\n ) -> pd.Series:\n # Workaround until following issue is fixed:\n # https://issues.apache.org/jira/browse/ARROW-9772\n\n # Pandas supports only `timedelta64[ns]`, hence the cast.\n pd_series = pd.Series(\n self.astype(\"timedelta64[ns]\").to_array(\"NAT\"), copy=False\n )\n\n if index is not None:\n pd_series.index = index\n\n return pd_series\n\n def _binary_op_floordiv(\n self, rhs: BinaryOperand\n ) -> Tuple[\"column.ColumnBase\", BinaryOperand, DtypeObj]:\n lhs = self # type: column.ColumnBase\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n common_dtype = determine_out_dtype(self.dtype, rhs.dtype)\n lhs = lhs.astype(common_dtype).astype(\"float64\")\n if isinstance(rhs, cudf.Scalar):\n if rhs.is_valid():\n rhs = cudf.Scalar(\n np.timedelta64(rhs.value)\n .astype(common_dtype)\n .astype(\"float64\")\n )\n else:\n rhs = cudf.Scalar(None, \"float64\")\n else:\n rhs = rhs.astype(common_dtype).astype(\"float64\")\n out_dtype = cudf.dtype(\"int64\")\n elif rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Floor Division of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return lhs, rhs, out_dtype\n\n def _binary_op_mul(self, rhs: BinaryOperand) -> DtypeObj:\n if rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Multiplication of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n return out_dtype\n\n def _binary_op_mod(self, rhs: BinaryOperand) -> DtypeObj:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = determine_out_dtype(self.dtype, rhs.dtype)\n elif rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Modulus of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n return out_dtype\n\n def _binary_op_eq_ne(self, rhs: BinaryOperand) -> DtypeObj:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = np.bool_\n else:\n raise TypeError(\n f\"Equality of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n return out_dtype\n\n def _binary_op_lt_gt_le_ge(self, rhs: BinaryOperand) -> DtypeObj:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n return np.bool_\n else:\n raise TypeError(\n f\"Invalid comparison between dtype={self.dtype}\"\n f\" and {rhs.dtype}\"\n )\n\n def _binary_op_truediv(\n self, rhs: BinaryOperand\n ) -> Tuple[\"column.ColumnBase\", BinaryOperand, DtypeObj]:\n lhs = self # type: column.ColumnBase\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n common_dtype = determine_out_dtype(self.dtype, rhs.dtype)\n lhs = lhs.astype(common_dtype).astype(\"float64\")\n if isinstance(rhs, cudf.Scalar):\n if rhs.is_valid():\n rhs = rhs.value.astype(common_dtype).astype(\"float64\")\n else:\n rhs = cudf.Scalar(None, \"float64\")\n else:\n rhs = rhs.astype(common_dtype).astype(\"float64\")\n\n out_dtype = cudf.dtype(\"float64\")\n elif rhs.dtype.kind in (\"f\", \"i\", \"u\"):\n out_dtype = self.dtype\n else:\n raise TypeError(\n f\"Division of {self.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return lhs, rhs, out_dtype\n\n def binary_operator(\n self, op: str, rhs: BinaryOperand, reflect: bool = False\n ) -> \"column.ColumnBase\":\n lhs, rhs = self, rhs\n\n if op in (\"eq\", \"ne\"):\n out_dtype = self._binary_op_eq_ne(rhs)\n elif op in (\"lt\", \"gt\", \"le\", \"ge\", \"NULL_EQUALS\"):\n out_dtype = self._binary_op_lt_gt_le_ge(rhs)\n elif op == \"mul\":\n out_dtype = self._binary_op_mul(rhs)\n elif op == \"mod\":\n out_dtype = self._binary_op_mod(rhs)\n elif op == \"truediv\":\n lhs, rhs, out_dtype = self._binary_op_truediv(rhs) # type: ignore\n elif op == \"floordiv\":\n lhs, rhs, out_dtype = self._binary_op_floordiv(rhs) # type: ignore\n op = \"truediv\"\n elif op == \"add\":\n out_dtype = _timedelta_add_result_dtype(lhs, rhs)\n elif op == \"sub\":\n out_dtype = _timedelta_sub_result_dtype(lhs, rhs)\n else:\n raise TypeError(\n f\"Series of dtype {self.dtype} cannot perform \"\n f\"the operation {op}\"\n )\n\n if reflect:\n lhs, rhs = rhs, lhs # type: ignore\n\n return libcudf.binaryop.binaryop(lhs, rhs, op, out_dtype)\n\n def normalize_binop_value(self, other) -> BinaryOperand:\n if isinstance(other, cudf.Scalar):\n return other\n\n if isinstance(other, np.ndarray) and other.ndim == 0:\n other = other.item()\n\n if isinstance(other, dt.timedelta):\n other = np.timedelta64(other)\n elif isinstance(other, pd.Timestamp):\n other = other.to_datetime64()\n elif isinstance(other, pd.Timedelta):\n other = other.to_timedelta64()\n if isinstance(other, np.timedelta64):\n other_time_unit = cudf.utils.dtypes.get_time_unit(other)\n if np.isnat(other):\n return cudf.Scalar(None, dtype=self.dtype)\n\n if other_time_unit not in (\"s\", \"ms\", \"ns\", \"us\"):\n other = other.astype(\"timedelta64[s]\")\n else:\n common_dtype = determine_out_dtype(self.dtype, other.dtype)\n other = other.astype(common_dtype)\n return cudf.Scalar(other)\n elif np.isscalar(other):\n return cudf.Scalar(other)\n elif other is None:\n return cudf.Scalar(other, dtype=self.dtype)\n else:\n raise TypeError(f\"cannot normalize {type(other)}\")\n\n @property\n def as_numerical(self) -> \"cudf.core.column.NumericalColumn\":\n return cast(\n \"cudf.core.column.NumericalColumn\",\n column.build_column(\n data=self.base_data,\n dtype=np.int64,\n mask=self.base_mask,\n offset=self.offset,\n size=self.size,\n ),\n )\n\n def default_na_value(self) -> ScalarLike:\n \"\"\"Returns the default NA value for this column\n \"\"\"\n return np.timedelta64(\"nat\", self.time_unit)\n\n @property\n def time_unit(self) -> str:\n return self._time_unit\n\n def fillna(\n self, fill_value: Any = None, method: str = None, dtype: Dtype = None\n ) -> TimeDeltaColumn:\n if fill_value is not None:\n if cudf.utils.utils._isnat(fill_value):\n return _fillna_natwise(self)\n col = self # type: column.ColumnBase\n if is_scalar(fill_value):\n if isinstance(fill_value, np.timedelta64):\n dtype = determine_out_dtype(self.dtype, fill_value.dtype)\n fill_value = fill_value.astype(dtype)\n col = col.astype(dtype)\n if not isinstance(fill_value, cudf.Scalar):\n fill_value = cudf.Scalar(fill_value, dtype=dtype)\n else:\n fill_value = column.as_column(fill_value, nan_as_null=False)\n return cast(TimeDeltaColumn, ColumnBase.fillna(col, fill_value))\n else:\n return super().fillna(method=method)\n\n def as_numerical_column(\n self, dtype: Dtype, **kwargs\n ) -> \"cudf.core.column.NumericalColumn\":\n return cast(\n \"cudf.core.column.NumericalColumn\", self.as_numerical.astype(dtype)\n )\n\n def as_datetime_column(\n self, dtype: Dtype, **kwargs\n ) -> \"cudf.core.column.DatetimeColumn\":\n raise TypeError(\n f\"cannot astype a timedelta from [{self.dtype}] to [{dtype}]\"\n )\n\n def as_string_column(\n self, dtype: Dtype, format=None, **kwargs\n ) -> \"cudf.core.column.StringColumn\":\n if format is None:\n format = _dtype_to_format_conversion.get(\n self.dtype.name, \"%D days %H:%M:%S\"\n )\n if len(self) > 0:\n return string._timedelta_to_str_typecast_functions[\n cudf.dtype(self.dtype)\n ](self, format=format)\n else:\n return cast(\n \"cudf.core.column.StringColumn\",\n column.column_empty(0, dtype=\"object\", masked=False),\n )\n\n def as_timedelta_column(self, dtype: Dtype, **kwargs) -> TimeDeltaColumn:\n dtype = cudf.dtype(dtype)\n if dtype == self.dtype:\n return self\n return libcudf.unary.cast(self, dtype=dtype)\n\n def mean(self, skipna=None, dtype: Dtype = np.float64) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.mean(skipna=skipna, dtype=dtype),\n unit=self.time_unit,\n )\n\n def median(self, skipna: bool = None) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.median(skipna=skipna), unit=self.time_unit\n )\n\n def isin(self, values: Sequence) -> ColumnBase:\n return cudf.core.tools.datetimes._isin_datetimelike(self, values)\n\n def quantile(\n self, q: Union[float, Sequence[float]], interpolation: str, exact: bool\n ) -> \"column.ColumnBase\":\n result = self.as_numerical.quantile(\n q=q, interpolation=interpolation, exact=exact\n )\n if isinstance(q, Number):\n return pd.Timedelta(result, unit=self.time_unit)\n return result.astype(self.dtype)\n\n def sum(\n self, skipna: bool = None, dtype: Dtype = None, min_count=0\n ) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.sum(\n skipna=skipna, dtype=dtype, min_count=min_count\n ),\n unit=self.time_unit,\n )\n\n def std(\n self, skipna: bool = None, ddof: int = 1, dtype: Dtype = np.float64\n ) -> pd.Timedelta:\n return pd.Timedelta(\n self.as_numerical.std(skipna=skipna, ddof=ddof, dtype=dtype),\n unit=self.time_unit,\n )\n\n def components(self, index=None) -> \"cudf.DataFrame\":\n \"\"\"\n Return a Dataframe of the components of the Timedeltas.\n\n Returns\n -------\n DataFrame\n\n Examples\n --------\n >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='s'))\n >>> s = cudf.Series([12231312123, 1231231231, 1123236768712, 2135656,\n ... 3244334234], dtype='timedelta64[ms]')\n >>> s\n 0 141 days 13:35:12.123\n 1 14 days 06:00:31.231\n 2 13000 days 10:12:48.712\n 3 0 days 00:35:35.656\n 4 37 days 13:12:14.234\n dtype: timedelta64[ms]\n >>> s.dt.components\n days hours minutes seconds milliseconds microseconds nanoseconds\n 0 141 13 35 12 123 0 0\n 1 14 6 0 31 231 0 0\n 2 13000 10 12 48 712 0 0\n 3 0 0 35 35 656 0 0\n 4 37 13 12 14 234 0 0\n \"\"\" # noqa: E501\n\n return cudf.DataFrame(\n data={\n \"days\": self\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n ),\n \"hours\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"h\"], \"ns\")\n ),\n \"minutes\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"h\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"m\"], \"ns\")\n ),\n \"seconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"m\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n ),\n \"milliseconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ms\"], \"ns\")\n ),\n \"microseconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ms\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n ),\n \"nanoseconds\": (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n )\n )\n // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ns\"], \"ns\")\n ),\n },\n index=index,\n )\n\n @property\n def days(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Number of days for each element.\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n return self // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n )\n\n @property\n def seconds(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Number of seconds (>= 0 and less than 1 day).\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n # This property must return the number of seconds (>= 0 and\n # less than 1 day) for each element, hence first performing\n # mod operation to remove the number of days and then performing\n # division operation to extract the number of seconds.\n\n return (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"D\"], \"ns\")\n )\n ) // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n )\n\n @property\n def microseconds(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Number of microseconds (>= 0 and less than 1 second).\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n # This property must return the number of microseconds (>= 0 and\n # less than 1 second) for each element, hence first performing\n # mod operation to remove the number of seconds and then performing\n # division operation to extract the number of microseconds.\n\n return (\n self % np.timedelta64(_numpy_to_pandas_conversion[\"s\"], \"ns\")\n ) // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n )\n\n @property\n def nanoseconds(self) -> \"cudf.core.column.NumericalColumn\":\n \"\"\"\n Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.\n\n Returns\n -------\n NumericalColumn\n \"\"\"\n # This property must return the number of nanoseconds (>= 0 and\n # less than 1 microsecond) for each element, hence first performing\n # mod operation to remove the number of microseconds and then\n # performing division operation to extract the number\n # of nanoseconds.\n\n return (\n self\n % cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"us\"], \"ns\")\n )\n ) // cudf.Scalar(\n np.timedelta64(_numpy_to_pandas_conversion[\"ns\"], \"ns\")\n )\n\n\ndef determine_out_dtype(lhs_dtype: Dtype, rhs_dtype: Dtype) -> Dtype:\n if np.can_cast(np.dtype(lhs_dtype), np.dtype(rhs_dtype)):\n return rhs_dtype\n elif np.can_cast(np.dtype(rhs_dtype), np.dtype(lhs_dtype)):\n return lhs_dtype\n else:\n raise TypeError(f\"Cannot type-cast {lhs_dtype} and {rhs_dtype}\")\n\n\ndef _timedelta_add_result_dtype(\n lhs: BinaryOperand, rhs: BinaryOperand\n) -> Dtype:\n if pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = determine_out_dtype(lhs.dtype, rhs.dtype)\n elif pd.api.types.is_datetime64_dtype(rhs.dtype):\n units = [\"s\", \"ms\", \"us\", \"ns\"]\n lhs_time_unit = cudf.utils.dtypes.get_time_unit(lhs)\n lhs_unit = units.index(lhs_time_unit)\n rhs_time_unit = cudf.utils.dtypes.get_time_unit(rhs)\n rhs_unit = units.index(rhs_time_unit)\n out_dtype = cudf.dtype(f\"datetime64[{units[max(lhs_unit, rhs_unit)]}]\")\n else:\n raise TypeError(\n f\"Addition of {lhs.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return out_dtype\n\n\ndef _timedelta_sub_result_dtype(\n lhs: BinaryOperand, rhs: BinaryOperand\n) -> Dtype:\n if pd.api.types.is_timedelta64_dtype(\n lhs.dtype\n ) and pd.api.types.is_timedelta64_dtype(rhs.dtype):\n out_dtype = determine_out_dtype(lhs.dtype, rhs.dtype)\n elif pd.api.types.is_timedelta64_dtype(\n rhs.dtype\n ) and pd.api.types.is_datetime64_dtype(lhs.dtype):\n units = [\"s\", \"ms\", \"us\", \"ns\"]\n lhs_time_unit = cudf.utils.dtypes.get_time_unit(lhs)\n lhs_unit = units.index(lhs_time_unit)\n rhs_time_unit = cudf.utils.dtypes.get_time_unit(rhs)\n rhs_unit = units.index(rhs_time_unit)\n out_dtype = cudf.dtype(f\"datetime64[{units[max(lhs_unit, rhs_unit)]}]\")\n else:\n raise TypeError(\n f\"Subtraction of {lhs.dtype} with {rhs.dtype} \"\n f\"cannot be performed.\"\n )\n\n return out_dtype\n" ]
[ [ "numpy.datetime_data", "pandas.api.types.is_datetime64_dtype", "numpy.isnat", "numpy.dtype", "pandas.Timedelta", "numpy.timedelta64", "numpy.isscalar", "pandas.api.types.is_timedelta64_dtype" ] ]
fAndreuzzi/GRAPE
[ "19eeb4447a2a1a3fd09dbb78ae22c78625b0f7e1" ]
[ "grape/general_graph.py" ]
[ "\"\"\"GeneralGraph for directed graphs (DiGraph) module\"\"\"\n\nfrom multiprocessing import Queue\nimport multiprocessing as mp\nfrom multiprocessing.sharedctypes import RawArray\nimport numpy as np\nimport sys\nimport csv\nimport ctypes\nimport logging\nimport warnings\nfrom itertools import chain\nimport copy\nimport networkx as nx\n\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nlogging.basicConfig(\n filename=\"general_code_output.log\", level=logging.DEBUG, filemode='w')\n\n\nclass GeneralGraph(nx.DiGraph):\n \"\"\"Class GeneralGraph for directed graphs (DiGraph).\n\n Constructs a new graph given an input file.\n A DiGraph stores nodes and edges with optional data or attributes.\n DiGraphs hold directed edges.\n Nodes can be arbitrary python objects with optional key/value attributes.\n Edges are represented as links between nodes with optional key/value\n attributes.\n \"\"\"\n\n def load(self, filename):\n \"\"\"\n\n Load input file. Input file must be in CSV format.\n Each line corresponds to a node/element description,\n with the relative hierarchy, together with the list\n of all the node attributes.\n\n :param str filename: input file in CSV format\n \"\"\"\n\n with open(filename, 'r') as csvfile:\n reader = csv.DictReader(csvfile, delimiter=',')\n\n for row in reader:\n\n if not row['Mark'] in self:\n self.add_node(row['Mark'])\n\n for key in [\n 'Area', 'PerturbationResistant', 'InitStatus',\n 'Description', 'Type', 'Mark', 'Father_mark'\n ]:\n self.nodes[row['Mark']][key] = row[key]\n\n if row['Father_mark'] == 'NULL':\n continue\n\n if not row['Father_mark'] in self:\n self.add_node(row['Father_mark'])\n\n self.add_edge(\n row['Father_mark'],\n row['Mark'],\n Father_cond = row['Father_cond'],\n weight = float(row['Service']) )\n\n self.newstatus = {}\n self.finalstatus = {}\n self.Status_Area = {}\n self.Mark_Status = {}\n\n self.area = nx.get_node_attributes(self, 'Area')\n self.FR = nx.get_node_attributes(self, 'PerturbationResistant')\n self.D = nx.get_node_attributes(self, 'Description')\n self.status = nx.get_node_attributes(self, 'InitStatus')\n self.Mark = nx.get_node_attributes(self, 'Mark')\n self.Father_mark = nx.get_node_attributes(self, 'Father_mark')\n self.condition = nx.get_edge_attributes(self, 'Father_cond')\n self.Type = nx.get_node_attributes(self, 'Type')\n self.Service = nx.get_edge_attributes(self, 'weight')\n\n self.services_SOURCE = []\n self.services_HUB = []\n self.services_USER = []\n for id, Type in self.Type.items():\n if Type == \"SOURCE\":\n self.services_SOURCE.append(id)\n elif Type == \"HUB\":\n self.services_HUB.append(id)\n elif Type == \"USER\":\n self.services_USER.append(id)\n\n self.valv = {\t\"isolation_A\" : { \"0\": \"OPEN\", \"1\": \"CLOSED\"},\n\t\t\t\"isolation_B\" : { \"0\": \"CLOSED\", \"1\": \"OPEN\"},\n\t\t\t\"unknown\" : { \"0\": \"OFF\", \"1\": \"ON\"} }\n\n def check_input_with_gephi(self):\n \"\"\"\n\n Write list of nodes and list of edges csv files\n to visualize the input with Gephi.\n \"\"\"\n\n nodes_to_print = []\n with open(\"check_import_nodes.csv\", \"w\") as csvFile:\n fields = [\n \"Mark\", \"Description\", \"InitStatus\", \"PerturbationResistant\",\n \"Area\"\n ]\n\n writer = csv.DictWriter(csvFile, fieldnames=fields)\n writer.writeheader()\n if hasattr(self, \"copy_of_self1\"):\n for n in self.copy_of_self1:\n nodes_to_print.append({\n 'Mark':\n n,\n 'Description':\n self.copy_of_self1.nodes[n][\"Description\"],\n 'InitStatus':\n self.copy_of_self1.nodes[n][\"InitStatus\"],\n 'PerturbationResistant':\n self.copy_of_self1.nodes[n][\"PerturbationResistant\"],\n 'Area':\n self.copy_of_self1.nodes[n][\"Area\"]\n })\n writer.writerows(nodes_to_print)\n else:\n for n in self:\n nodes_to_print.append({\n 'Mark':\n n,\n 'Description':\n self.nodes[n][\"Description\"],\n 'InitStatus':\n self.nodes[n][\"InitStatus\"],\n 'PerturbationResistant':\n self.nodes[n][\"PerturbationResistant\"],\n 'Area':\n self.nodes[n][\"Area\"]\n })\n writer.writerows(nodes_to_print)\n\n csvFile.close()\n\n edges_to_print = []\n with open(\"check_import_edges.csv\", \"w\") as csvFile:\n fields = [\"Mark\", \"Father_mark\"]\n writer = csv.DictWriter(csvFile, fieldnames=fields)\n writer.writeheader()\n\n if hasattr(self, \"copy_of_self1\"):\n for n in self.copy_of_self1:\n for p in self.copy_of_self1.predecessors(n):\n edges_to_print.append({'Mark': n, 'Father_mark': p})\n\n else:\n for n in self:\n for p in self.predecessors(n):\n edges_to_print.append({'Mark': n, 'Father_mark': p})\n\n writer.writerows(edges_to_print)\n\n csvFile.close()\n\n def construct_path(self, source, target, pred):\n \"\"\"\n\n Reconstruct source-target paths starting from predecessors\n matrix.\n\n :param source: starting node for the path\n :param target: ending node for the path\n :param numpy.ndarray pred: matrix of predecessors, computed\n with Floyd Warshall APSP algorithm\n\n :return: the shortest path between source and target\n (source and target included)\n :rtype: list\n \"\"\"\n\n if source == target:\n path = [source]\n else:\n pred.astype(int)\n curr = pred[source, target]\n if curr != np.inf:\n curr = int(curr)\n path = [int(target), int(curr)]\n while curr != source:\n curr = int(pred[int(source), int(curr)])\n path.append(curr)\n else:\n path = []\n\n path1 = list(map(self.ids.get, path))\n path1 = list(reversed(path1))\n\n return path1\n\n def construct_path_kernel(self, pred, nodi):\n \"\"\"\n\n Populate the dictionary of shortest paths.\n\n :param numpy.ndarray pred: matrix of predecessors,\n computed with Floyd Warshall APSP algorithm\n :param list nodi: list of nodes for which to compute the\n shortest path between them and all the other nodes\n\n :return: nested dictionary with key corresponding to\n source, while as value a dictionary keyed by target and valued\n by the source-target shortest path\n :rtype: dict\n \"\"\"\n\n paths = {}\n\n for i in nodi:\n paths[self.ids[i]] = {\n self.ids[j]: self.construct_path(i,j,pred)\n for j in sorted(list(self.H))\n } \n\n return paths\n\n def construct_path_iteration_parallel(self, pred, nodi, record):\n \"\"\"\n\n Inner iteration for parallel Floyd Warshall APSP algorithm,\n to update shared dictionary.\n\n :param numpy.ndarray pred: matrix of predecessors,\n computed with Floyd Warshall APSP algorithm\n :param list nodi: list of nodes for which to compute the\n shortest path between them and all the other nodes\n :param multiprocessing.managers.dict record: nested dictionary\n with key corresponding to source, while as value a\n dictionary keyed by target and valued by the\n source-target shortest path\n \"\"\"\n\n paths = self.construct_path_kernel(pred, nodi)\n record.update(paths) \n\n def compute_efficiency_kernel(self, nodi):\n \"\"\"\n\n Compute efficiency, starting from path length attribute.\n Efficiency is a measure of how good is the exchange of commodities\n flowing from one node to the others.\n\n :param list nodi: list of nodes for which to compute the\n efficiency between them and all the other nodes\n\n :return: nested dictionary with key corresponding to\n source, while as value a dictionary keyed by target and valued\n by the source-target efficiency\n :rtype: dict\n \"\"\"\n\n dict_efficiency = {}\n\n for n in nodi:\n dict_efficiency[n] = {}\n for key, length_path in self.nodes[n][\"shpath_length\"].items():\n if length_path != 0 : \n efficiency = 1 / length_path\n dict_efficiency[n].update({key: efficiency})\n else:\n efficiency = 0\n dict_efficiency[n].update({key: efficiency})\n\n return dict_efficiency\n\n def compute_efficiency_iteration_parallel(self, nodi, record):\n \"\"\"\n\n Inner iteration for parallel efficiency calculation,\n to update shared dictionary.\n\n :param list nodi: nodes for which to compute the\n shortest path between them and all the other nodes\n :param multiprocessing.managers.dict record: nested dictionary\n with key corresponding to source, while as value a\n dictionary keyed by target and valued by the\n source-target efficiency\n \"\"\"\n\n dict_efficiency = self.compute_efficiency_kernel(nodi)\n record.update(dict_efficiency) \n\n def floyd_warshall_initialization(self):\n \"\"\"\n\n Initialization of Floyd Warshall APSP algorithm.\n The distancy matrix is mutuated by NetworkX graph adjacency\n matrix, while the predecessors matrix is initialized\n with node fathers.\n The conversion between the labels (ids) in the graph and Numpy\n matrix indices (and viceversa) is also exploited.\n\n .. note:: In order for the ids relation to be bijective,\n \"Mark\" attribute must be unique for each node.\n \"\"\"\n\n self.H = nx.convert_node_labels_to_integers(\n self, first_label=0, label_attribute='Mark_ids')\n self.ids = nx.get_node_attributes(self.H, 'Mark_ids')\n self.ids_reversed = { value: key for key, value in self.ids.items() }\n\n dist = nx.to_numpy_matrix(self.H, nodelist=sorted(list(self.H)))\n dist[dist == 0] = np.inf\n np.fill_diagonal(dist, 0.)\n\n pred = np.full((len(self.H), len(self.H)), np.inf)\n for u, v, d in self.H.edges(data=True):\n pred[u, v] = u\n\n return dist, pred\n\n def floyd_warshall_kernel(self, dist, pred, init, stop, barrier=None):\n \"\"\"\n\n Floyd Warshall's APSP inner iteration.\n Distance matrix is intended to take edges weight into account.\n\n :param numpy.ndarray dist: matrix of distances\n :param numpy.ndarray pred: matrix of predecessors\n :param int init: starting column of numpy matrix slice\n :param int stop: ending column of numpy matrix slice\n :param multiprocessing.synchronize.Barrier barrier:\n multiprocessing barrier to moderate writing on\n distance and predecessors matrices\n \"\"\"\n\n n = dist.shape[0]\n for w in range(n): # k\n dist_copy = copy.deepcopy(dist[init:stop, :])\n np.minimum(\n np.reshape(\n np.add.outer(dist[init:stop, w], dist[w, :]),\n (stop-init, n)),\n dist[init:stop, :],\n dist[init:stop, :])\n diff = np.equal(dist[init:stop, :], dist_copy)\n pred[init:stop, :][~diff] = np.tile(pred[w, :], (stop-init, 1))[~diff]\n \n if barrier: barrier.wait() \n\n def floyd_warshall_predecessor_and_distance_parallel(self):\n \"\"\"\n\n Parallel Floyd Warshall's APSP algorithm. The predecessors\n and distance matrices are evaluated, together with the nested\n dictionaries for shortest-path, length of the paths and\n efficiency attributes.\n\n .. note:: Edges weight is taken into account in the distance matrix.\n Edge weight attributes must be numerical. Distances are calculated\n as sums of weighted edges traversed.\n \"\"\"\n\n dist, pred = self.floyd_warshall_initialization()\n\n shared_arr = mp.sharedctypes.RawArray(ctypes.c_double, dist.shape[0]**2)\n arr = np.frombuffer(shared_arr, 'float64').reshape(dist.shape)\n arr[:] = dist\n\n shared_arr_pred = mp.sharedctypes.RawArray(ctypes.c_double,pred.shape[0]**2)\n arr1 = np.frombuffer(shared_arr_pred, 'float64').reshape(pred.shape)\n arr1[:] = pred\n\n n = len(self.nodes())\n chunk = [(0, int(n / self.num))]\n node_chunks = self.chunk_it(list(self.nodes()), self.num)\n\n for i in range(1, self.num):\n chunk.append((chunk[i - 1][1],\n chunk[i - 1][1] + len(node_chunks[i])))\n\n barrier = mp.Barrier(self.num)\n processes = [\n mp.Process( target=self.floyd_warshall_kernel,\n args=(arr, arr1, chunk[p][0], chunk[p][1], barrier))\n for p in range(self.num) ]\n\n for proc in processes:\n proc.start()\n\n for proc in processes:\n proc.join()\n\n manager = mp.Manager()\n shpaths_dicts = manager.dict()\n\n processes = [\n mp.Process( target=self.construct_path_iteration_parallel,\n args=(arr1, list(map(self.ids_reversed.get, node_chunks[p])), shpaths_dicts))\n for p in range(self.num) ]\n\n for proc in processes:\n proc.start()\n\n for proc in processes:\n proc.join()\n\n for k in shpaths_dicts.keys():\n self.nodes[k][\"shortest_path\"] = {\n key: value\n for key, value in shpaths_dicts[k].items() if value\n }\n\n for i in list(self.H):\n\n self.nodes[self.ids[i]][\"shpath_length\"] = {}\n\n for key, value in self.nodes[self.ids[i]][\"shortest_path\"].items():\n length_path = arr[self.ids_reversed[value[0]], self.ids_reversed[value[-1]]]\n self.nodes[self.ids[i]][\"shpath_length\"][key] = length_path\n\n eff_dicts = manager.dict()\n \n processes = [\n mp.Process( target=self.compute_efficiency_iteration_parallel,\n args=(node_chunks[p], eff_dicts) )\n for p in range(self.num) ]\n\n for proc in processes:\n proc.start()\n\n for proc in processes:\n proc.join()\n\n nx.set_node_attributes(self, eff_dicts, name=\"efficiency\")\n\n def floyd_warshall_predecessor_and_distance_serial(self):\n \"\"\"\n\n Serial Floyd Warshall's APSP algorithm. The predecessors\n and distance matrices are evaluated, together with the nested\n dictionaries for shortest-path, length of the paths and\n efficiency attributes.\n\n .. note:: Edges weight is taken into account in the distance matrix.\n Edge weight attributes must be numerical. Distances are calculated\n as sums of weighted edges traversed.\n \"\"\"\n\n dist, pred = self.floyd_warshall_initialization()\n\n self.floyd_warshall_kernel(dist, pred, 0, dist.shape[0])\n\n shpaths_dicts = self.construct_path_kernel(pred, list(self.H))\n\n for k in shpaths_dicts.keys():\n self.nodes[k][\"shortest_path\"] = {\n key: value\n for key, value in shpaths_dicts[k].items() if value\n }\n\n for i in list(self.H):\n\n self.nodes[self.ids[i]][\"shpath_length\"] = {}\n \n for key, value in self.nodes[self.ids[i]][\"shortest_path\"].items():\n length_path = dist[self.ids_reversed[value[0]], self.ids_reversed[value[-1]]]\n self.nodes[self.ids[i]][\"shpath_length\"][key] = length_path\n\n eff_dicts = self.compute_efficiency_kernel(list(self))\n nx.set_node_attributes(self, eff_dicts, name=\"efficiency\")\n\n def single_source_shortest_path_serial(self):\n \"\"\"\n\n Serial SSSP algorithm based on Dijkstra’s method.\n The nested dictionaries for shortest-path, length of the paths and\n efficiency attributes are evaluated.\n\n .. note:: Edges weight is taken into account. Edge weight attributes must\n be numerical. Distances are calculated as sums of weighted edges traversed.\n \"\"\"\n\n for n in self:\n sssps = (n, nx.single_source_dijkstra(self, n, weight = 'weight'))\n self.nodes[n][\"shortest_path\"] = sssps[1][1]\n self.nodes[n][\"shpath_length\"] = sssps[1][0]\n \n eff_dicts = self.compute_efficiency_kernel(list(self))\n nx.set_node_attributes(self, eff_dicts, name=\"efficiency\")\n\n def single_source_shortest_path_parallel(self, out_q, nodi):\n \"\"\"\n\n Parallel SSSP algorithm based on Dijkstra’s method.\n\n :param multiprocessing.queues.Queue out_q: multiprocessing queue\n :param list nodi: list of starting nodes from which the SSSP should be\n computed to every other target node in the graph\n\n .. note:: Edges weight is taken into account. Edge weight attributes must\n be numerical. Distances are calculated as sums of weighted edges traversed.\n \"\"\"\n\n for n in nodi:\n ssspp = (n, nx.single_source_dijkstra(self, n, weight = 'weight'))\n out_q.put(ssspp)\n\n @staticmethod\n def chunk_it(nodi, n):\n \"\"\"\n\n Divide graph nodes in chunks according to number of processes.\n\n :param list nodi: list of nodes in the graph\n :param int n: number of available processes\n \n :return: list of graph nodes to be assigned to every process\n :rtype: list\n \"\"\"\n\n avg = len(nodi) / n\n out = []\n last = 0.0\n\n while last < len(nodi):\n out.append(nodi[int(last):int(last + avg)])\n last += avg\n return out\n\n def parallel_wrapper_proc(self):\n \"\"\"\n\n Wrapper for parallel SSSP algorithm based on Dijkstra’s method.\n The nested dictionaries for shortest-path, length of the paths and\n efficiency attributes are evaluated.\n\n .. note:: Edges weight is taken into account. Edge weight attributes must\n be numerical. Distances are calculated as sums of weighted edges traversed.\n \"\"\"\n\n self.attribute_ssspp = []\n \n out_q = Queue()\n\n node_chunks = self.chunk_it(list(self.nodes()), self.num)\n\n processes = [\n mp.Process( target=self.single_source_shortest_path_parallel,\n args=( out_q,node_chunks[p] ))\n for p in range(self.num) ]\n\n for proc in processes:\n proc.start()\n\n while 1:\n running = any(p.is_alive() for p in processes)\n while not out_q.empty():\n\n self.attribute_ssspp.append(out_q.get())\n\n if not running:\n break\n\n for ssspp in self.attribute_ssspp:\n\n n = ssspp[0]\n self.nodes[n][\"shortest_path\"] = ssspp[1][1]\n self.nodes[n][\"shpath_length\"] = ssspp[1][0]\n\n manager = mp.Manager()\n eff_dicts = manager.dict()\n \n processes = [\n mp.Process( target=self.compute_efficiency_iteration_parallel,\n args=(node_chunks[p], eff_dicts) )\n for p in range(self.num) ]\n\n for proc in processes:\n proc.start()\n\n for proc in processes:\n proc.join()\n\n nx.set_node_attributes(self, eff_dicts, name=\"efficiency\")\n\n def nodal_efficiency(self):\n \"\"\"\n\n Global efficiency of the node.\n Nodes' \"original_nodal_eff\", or \"final_nodal_eff\" attribute\n is evaluated.\n\n \"original_nodal_eff\" is the efficiency of each node in the\n intact graph, before the occurrence of any perturbation, while\n \"final_nodal_eff\" is the efficiency of each node in the potentially\n perturbed graph, after the propagation of a perturbation.\n\n .. note:: The global efficiency of the node is equal to zero for a node\n without any outgoing path and equal to one if from it we can reach\n each node of the digraph.\n \"\"\"\n \n g_len = len(list(self))\n first_node = list(self)[0]\n all_attributes = list(self.nodes[first_node].keys())\n\n if \"original_nodal_eff\" in all_attributes:\n\n deleted_nodes = set(list(self.copy_of_self1)) - set(list(self))\n\n for v in deleted_nodes:\n self.copy_of_self1.nodes[v][\"final_nodal_eff\"] = \" \"\n\n for v in self:\n sum_efficiencies = sum(self.nodes[v][\"efficiency\"].values())\n self.copy_of_self1.nodes[v][\n \"final_nodal_eff\"] = sum_efficiencies / (g_len - 1)\n\n else:\n for v in self:\n sum_efficiencies = sum(self.nodes[v][\"efficiency\"].values())\n self.nodes[v][\"original_nodal_eff\"] = sum_efficiencies / (g_len - 1)\n\n def local_efficiency(self):\n \"\"\"\n\n Local efficiency of the node.\n Nodes' \"original_local_eff\", or \"final_local_eff\" attribute\n is evaluated.\n\n \"original_local_eff\" is the local efficiency of each node in the\n intact graph, before the occurrence of any perturbation, while\n \"final_local_eff\" is the local efficiency of each node in the\n potentially perturbed graph, after the propagation of a perturbation.\n\n .. note:: The local efficiency shows the efficiency of the connections\n between the first-order outgoing neighbors of node v when v is removed.\n Equivalently, local efficiency measures the \"resilience\" of the digraph\n to the perturbation of node removal, i.e. if we remove a node,\n how efficiently its first-order outgoing neighbors can communicate.\n It is in the range [0, 1].\n \"\"\"\n\n first_node = list(self)[0]\n all_attributes = list(self.nodes[first_node].keys())\n\n if \"original_local_eff\" in all_attributes:\n\n deleted_nodes = set(list(self.copy_of_self1)) - set(list(self))\n\n for v in deleted_nodes:\n self.copy_of_self1.nodes[v][\"final_local_eff\"] = \" \"\n\n for v in self:\n subgraph = list(self.successors(v))\n denom_subg = len(list(subgraph))\n\n if denom_subg != 0:\n sum_efficiencies = 0\n for w in list(subgraph):\n kv_efficiency = self.copy_of_self1.nodes[w][\n \"final_nodal_eff\"]\n sum_efficiencies = sum_efficiencies + kv_efficiency\n\n loc_eff = sum_efficiencies / denom_subg\n\n self.copy_of_self1.nodes[v][\"final_local_eff\"] = loc_eff\n else:\n self.copy_of_self1.nodes[v][\"final_local_eff\"] = 0\n else:\n for v in self:\n subgraph = list(self.successors(v))\n denom_subg = len(list(subgraph))\n if denom_subg != 0:\n sum_efficiencies = 0\n for w in list(subgraph):\n kv_efficiency = self.nodes[w][\"original_nodal_eff\"]\n sum_efficiencies = sum_efficiencies + kv_efficiency\n\n loc_eff = sum_efficiencies / denom_subg\n self.nodes[v][\"original_local_eff\"] = loc_eff\n else:\n self.nodes[v][\"original_local_eff\"] = 0\n\n def global_efficiency(self):\n \"\"\"\n\n Average global efficiency of the whole graph.\n Nodes' \"original_avg_global_eff\", or \"final_avg_global_eff\" attribute\n is evaluated.\n\n \"original_avg_global_eff\" is the average global efficiency of the\n intact graph, before the occurrence of any perturbation, while\n \"final_avg_global_eff\" is the efficiency of each node in the\n potentially perturbed graph, after the propagation of a perturbation.\n\n .. note:: The average global efficiency of a graph is the average\n efficiency of all pairs of nodes.\n \"\"\"\n\n g_len = len(list(self))\n sum_eff = 0\n first_node = list(self)[0]\n all_attributes = list(self.nodes[first_node].keys())\n\n for v in self:\n kv_efficiency = self.nodes[v][\"original_nodal_eff\"]\n sum_eff = sum_eff + kv_efficiency\n\n if \"original_avg_global_eff\" in all_attributes:\n for v in self.copy_of_self1:\n self.copy_of_self1.nodes[v][\"final_avg_global_eff\"] = sum_eff / g_len\n else:\n for v in self:\n self.nodes[v][\"original_avg_global_eff\"] = sum_eff / g_len\n\n def betweenness_centrality(self):\n \"\"\"\n\n Betweenness_centrality measure of each node.\n Nodes' \"betweenness_centrality\" attribute is evaluated.\n\n .. note:: Betweenness centrality is an index of the relative importance\n of a node and it is defined by the number of shortest paths that run\n through it.\n Nodes with the highest betweenness centrality hold the higher level\n of control on the information flowing between different nodes in\n the network, because more information will pass through them.\n \"\"\"\n\n tot_shortest_paths = nx.get_node_attributes(self, 'shortest_path')\n tot_shortest_paths_list = []\n\n for node in self:\n node_tot_shortest_paths = tot_shortest_paths[node]\n for key, value in node_tot_shortest_paths.items():\n if len(value) > 1:\n tot_shortest_paths_list.append(value)\n length_tot_shortest_paths_list = len(tot_shortest_paths_list)\n\n for node in self:\n sp_with_node = []\n for l in tot_shortest_paths_list:\n if node in l and node != l[0] and node != l[-1]:\n sp_with_node.append(l)\n\n numb_sp_with_node = len(sp_with_node)\n bet_cen = numb_sp_with_node / length_tot_shortest_paths_list\n self.nodes[node][\"betweenness_centrality\"] = bet_cen\n\n def closeness_centrality(self):\n \"\"\"\n\n Closeness_centrality measure of each node.\n Nodes' \"closeness_centrality\" attribute is evaluated.\n\n .. note:: Closeness centrality measures the reciprocal of the\n average shortest path distance from a node to all other reachable\n nodes in the graph. Thus, the more central a node is, the closer\n it is to all other nodes. This measure allows to identify good\n broadcasters, that is key elements in a graph, depicting how\n closely the nodes are connected with each other.\n \"\"\"\n\n g_len = len(list(self))\n tot_shortest_paths = nx.get_node_attributes(self, 'shortest_path')\n tot_shortest_paths_list = []\n\n for node in self:\n node_tot_shortest_paths = tot_shortest_paths[node]\n for key, value in node_tot_shortest_paths.items():\n if len(value) > 1:\n tot_shortest_paths_list.append(value)\n\n for node in self:\n totsp = []\n sp_with_node = []\n for l in tot_shortest_paths_list:\n if node in l and node == l[-1]:\n sp_with_node.append(l)\n length_path = self.nodes[l[0]][\"shpath_length\"][l[-1]]\n totsp.append(length_path)\n norm = len(totsp) / (g_len - 1)\n clo_cen = (\n len(totsp) / sum(totsp)) * norm if (sum(totsp)) != 0 else 0\n self.nodes[node][\"closeness_centrality\"] = clo_cen\n\n def degree_centrality(self):\n \"\"\"\n\n Degree centrality measure of each node.\n Nodes' \"degree_centrality\" attribute is evaluated.\n\n .. note:: Degree centrality is a simple centrality measure that counts\n how many neighbors a node has in an undirected graph.\n The more neighbors the node has the most important it is,\n occupying a strategic position that serves as a source or conduit\n for large volumes of flux transactions with other nodes.\n A node with high degree centrality is a node with many dependencies.\n \"\"\"\n\n #TODO: it can be trivially parallelized\n #(see single_source_shortest_path_parallel for the way to go)\n g_len = len(list(self))\n\n for node in self:\n num_neighbor_nodes = self.degree(node, weight = 'weight')\n deg_cen = num_neighbor_nodes / (g_len - 1)\n self.nodes[node][\"degree_centrality\"] = deg_cen\n\n def indegree_centrality(self):\n \"\"\"\n\n Indegree centrality measure of each node.\n Nodes' \"indegree_centrality\" attribute is evaluated.\n\n .. note:: Indegree centrality is measured by the number of edges\n ending at the node in a directed graph. Nodes with high indegree\n centrality are called cascade resulting nodes.\n \"\"\"\n\n #TODO: it can be trivially parallelized\n #(see single_source_shortest_path_parallel for the way to go)\n g_len = len(list(self))\n \n for node in self:\n num_incoming_nodes = self.in_degree(node, weight = 'weight')\n if num_incoming_nodes > 0:\n in_cen = num_incoming_nodes / (g_len - 1)\n self.nodes[node][\"indegree_centrality\"] = in_cen\n else:\n self.nodes[node][\"indegree_centrality\"] = 0\n\n def outdegree_centrality(self):\n \"\"\"\n\n Outdegree centrality measure of each node.\n Nodes' \"outdegree_centrality\" attribute is evaluated.\n\n .. note:: Outdegree centrality is measured by the number of edges\n starting from a node in a directed graph. Nodes with high outdegree\n centrality are called cascade inititing nodes.\n \"\"\"\n\n #TODO: it can be trivially parallelized\n #(see single_source_shortest_path_parallel for the way to go)\n g_len = len(list(self))\n \n for node in self:\n num_outcoming_nodes = self.out_degree(node, weight = 'weight')\n if num_outcoming_nodes > 0:\n out_cen = num_outcoming_nodes / (g_len - 1)\n self.nodes[node][\"outdegree_centrality\"] = out_cen\n else:\n self.nodes[node][\"outdegree_centrality\"] = 0\n\n def calculate_shortest_path(self):\n \"\"\"\n\n Choose the most appropriate way to compute the all-pairs shortest\n path depending on graph size and density.\n\n For a dense graph choose Floyd Warshall algorithm.\n\n For a sparse graph choose SSSP algorithm based on Dijkstra's method.\n \n For big graphs go parallel (number of processes equals the total\n number of available CPUs).\n\n For small graphs go serial.\n\n .. note:: Edge weights of the graph are taken into account in the computation.\n \"\"\"\n\n n_of_nodes = self.order()\n g_density = nx.density(self)\n self.num = mp.cpu_count()\n\n print(\"PROC NUM\", self.num)\n\n print(\"In the graph are present\", n_of_nodes, \"nodes\")\n if n_of_nodes > 10000:\n print(\"go parallel!\")\n if g_density <= 0.000001:\n print(\"the graph is sparse, density =\", g_density)\n self.parallel_wrapper_proc()\n else:\n print(\"the graph is dense, density =\", g_density)\n self.floyd_warshall_predecessor_and_distance_parallel()\n else:\n print(\"go serial!\")\n if g_density <= 0.000001:\n print(\"the graph is sparse, density =\", g_density)\n self.single_source_shortest_path_serial()\n else:\n print(\"the graph is dense, density =\", g_density)\n self.floyd_warshall_predecessor_and_distance_serial()\n\n def check_before(self):\n \"\"\"\n\n Describe the topology of the integer graph, before the\n occurrence of any perturbation in the system.\n Compute efficiency measures for the whole graph and its nodes.\n Check the availability of paths between source and target nodes.\n \"\"\"\n\n self.calculate_shortest_path()\n self.lst0 = []\n self.nodal_efficiency()\n self.global_efficiency()\n self.local_efficiency()\n\n for ii in self.services_SOURCE:\n i = list(self.Mark.keys())[list(self.Mark.values()).index(ii)]\n for jj in self.services_USER:\n j = list(self.Mark.keys())[list(self.Mark.values()).index(jj)]\n if i in self.nodes() and j in self.nodes():\n if nx.has_path(self, i, j):\n\n osip = list(nx.all_simple_paths(self, i, j))\n oshp = self.nodes[i][\"shortest_path\"][j]\n oshpl = self.nodes[i][\"shpath_length\"][j]\n oeff = 1 / oshpl\n ids = ii + jj\n\n self.lst0.append({\n 'from':\n ii,\n 'to':\n jj,\n 'original_shortest_path_length':\n oshpl,\n 'original_shortest_path':\n oshp,\n 'original_simple path':\n osip,\n 'original_pair_efficiency':\n oeff,\n 'ids':\n ids\n })\n\n else:\n oshpl = \"NO_PATH\"\n osip = \"NO_PATH\"\n oshp = \"NO_PATH\"\n oeff = \"NO_PATH\"\n ids = ii + jj\n\n self.lst0.append({\n 'from':\n ii,\n 'to':\n jj,\n 'original_shortest_path_length':\n oshpl,\n 'original_shortest_path':\n oshp,\n 'original_simple path':\n osip,\n 'original_pair_efficiency':\n oeff,\n 'ids':\n ids\n })\n\n else:\n\n oshpl = \"NO_PATH\"\n osip = \"NO_PATH\"\n oshp = \"NO_PATH\"\n oeff = \"NO_PATH\"\n ids = ii + jj\n\n self.lst0.append({\n 'from': ii,\n 'to': jj,\n 'original_shortest_path_length': oshpl,\n 'original_shortest_path': oshp,\n 'original_simple path': osip,\n 'original_pair_efficiency': oeff,\n 'ids': ids\n })\n\n def check_after(self):\n \"\"\"\n\n Describe the topology of the potentially perturbed graph,\n after the occurrence of a perturbation in the system.\n Compute efficiency measures for the whole graph and its nodes.\n Check the availability of paths between source and target nodes.\n \"\"\"\n\n self.calculate_shortest_path()\n self.nodal_efficiency()\n self.global_efficiency()\n self.local_efficiency()\n\n for nn in self.services_SOURCE:\n n = list(self.Mark.keys())[list(self.Mark.values()).index(nn)]\n for OODD in self.services_USER:\n OD = list(self.Mark.keys())[list(\n self.Mark.values()).index(OODD)]\n\n if n in self.nodes() and OD in self.nodes():\n if nx.has_path(self, n, OD):\n\n sip = list(nx.all_simple_paths(self, n, OD))\n\n set_sip = set(x for lst in sip for x in lst)\n\n for node in set_sip:\n\n if self.D[node] in self.valv:\n\n if node in self.newstatus:\n\n if self.newstatus[node] == \"1\":\n\n logging.debug(\n \"valve %s at node %s, state %s\",\n self.D[node], node, self.valv[self.D[node]][\"1\"])\n\n elif self.newstatus[node] == \"0\":\n\n self.finalstatus.update({node: \"1\"})\n \n logging.debug(\n \"valve %s at node %s, from %s to %s\",\n self.D[node], node, self.valv[self.D[node]][\"0\"],\n self.valv[self.D[node]][\"1\"])\n else:\n if self.status[node] == \"1\":\n\n logging.debug(\n \"valve %s at node %s, state %s\",\n self.D[node], node, self.valv[self.D[node]][\"1\"])\n elif self.status[node] == \"0\":\n\n self.finalstatus.update({node: \"1\"})\n\n logging.debug(\n \"valve %s at node %s, from %s to %s\",\n self.D[node], node, self.valv[self.D[node]][\"0\"],\n self.valv[self.D[node]][\"1\"])\n\n shp = self.nodes[n][\"shortest_path\"][OD]\n shpl = self.nodes[n][\"shpath_length\"][OD]\n neff = 1 / shpl\n ids = nn + OODD\n\n else:\n\n shpl = \"NO_PATH\"\n sip = \"NO_PATH\"\n shp = \"NO_PATH\"\n neff = \"NO_PATH\"\n ids = nn + OODD\n\n else:\n shpl = \"NO_PATH\"\n sip = \"NO_PATH\"\n shp = \"NO_PATH\"\n neff = \"NO_PATH\"\n ids = nn + OODD\n\n self.lst.append({\n 'from': nn,\n 'area': self.area[n],\n 'to': OODD,\n 'final_shortest_path_length': shpl,\n 'final_shortest_path': shp,\n 'final_simple_path': sip,\n 'final_pair_efficiency': neff,\n 'ids': ids\n })\n\n def rm_nodes(self, node, visited=None):\n \"\"\"\n\n Remove nodes from the graph in a depth first search way to\n propagate the perturbation.\n\n :param str node: the id of the node to remove\n :param visited: list of nodes already visited\n :type visited: set, optional\n \"\"\"\n\n if visited is None:\n visited = set()\n visited.add(node)\n logging.debug('visited: %s', visited)\n logging.debug('node: %s', node)\n\n if self.D[node] in self.valv:\n\n if self.status[node] == \"0\":\n logging.debug('valve %s at node %s, state %s',\n self.D[node], node, self.valv[self.D[node]][\"0\"])\n\n elif self.status[node] == \"1\":\n self.newstatus.update({node: \"0\"})\n logging.debug(\n 'valve %s at node %s, from %s to %s',\n self.D[node], node, self.valv[self.D[node]][\"1\"],\n self.valv[self.D[node]][\"0\"])\n\n if len(visited) == 1:\n self.broken.append((node, \"NULL\"))\n logging.debug(\"broken1: %s\", self.broken)\n\n else:\n return visited\n\n else:\n pred = list(self.predecessors(node))\n logging.debug(\"predecessors: %s\", pred)\n cond = set()\n count = 0\n if pred:\n for p in pred:\n cond.add(self.condition[(p, node)])\n if any(p in x for x in self.broken):\n count = count + 1\n else:\n cond.add(\"SINGLE\")\n\n if list(cond)[0] != \"OR\":\n self.broken.append((node, \"NULL\"))\n logging.debug(\"broken2: %s\", self.broken)\n else:\n\n if len(visited) == 1:\n self.broken.append((node, \"NULL\"))\n logging.debug(\"broken1: %s\", self.broken)\n else:\n if (len(pred) - count) == 0:\n self.broken.append((node, \"NULL\"))\n else:\n return 0\n\n for next in set(self[node]) - visited:\n self.rm_nodes(next, visited)\n\n return visited\n\n @staticmethod\n def merge_lists(l1, l2, key):\n \"\"\"\n\n Merge two lists of dictionaries according to their keys.\n\n :param list l1: first list of dictionaries to be merged\n :param list l2: second list of dictionaries to be merged\n :param list key: key on which to merge the two lists of dictionaries\n\n :return: the merged list of dictionaries\n :rtype: list\n \"\"\"\n\n merged = {}\n for item in l1 + l2:\n if item[key] in merged:\n merged[item[key]].update(item)\n else:\n merged[item[key]] = item\n return [val for (_, val) in merged.items()]\n\n def update_areas(self, multi_areas):\n \"\"\"\n\n Update the status of the elements in the areas after\n the propagation of the perturbation.\n Nodes' \"IntermediateStatus\", \"FinalStatus\", \"Mark_Status\"\n and \"Status_Area\" attributes are evaluated.\n\n :param list multi_areas: area(s) in which to update the status\n of the elements\n \"\"\"\n\n self.update_status(self.newstatus, \"IntermediateStatus\", self.nodes_in_area)\n \n self.update_status(self.finalstatus, \"FinalStatus\", self.nodes_in_area)\n \n deleted_nodes = set(self.copy_of_self1) - set(self)\n \n for n in self.copy_of_self1:\n\n if n in deleted_nodes:\n self.copy_of_self1.nodes[n][\"Mark_Status\"] = \"NOT_ACTIVE\"\n else:\n self.copy_of_self1.nodes[n][\"Mark_Status\"] = \"ACTIVE\"\n\n self.copy_of_self1.nodes[n][\"Status_Area\"] = \"AVAILABLE\"\n\n if self.copy_of_self1.nodes[n][\"Area\"] in multi_areas:\n self.copy_of_self1.nodes[n][\"Status_Area\"] = \"DAMAGED\"\n else:\n self.copy_of_self1.nodes[n][\"Status_Area\"] = \"AVAILABLE\"\n\n def delete_a_node(self, node):\n \"\"\"\n\n Delete a node in the graph to simulate a perturbation to an element in\n a plant and start to propagate the perturbation.\n Nodes' \"IntermediateStatus\", \"FinalStatus\", \"Mark_Status\"\n and \"Status_Area\" attributes are evaluated.\n\n :param str node: the id of the node to remove\n \"\"\"\n\n self.broken = [] #clear previous perturbation broken nodes\n if node in self.nodes():\n\n self.check_before()\n\n self.closeness_centrality()\n\n self.betweenness_centrality()\n\n self.indegree_centrality()\n\n self.outdegree_centrality()\n\n self.degree_centrality()\n\n self.copy_of_self1 = copy.deepcopy(self)\n\n self.rm_nodes(node)\n\n self.bn = list(set(list(chain(*self.broken))))\n\n if \"NULL\" in self.bn:\n self.bn.remove(\"NULL\")\n\n for n in self.bn:\n self.remove_node(n)\n\n self.lst = []\n\n self.check_after()\n\n self.service_paths_to_file(\"service_paths_element_perturbation.csv\")\n \n self.update_status(self.newstatus, \"IntermediateStatus\", self.bn)\n \n self.update_status(self.finalstatus, \"FinalStatus\", self.bn)\n\n for n in self.copy_of_self1:\n\n if n in self.bn:\n self.copy_of_self1.nodes[n][\"Mark_Status\"] = \"NOT_ACTIVE\"\n else:\n self.copy_of_self1.nodes[n][\"Mark_Status\"] = \"ACTIVE\"\n\n self.copy_of_self1.nodes[n][\"Status_Area\"] = \"AVAILABLE\"\n\n self.graph_characterization_to_file(\"element_perturbation.csv\")\n\n else:\n print('The node is not in the graph')\n print('Insert a valid node')\n\n def simulate_multi_area_perturbation(self, multi_areas):\n \"\"\"\n\n Simulate a perturbation in one or multiple areas.\n Nodes' \"IntermediateStatus\", \"FinalStatus\", \"Mark_Status\"\n and \"Status_Area\" attributes are evaluated.\n\n :param list multi_areas: area(s) in which the perturbing event\n occurred\n \"\"\"\n\n self.broken = [] #clear previous perturbation broken nodes\n self.nodes_in_area = []\n\n for area in multi_areas:\n\n if area not in list(self.area.values()):\n print('The area is not in the graph')\n print('Insert a valid area')\n print(\"Valid areas:\", set(self.area.values()))\n sys.exit()\n else:\n for id, Area in self.area.items():\n if Area == area:\n self.nodes_in_area.append(id)\n\n self.check_before()\n self.closeness_centrality()\n self.betweenness_centrality()\n self.indegree_centrality()\n self.copy_of_self1 = copy.deepcopy(self)\n\n FR_nodes = []\n\n for id, PerturbationResistant in self.FR.items():\n if PerturbationResistant == \"1\":\n FR_nodes.append(id)\n\n FV_nodes_in_area = set(self.nodes_in_area) - set(FR_nodes)\n FV_nodes_in_area = [x for x in FV_nodes_in_area if str(x) != 'nan']\n\n if (len(FV_nodes_in_area)) != 0:\n for node in FV_nodes_in_area:\n self.broken = []\n if node in self.nodes():\n self.rm_nodes(node)\n self.bn = list(set(list(chain(*self.broken))))\n if \"NULL\" in self.bn:\n self.bn.remove(\"NULL\")\n for n in self.bn:\n self.remove_node(n)\n\n FV_nodes_in_area = list(set(FV_nodes_in_area) - set(self.bn))\n\n FV_nodes_in_area = FV_nodes_in_area\n\n self.lst = []\n\n self.check_after()\n\n else:\n self.lst = []\n\n self.check_after()\n\n self.service_paths_to_file(\"service_paths_multi_area_perturbation.csv\")\n \n self.update_areas(multi_areas)\n \n self.graph_characterization_to_file(\"area_perturbation.csv\")\n \n def update_status(self, which_status, field, already_updated):\n \"\"\"\n\n Update the status of the nodes not concerned by the\n perturbation. The status of nodes interested by the perturbation\n is already updated during perturbation propagation.\n\n :param dict which_status: status to be updated\n :param str field: name of the attribute to be updated\n :param list already_updated: already updated nodes\n \"\"\"\n\n if which_status:\n which_status = {\n k: v\n for k, v in which_status.items()\n if k not in already_updated\n }\n ns_keys = which_status.keys() & list(self.copy_of_self1)\n os_keys = set(self.copy_of_self1) - set(ns_keys)\n\n for index, updated_status in which_status.items():\n self.copy_of_self1.nodes[index][field] = updated_status\n for index in os_keys:\n self.copy_of_self1.nodes[index][field] = \" \"\n else:\n for index in list(self.copy_of_self1):\n self.copy_of_self1.nodes[index][field] = \" \"\n\n def service_paths_to_file(self, filename):\n \"\"\"\n\n Write to file the service paths situation\n after the perturbation.\n\n :param str filename: output file name where to print the\n service paths situation\n \"\"\"\n\n rb_paths_p = self.merge_lists(self.lst0, self.lst, \"ids\")\n\n with open(filename, \"w\") as csvFile:\n fields = [\n \"from\", \"to\", \"final_simple_path\", \"final_shortest_path\",\n \"final_shortest_path_length\", \"final_pair_efficiency\", \"area\",\n \"ids\", 'original_simple path', 'original_shortest_path_length',\n 'original_pair_efficiency', 'original_shortest_path'\n ]\n writer = csv.DictWriter(csvFile, fieldnames=fields)\n writer.writeheader()\n writer.writerows(rb_paths_p)\n csvFile.close()\n\n def graph_characterization_to_file(self, filename):\n \"\"\"\n\n Write to file graph characterization\n after the perturbation.\n\n :param str filename: output file name where to print the\n graph characterization\n \"\"\"\n\n list_to_print = []\n with open(filename, \"w\") as csvFile:\n fields = [\n \"Mark\", \"Description\", \"InitStatus\", \"IntermediateStatus\",\n \"FinalStatus\", \"Mark_Status\", \"PerturbationResistant\", \"Area\",\n \"Status_Area\", \"closeness_centrality\", \"betweenness_centrality\",\n \"indegree_centrality\", \"original_local_eff\", \"final_local_eff\",\n \"original_global_eff\", \"final_global_eff\",\n \"original_avg_global_eff\", \"final_avg_global_eff\"\n ]\n\n writer = csv.DictWriter(csvFile, fieldnames=fields)\n writer.writeheader()\n for n in self.copy_of_self1:\n list_to_print.append({\n 'Mark':\n n,\n 'Description':\n self.copy_of_self1.nodes[n][\"Description\"],\n 'InitStatus':\n self.copy_of_self1.nodes[n][\"InitStatus\"],\n 'IntermediateStatus':\n self.copy_of_self1.nodes[n][\"IntermediateStatus\"],\n 'FinalStatus':\n self.copy_of_self1.nodes[n][\"FinalStatus\"],\n 'Mark_Status':\n self.copy_of_self1.nodes[n][\"Mark_Status\"],\n 'PerturbationResistant':\n self.copy_of_self1.nodes[n][\"PerturbationResistant\"],\n 'Area':\n self.copy_of_self1.nodes[n][\"Area\"],\n 'Status_Area':\n self.copy_of_self1.nodes[n][\"Status_Area\"],\n 'closeness_centrality':\n self.copy_of_self1.nodes[n][\"closeness_centrality\"],\n 'betweenness_centrality':\n self.copy_of_self1.nodes[n][\"betweenness_centrality\"],\n 'indegree_centrality':\n self.copy_of_self1.nodes[n][\"indegree_centrality\"],\n 'original_local_eff':\n self.copy_of_self1.nodes[n][\"original_local_eff\"],\n 'final_local_eff':\n self.copy_of_self1.nodes[n][\"final_local_eff\"],\n 'original_global_eff':\n self.copy_of_self1.nodes[n][\"original_nodal_eff\"],\n 'final_global_eff':\n self.copy_of_self1.nodes[n][\"final_nodal_eff\"],\n 'original_avg_global_eff':\n self.copy_of_self1.nodes[n][\"original_avg_global_eff\"],\n 'final_avg_global_eff':\n self.copy_of_self1.nodes[n][\"final_avg_global_eff\"]\n })\n writer.writerows(list_to_print)\n csvFile.close()\n\n\nif __name__ == '__main__':\n\n g = GeneralGraph()\n g.load(sys.argv[1])\n \n g.check_input_with_gephi()\n g.delete_a_node(\"1\")\n #g.simulate_multi_area_perturbation(['area1'])\n ##g.simulate_multi_area_perturbation(['area1','area2','area3'])\n" ]
[ [ "numpy.add.outer", "numpy.tile", "numpy.frombuffer", "numpy.equal", "numpy.fill_diagonal" ] ]
nivosco/pycls
[ "e8b4ea18db0a15ca0c9c815c4ce791d2e88bc1f2" ]
[ "pycls/models/blocks.py" ]
[ "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"Common model blocks.\"\"\"\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom pycls.core.config import cfg\nfrom torch.nn import Module\n\n\n# ----------------------- Shortcuts for common torch.nn layers ----------------------- #\n\n\ndef conv2d(w_in, w_out, k, *, stride=1, groups=1, bias=False):\n \"\"\"Helper for building a conv2d layer.\"\"\"\n assert k % 2 == 1, \"Only odd size kernels supported to avoid padding issues.\"\n s, p, g, b = stride, (k - 1) // 2, groups, bias\n return nn.Conv2d(w_in, w_out, k, stride=s, padding=p, groups=g, bias=b)\n\n\ndef norm2d(w_in):\n \"\"\"Helper for building a norm2d layer.\"\"\"\n return nn.BatchNorm2d(num_features=w_in, eps=cfg.BN.EPS, momentum=cfg.BN.MOM)\n\n\ndef pool2d(_w_in, k, *, stride=1):\n \"\"\"Helper for building a pool2d layer.\"\"\"\n assert k % 2 == 1, \"Only odd size kernels supported to avoid padding issues.\"\n return nn.MaxPool2d(k, stride=stride, padding=(k - 1) // 2)\n\n\ndef gap2d(_w_in):\n \"\"\"Helper for building a gap2d layer.\"\"\"\n return nn.AdaptiveAvgPool2d((1, 1))\n\n\ndef wap2d(_w_in):\n \"\"\"Helper for building a wap2d layer.\"\"\"\n return nn.AdaptiveAvgPool2d((None, 1))\n\n\ndef linear(w_in, w_out, *, bias=False):\n \"\"\"Helper for building a linear layer.\"\"\"\n return nn.Linear(w_in, w_out, bias=bias)\n\n\ndef activation():\n \"\"\"Helper for building an activation layer.\"\"\"\n activation_fun = cfg.MODEL.ACTIVATION_FUN.lower()\n if activation_fun == \"relu\":\n return nn.ReLU(inplace=cfg.MODEL.ACTIVATION_INPLACE)\n elif activation_fun == \"silu\" or activation_fun == \"swish\":\n try:\n return torch.nn.SiLU()\n except AttributeError:\n return SiLU()\n else:\n raise AssertionError(\"Unknown MODEL.ACTIVATION_FUN: \" + activation_fun)\n\n\n# --------------------------- Complexity (cx) calculations --------------------------- #\n\n\ndef conv2d_cx(cx, w_in, w_out, k, *, stride=1, groups=1, bias=False):\n \"\"\"Accumulates complexity of conv2d into cx = (h, w, flops, params, acts).\"\"\"\n h, w, flops, params, acts = cx[\"h\"], cx[\"w\"], cx[\"flops\"], cx[\"params\"], cx[\"acts\"]\n if type(k) == tuple:\n flops += k[0] * k[1] * w_in * h + 1\n params += k[0] * k[1] + 1\n return {\"h\": h, \"w\": w, \"flops\": flops, \"params\": params, \"acts\": acts}\n else:\n assert k % 2 == 1, \"Only odd size kernels supported to avoid padding issues.\"\n h, w = (h - 1) // stride + 1, (w - 1) // stride + 1\n flops += k * k * w_in * w_out * h * w // groups + (w_out if bias else 0)\n params += k * k * w_in * w_out // groups + (w_out if bias else 0)\n acts += w_in * w * k\n return {\"h\": h, \"w\": w, \"flops\": flops, \"params\": params, \"acts\": acts}\n\n\ndef conv1d_cx(cx, w_in, w_out, k, *, stride=1, groups=1, bias=False):\n \"\"\"Accumulates complexity of conv2d into cx = (h, w, flops, params, acts).\"\"\"\n assert k % 2 == 1, \"Only odd size kernels supported to avoid padding issues.\"\n h, w, flops, params, acts = cx[\"h\"], cx[\"w\"], cx[\"flops\"], cx[\"params\"], cx[\"acts\"]\n flops += k * w_in * w_out * h * w // groups + (w_out if bias else 0)\n params += k * w_in * w_out // groups + (w_out if bias else 0)\n acts += w_in * w * k\n return {\"h\": h, \"w\": w, \"flops\": flops, \"params\": params, \"acts\": acts}\n \n\ndef norm2d_cx(cx, w_in):\n \"\"\"Accumulates complexity of norm2d into cx = (h, w, flops, params, acts).\"\"\"\n h, w, flops, params, acts = cx[\"h\"], cx[\"w\"], cx[\"flops\"], cx[\"params\"], cx[\"acts\"]\n params += 2 * w_in\n return {\"h\": h, \"w\": w, \"flops\": flops, \"params\": params, \"acts\": acts}\n\n\ndef pool2d_cx(cx, w_in, k, *, stride=1):\n \"\"\"Accumulates complexity of pool2d into cx = (h, w, flops, params, acts).\"\"\"\n assert k % 2 == 1, \"Only odd size kernels supported to avoid padding issues.\"\n h, w, flops, params, acts = cx[\"h\"], cx[\"w\"], cx[\"flops\"], cx[\"params\"], cx[\"acts\"]\n h, w = (h - 1) // stride + 1, (w - 1) // stride + 1\n acts += w_in * w * k\n return {\"h\": h, \"w\": w, \"flops\": flops, \"params\": params, \"acts\": acts}\n\n\ndef wap2d_cx(cx, _w_in):\n \"\"\"Accumulates complexity of wap2d into cx = (h, w, flops, params, acts).\"\"\"\n h, w, flops, params, acts = cx[\"h\"], cx[\"w\"], cx[\"flops\"], cx[\"params\"], cx[\"acts\"]\n acts += _w_in * w\n return {\"h\": h, \"w\": 1, \"flops\": flops, \"params\": params, \"acts\": acts}\n\n\ndef gap2d_cx(cx, _w_in):\n \"\"\"Accumulates complexity of gap2d into cx = (h, w, flops, params, acts).\"\"\"\n h, w, flops, params, acts = cx[\"h\"], cx[\"w\"], cx[\"flops\"], cx[\"params\"], cx[\"acts\"]\n acts += _w_in * w * h\n return {\"h\": 1, \"w\": 1, \"flops\": flops, \"params\": params, \"acts\": acts}\n\n\ndef linear_cx(cx, w_in, w_out, *, bias=False):\n \"\"\"Accumulates complexity of linear into cx = (h, w, flops, params, acts).\"\"\"\n h, w, flops, params, acts = cx[\"h\"], cx[\"w\"], cx[\"flops\"], cx[\"params\"], cx[\"acts\"]\n flops += w_in * w_out + (w_out if bias else 0)\n params += w_in * w_out + (w_out if bias else 0)\n acts += w_in\n return {\"h\": h, \"w\": w, \"flops\": flops, \"params\": params, \"acts\": acts}\n\n\n# ---------------------------------- Shared blocks ----------------------------------- #\n\n\nclass SiLU(Module):\n \"\"\"SiLU activation function (also known as Swish): x * sigmoid(x).\"\"\"\n\n # Note: will be part of Pytorch 1.7, at which point can remove this.\n\n def __init__(self):\n super(SiLU, self).__init__()\n\n def forward(self, x):\n return x * torch.sigmoid(x)\n\n\ndef get_fca_weights(shape, freq=16):\n _, c, h, w = shape\n channels_per_freq = c // freq\n weights = np.ones((1,freq, h, w), np.float32)\n for i in range(1,freq):\n for wh in range(h):\n for ww in range(w):\n weights[0, i, wh, ww] = np.cos((np.pi * wh / h) * (wh + 0.5)) * np.cos((np.pi * ww / w) * (ww + 0.5))\n return torch.repeat_interleave(torch.from_numpy(weights), channels_per_freq, dim=1).cuda().float()\n\n\nclass FCA_SE(Module):\n \"\"\"FcaNet Squeeze-and-Excitation (SE) block: AvgPool, FC, Act, FC, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(FCA_SE, self).__init__()\n self.pre_computed_weights = None\n self.f_ex = nn.Sequential(\n conv2d(w_in, w_se, 1, bias=True),\n activation(),\n conv2d(w_se, w_in, 1, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n if self.pre_computed_weights is None:\n self.pre_computed_weights = get_fca_weights([int(i) for i in x.shape])\n sq = torch.unsqueeze(torch.unsqueeze(torch.sum(x * self.pre_computed_weights, dim=[2,3]), axis=-1), axis=-1)\n ex = self.f_ex(sq)\n return x * ex\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = gap2d_cx(cx, w_in)\n cx = conv2d_cx(cx, w_in, w_se, 1, bias=True)\n cx = conv2d_cx(cx, w_se, w_in, 1, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass SE(Module):\n \"\"\"Squeeze-and-Excitation (SE) block: AvgPool, FC, Act, FC, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(SE, self).__init__()\n self.avg_pool = gap2d(w_in)\n self.f_ex = nn.Sequential(\n conv2d(w_in, w_se, 1, bias=True),\n activation(),\n conv2d(w_se, w_in, 1, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n return x * self.f_ex(self.avg_pool(x))\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = gap2d_cx(cx, w_in)\n cx = conv2d_cx(cx, w_in, w_se, 1, bias=True)\n cx = conv2d_cx(cx, w_se, w_in, 1, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass C_SE(Module):\n \"\"\"Channel Squeeze-and-Excitation (cSE) block: 1x1, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(C_SE, self).__init__()\n self.f_ex = nn.Sequential(\n conv2d(w_in, 1, 1, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n return x * self.f_ex(x)\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = conv2d_cx(cx, w_in, 1, 1, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass SE_GAP(Module):\n \"\"\"Squeeze-and-Excitation without GAP (SE_GAP) block: 3x3, Act, 3x3, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(SE_GAP, self).__init__()\n self.f_ex = nn.Sequential(\n conv2d(w_in, w_se, 3, bias=True),\n activation(),\n conv2d(w_se, w_in, 3, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n return x * self.f_ex(x)\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = conv2d_cx(cx, w_in, w_se, 3, bias=True)\n cx = conv2d_cx(cx, w_se, w_in, 3, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass SE_GAP1(Module):\n \"\"\"Squeeze-and-Excitation without GAP (SE_GAP) block: 3x3, Act, 3x3, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(SE_GAP1, self).__init__()\n self.f_ex = nn.Sequential(\n conv2d(w_in, w_se, 1, bias=True),\n activation(),\n conv2d(w_se, w_in, 1, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n return x * self.f_ex(x)\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = conv2d_cx(cx, w_in, w_se, 1, bias=True)\n cx = conv2d_cx(cx, w_se, w_in, 1, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass SE_GAP_DW(Module):\n \"\"\"Squeeze-and-Excitation without GAP (SE_GAP) block: dw3x3, Act, dw3x3, Sigmoid.\"\"\"\n\n def __init__(self, w_in):\n super(SE_GAP_DW, self).__init__()\n self.f_ex = nn.Sequential(\n conv2d(w_in, w_in, 3, groups=w_in, bias=True),\n activation(),\n conv2d(w_in, w_in, 3, groups=w_in, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n return x * self.f_ex(x)\n\n @staticmethod\n def complexity(cx, w_in):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = conv2d_cx(cx, w_in, w_in, 3, groups=w_in, bias=True)\n cx = conv2d_cx(cx, w_in, w_in, 3, groups=w_in, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass EW_SE(Module):\n \"\"\"Efficient Width Squeeze-and-Excitation (EW_SE) block: AvgPool, 3x1, Act, 3x1, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(EW_SE, self).__init__()\n self.avg_pool = None\n self.f_ex = nn.Sequential(\n nn.Conv2d(w_in, w_se, 1, stride=1, padding=0, bias=True),\n activation(),\n nn.Conv2d(w_se, w_in, 1, stride=1, padding=0, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n if self.avg_pool is None:\n w = int(x.shape[-1])\n c = int(x.shape[1])\n self.avg_pool = nn.AvgPool2d((7, w), stride=(7, w), padding=0, ceil_mode=True)\n sq = self.avg_pool(x)\n ex = self.f_ex(sq)\n return x * torch.repeat_interleave(ex, 7, dim=-2)[:,:,:int(x.shape[-2]),:]\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = wap2d_cx(cx, w_in)\n cx = conv2d_cx(cx, w_in, w_se, 1, bias=True)\n cx = conv2d_cx(cx, w_in, w_se, 1, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\n\nclass W_SE(Module):\n \"\"\"Width Squeeze-and-Excitation (W_SE) block: AvgPool, 3x1, Act, 3x1, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se, add=False):\n super(W_SE, self).__init__()\n self.avg_pool = wap2d(w_in)\n self.add = add\n if self.add:\n self.f_ex = nn.Sequential(\n nn.Conv1d(w_in, w_se, 3, stride=1, padding=1, bias=True),\n activation(),\n nn.Conv1d(w_se, w_in, 3, stride=1, padding=1, bias=True),\n )\n else:\n self.f_ex = nn.Sequential(\n nn.Conv1d(w_in, w_se, 3, stride=1, padding=1, bias=True),\n activation(),\n nn.Conv1d(w_se, w_in, 3, stride=1, padding=1, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n sq = torch.squeeze(self.avg_pool(x))\n ex = torch.unsqueeze(self.f_ex(sq), -1)\n if self.add:\n return x + ex\n else:\n return x * ex\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = wap2d_cx(cx, w_in)\n cx = conv1d_cx(cx, w_in, w_se, 3, bias=True)\n cx = conv1d_cx(cx, w_se, w_in, 3, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass W1_SE(Module):\n \"\"\"Width Squeeze-and-Excitation (W_SE) block: AvgPool, 3x1, Act, 3x1, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(W1_SE, self).__init__()\n self.avg_pool = wap2d(w_in)\n self.f_ex = nn.Sequential(\n nn.Conv1d(w_in, w_se, 1, stride=1, padding=0, bias=True),\n activation(),\n nn.Conv1d(w_se, w_in, 1, stride=1, padding=0, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n return x * torch.unsqueeze(self.f_ex(torch.squeeze(self.avg_pool(x))), -1)\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = wap2d_cx(cx, w_in)\n cx = conv1d_cx(cx, w_in, w_se, 1, bias=True)\n cx = conv1d_cx(cx, w_se, w_in, 1, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\nclass W13_SE(Module):\n \"\"\"Width Squeeze-and-Excitation (W_SE) block: AvgPool, 1x1, Act, 3x1, Sigmoid.\"\"\"\n\n def __init__(self, w_in, w_se):\n super(W13_SE, self).__init__()\n self.avg_pool = wap2d(w_in)\n self.f_ex = nn.Sequential(\n nn.Conv1d(w_in, w_se, 1, stride=1, padding=0, bias=True),\n activation(),\n nn.Conv1d(w_se, w_in, 3, stride=1, padding=1, bias=True),\n nn.Sigmoid(),\n )\n\n def forward(self, x):\n return x * torch.unsqueeze(self.f_ex(torch.squeeze(self.avg_pool(x))), -1)\n\n @staticmethod\n def complexity(cx, w_in, w_se):\n h, w = cx[\"h\"], cx[\"w\"]\n cx = wap2d_cx(cx, w_in)\n cx = conv1d_cx(cx, w_in, w_se, 1, bias=True)\n cx = conv1d_cx(cx, w_se, w_in, 3, bias=True)\n cx[\"h\"], cx[\"w\"] = h, w\n return cx\n\n\n# ---------------------------------- Miscellaneous ----------------------------------- #\n\n\ndef adjust_block_compatibility(ws, bs, gs):\n \"\"\"Adjusts the compatibility of widths, bottlenecks, and groups.\"\"\"\n assert len(ws) == len(bs) == len(gs)\n assert all(w > 0 and b > 0 and g > 0 for w, b, g in zip(ws, bs, gs))\n vs = [int(max(1, w * b)) for w, b in zip(ws, bs)]\n gs = [int(min(g, v)) for g, v in zip(gs, vs)]\n ms = [np.lcm(g, b) if b > 1 else g for g, b in zip(gs, bs)]\n vs = [max(m, int(round(v / m) * m)) for v, m in zip(vs, ms)]\n ws = [int(v / b) for v, b in zip(vs, bs)]\n assert all(w * b % g == 0 for w, b, g in zip(ws, bs, gs))\n return ws, bs, gs\n\n\ndef init_weights(m):\n \"\"\"Performs ResNet-style weight initialization.\"\"\"\n if isinstance(m, nn.Conv2d):\n # Note that there is no bias due to BN\n fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(mean=0.0, std=np.sqrt(2.0 / fan_out))\n elif isinstance(m, nn.BatchNorm2d):\n zero_init_gamma = cfg.BN.ZERO_INIT_FINAL_GAMMA\n zero_init_gamma = hasattr(m, \"final_bn\") and m.final_bn and zero_init_gamma\n m.weight.data.fill_(0.0 if zero_init_gamma else 1.0)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(mean=0.0, std=0.01)\n m.bias.data.zero_()\n\n\ndef drop_connect(x, drop_ratio):\n \"\"\"Drop connect (adapted from DARTS).\"\"\"\n keep_ratio = 1.0 - drop_ratio\n mask = torch.empty([x.shape[0], 1, 1, 1], dtype=x.dtype, device=x.device)\n mask.bernoulli_(keep_ratio)\n x.div_(keep_ratio)\n x.mul_(mask)\n return x\n" ]
[ [ "numpy.sqrt", "torch.sum", "torch.repeat_interleave", "torch.from_numpy", "torch.nn.Sigmoid", "torch.sigmoid", "torch.empty", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.AvgPool2d", "torch.nn.Conv1d", "torch.nn.BatchNorm2d", "torch.nn.SiLU", "numpy.cos", "numpy.ones", "torch.nn.MaxPool2d", "torch.nn.AdaptiveAvgPool2d", "numpy.lcm", "torch.nn.ReLU" ] ]
paripooranan/Qiskit-India-Challenge
[ "7c016f85c9169c52f33c3d0a7a2f200477d2415d" ]
[ "answer_zz_2249.py" ]
[ "# the write_and_run function writes the content in this cell into the file \"feature_map.py\"\n\n### WRITE YOUR CODE BETWEEN THESE LINES - START\n \n# import libraries that are used in the function below.\nfrom qiskit import QuantumCircuit\nfrom qiskit.circuit import ParameterVector\nfrom qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap\n \n### WRITE YOUR CODE BETWEEN THESE LINES - END\n\ndef feature_map(): \n # BUILD FEATURE MAP HERE - START\n \n # import required qiskit libraries if additional libraries are required\n \n # build the feature map\n feature_dim = 3 # equal to the dimension of the data\n\n feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2)\n feature_map.draw()\n # BUILD FEATURE MAP HERE - END\n \n #return the feature map which is either a FeatureMap or QuantumCircuit object\n return feature_map# the write_and_run function writes the content in this cell into the file \"variational_circuit.py\"\n\n### WRITE YOUR CODE BETWEEN THESE LINES - START\n \n# import libraries that are used in the function below.\nfrom qiskit import QuantumCircuit\nfrom qiskit.circuit import ParameterVector\nfrom qiskit.circuit.library import RealAmplitudes, EfficientSU2\n \n### WRITE YOUR CODE BETWEEN THESE LINES - END\n\ndef variational_circuit():\n # BUILD VARIATIONAL CIRCUIT HERE - START\n \n # import required qiskit libraries if additional libraries are required\n num_qubits = 3\n # build the variational circuit\n var_circuit = RealAmplitudes(num_qubits, entanglement='full', reps=3)\n var_circuit.draw()\n # BUILD VARIATIONAL CIRCUIT HERE - END\n \n # return the variational circuit which is either a VaritionalForm or QuantumCircuit object\n return var_circuit# # the write_and_run function writes the content in this cell into the file \"optimal_params.py\"\n\n### WRITE YOUR CODE BETWEEN THESE LINES - START\n \n# import libraries that are used in the function below.\nimport numpy as np\n \n### WRITE YOUR CODE BETWEEN THESE LINES - END\n\ndef return_optimal_params():\n # STORE THE OPTIMAL PARAMETERS AS AN ARRAY IN THE VARIABLE optimal_parameters \n \n optimal_parameters = [ 2.01351742, 0.74134375, -0.47138808, -0.88925234, 2.21401814,\n -0.96824455, 0.59527984, -0.85758021, 1.3078055 , 0.3395687 ,\n 1.18676443, 0.27240381]\n \n # STORE THE OPTIMAL PARAMETERS AS AN ARRAY IN THE VARIABLE optimal_parameters \n return np.array(optimal_parameters)" ]
[ [ "numpy.array" ] ]
tianmingl/maincode
[ "724c60d5281ba3911ca065d9e144bb1b09e8257f" ]
[ "BiLstm_CNN_CRF_CWS/fenci_server.py" ]
[ "#coding:utf-8\n# py3.5+tensorflow-1.0.1+keras-2.0.6\n# seq2seq bilstm+cnn+crf\nimport os,re\nimport codecs \nimport pickle\nimport time\n\nimport bottle\nimport jieba\njieba.initialize()\n\nimport gc\nimport numpy as np\nnp.random.seed(1111)\n\nimport gensim\nimport random\n\nimport keras\n# keras.backend.clear_session() \n\nfrom keras.layers import *\nfrom keras.models import *\nfrom keras_contrib.layers import CRF\n\nfrom keras import backend as K\n\nfrom keras.utils import plot_model\nfrom keras.utils import np_utils\n\nfrom keras.preprocessing import sequence\nfrom keras.callbacks import ModelCheckpoint\n\nfrom keras.models import model_from_json\n\n# input:\n# maxlen char_value_dict_len class_label_count\ndef Bilstm_CNN_Crf(maxlen,char_value_dict_len,class_label_count,embedding_weights=None,is_train=True):\n\tword_input=Input(shape=(maxlen,),dtype='int32',name='word_input')\n\tif is_train:\n\t\tword_emb=Embedding(char_value_dict_len+2,output_dim=100,\\\n\t\t\t\t\tinput_length=maxlen,weights=[embedding_weights],\\\n\t\t\t\t\tname='word_emb')(word_input)\n\telse:\n\t\tword_emb=Embedding(char_value_dict_len+2,output_dim=100,\\\n\t\t\t\t\tinput_length=maxlen,\\\n\t\t\t\t\tname='word_emb')(word_input)\n\t\n\t# bilstm\n\tbilstm=Bidirectional(LSTM(64,return_sequences=True))(word_emb)\n\tbilstm_d=Dropout(0.1)(bilstm)\n\n\t# cnn\n\thalf_window_size=2\n\tpadding_layer=ZeroPadding1D(padding=half_window_size)(word_emb)\n\tconv=Conv1D(nb_filter=50,filter_length=2*half_window_size+1,\\\n\t\t\tpadding='valid')(padding_layer)\n\tconv_d=Dropout(0.1)(conv)\n\tdense_conv=TimeDistributed(Dense(50))(conv_d)\n\n\t# merge\n\trnn_cnn_merge=merge([bilstm_d,dense_conv],mode='concat',concat_axis=2)\n\tdense=TimeDistributed(Dense(class_label_count))(rnn_cnn_merge)\n\n\t# crf\n\tcrf=CRF(class_label_count,sparse_target=False)\n\tcrf_output=crf(dense)\n\n\t# build model\n\tmodel=Model(input=[word_input],output=[crf_output])\n\n\tmodel.compile(loss=crf.loss_function,optimizer='adam',metrics=[crf.accuracy])\n\n\t# model.summary()\n\n\treturn model\n\nclass Documents():\n\tdef __init__(self,chars,labels,index):\n\t\tself.chars=chars\n\t\tself.labels=labels\n\t\tself.index=index\n\n# 读取数据\ndef create_documents(file_name):\n\tdocuments=[]\n\tchars,labels=[],[]\n\n\twith codecs.open(file_name,'r','utf-8') as f:\n\t\tindex=0\n\t\tfor line in f:\n\n\t\t\tline=line.strip()\n\t\t\t\n\t\t\tif len(line)==0:\n\t\t\t\tif len(chars)!=0:\n\t\t\t\t\tdocuments.append(Documents(chars,labels,index))\n\t\t\t\t\tchars=[]\n\t\t\t\t\tlabels=[]\n\t\t\t\tindex+=1\n\n\t\t\telse:\n\t\t\t\tpieces=line.strip().split()\n\t\t\t\tchars.append(pieces[0])\n\t\t\t\tlabels.append(pieces[1])\n\n\t\t\t\tif pieces[0] in ['。',',',';']:\n\t\t\t\t\tdocuments.append(Documents(chars,labels,index))\n\t\t\t\t\tchars=[]\n\t\t\t\t\tlabels=[]\n\n\t\tif len(chars)!=0:\n\t\t\t\tdocuments.append(Documents(chars,labels,index))\n\t\t\t\tchars,labels=[],[]\n\treturn documents\n\n\n# 生成词典\ndef get_lexicon(all_documents):\n\tchars={}\n\tfor doc in all_documents:\n\t\tfor char in doc.chars:\n\t\t\tchars[char]=chars.get(char,0)+1\n\n\tsorted_chars=sorted(chars.items(),key=lambda x:x[1],reverse=True)\n\n\t# 下标从1开始 0用来补长\n\tlexicon=dict([(item[0],index+1) for index,item in enumerate(sorted_chars)])\n\tlexicon_reverse=dict([(index+1,item[0]) for index,item in enumerate(sorted_chars)])\n\treturn lexicon,lexicon_reverse\n\ndef create_embedding(embedding_model,embedding_size,lexicon_reverse):\n\tembedding_weights=np.zeros((len(lexicon_reverse)+2,embedding_size))\n\n\tfor i in range(len(lexicon_reverse)):\n\t\tembedding_weights[i+1]=embedding_model[lexicon_reverse[i+1]]\n\n\tembedding_weights[-1]=np.random.uniform(-1,1,embedding_size)\n\n\treturn embedding_weights\n\n\ndef create_matrix(documents,lexicon,label_2_index):\n\tdata_list=[]\n\tlabel_list=[]\n\tindex_list=[]\n\tfor doc in documents:\n\t\tdata_tmp=[]\n\t\tlabel_tmp=[]\n\n\t\tfor char,label in zip(doc.chars,doc.labels):\n\t\t\tdata_tmp.append(lexicon[char])\n\t\t\tlabel_tmp.append(label_2_index[label])\n\n\t\tdata_list.append(data_tmp)\n\t\tlabel_list.append(label_tmp)\n\t\tindex_list.append(doc.index)\n\n\treturn data_list,label_list,index_list\n\n\ndef padding_sentences(data_list,label_list,max_len):\n\tpadding_data_list=sequence.pad_sequences(data_list,maxlen=max_len)\n\tpadding_label_list=[]\n\tfor item in label_list:\n\t\tpadding_label_list.append([0]*(max_len-len(item))+item)\n\n\treturn padding_data_list,np.array(padding_label_list)\n\n\ndef process_data(s_file_list,t_file):\n\tft=codecs.open(t_file,'w','utf-8')\n\tk=0\n\tfor s_file in s_file_list:\n\t\twith codecs.open(s_file,'r','utf-8') as fs:\n\t\t\tlines=fs.readlines()\n\t\t\t# print(len(lines))\n\t\t\tfor line in lines:\n\t\t\t\tword_list=line.strip().split()\n\t\t\t\tfor word in word_list:\n\t\t\t\t\tif len(word)==1:\n\t\t\t\t\t\tft.write(word+'\\tS\\n')\n\t\t\t\t\telse:\n\t\t\t\t\t\tft.write(word[0]+'\\tB\\n')\n\t\t\t\t\t\tfor w in word[1:-1]:\n\t\t\t\t\t\t\tft.write(w+'\\tM\\n')\n\t\t\t\t\t\tft.write(word[-1]+'\\tE\\n')\n\t\t\t\tft.write('\\n')\n\tft.close()\n\n# 训练模型 保存weights\ndef process_train(corpus_path,nb_epoch):\n\t# 训练语料\n\traw_train_file=[corpus_path+os.sep+type_path+os.sep+type_file \\\n\t\t\t\tfor type_path in os.listdir(corpus_path) \\\n\t\t\t\tfor type_file in os.listdir(corpus_path+os.sep+type_path)]\n\n\n\tprocess_data(raw_train_file,'train.data')\n\n\ttrain_documents=create_documents('train.data')\n\n\tprint(len(train_documents))\n\n\t# for doc in train_documents[-20:]:\n\t# \tprint(doc.index,doc.chars,doc.labels)\n\n\t# 生成词典\n\tlexicon,lexicon_reverse=get_lexicon(train_documents)\n\tprint(len(lexicon),len(lexicon_reverse))\n\n\tembedding_model=gensim.models.Word2Vec.load(r'model_conll_law.m')\n\tembedding_size=embedding_model.vector_size\n\tprint(embedding_size)\n\n\t# 预训练词向量\n\tembedding_weights=create_embedding(embedding_model,embedding_size,lexicon_reverse)\n\tprint(embedding_weights.shape)\n\t# print(embedding_weights[-1])\n\n\t# print(lexicon_reverse[4351])\n\t# print(embedding_weights[-2])\n\n\t# 0 为padding的label\n\tlabel_2_index={'Pad':0,'B':1,'M':2,'E':3,'S':4,'Unk':5}\n\tindex_2_label={0:'Pad',1:'B',2:'M',3:'E',4:'S',5:'Unk'}\n\n\ttrain_data_list,train_label_list,train_index_list=create_matrix(train_documents,lexicon,label_2_index)\n\tprint(len(train_data_list),len(train_label_list),len(train_label_list))\n\tprint(train_data_list[0])\n\tprint(train_label_list[0])\n\n\tmax_len=max(map(len,train_data_list))\n\tprint('maxlen:',max_len)\n\n\ttrain_data_array,train_label_list_padding=padding_sentences(train_data_list,train_label_list,max_len)\n\tprint(train_data_array.shape)\n\tprint(train_data_array[0])\n\n\ttrain_label_array=np_utils.to_categorical(train_label_list_padding,len(label_2_index)).\\\n\t\t\t\t\treshape((len(train_label_list_padding),len(train_label_list_padding[0]),-1))\n\tprint(train_label_array.shape)\n\tprint(train_label_array[0])\n\n\t# model\n\tmodel=Bilstm_CNN_Crf(max_len,len(lexicon),len(label_2_index),embedding_weights)\n\tprint(model.input_shape)\n\tprint(model.output_shape)\n\n\tplot_model(model, to_file='bilstm_cnn_crf_model.png',show_shapes=True,show_layer_names=True)\n\n\tmodel.load_weights('train_model.hdf5')\n\n\thist=model.fit(train_data_array,train_label_array,batch_size=256,epochs=nb_epoch,verbose=1)\n\n\t# model.load_weights('best_val_model.hdf5')\n\t\n\n\t'''\n\ttest_y_pred=model.predict(train_data_array,batch_size=512,verbose=1)\n\tpred_label=np.argmax(test_y_pred,axis=2)\n\tprint(pred_label[0])\n\t\n\t'''\n\tscore=model.evaluate(train_data_array,train_label_array,batch_size=512)\n\tprint(score)\n\t\n\n\t# save model\n\tmodel.save_weights('train_model.hdf5')\n\n\t# save lexicon\n\tpickle.dump([lexicon,lexicon_reverse,max_len,index_2_label],open('lexicon.pkl','wb'))\n\n\n#===========Test================\n\n\n# input:text\ndef process_test(text,lexicon,max_len,model):\n\ttest_list=[]\n\tfor c in text:\n\t\ttest_list.append(lexicon.get(c,len(lexicon)+1))\n\n\tpadding_test_array=sequence.pad_sequences([test_list],maxlen=max_len)\n\t# print(padding_test_array.shape)\n\n\ttest_y_pred=model.predict(padding_test_array,verbose=1)\n\tpred_label=np.argmax(test_y_pred,axis=2)\n\t# print(pred_label[0])\n\n\treturn pred_label[0],padding_test_array[0]\n\n\ndef create_pred_text(text,pred_label):\n\n\tstart_index=len(pred_label)-len(text)\n\tpred_label=pred_label[start_index:]\n\n\tpred_text=''\n\tfor p,t in zip(pred_label,text):\n\t\tif p in [0,3,4,5]:\n\t\t\tpred_text+=(t+' ')\n\t\telse:\n\t\t\tpred_text+=t\n\n\treturn pred_text,pred_label\n\nlexicon,lexicon_reverse,max_len,index_2_label=pickle.load(open('lexicon.pkl','rb'))\n# model\nmodel=Bilstm_CNN_Crf(max_len,len(lexicon),len(index_2_label),is_train=False)\nmodel.load_weights('train_model.hdf5')\n\n# 句子长度太长会截断\ndef word_seg(text):\n\t# train 需要训练就取消这部分注释\n\t# corpus_path='corpus'\n\t# nb_epoch=5\n\t# process_train(corpus_path,nb_epoch)\n\t#=========Test===========\n\t\n\t# raw_len=len(text)\n\tpred_label,padding_test_array=process_test(text,lexicon,max_len,model)\n\n\tpred_text,pred_label=create_pred_text(text,pred_label)\n\n\t# print(pred_text)\n\t# print(pred_label)\n\n\treturn pred_text,pred_label\n\nimport math\n\ndef word_seg_by_sentences(text):\n\t'''\n\t# 长度1001切分 不好 如:中国人|寿\n\tcount=math.ceil(len(text)/100)\n\ttext_list=[]\n\ttext_list2=[]\n\tfor i in range(count):\n\t\t# text_list.append(text[i*100:(i+1)*100])\n\t\ttmp=text[i*100:(i+1)*100]\n\t\ttmp2=[]\n\t\tfor c in tmp:\n\t\t\ttmp2.append(lexicon.get(c,len(lexicon)+1))\n\t\ttext_list.append(tmp)\n\t\ttext_list2.append(tmp2)\n\t'''\n\n\ttext_list=[]\n\ttext_list2=[]\n\ti=0\n\tfor j in range(len(text)):\n\t\tif text[j] in [',','。','!',';','?'] or i+100<=j:\n\t\t\ttmp=text[i:j+1]\n\t\t\ti=j+1\n\n\t\t\ttmp2=[]\n\t\t\tfor c in tmp:\n\t\t\t\ttmp2.append(lexicon.get(c,len(lexicon)+1))\n\t\t\ttext_list.append(tmp)\n\t\t\ttext_list2.append(tmp2)\n\n\tif i!=j+1:\n\t\ttmp=text[i:j+1]\n\t\ttmp2=[]\n\t\tfor c in tmp:\n\t\t\ttmp2.append(lexicon.get(c,len(lexicon)+1))\n\t\ttext_list.append(tmp)\n\t\ttext_list2.append(tmp2)\n\n\n\tpadding_test_array=sequence.pad_sequences(text_list2,maxlen=max_len)\n\t\n\ttest_y_pred=model.predict(padding_test_array,verbose=1)\n\tpred_label_list=np.argmax(test_y_pred,axis=2)\n\n\n\tpred_text_all=''\n\tpred_label_all=[]\n\tfor text,label in zip(text_list,pred_label_list):\n\t\tpred_text,pred_label=create_pred_text(text,label)\n\t\tpred_text_all+=pred_text\n\t\tpred_label_all.extend(pred_label)\n\n\treturn pred_text_all,pred_label_all\n\n\n\nfrom lss_fenci_api import samme_cws\n\ndef add_color(s):\n\tns=''\n\tfor item in s.split():\n\t\tns+=('<b style=\"background:#ccffe6;\">%s</b>' %item)+' '\n\n\treturn ns\n\n'''\n# http://127.0.0.1:7777/cut?type=jieba/mine&text=我喜欢你\[email protected]('/cut',method='GET')\ndef token_home():\n\ttext=bottle.request.GET.getunicode('text')\n\tcut_type=bottle.request.GET.getunicode('type')\n\tif not text:\n\t\ttext=''\n\tif cut_type=='jieba':\n\t\ts=' '.join(jieba.cut(text.strip())).strip()\n\n\t\ts=add_color(s)\n\n\t\treturn s+'<br>%s<font color=\"green\">[By结巴分词]</font>' %('-'*20)\n\telif cut_type=='samme':\n\t\ts=samme_cws(text.strip())[0].strip()\n\n\t\ts=add_color(s)\n\n\t\treturn s+'<br>%s<font color=\"green\">[By Samme分词]</font>' %('-'*20)\n\telse:\n\t\ts,_=word_seg_by_sentences(text.strip())\n\t\ts=s.strip()\n\n\t\ts=add_color(s)\n\n\t\treturn s+'<br>%s<font color=\"green\">[By我的分词]</font>' %('-'*20)\n'''\n\nfrom flask import Flask,jsonify,abort\nfrom flask import request\nfrom flask import make_response\napp=Flask(__name__)\n\n# 首页\[email protected]('/')\ndef index():\n\treturn 'welcome to suda nlp fenci.'\n\[email protected]('/fenci',methods=['GET'])\ndef get_reply():\n\ttext=request.args.get('text','None')\n\tcut_type=request.args.get('type','mine')\n\n\tif cut_type=='jieba':\n\t\ts=' '.join(jieba.cut(text.strip())).strip()\n\n\t\ts=add_color(s)\n\n\t\treturn s+'<br>%s<font color=\"green\">[By结巴分词]</font>' %('-'*20)\n\telif cut_type=='samme':\n\t\ts=samme_cws(text.strip())[0].strip()\n\n\t\ts=add_color(s)\n\n\t\treturn s+'<br>%s<font color=\"green\">[By Samme分词]</font>' %('-'*20)\n\telse:\n\t\ts,_=word_seg_by_sentences(text.strip())\n\n\t\t##\n\t\t# keras.backend.clear_session() \n\n\t\ts=s.strip()\n\n\t\ts=add_color(s)\n\n\t\treturn s+'<br>%s<font color=\"green\">[By我的分词]</font>' %('-'*20)\n\n\n\n# def main():\n# \ttext='北京大学生,产量三年中将增长两倍'\n\n# \tK.clear_session()\n\n\ndef fenci_by_file(source_path,target_path):\n\n\tif not os.path.exists(target_path):\n\t\tos.mkdir(target_path)\n\n\n\tfor filename in os.listdir(source_path):\n\t\tlines=codecs.open(source_path+os.sep+filename,'r','utf-8').readlines()\n\t\t\n\t\tf=codecs.open(target_path+os.sep+filename,'w','utf-8')\n\t\tfor line in lines:\n\t\t\tline=line.strip()\n\t\t\t# splitText,_,_=samme_cws(line)\n\n\t\t\t# splitText=' '.join(jieba.cut(line))\n\n\t\t\tsplitText,_=word_seg_by_sentences(line)\n\n\t\t\tf.write(splitText+'\\n')\n\t\tf.close()\n\tprint('fenci success!')\n\ndef main():\n\t## word_seg 中有训练模块 指定corpus_path 和 nb_epoch\n\t# text='南京市长莅临指导,大家热烈欢迎。'\n\t# print(len(text))\n\n\t# pred_text,pred_label=word_seg(text)\n\t# print(pred_text)\n\n\n\t##############################################\n\t# 长句子测试 按标点切分后测试\n\ttext=''\n\tfor i in range(10):\n\n\t# \ttext+='''项脊轩,旧南阁子也。室仅方丈,可容一人居。百年老屋,尘泥渗漉,雨泽下注;每移案,顾视,无可置者。又北向,不能得日,日过午已昏。余稍为修葺,使不上漏。前辟四窗,垣墙周庭,以当南日,日影反照,室始洞然。又杂植兰桂竹木于庭,旧时栏楯,亦遂增胜。借书满架,偃仰啸歌,冥然兀坐,万籁有声;而庭堦寂寂,小鸟时来啄食,人至不去。三五之夜,明月半墙,桂影斑驳,风移影动,珊珊可爱。\n\t# 然余居于此,多可喜,亦多可悲。先是庭中通南北为一。迨诸父异爨,内外多置小门,墙往往而是。东犬西吠,客逾庖而宴,鸡栖于厅。庭中始为篱,已为墙,凡再变矣。家有老妪,尝居于此。妪,先大母婢也,乳二世,先妣抚之甚厚。室西连于中闺,先妣尝一至。妪每谓余曰:”某所,而母立于兹。”妪又曰:”汝姊在吾怀,呱呱而泣;娘以指叩门扉曰:‘儿寒乎?欲食乎?’吾从板外相为应答。”语未毕,余泣,妪亦泣。余自束发,读书轩中,一日,大母过余曰:”吾儿,久不见若影,何竟日默默在此,大类女郎也?”比去,以手阖门,自语曰:”吾家读书久不效,儿之成,则可待乎!”顷之,持一象笏至,曰:”此吾祖太常公宣德间执此以朝,他日汝当用之!”瞻顾遗迹,如在昨日,令人长号不自禁。\n\t# 轩东,故尝为厨,人往,从轩前过。余扃牖而居,久之,能以足音辨人。轩凡四遭火,得不焚,殆有神护者。\n\t# 项脊生曰:”蜀清守丹穴,利甲天下,其后秦皇帝筑女怀清台;刘玄德与曹操争天下,诸葛孔明起陇中。方二人之昧昧于一隅也,世何足以知之,余区区处败屋中,方扬眉、瞬目,谓有奇景。人知之者,其谓与坎井之蛙何异?”\n\t# 余既为此志,后五年,吾妻来归,时至轩中,从余问古事,或凭几学书。吾妻归宁,述诸小妹语曰:”闻姊家有阁子,且何谓阁子也?”其后六年,吾妻死,室坏不修。其后二年,余久卧病无聊,乃使人复葺南阁子,其制稍异于前。然自后余多在外,不常居。\n\t# 庭有枇杷树,吾妻死之年所手植也,今已亭亭如盖矣。殷昊。'''\n\n\t\ttext+='南京市长莅临指导,大家热烈欢迎。公交车中将禁止吃东西!'\n\tsplitText,predLabel=word_seg_by_sentences(text)\n\tprint(splitText)\n\n\t\n\t# 测试速度[极慢] 23362字 71KB / 248s word_seg\n\t# jieba 0.11s\n\t\n\t'''\n\t# big_test:\n\t# jieba:3737920字/18.97s=179043字/s 11487682B/18.97s=0.578M/s\n\t# Samme-Java:3737920字/3.641s=1026619字/s 11487682B/3.641s=3.0089M/s\n\tlines=codecs.open('test_documents/test_file_big.txt','r','utf-8').readlines()\n\t\n\ttime0=time.time()\n\n\t\n\tcount=0\n\tsplitTextList=[]\n\t# for line in codecs.open('test_documents/test_file.txt','r','utf-8'):\n\tfor line in lines:\n\t\tline=line.strip()\n\t\t# mine\n\t\t# splitText,predLabel=word_seg(line)\n\t\t# jieba\n\t\tsplitText=' '.join(jieba.cut(line))\n\n\t\tsplitTextList.append(splitText)\n\t\tcount+=len(line)\n\t\n\n\tlines=codecs.open('test_documents/test_file_big.txt','r','utf-8').read()\n\tsplitText,predLabel=word_seg_by_sentences(lines)\n\n\tprint('cost time:' ,(time.time()-time0))\n\n\t# print(len(splitTextList),count)\n\tprint(splitText[0])\n\n\t# f=codecs.open('test_documents/cws_result_jieba.txt','w','utf-8')\n\t# f.write('\\n'.join(splitTextList))\n\t# f.close()\n\t'''\n\t\n\t# fenci_by_file('test_documents/conll2012_test_raw','test_documents/conll2012_test_pred_mine')\n\t\n\nif __name__ == '__main__':\n \t# bottle.run(host='0.0.0.0',port=7777)\n \tapp.run(host='0.0.0.0',port=7777,debug=False)\n\t# main()\n\n" ]
[ [ "numpy.random.uniform", "numpy.array", "numpy.argmax", "numpy.random.seed" ] ]
NasaSpaceGrantRobotics/ASUR2019Drivetrain
[ "56c160a88008b558e87d8aac45f571c39e5fbafd" ]
[ "release/simpledrivetrain/simpledrivetrain/simple_drivetrain.py" ]
[ "import numpy as np\nfrom motor import Motor\nimport vectorutils as vutils\nfrom lxml import etree\n\n\nclass SimpleDrivetrain(object):\n def __init__(self, orientation=(0.0, 0.0, np.pi / 2.0)):\n self.__motors = None\n self.orientation = orientation\n\n def load_drivetrain_from_file(self, filepath):\n root = etree.parse(filepath).getroot()\n\n orientation_element = root.find('orientation')\n if orientation_element is not None:\n orientation_pitch = float(orientation_element.get('pitch'))\n orientation_roll = float(orientation_element.get('roll'))\n orientation_yaw = float(orientation_element.get('yaw'))\n orientation = (orientation_pitch, orientation_roll, orientation_yaw)\n self.orientation = orientation\n\n for motor_element in root.findall('motor'):\n name = motor_element.get('name')\n\n inverted = False\n if motor_element.get('inverted') == 'True':\n inverted = True\n\n position_element = motor_element.find('position')\n position_x = float(position_element.get('x'))\n position_y = float(position_element.get('y'))\n position_z = float(position_element.get('z'))\n position = (position_x, position_y, position_z)\n\n direction_element = motor_element.find('direction')\n direction_x = float(direction_element.get('x'))\n direction_y = float(direction_element.get('y'))\n direction_z = float(direction_element.get('z'))\n direction = (direction_x, direction_y, direction_z)\n\n pwm_bounds_element = motor_element.find('pwm_bounds')\n pwm_reverse = int(pwm_bounds_element.get('reverse'))\n pwm_stop = int(pwm_bounds_element.get('stop'))\n pwm_forward = int(pwm_bounds_element.get('forward'))\n pwm_bounds = (pwm_reverse, pwm_stop, pwm_forward)\n\n self.add_new_motor(name, position, direction, inverted, pwm_bounds)\n\n def add_new_motor(self, name, position, direction, inverted=False, pwm_bounds=(0, 512, 1024), pwm_scaling_func=None):\n if self.__motors is None:\n self.__motors = [Motor(name, position, direction, inverted, pwm_bounds, pwm_scaling_func)]\n else:\n self.__motors.append(Motor(name, position, direction, inverted, pwm_bounds, pwm_scaling_func))\n\n def get_motor_by_index(self, index):\n if (self.__motors is None) or not (0 <= index < len(self.__motors)):\n raise IndexError('Attempted to access a motor with an index that is out of bounds.')\n return self.__motors[index]\n\n def get_motor_by_name(self, name):\n if not (self.__motors is None):\n for motor in self.__motors:\n if motor.name == name:\n return motor\n\n def remove_motor_by_index(self, index):\n if (self.__motors is None) or not (0 <= index < len(self.__motors)):\n raise IndexError('Attempted to remove a motor with an index that is out of bounds.')\n else:\n self.__motors.pop(index)\n\n def remove_motor_by_name(self, name):\n if not (self.__motors is None):\n for motor in self.__motors:\n if motor.name == name:\n self.__motors.remove(motor)\n\n # translation = (x-axis translational velocity, y-axis translational velocity, z-axis translational velocity)\n # rotation = (x-axis angular velocity, y-axis angular velocity, z-axis angular velocity)\n # force_local_oriented is a boolean value\n # If set to True, ignores current drivetrain orientation and calculates local-oriented motor values\n # If set to False, uses current drivetrain orientation to calculate field-oriented motor values\n def get_motor_vels(self, translation, rotation, force_local_oriented=False):\n if self.__motors is None:\n raise RuntimeError(\"Attempted to get motor velocities for a drivetrain with an empty motor list.\")\n\n global_vector = translation\n motor_vels = [x * 0.0 for x in range(0, len(self.__motors))]\n orientation_reference_vector = np.array((0.0, 0.0, np.pi / 2.0))\n orientation_difference_vector = self.orientation - orientation_reference_vector\n\n for i in range(0, len(self.__motors)):\n motor_angle_pos = self.__motors[i].angle_position\n motor_dir_local = self.__motors[i].direction\n motor_dir_globalized = motor_dir_local\n\n if not force_local_oriented:\n motor_dir_globalized = vutils.rotate_vector(motor_dir_local, orientation_difference_vector[0],\n orientation_difference_vector[1],\n orientation_difference_vector[2])\n\n motor_vels[i] = (np.dot(motor_dir_globalized, global_vector))\n\n # apply any applicable rotational velocity\n yz_angle = motor_angle_pos[0]\n xz_angle = motor_angle_pos[1]\n xy_angle = motor_angle_pos[2]\n\n if yz_angle is not None:\n rot_vec_ccw_x = np.array([0, -np.sin(yz_angle), np.cos(yz_angle)])\n motor_vels[i] += rotation[0] * np.dot(motor_dir_local, rot_vec_ccw_x)\n\n if xz_angle is not None:\n rot_vec_ccw_y = np.array([-np.sin(xz_angle), 0, np.cos(xz_angle)])\n motor_vels[i] += rotation[1] * np.dot(motor_dir_local, rot_vec_ccw_y)\n\n if xy_angle is not None:\n rot_vec_ccw_z = np.array([-np.sin(xy_angle), np.cos(xy_angle), 0])\n motor_vels[i] += rotation[2] * np.dot(motor_dir_local, rot_vec_ccw_z)\n\n # scale each motor velocity by the maximum velocity\n mag_list = np.array(map(abs, motor_vels))\n max_mag = mag_list.max()\n if max_mag > 1.0:\n motor_vels = map(lambda x: x / max_mag, motor_vels)\n\n return motor_vels\n\n # translation = (x-axis translational velocity, y-axis translational velocity, z-axis translational velocity)\n # rotation = (x-axis angular velocity, y-axis angular velocity, z-axis angular velocity)\n # force_local_oriented is a boolean value\n # If set to True, ignores current drivetrain orientation and calculates local-oriented motor values\n # If set to False, uses current drivetrain orientation to calculate field-oriented motor values\n def get_motor_vels_scaled(self, translation, rotation, force_local_oriented=False):\n motor_vels = self.get_motor_vels(translation, rotation, force_local_oriented)\n\n for i in range(0, len(self.__motors)):\n motor_vels[i] = self.__motors[i].scale_velocity_to_pwm(motor_vels[i])\n\n return motor_vels\n\n @property\n def motors(self):\n return self.__motors\n\n @motors.setter\n def motors(self, value):\n pass\n\n def __str__(self):\n outstr = self.__repr__() + '\\n'\n\n for motor in self.__motors:\n outstr += '\\tMotor ' + motor.name + ':\\n'\n outstr += '\\t\\tInverted: ' + str(motor.inverted) + '\\n'\n outstr += '\\t\\tPosition: ' + str(motor.position) + '\\n'\n outstr += '\\t\\tDirection: ' + str(motor.direction) + '\\n'\n outstr += '\\t\\tPWM Bounds: ' + str(motor.pwm_bounds) + '\\n'\n if motor._Motor__pwm_scaling_func is not None:\n outstr += '\\t\\tPWM Scaling Function: Defined\\n'\n else:\n outstr += '\\t\\tPWM Scaling Function: Undefined\\n'\n\n outstr += '\\n'\n return outstr\n" ]
[ [ "numpy.dot", "numpy.array", "numpy.cos", "numpy.sin" ] ]
ssitaru/bodypart-id
[ "b46b0e18b041697dc27a029b978e27d911c9dca9" ]
[ "test.py" ]
[ "#!/usr/bin/python\n# This script predicts body part in test dataset\nimport os\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nimport numpy as np\nimport tensorflow\nfrom tensorflow import keras\nfrom keras import optimizers\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport csv\nimport re\n\n#csv\ncsvFile = open('delta.csv', 'a', newline=\"\")\ncsvWriter = csv.writer(csvFile)\n\n\n# Loading and Compiling Model\nMODEL = load_model('inception_v3_0.9635416865348816.h5')\nMODEL.compile(optimizer=optimizers.RMSprop(lr=2e-5),\n loss='categorical_crossentropy',\n metrics=['acc'])\n\n# Path of image you want to predict\nfor imageFile in os.listdir('./tests/images/'):\n # Find out real class\n realClass = re.sub(\"([a-zA-Z]+)\\-(\\d+).jpg\", r\"\\1\", imageFile)\n\n\n # Convert Img to an appropriate numpy array\n IMG = image.load_img('./tests/images/'+imageFile, target_size=(299, 299))\n X = image.img_to_array(IMG)\n X = np.expand_dims(X, axis=0)\n IMAGES = np.vstack([X])\n\n # The actual prediction\n CLASSES = MODEL.predict(IMAGES, batch_size=10)\n\n\n #if(CLASSES[0][CLASSES.argmax(axis=1)] < 0.1):\n # print('Predicted Classes for Images: others')\n #else:\n # Converting result of prediction to readable categories\n CATEGORIES = {0: 'anal', 1: 'arms', 2: 'armsAndHands',\n 3: 'face', 4: 'feet', 5: 'genitalsFemale',\n 6: 'genitalsMale', 7: 'hands', 8: 'head',\n 9: 'legs', 10: 'legsAndfeet', 11: 'torso'}\n #RESPONSE = [CATEGORIES[i] for i in CLASSES[0]]\n\n # delta: max value - mean value\n maxV = CLASSES[0][CLASSES.argmax()]\n newClassesWithoutMax = np.delete(CLASSES[0], CLASSES.argmax())\n print('Predicted Classes for Images: {}'.format(CATEGORIES[CLASSES.argmax()]))\n print(\"max prediction is\", maxV)\n print(\"delta is\", maxV - newClassesWithoutMax.mean())\n csvWriter.writerow([imageFile, realClass, CATEGORIES[CLASSES.argmax()], maxV, maxV - newClassesWithoutMax.mean()])" ]
[ [ "numpy.expand_dims", "numpy.vstack" ] ]
abidsikder/mit_crushes_analysis
[ "ef793af9644e55d20f89bc97b2a4e7edec176596" ]
[ "in_out_degree.py" ]
[ "import pandas as pd\n\ndata = pd.read_csv(\"anonymized_crushes.csv\")\n\n# indegree\nkerb_in = {}\n# outdegree\nkerb_out = {}\n\nfor row in range(0, data.shape[0]):\n # filter out all the NaNs\n person_info = list(filter(lambda x: not (pd.isna(x)), data.iloc[row]))\n kerb = person_info[0]\n crushes = list(person_info[1:])\n # remove duplicates\n crushes = list(set(crushes))\n\n # make sure this entry exists in both dictionaries\n if kerb not in kerb_in:\n kerb_in[kerb] = 0\n if kerb not in kerb_out:\n kerb_out[kerb] = 0\n\n # make sure all crushes exist in the indegree\n for crush in crushes:\n if crush not in kerb_in:\n kerb_in[crush] = 0\n\n # indegree\n for crush in crushes:\n kerb_in[crush] = kerb_in[crush] + 1\n\n # outdegree\n outdegree = len(crushes)\n kerb_out[kerb] = outdegree\n\noutput = []\nfor kerb in kerb_out:\n indegree = kerb_in[kerb]\n outdegree = kerb_out[kerb]\n output.append([kerb, indegree, outdegree])\n\ncsv_out = pd.DataFrame(output, columns=[\"kerb\", \"indegree\", \"outdegree\"])\n\ncsv_out.to_csv(\"InOutDegrees.csv\", index=False)\n" ]
[ [ "pandas.isna", "pandas.read_csv", "pandas.DataFrame" ] ]
Nishitha77/interfacegan
[ "20be1b1861a0a71dfad44ad61d517a8bef73bddc" ]
[ "models/stylegan_tf_official/metrics/perceptual_path_length.py" ]
[ "# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\r\n#\r\n# This work is licensed under the Creative Commons Attribution-NonCommercial\r\n# 4.0 International License. To view a copy of this license, visit\r\n# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to\r\n# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.\r\n\r\n\"\"\"Perceptual Path Length (PPL).\"\"\"\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport dnnlib.tflib as tflib\r\n\r\nfrom metrics import metric_base\r\nfrom training import misc\r\n\r\n#----------------------------------------------------------------------------\r\n\r\n# Normalize batch of vectors.\r\ndef normalize(v):\r\n return v / tf.sqrt(tf.reduce_sum(tf.square(v), axis=-1, keepdims=True))\r\n\r\n# Spherical interpolation of a batch of vectors.\r\ndef slerp(a, b, t):\r\n a = normalize(a)\r\n b = normalize(b)\r\n d = tf.reduce_sum(a * b, axis=-1, keepdims=True)\r\n p = t * tf.math.acos(d)\r\n c = normalize(b - d * a)\r\n d = a * tf.math.cos(p) + c * tf.math.sin(p)\r\n return normalize(d)\r\n\r\n#----------------------------------------------------------------------------\r\n\r\nclass PPL(metric_base.MetricBase):\r\n def __init__(self, num_samples, epsilon, space, sampling, minibatch_per_gpu, **kwargs):\r\n assert space in ['z', 'w']\r\n assert sampling in ['full', 'end']\r\n super().__init__(**kwargs)\r\n self.num_samples = num_samples\r\n self.epsilon = epsilon\r\n self.space = space\r\n self.sampling = sampling\r\n self.minibatch_per_gpu = minibatch_per_gpu\r\n\r\n def _evaluate(self, Gs, num_gpus):\r\n minibatch_size = num_gpus * self.minibatch_per_gpu\r\n\r\n # Construct TensorFlow graph.\r\n distance_expr = []\r\n for gpu_idx in range(num_gpus):\r\n with tf.device('/gpu:%d' % gpu_idx):\r\n Gs_clone = Gs.clone()\r\n noise_vars = [var for name, var in Gs_clone.components.synthesis.vars.items() if name.startswith('noise')]\r\n\r\n # Generate random latents and interpolation t-values.\r\n lat_t01 = tf.random_normal([self.minibatch_per_gpu * 2] + Gs_clone.input_shape[1:])\r\n lerp_t = tf.random_uniform([self.minibatch_per_gpu], 0.0, 1.0 if self.sampling == 'full' else 0.0)\r\n\r\n # Interpolate in W or Z.\r\n if self.space == 'w':\r\n dlat_t01 = Gs_clone.components.mapping.get_output_for(lat_t01, None, is_validation=True)\r\n dlat_t0, dlat_t1 = dlat_t01[0::2], dlat_t01[1::2]\r\n dlat_e0 = tflib.lerp(dlat_t0, dlat_t1, lerp_t[:, np.newaxis, np.newaxis])\r\n dlat_e1 = tflib.lerp(dlat_t0, dlat_t1, lerp_t[:, np.newaxis, np.newaxis] + self.epsilon)\r\n dlat_e01 = tf.reshape(tf.stack([dlat_e0, dlat_e1], axis=1), dlat_t01.shape)\r\n else: # space == 'z'\r\n lat_t0, lat_t1 = lat_t01[0::2], lat_t01[1::2]\r\n lat_e0 = slerp(lat_t0, lat_t1, lerp_t[:, np.newaxis])\r\n lat_e1 = slerp(lat_t0, lat_t1, lerp_t[:, np.newaxis] + self.epsilon)\r\n lat_e01 = tf.reshape(tf.stack([lat_e0, lat_e1], axis=1), lat_t01.shape)\r\n dlat_e01 = Gs_clone.components.mapping.get_output_for(lat_e01, None, is_validation=True)\r\n\r\n # Synthesize images.\r\n with tf.control_dependencies([var.initializer for var in noise_vars]): # use same noise inputs for the entire minibatch\r\n images = Gs_clone.components.synthesis.get_output_for(dlat_e01, is_validation=True, randomize_noise=False)\r\n\r\n # Crop only the face region.\r\n c = int(images.shape[2] // 8)\r\n images = images[:, :, c*3 : c*7, c*2 : c*6]\r\n\r\n # Downsample image to 256x256 if it's larger than that. VGG was built for 224x224 images.\r\n if images.shape[2] > 256:\r\n factor = images.shape[2] // 256\r\n images = tf.reshape(images, [-1, images.shape[1], images.shape[2] // factor, factor, images.shape[3] // factor, factor])\r\n images = tf.reduce_mean(images, axis=[3,5])\r\n\r\n # Scale dynamic range from [-1,1] to [0,255] for VGG.\r\n images = (images + 1) * (255 / 2)\r\n\r\n # Evaluate perceptual distance.\r\n img_e0, img_e1 = images[0::2], images[1::2]\r\n distance_measure = misc.load_pkl('https://drive.google.com/uc?id=1N2-m9qszOeVC9Tq77WxsLnuWwOedQiD2') # vgg16_zhang_perceptual.pkl\r\n distance_expr.append(distance_measure.get_output_for(img_e0, img_e1) * (1 / self.epsilon**2))\r\n\r\n # Sampling loop.\r\n all_distances = []\r\n for _ in range(0, self.num_samples, minibatch_size):\r\n all_distances += tflib.run(distance_expr)\r\n all_distances = np.concatenate(all_distances, axis=0)\r\n\r\n # Reject outliers.\r\n lo = np.percentile(all_distances, 1, interpolation='lower')\r\n hi = np.percentile(all_distances, 99, interpolation='higher')\r\n filtered_distances = np.extract(np.logical_and(lo <= all_distances, all_distances <= hi), all_distances)\r\n self._report_result(np.mean(filtered_distances))\r\n\r\n#----------------------------------------------------------------------------\r\n" ]
[ [ "tensorflow.device", "tensorflow.math.cos", "tensorflow.control_dependencies", "tensorflow.reduce_mean", "tensorflow.reduce_sum", "tensorflow.stack", "tensorflow.reshape", "numpy.percentile", "numpy.concatenate", "tensorflow.math.sin", "numpy.mean", "tensorflow.square", "tensorflow.math.acos", "numpy.logical_and", "tensorflow.random_uniform", "tensorflow.random_normal" ] ]
james-alvey-42/BoostedDM
[ "72ff9c707657f95806bea759cb819c2a8e90b23c", "72ff9c707657f95806bea759cb819c2a8e90b23c" ]
[ "Code/Python/limits.py", "Code/Python/atmos_dm_flux.py" ]
[ "# File: limits.py\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport sys\nimport scipy.stats\n\nfrom atmos_dm_flux import kdemultifit\nfrom mean_free_path import TzMin\n\ndef get_kernel(particle):\n r\"\"\"\n Obtains the kernel and the normalisation factor for the dark matter flux from pions and eta particle decays. This can then be called directly on an array of energies as `kernel.evaluate(energies)`.\n\n Parameters\n ----------\n particle : str ('pion' or 'eta')\n the particle from which the dark matter particles are produced\n\n Returns\n -------\n kernel : scipy.stats.gaussian_kde\n the kernel, which can be called directly on an array of energies\n normalisation factor : float\n the normalisation factor for the flux, this is because the scipy.stats.gaussian_kde is normalised by default\n\n Examples\n --------\n >>> kernel, norm = get_kernel('eta')\n >>> kernel.evaluate(np.power(10.0, -1))\n 1.24491518\n >>> norm\n 8.905796945913948e-27\n \"\"\"\n if particle == 'pion':\n save_directory = '/mnt/james/atmos/'\n elif particle == 'eta':\n save_directory = '../data/'\n chi_energies = np.load('{}chienergies.npy'.format(save_directory))\n chi_weights = np.load('{}chiweights.npy'.format(save_directory))\n bw = np.power(10.0, -1.5)\n kernel = scipy.stats.gaussian_kde(dataset=chi_energies, weights=chi_weights, bw_method=bw)\n counts, _ = np.histogram(chi_energies, bins=1, weights=chi_weights)\n norm = counts[0]\n return kernel, norm\n\ndef get_Gdet_fit():\n r\"\"\"\n Returns the 1d interpolation for the :py:func:`Gdet` function, trained on 100 cross sections between :math:`10^{-34}` and :math:`10^{-28}\\,\\textrm{cm}^2`.\n\n Returns\n -------\n GdetFit : scipy.interpolate.interp1d\n Gdet interpolation [:math:`\\textrm{cm}^{-2}`]\n\n Examples\n --------\n >>> GdetFit = get_Gdet_fit()\n >>> GdetFit(np.power(10.0, -34))\n array(2.52933574e+25)\n \"\"\"\n GdetFit = np.load('GdetFit.npy')[0]\n return GdetFit\n\ndef limit_prefactor(mchi=0.001):\n r\"\"\"\n Returns the prefactor for the limit plot.\n\n Parameters\n ----------\n mchi : float\n mass of the dark matter particle [:math:`\\textrm{GeV}`]\n\n Returns\n -------\n prefactor : float\n the prefactor [:math:`\\textrm{s}^{-1}`]\n\n Notes\n -----\n We are implementing the following definition for the prefactor,\n\n .. math:: \\kappa (\\bar{v} \\rho_{\\textrm{DM}})^{\\textrm{ local}}\\left(\\frac{m_\\chi + m_N}{m_\\chi + m_p}\\right)^2\\left(\\frac{\\sigma^{\\textrm{ SI, lim}}_{\\textrm{ DM}}}{m_{\\textrm{ DM}}}\\right)_{m_{\\textrm{DM}}\\rightarrow \\infty}\n\n In terms of parameter values we are taking :math:`\\kappa = 0.23`, :math:`\\bar{v} = 250\\,\\textrm{km}\\,\\textrm{s}^{-1}`, :math:`\\rho_{\\textrm{ DM}} = 0.3\\,\\textrm{GeV}\\,\\textrm{cm}^{-3}`, :math:`m_N = m_{\\textrm{Xe}} = 115.3909 \\,\\textrm{GeV}`, :math:`\\left(\\frac{\\sigma^{\\textrm{ SI, lim}}_{\\textrm{ DM}}}{m_{\\textrm{ DM}}}\\right)_{m_{\\textrm{DM}}\\rightarrow \\infty} = 8.3 \\times 10^{-49}\\,\\textrm{cm}^2 \\,\\textrm{GeV}^{-1}`, :math:`m_p = 0.938272\\,\\textrm{GeV}`.\n\n Examples\n --------\n >>> limit_prefactor(mchi=0.001)\n 2.1609020839512918e-32\n \"\"\"\n k = 0.23\n vbar = 250*np.power(10.0, 5) # cm s^-1\n rhodm = 0.3 # GeV cm^-3\n mXe = 115.3909 # GeV\n mp = 0.938272 # GeV\n sigmamchi = 8.3*np.power(10.0, -49) # cm^2 GeV^-1\n return k*vbar*rhodm*np.power(mchi + mXe, 2.0)*np.power(mchi + mp, -2.0)*sigmamchi\n\ndef get_integral(particle, mchi=0.001, dTN=np.power(10.0, -7), dTchi=np.power(10.0, -3)):\n r\"\"\"\n Computes the integral in the denominator of equation (16) in `1810.10543 <https://arxiv.org/pdf/1810.10543.pdf>`_. Computes it in the case of both the pions and the eta fluxes.\n\n Parameters\n ----------\n particle : str ('pion' or 'dm')\n the dm flux being considered\n mchi : float\n mass of the dark matter particle [:math:`\\textrm{GeV}`]\n dTN : float\n nuclear recoil interval [:math:`\\textrm{GeV}`]\n dTchi : float\n dark matter energy interval [:math:`\\textrm{GeV}`]\n\n Returns\n -------\n integral : float\n the result of the double integral [:math:`\\textrm{s}^{-1}`]\n\n Notes\n -----\n We are computing,\n\n .. math:: \\int_{T_1}^{T_2}{\\textrm{d}T_N\\,\\int^{\\infty}_{T_\\chi(T_\\chi^{z, \\textrm{min}})}{\\textrm{d}T_\\chi}\\,\\frac{1}{T^{\\textrm{max}}_{r, N}}\\frac{\\textrm{d}\\phi_\\chi}{\\textrm{d}T_\\chi} }\n\n Here :math:`T_1 = 4.9 \\,\\textrm{keV}` and :math:`40.9\\,\\textrm{keV}` are the recoil energy bounds in the Xenon 1T detector.\n \"\"\"\n #TzMin(mchi=mchi, TN=TN)\n TchiMax = np.power(10.0, 1)\n T1 = 4.9*np.power(10.0, -6) # GeV\n T2 = 40.9*np.power(10.0, -6) # GeV\n kernel, norm = get_kernel(particle)\n TNarr = np.arange(T1, T2, dTN)\n\n integral = 0.0\n count = 1\n print('Starting Integration')\n for TN in TNarr:\n TchiMin = TzMin(mchi=mchi, TN=TN)\n Tchiarr = np.arange(TchiMin, TchiMax, dTchi)\n TrNarr = TrNMax(Tchiarr, mchi)\n fluxarr = norm*kernel.evaluate(Tchiarr)\n farr = fluxarr*np.power(TrNarr, -1.0)\n integral += farr.sum()*dTN*dTchi\n print('Completed {} out of {} recoil energies'.format(count, len(TNarr)), end='\\r')\n count += 1\n print('\\n--------\\nResults:\\n--------\\n\\nIntegral: {}, particle = {}\\n'.format(integral, particle))\n return integral\n\ndef get_integral_v2(particle, mchi=0.001, dTchi=np.power(10.0, -3.0), TchiMax=np.power(10.0, 1.0)):\n r\"\"\"\n Computes the integral in the denominator of equation (16) in `1810.10543 <https://arxiv.org/pdf/1810.10543.pdf>`_. Computes it in the case of both the pions and the eta fluxes. [version 2]\n\n Parameters\n ----------\n particle : str ('pion' or 'dm')\n the dm flux being considered\n mchi : float\n mass of the dark matter particle [:math:`\\textrm{GeV}`]\n dTN : float\n nuclear recoil\n\n Returns\n -------\n integral : float\n the result of the double integral\n\n Notes\n -----\n We are computing,\n\n .. math:: \\int_{T_1}^{T_2}{\\textrm{d}T_N\\,\\int^{\\infty}_{T_\\chi(T_\\chi^{z, \\textrm{min}})}{\\textrm{d}T_\\chi}\\,\\frac{1}{T^{\\textrm{max}}_{r, N}}\\frac{\\textrm{d}\\phi_\\chi}{\\textrm{d}T_\\chi} }\n\n Here :math:`T_1 = 4.9 \\,\\textrm{keV}` and :math:`40.9\\,\\textrm{keV}` are the recoil energy bounds in the Xenon 1T detector.\n \"\"\"\n TchiMin = TzMin(mchi=mchi)\n TchiArr = np.arange(TchiMin, TchiMax, dTchi)\n TNBoundArr = TNBound(TchiArr, mchi=mchi)\n dTNArr = TNBoundArr - 4.9*np.power(10.0, -6.0)\n kernel, norm = get_kernel(particle)\n fluxArr = norm*kernel.evaluate(TchiArr)\n TrNArr = TrNMax(TchiArr, mchi)\n integrands = fluxArr*np.power(TrNArr, -1.0)*dTNArr*dTchi\n integral = integrands.sum()\n print('\\n--------\\nResults:\\n--------\\n\\nIntegral: {}, particle = {}\\n'.format(integral, particle))\n return integral\n\ndef TrNMax(Tchi, mchi=0.001):\n r\"\"\"\n Returns the maximum recoil energy using equation (1) in `1810.10543 <https://arxiv.org/pdf/1810.10543.pdf>`_.\n\n Parameters\n ----------\n Tchi : float\n kinetic energy of the dark matter particle [:math:`\\textrm{GeV}`]\n mchi : float\n mass of the dark matter particle [:math:`\\textrm{GeV}`]\n\n Returns\n -------\n TrNMax : float or np.array\n maximum recoil energy [:math:`\\textrm{GeV}`]\n\n Notes\n -----\n We are implementing the expression,\n\n .. math:: \\frac{T_\\chi^2 + 2m_\\chi T_\\chi}{T_\\chi + \\frac{(m_\\chi + m_{\\textrm{Xe}})^2}{2m_\\textrm{Xe}}}\n\n Examples\n --------\n >>> TrNMax(Tchi=np.power(10.0, -2), mchi=0.001)\n 2.0794902474678193e-06\n >>> TrNMax(Tchi=np.array([np.power(10.0, -2.0), np.power(10.0, -1.0)]), mchi=0.001)\n array([2.07949025e-06, 1.76481427e-04])\n \"\"\"\n mXe = 115.3909 # GeV\n num = np.power(Tchi, 2.0) + 2*mchi*Tchi\n denom = Tchi + np.power(mchi + mXe, 2.0)*np.power(2*mXe, -1.0)\n return num*np.power(denom, -1.0)\n\ndef get_xenon_rate(gu=5.0*np.power(10.0, -5.0), ms=0.001, dTN=np.power(10.0, -8.0), dTchi=np.power(10.0, -3.0), TchiMax=np.power(10.0, 0)):\n r\"\"\"\n Computes the rate for the specific hadrophilic model given in `Batell et al. <http://inspirehep.net/record/1708854>`_ in the Xenon 1T detector. Given an exposure time (278.8 days), the number of expected events can be calculated as :math:`\\Gamma_N T_{\\textrm{exp}}`. The 90% confidence level is then found by comparing this event number to 3.56 events, from Table I in the most recent `Xenon 1T paper <https://arxiv.org/pdf/1805.12562.pdf>`_.\n\n Parameters\n ----------\n gu : float\n coupling to up-quark\n ms : float\n mass of the scalar mediator [:math:`\\textrm{GeV}`]\n dTN : float\n recoil energy integration resolution [:math:`\\textrm{GeV}`]\n dTchi : float\n dark matter energy resolution [:math:`\\textrm{GeV}`]\n TchiMax : float\n maximum dark matter energy [:math:`\\textrm{GeV}`]\n\n Returns\n -------\n gN : float\n rate [:math:`\\textrm{s}^{-1}`]\n\n Notes\n -----\n We are implementing the following definition,\n\n .. math:: \\Gamma_N = N_T \\int_{T_1}^{T_2}{\\textrm{d}T_N \\, \\int_{T_\\chi^{\\textrm{min}}(T_N)}^{\\infty}{\\textrm{d}T_\\chi \\, \\epsilon(T_N)\\frac{\\textrm{d}\\phi_\\chi}{\\textrm{d}T_\\chi}\\frac{\\textrm{d}\\sigma_{\\chi N}}{\\textrm{d}T_N} } }\n\n Examples\n --------\n >>> get_xenon_rate(gu=5.0*np.power(10.0, -5.0), ms=0.001)\n \"\"\"\n print('-----------------------------------------------------\\nXenon 1T Rate Calculator\\n-----------------------------------------------------\\nComputing rate for gu = {}, ms = {} GeV'.format(gu, ms))\n print('dTchi = {}, dTN = {}'.format(dTchi, dTN))\n Gdet = 2.529335739713634*np.power(10.0, 25.0) # Assuming Earth is transparent on the lower boundary\n mchi = ms/3\n gchi = 1.0\n A = 131.293\n Z = 54.0\n NT = 1300/(A*1.66054*np.power(10.0, -27))\n epsilon = 0.89\n mN = 0.9314941*A\n mp = 0.938272 # GeV\n mn = 0.939565 # GeV\n mu = 0.0022 # GeV\n yspp = 0.014*gu*mp/mu\n ysnn = 0.012*gu*mn/mu\n br = get_branching_ratio(gu=gu, ms=ms)\n print('\\nBranching Ratio = {}'.format(br))\n TchiArr = np.arange(0.015, TchiMax, dTchi)\n TNArr = np.arange(4.9*np.power(10.0, -6.0), 40.9*np.power(10.0, -6.0), dTN)\n TN, TCHI = np.meshgrid(TNArr, TchiArr)\n kernel, norm = get_kernel('eta')\n FluxArr = norm*Gdet*br*kernel.evaluate(TchiArr)\n _, FLUX = np.meshgrid(TNArr, FluxArr)\n prefactor = (np.power(Z*yspp + (A - Z)*ysnn, 2.0)*np.power(gchi, 2.0)/(8*np.pi))\n DSIGMATN = prefactor*(2*mN + TN)*(2*np.power(mchi, 2.0) + mN*TN)*np.power(2*mN*TN + np.power(ms, 2.0), -2.0)*form_factor(TN)\n DSIGMATCHI = np.power(np.power(TCHI, 2.0) + 2*mchi*TCHI, -1.0)\n DSIGMA = DSIGMATN*DSIGMATCHI*np.power(1/(5.06*np.power(10.0, 13)), 2.0)\n INTEGRAND = NT*epsilon*DSIGMA*FLUX*np.heaviside(TNBound(TCHI) - TN, 1.0)\n gN = INTEGRAND.sum()*dTchi*dTN\n events = gN*278.8*86400\n print('\\n--------\\nResults:\\n--------\\n\\nRate: {} per second, Events = {}\\n'.format(gN, events))\n return gN, events\n\n\ndef form_factor(TN):\n r\"\"\"\n Returns the Helm Form Factor from `0608.035 <https://arxiv.org/pdf/hep-ph/0608035.pdf>`_.\n\n Parameters\n ----------\n TN : np.array\n nuclear recoil energy [:math:`\\textrm{GeV}`]\n\n Returns\n -------\n FHsq : np.array\n square of the Helm Form Factor\n\n Examples\n --------\n >>> form_factor(TN=5.0*np.power(10.0, -6.0))\n 0.7854737713313549\n \"\"\"\n A = 131.293\n mN = 0.9314941*A\n q = np.sqrt(2*mN*TN)\n fmGeV = 1/(1.98*np.power(10.0, -1.0))\n s = 0.9*fmGeV\n a = 0.52*fmGeV\n c = (1.23*np.power(A, 1/3) - 0.60)*fmGeV\n R1 = np.sqrt(np.power(c, 2.0) + (7/3)*np.power(np.pi, 2.0)*np.power(a, 2.0) - 5*np.power(s, 2.0))\n FHsq = 9*np.exp(-np.power(q*s, 2.0))*np.power(q*R1, -2.0)*np.power(np.sin(q*R1)*np.power(q*R1, -2.0) - np.cos(q*R1)*np.power(q*R1, -1.0), 2.0)\n return FHsq\n\ndef get_branching_ratio(gu, ms):\n r\"\"\"\n Returns the branching ratio for the process :math:`\\eta \\rightarrow \\pi^0 \\chi\\chi` from the model in `Batell et al. <https://arxiv.org/pdf/1812.05103.pdf>`_.\n\n Parameters\n ----------\n gu : float\n coupling to up-quark\n ms : float\n scalar mediator mass [:math:`\\textrm{GeV}`]\n\n Returns\n -------\n br : float\n branching ratio :math:`\\textrm{BR}(\\eta \\rightarrow \\pi^0 \\chi\\chi)`\n\n Notes\n -----\n We are implementing the following expression,\n\n .. math:: \\textrm(\\eta \\rightarrow \\pi^0 S) = \\frac{C^2 g_u^2 B^2}{16\\pi m_\\eta \\Gamma_\\eta}\\lambda^{1/2}\\left(1, \\frac{m_S^2}{m_\\eta^2}, \\frac{m_\\pi^2}{m_\\eta^2}\\right)\n\n where we are assuming a branching ratio :math:`\\textrm{BR}(S \\rightarrow \\chi\\chi) = 1`, and :math:`\\lambda(a, b, c) = a^2 + b^2 + c^2 - 2(ab + bc + ac)`.\n\n Examples\n --------\n >>> get_branching_ratio(gu=7*np.power(10.0, -4.0), ms=0.1)\n 0.05765234404584737\n \"\"\"\n thetapr = -np.pi/9\n mpi = 0.1349770 # GeV\n meta = 0.547862 # GeV\n mu = 0.0022 # GeV\n md = 0.0047 # GeV\n geta = 1.31*np.power(10.0, -6.0) # GeV\n C = np.sqrt(1/3)*np.cos(thetapr) - np.sqrt(2/3)*np.sin(thetapr)\n B = np.power(mpi, 2.0)*np.power(mu + md, -1.0)\n a = 1.0\n b = np.power(ms/meta, 2.0)\n c = np.power(mpi/meta, 2.0)\n br = np.power(C*gu*B, 2.0)*np.power(16*np.pi*meta*geta, -1.0)*np.sqrt(np.power(a, 2) + np.power(b, 2) + np.power(c, 2) - 2*a*b - 2*b*c - 2*a*c)\n return br\n\n\ndef TNBound(Tchi, mchi=0.001, mN=115.3909, Trecoil_max=40.9*np.power(10.0, -6.0)):\n r\"\"\"\n Inverts the relation for the expression in :py:func:`TzMin` to find the maximum recoil energy that can be generated from a dark matter kinetic energy :math:`T_\\chi`.\n\n Parameters\n ----------\n Tchi : float\n kinetic energies of dark matter particle [:math:`\\textrm{GeV}`]\n mchi : float\n mass of the dark matter particle [:math:`\\textrm{GeV}`]\n mN : float\n mass of the recoil nucleus [:math:`\\textrm{GeV}`]\n Trecoil_max : float\n maximum detector sensitivity for recoil energies [:math:`\\textrm{GeV}`]\n\n Returns\n -------\n TNBound : np.array\n maximum recoil energy, either kinematically or by detector sensitivity\n\n Notes\n -----\n We are implementing the following,\n\n .. math:: T_N^{\\textrm{bound}} = \\textrm{min}\\left[\\frac{2(2 m_\\chi + T_\\chi)m_N T_\\chi}{m_\\chi^2 + 2m_\\chi m_N + m_N^2 + 2m_N T_\\chi}, T_N^{\\textrm{recoil}}\\right]\n\n For Xenon 1T, :math:`T_N^{\\textrm{recoil}} = 40.9\\,\\textrm{keV}` and :math:`m_N = 115.3909\\,\\textrm{GeV}`.\n\n Examples\n --------\n >>> TNBound(np.array([0.015, 0.020]), mchi=0.001, mN=115.3909, Trecoil_max=40.9*np.power(10.0, -6.0))\n array([4.41853393e-06, 7.62347650e-06])\n >>> TNBound(np.array([0.040, 0.050, 0.055]), mchi=0.001, mN=115.3909, Trecoil_max=40.9*np.power(10.0, -6.0))\n array([2.90977363e-05, 4.09000000e-05, 4.09000000e-05])\n \"\"\"\n TNBound = 2*mN*Tchi*(2*mchi + Tchi)*np.power(np.power(mchi, 2.0) + 2*mchi*mN + np.power(mN, 2.0) + 2*mN*Tchi, -1.0)\n mask = (TNBound > Trecoil_max)\n TNBound[mask] = Trecoil_max\n return TNBound\n\ndef get_miniboone_data():\n r\"\"\"\n Loads miniboone data from miniboone.csv. Data taken from `Batell et al. <http://inspirehep.net/record/1708854>`_.\n\n Returns\n -------\n mini_df : pd.DataFrame\n miniboone dataframe with columns [:math:`m_S` (in GeV), :math:`g_u`]\n \"\"\"\n mini_df = pd.read_csv('miniboone.csv', header=None)\n mini_df.columns = ['ms [GeV]', 'gu']\n return mini_df\n\nif __name__ == '__main__':\n # dTchiArr = np.logspace(-3.0, -2.0)\n # eventsarr = np.empty(len(dTchiArr))\n # idx = 0\n # for dTchi in dTchiArr:\n # rate, events = get_xenon_rate(dTchi=dTchi)\n # eventsarr[idx] = events\n # idx += 1\n # plt.figure()\n # plt.semilogx(dTchiArr, eventsarr)\n # plt.title(r'Rate Integral Convergence')\n # plt.xlabel(r'$\\Delta T_\\chi\\,\\textrm{[GeV]}$')\n # plt.ylabel(r'Events')\n # plt.savefig('plots/events.pdf')\n\n # HADROPHILIC PLOT\n import matplotlib\n plt.rcParams['axes.linewidth'] = 1.75\n plt.rcParams['xtick.minor.size'] = 5\n plt.rcParams['xtick.major.size'] = 7\n plt.rcParams['ytick.minor.size'] = 5\n plt.rcParams['ytick.major.size'] = 7\n plt.rcParams['xtick.major.width'] = 1.0\n plt.rcParams['ytick.major.width'] = 1.0\n plt.rcParams['xtick.minor.visible'] = True\n plt.rcParams['ytick.minor.visible'] = True\n matplotlib.rcParams['text.latex.preamble'] = [r\"\\usepackage{amsmath}\"]\n\n guArr = np.logspace(-5.0, -3.0, 25)\n msArr = np.logspace(-3.0, np.log10(0.5), 25)\n MS, GU = np.meshgrid(msArr, guArr)\n # EVENTS = np.empty([len(guArr), len(msArr)])\n # idx = 1\n # for i in range(0, len(guArr)):\n # for j in range(0, len(msArr)):\n # print('Completed {} out of {}'.format(idx, len(msArr)*len(guArr)))\n # rate, events = get_xenon_rate(ms=msArr[j], gu=guArr[i])\n # EVENTS[i][j] = events\n # idx += 1\n # np.save('events.npy', EVENTS)\n EVENTS = np.load('events.npy')\n LZ_EVENTS = (1.0/0.89)*((5.6*1000)/(1.3*278.8))*EVENTS\n #print(EVENTS.shape)\n event_lim = 3.56\n cmap = 'Greens'\n from matplotlib import ticker\n miniboone_df = get_miniboone_data()\n plt.figure()\n plt.plot(miniboone_df['ms [GeV]'], miniboone_df['gu'], color='#62656E', lw=1.0)\n #plt.contourf(MS, GU, EVENTS, locator=ticker.LogLocator(), cmap=cmap, alpha=1.0)\n #plt.colorbar(label='Event Count')\n CS = plt.contour(MS, GU, EVENTS, levels=[event_lim], colors=['#D81159'], linewidths=1.0, alpha=1.0, linestyles='-')\n plt.contour(MS, GU, LZ_EVENTS, levels=[event_lim], colors=['#D81159'], linewidths=1.0, alpha=1.0, linestyles='--')\n mss, guu = CS.allsegs[0][0].T\n plt.fill(np.append(miniboone_df['ms [GeV]'], mss[::-1]), np.append(miniboone_df['gu'], guu[::-1]), edgecolor='k', facecolor='#62656E', alpha=0.3, linewidth=0.0)\n mss = np.append(mss, np.array([mss[-1], mss[0]]))\n guu = np.append(guu, np.array([np.power(10.0, -3), np.power(10.0, -3)]))\n plt.fill(mss, guu, edgecolor='k', facecolor='#D81159', alpha=0.3, linewidth=0.0)\n plt.xlabel(r'$m_S\\,\\mathrm{[GeV]}$')\n plt.ylabel(r'$g_u$')\n #plt.title('Hadrophilic Exclusion Limits')\n plt.gca().set_xscale('log')\n plt.gca().set_yscale('log')\n axes = plt.axis()\n plt.axis([np.power(10.0, -3.0), mss.max(), 5*np.power(10.0, -6.0), np.power(10.0, -3.0)])\n #plt.scatter(MS, GU, c='k', marker='x', s=4.0)\n axes = plt.axis()\n plt.text(2*np.power(10.0, -2.0), 1.05*miniboone_df['gu'][0], 'MINIBOONE', fontsize=12, color='#62656E')\n plt.text(1.1*axes[0], 5.5*np.power(10.0, -5.0), r'ICRDM ($\\eta$) (XENON1T)', fontsize=12, color='#D81159')\n plt.text(1.1*axes[0], 2.55*np.power(10.0, -5.0), r'ICRDM ($\\eta$) (LZ)', fontsize=12, color='#D81159')\n\n plt.text(np.power(10.0, -2.9), np.power(10.0, -5.1), r'$g_\\chi = 1$')\n plt.text(np.power(10.0, -2.9), np.power(10.0, -5.25), r'$m_\\chi = m_S/3$')\n xmin, xmax = axes[0], axes[1]\n ymin, ymax = axes[2], axes[3]\n xy = (xmin, ymin)\n width = xmax - xmin\n height = ymax - ymin\n import matplotlib.patches as patches\n # create the patch and place it in the back of countourf (zorder!)\n p = patches.Rectangle(xy, width, height, hatch=4*'/', fill=None, alpha=0.2, zorder=-10)\n ax = plt.gca()\n ax.tick_params(which='minor', length=4)\n #ax.add_patch(p)\n plt.savefig('plots/hadrophilic.pdf')\n\n\n # dTchi = np.power(10.0, -4)\n # dtc = 'minus4'\n # TchiMaxArr = np.logspace(-1.0, 0.0, 25)\n # integrals = np.empty(len(TchiMaxArr))\n # idx = 0\n # for TchiMax in TchiMaxArr:\n # integrals[idx] = get_integral_v2('eta', mchi=0.001, TchiMax=TchiMax, dTchi=dTchi)\n # idx += 1\n # np.save('TchiMax{}.npy'.format(dtc), TchiMaxArr)\n # np.save('integrals{}.npy'.format(dtc), integrals)\n\n # print(integrals)\n # plt.semilogx(TchiMaxArr, integrals)\n # plt.show()\n # plt.figure()\n # # dtc = 'minus1'\n # # integrals = np.load('integrals{}.npy'.format(dtc))\n # # TchiMaxArr = np.load('TchiMax{}.npy'.format(dtc))\n # # plt.semilogx(TchiMaxArr, integrals/np.power(10.0, -28.0), label = r'$10^{-1}$')\n # dtc = 'minus2'\n # integrals = np.load('integrals{}.npy'.format(dtc))\n # TchiMaxArr = np.load('TchiMax{}.npy'.format(dtc))\n # plt.semilogx(TchiMaxArr, integrals/np.power(10.0, -28.0), label = r'$10^{-2}$')\n # dtc = 'minus3'\n # integrals = np.load('integrals{}.npy'.format(dtc))\n # TchiMaxArr = np.load('TchiMax{}.npy'.format(dtc))\n # plt.semilogx(TchiMaxArr, integrals/np.power(10.0, -28.0), label = r'$10^{-3}$')\n # dtc = 'minus4'\n # integrals = np.load('integrals{}.npy'.format(dtc))\n # TchiMaxArr = np.load('TchiMax{}.npy'.format(dtc))\n # plt.semilogx(TchiMaxArr, integrals/np.power(10.0, -28.0), label = r'$10^{-4}$')\n # plt.title('Flux Integral Convergence')\n # plt.xlabel(r'$T_\\chi^{\\textrm{\\small max}}\\,\\textrm{[GeV]}$')\n # plt.ylabel(r'Integral $\\textrm{[}10^{-28}\\,s^{-1}\\textrm{]}$')\n # plt.legend(loc='lower right', fontsize=10, title=r'$\\Delta T_\\chi$', title_fontsize=10)\n # plt.savefig('plots/int_convergence.pdf')\n\n\n from matplotlib import ticker\n from scipy.interpolate import interp1d\n prefactor = limit_prefactor()\n integral = 1.871660096591386*np.power(10.0, -26)\n integral = 2.061418762860559*np.power(10.0, -27)\n integral = 5.863077015127929*np.power(10.0, -28)\n eta_integral = 5.863064797490202*np.power(10.0, -28.0) # get_integral_v2('eta')\n pion_integral = 7.190987691388251*np.power(10.0, -27.0) # get_integral_v2('pion')\n eta_level = prefactor*np.power(eta_integral, -1.0)\n pion_level = prefactor*np.power(pion_integral, -1.0)\n LZ_FACTOR = (3.3217544185377643e-47/1757.9236139586912)/(8.3*np.power(10.0, -49))\n\n pion_color = '#01295F'\n pion_color = '#29AB87'\n eta_color = '#D81159'\n pospelov_color = '#FF8514'\n\n\n # size = 100\n # sigmaarray = np.logspace(-34.0, -28.0, size)\n # Gdetarr = np.load('Gdetarr.npy')\n # sigmaarray = np.append(np.logspace(-40.0, -34.0, size)[:-1], sigmaarray)\n # Gdetarr = np.append(np.full(size - 1, Gdetarr[0]), Gdetarr)\n #\n # GdetFun = interp1d(sigmaarray, Gdetarr, kind='slinear')\n\n\n # GdetFun = get_Gdet_fit()\n # B = np.array([np.power(10.0, -2.0), np.power(10.0, -4.0), np.power(10.0, -6.0), np.power(10.0, -7.0), np.power(10.0, -8.0)])\n # labels = np.array([r'$10^{-2}$', r'$10^{-4}$', r'$10^{-6}$', r'$10^{-7}$', r'$10^{-8}$'])\n # S = np.logspace(-35.0, -28.0)\n # idx = 0\n # for br in B:\n # plt.loglog(S, S*GdetFun(S)*br, label=labels[idx])\n # idx += 1\n # plt.plot([S[0], S[-1]], [eta_level, eta_level], 'k--')\n # plt.plot([S[0], S[-1]], [pion_level, pion_level], 'k--')\n # plt.text(np.power(10.0, -34.8), np.power(10.0, -10.3), 'Eta Flux', fontsize=8)\n # plt.text(np.power(10.0, -34.2), np.power(10.0, -11.4), 'Pion Flux', fontsize=8)\n # plt.title('Limits for different branching ratios')\n # plt.legend(fontsize=9, title=r'$\\textrm{BR}(\\eta \\rightarrow \\chi\\chi)$', title_fontsize=9, frameon=True, fancybox=True)\n # plt.xlabel(r'$\\sigma_\\chi^{\\textrm{\\tiny SI}}\\,\\textrm{[cm}^2\\textrm{]}$')\n # plt.ylabel(r'$\\sigma_\\chi^{\\textrm{\\tiny SI}} G(\\sigma_\\chi^{\\textrm{\\tiny SI}})\\textrm{BR}(\\eta \\rightarrow \\chi\\chi)$')\n # plt.savefig('plots/gdetbrs.pdf')\n\n\n GdetFun = get_Gdet_fit()\n lw = 1.0\n alpha = 0.3\n pospelov_top = 2.411345e-28\n pospelov_low = 1.543418e-31\n\n plt.figure()\n plt.plot([np.power(10.0, -10.0), np.power(10.0, -1.0)], [pospelov_top, pospelov_top], c=pospelov_color, label=r'Elastic CRDM', lw=lw)\n plt.plot([np.power(10.0, -10.0), np.power(10.0, -1.0)], [pospelov_low, pospelov_low], c=pospelov_color, lw=lw)\n plt.fill([np.power(10.0, -10.0), np.power(10.0, -1.0), np.power(10.0, -1.0), np.power(10.0, -10.0)], [pospelov_low, pospelov_low, pospelov_top, pospelov_top], edgecolor=pospelov_color, facecolor=pospelov_color, alpha=alpha, linewidth=0.0), #fill=False, hatch=2*'//')\n B, S = np.meshgrid(np.logspace(-9.0, np.log10(5*10**(-2)), 10000), np.logspace(-38.0, -28.0, 10000))\n C = S*GdetFun(S)*B\n CS = plt.contour(B, S, C, levels=[eta_level], colors=[eta_color], linewidths=0.0)\n plt.contour(B, S, C, levels=[eta_level*LZ_FACTOR], colors=[eta_color], linewidths=1.0, linestyles='--')\n br, sig = CS.allsegs[0][0].T\n plt.fill(br, sig, edgecolor='k', facecolor=eta_color, alpha=alpha, linewidth=0.0)\n\n plt.plot(br, sig, c=eta_color, lw=lw, label=r'Inelastic CRDM ($\\eta$)')\n #plt.plot([br[1], br[-1]], [sig[1], sig[-1]], c=eta_color, lw=1.0)\n\n B, S = np.meshgrid(np.logspace(-10.0, np.log10(6*10**(-4)), 10000), np.logspace(-38.0, -28.0, 10000))\n C = S*GdetFun(S)*B\n CS = plt.contour(B, S, C, levels=[pion_level], colors=[pion_color], linewidths=0.0)\n br, sig = CS.allsegs[0][0].T\n plt.fill(br, sig, edgecolor='k', facecolor=pion_color, alpha=alpha, linewidth=0.0)\n\n plt.plot(br, sig, c=pion_color, lw=lw, label=r'Inelastic CRDM ($\\pi$)')\n plt.plot([br[1], br[-1]], [sig[1], sig[-1]], c=pion_color, lw=lw)\n\n CS = plt.contour(B, S, C, levels=[pion_level*LZ_FACTOR], colors=[pion_color], linewidths=0.0)\n br, sig = CS.allsegs[0][0].T\n #plt.fill(br, sig, edgecolor='k', facecolor=pion_color, alpha=alpha, linewidth=0.0)\n\n plt.plot(br, sig, c=pion_color, lw=lw, ls='--')\n plt.plot([br[1], br[-1]], [sig[1], sig[-1]], c=pion_color, lw=lw, ls='--')\n\n plt.xlabel(r'$\\mathrm{BR}(M \\rightarrow X\\chi\\chi)$')\n plt.ylabel(r'$\\sigma_\\chi^{\\mathrm{\\tiny SI}}\\,\\mathrm{[cm}^2\\mathrm{]}$')\n #plt.title(r'Exclusion Limits')\n plt.gca().set_xscale('log')\n plt.gca().set_yscale('log')\n ax = plt.gca()\n ax.xaxis.set_major_locator(ticker.LogLocator(numticks=6))\n ax.tick_params(which='minor', length=4)\n plt.legend(fontsize=14, loc='lower left')\n axes = plt.axis()\n plt.axis([np.power(10.0, -10.0), 5*np.power(10.0, -3.0), np.power(10.0, -37), np.power(10.0, -27)])\n fontsize = 12\n plt.text(np.power(10.0, -6.35), np.power(10.0, -28.85), 'XENON1T', color=eta_color, fontsize=fontsize, rotation=-43.0)\n plt.text(np.power(10.0, -3.1), np.power(10.0, -34.2), 'LZ', color=eta_color, fontsize=fontsize, rotation=-41.0)\n plt.text(np.power(10.0, -7.45), np.power(10.0, -28.85), 'XENON1T', color=pion_color, fontsize=fontsize, rotation=-43.0)\n plt.text(np.power(10.0, -8.0), np.power(10.0, -30.15), 'LZ', color=pion_color, fontsize=fontsize, rotation=-47.0)\n plt.text(1.1*np.power(10.0, -9.85), np.power(10.0, -30.73), 'XENON1T', color=pospelov_color, fontsize=fontsize, rotation=0.0)\n plt.text(np.power(10.0, -9.5), np.power(10.0, -33.9), r'$m_\\chi = 1\\,\\mathrm{MeV}$')\n plt.text(np.power(10.0, -9.5), np.power(10.0, -34.4), r'$m_{\\mathrm{med}} = 10\\,\\mathrm{MeV}$')\n plt.savefig('plots/limit_no_title.pdf')\n", "# File: atmos_dm_flux.py\n#\n# Computing the atmospheric dark matter flux\n\nimport numpy as np\nimport scipy.stats\nfrom joblib import Parallel, delayed\n\nfrom crmc_utils import sigmapN, atmos_generate_all_LHE, remove_all_LHE, save_all_energies, load_all_energies\nfrom proton_flux import dPhiPatmosdT\n\nfrom air_density import suppression_factor, rho\n\ndef kdemultifit(energies, weights, cuts, bandwidths, branching_ratio, particle):\n r\"\"\"\n Returns the normalised multi fit for the kde given an array of energies and weights. This allows for the user to choose multiple energy cuts and apply different bandwidth fits in each bin.\n\n Parameters\n ----------\n energies : np.array\n array of energies to fit\n weights : np.array\n array of weights\n cuts : np.array[L + 1]\n energy intervals to fit the kde on\n bandwidths : np.array[L]\n array of bandwidths to use in each interval\n branching_ratio : float\n branching ratio for :math:`\\pi^0 \\rightarrow \\gamma \\chi \\chi`\n particle : str\n if particle is 'dm' pre multiplies by branching_ratio, else doesn't\n\n Returns\n -------\n kernel_evals, kernel_pdf : np.array, np.array\n evaluation points for the pdf [default = 100 points] and a normalised array that has been pre-multiplied by the branching_ratio and energies\n\n Examples\n --------\n >>> energies = np.random.normal(loc=0.0, scale=1.0, size=1000)\n >>> weights = np.random.uniform(0.0, 1.0, 1000)\n >>> cuts = np.array([-5.0, -1.5, 1.5, 5.0])\n >>> bandwidths = np.array([1.0, 0.5, 3.0])\n >>> kde_evals, kde_pdf = kdemultifit(energies, weights, cuts, bandwidths, branching_ratio, particle)\n >>> plt.plot(kde_evals, kde_pdf)\n \"\"\"\n kde_evals = np.array([])\n kde_pdf = np.array([])\n for idx in range(0, len(bandwidths)):\n temp_evals, temp_pdf = kdekernel(energies, weights, cuts[idx], cuts[idx + 1], branching_ratio, particle, bandwidths[idx])\n kde_evals = np.append(kde_evals, temp_evals[:-1])\n kde_pdf = np.append(kde_pdf, temp_pdf[:-1])\n return kde_evals, kde_pdf\n\ndef kdekernel(energies, weights, Emin, Emax, branching_ratio, particle, bw):\n r\"\"\"\n Returns the normalised kde kernel that fits a set of energies and weights for a given bandwidth. Used to provide multiple fits across the energy range of interest since variable bandwidth does not appear to be an option.\n\n Parameters\n ----------\n energies : np.array\n array of energies to fit\n weights : np.array\n array of weights\n Emin : float\n minumum energy to fit the kde on\n Emax : float\n maximum energy to fit the kde on\n branching_ratio : float\n branching ratio for :math:`\\pi^0 \\rightarrow \\gamma \\chi \\chi`\n particle : str\n if particle is 'dm' pre multiplies by branching_ratio, else doesn't\n bw : float or None\n chosen bandwidth, if None, uses the default `scipy.stats.gaussian_kde` choice\n\n Returns\n -------\n kernel_evals, kernel_pdf : np.array, np.array\n evaluation points for the pdf [default = 100 points] and a normalised array that has been pre-multiplied by the branching_ratio and energies\n\n Examples\n --------\n >>> energies = np.random.normal(loc=0.0, scale=1.0, size=1000)\n >>> weights = np.random.uniform(0.0, 1.0, 1000)\n >>> kde_evals, kde_pdf = kdekernel(data, weights, -3.0, 3.0, 10**(-6), 'dm', bw=0.1)\n >>> plt.plot(kde_evals, kde_pdf)\n \"\"\"\n counts, kdebins = np.histogram(energies, bins=1, weights=weights)\n # Normalise the kernel estiamte as it generates a density\n area = counts[0]\n\n kernel = scipy.stats.gaussian_kde(dataset=energies, weights=weights, bw_method=bw)\n\n log_kernel_evals = np.linspace(np.log10(Emin), np.log10(Emax), 100)\n kernel_evals = np.power(10.0, log_kernel_evals)\n if particle == 'dm':\n kernel_pdf = area*branching_ratio*kernel_evals*kernel.evaluate(kernel_evals)\n elif particle == 'pion':\n kernel_pdf = area*kernel_evals*kernel.evaluate(kernel_evals)\n return kernel_evals, kernel_pdf\n\n\ndef geometrical_factor(h1, h2, npts=1000):\n r\"\"\"\n Computes the geometrical factor, :math:`F_g`, obtained by integrating around the whole Earth between a minimum height h1 [:math:`\\textrm{km}`] and a maximum height h2 [:math:`\\textrm{km}`].\n\n Parameters\n ----------\n h1 : float\n minimum height [:math:`\\textrm{km}`]\n h2 : float\n maximum height [:math:`\\textrm{km}`]\n npts : int\n number of integration points\n\n Returns\n -------\n Fg : float\n geometrical factor [:math:`\\textrm{cm}^{-2}`]\n\n Examples\n --------\n >>> geometrical_factor(h1=5, h2=180, npts=100)\n 2.556488314653994e+25\n \"\"\"\n harr = np.linspace(h1, h2, npts)\n dh = (harr[1] - harr[0])*np.power(10.0, 5.0) # so dh is in [cm]\n Fg = 0.0\n Fg -= 0.5*(geometrical_integrand(harr[0]) + geometrical_integrand(harr[-1]))\n for height in harr:\n Fg += geometrical_integrand(height)\n Fg = Fg*dh\n return Fg\n\ndef geometrical_integrand(h):\n r\"\"\"\n Returns the value of the integrand for the height integral used to calculate the geometrical factor.\n\n Parameters\n ----------\n h : float\n height [:math:`\\textrm{km}`]\n\n Returns\n -------\n integrand : float\n integrand [:math:`\\textrm{cm}^{-3}`]\n\n Examples\n --------\n >>> geometrical_integrand(h=10)\n 6.437549297644509e+18\n \"\"\"\n Re = 6378.1 # radius of the Earth [km]\n return ((Re + h)/(2*Re))*rho(h)*suppression_factor(h)*np.log((4*Re*(Re + h) + np.power(h, 2))/(np.power(h, 2)))\n\ndef atmos_run_all_energies(evals, nMC, save_directory='/mnt/james/muon/', lhe_directory='/mnt/james/lhe/', crmcinstall='/home/k1893416/crmcinstall/'):\n r\"\"\"\n Runs the crmc process across all energies in eval, with nMC monte carlo events at each energy. Generates the .lhe files at each energy which are used to construct the .npy files used in :py:func:`atmos_generate_energies_and_weights`. The .lhe files are then deleted to save memory.\n\n Parameters\n ----------\n evals : np.array[floats]\n proton energies [:math:`\\textrm{GeV}`]\n nMC : int\n total number of monte carlo simulations at each energy\n save_directory : str\n save location for .npy files\n lhe_directory : str\n save location for .lhe files\n crmcinstall : str\n file location for crmc install\n \"\"\"\n count = 1\n Ntot = len(evals)\n # for Ep in evals:\n # atmos_generate_all_LHE(Ep, nMC, lhe_directory, crmcinstall)\n # save_all_energies(Ep, nMC, save_directory=save_directory, pid=14.0, lhe_directory=lhe_directory)\n # remove_all_LHE(Ep, lhe_directory)\n #\n # print('\\n\\nCompleted simulations for {} out of {} energies\\n\\n'.format(count, Ntot))\n # count += 1\n Parallel(n_jobs=-1)(delayed(parallel_fn)(Ep, nMC, lhe_directory, crmcinstall, save_directory) for Ep in evals)\n\ndef parallel_fn(Ep, nMC, lhe_directory, crmcinstall, save_directory):\n atmos_generate_all_LHE(Ep, nMC, lhe_directory, crmcinstall)\n save_all_energies(Ep, nMC, save_directory=save_directory, pid=14.0, lhe_directory=lhe_directory)\n remove_all_LHE(Ep, lhe_directory)\n print('Completed simulations for Ep = {:.1f} GeV\\n'.format(Ep))\n\ndef atmos_generate_energies_and_weights(proton_evals, nMC, Fg=None, save_directory='/mnt/james/muon/'):\n r\"\"\"\n After running crmc to generate the .npy files in :py:func:`atmos_run_all_energies`, we need to combine them into a large array. When eventually plotted, also need to rescale the heights of the bins by the weighting factor. This can be done by generating a set of weights that is the same length as the array of pion energies. This function returns both the concatenated energies from all Ep runs, as well as the weighting factors. After dividing the heights by the bin widths, these can then be plotted directly onto a histogram to obtain the pion flux.\n\n Parameters\n ----------\n proton_evals : np.array\n array of evaluation points for proton energies [:math:`\\textrm{GeV}`], derive :math:`\\Delta T_p` from this\n nMC : int\n total number of Monte Carlo runs at each proton energy\n Fg : float\n geometrical factor calculated in :py:func:`geometrical_factor`\n save_directory : str\n save directory for the .npy files\n\n Returns\n -------\n energies : np.array\n large array of all energies from all the runs\n weights : np.array\n large array of weights to account for the flux normalisation.\n\n Notes\n -----\n The exact formula for the weight depends on the proton energy and is given by\n\n .. math:: W(T_p) = \\frac{1}{n_{\\textrm{MC}}} \\frac{\\textrm{d}\\phi_p}{\\textrm{d}T_p}\\Delta T_p\n\n All pions produced from protons at this energy are given the same weight. Also note that the two arrays are of the same length.\n \"\"\"\n energies = np.array([])\n weights = np.array([])\n dEp = proton_evals[1] - proton_evals[0]\n if Fg == None:\n Fg = geometrical_factor(0.5, 180)\n\n for Ep in proton_evals:\n energies_from_Ep = load_all_energies(Ep, save_directory)\n length_weights_from_Ep = len(energies_from_Ep)\n weight = (1/nMC)*sigmapN(Ep)*dPhiPatmosdT(Ep)*dEp\n weights_from_Ep = np.full(length_weights_from_Ep, weight)\n\n energies = np.append(energies, energies_from_Ep)\n weights = np.append(weights, weights_from_Ep)\n return energies, weights\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.sqrt", "matplotlib.pyplot.plot", "numpy.histogram", "matplotlib.pyplot.gca", "pandas.read_csv", "numpy.arange", "numpy.sin", "matplotlib.pyplot.axis", "numpy.load", "matplotlib.pyplot.figure", "numpy.power", "numpy.logspace", "matplotlib.patches.Rectangle", "matplotlib.pyplot.savefig", "numpy.append", "numpy.log10", "matplotlib.pyplot.fill", "numpy.meshgrid", "numpy.array", "matplotlib.pyplot.ylabel", "numpy.cos", "matplotlib.ticker.LogLocator", "matplotlib.pyplot.contour", "matplotlib.pyplot.xlabel" ], [ "numpy.linspace", "numpy.power", "numpy.full", "numpy.append", "numpy.log10", "numpy.array", "numpy.histogram" ] ]
chudur-budur/models
[ "bb3aab1606aa1b207a1d05f4dadc298c6f8fd4cc" ]
[ "research/object_detection/dataset_tools/create_coco_tf_record.py" ]
[ "# Copyright 2017 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# ==============================================================================\nr\"\"\"Convert raw COCO dataset to TFRecord for object_detection.\n\nThis tool supports data generation for object detection (boxes, masks),\nkeypoint detection, and DensePose.\n\nPlease note that this tool creates sharded output files.\n\nExample usage:\n python create_coco_tf_record.py --logtostderr \\\n --train_image_dir=\"${TRAIN_IMAGE_DIR}\" \\\n --val_image_dir=\"${VAL_IMAGE_DIR}\" \\\n --test_image_dir=\"${TEST_IMAGE_DIR}\" \\\n --train_annotations_file=\"${TRAIN_ANNOTATIONS_FILE}\" \\\n --val_annotations_file=\"${VAL_ANNOTATIONS_FILE}\" \\\n --testdev_annotations_file=\"${TESTDEV_ANNOTATIONS_FILE}\" \\\n --output_dir=\"${OUTPUT_DIR}\"\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport hashlib\nimport io\nimport json\nimport logging\nimport os\nimport contextlib2\nimport numpy as np\nimport PIL.Image\n\nfrom pycocotools import mask\nimport tensorflow.compat.v1 as tf\n\nfrom object_detection.dataset_tools import tf_record_creation_util\nfrom object_detection.utils import dataset_util\nfrom object_detection.utils import label_map_util\n\nflags = tf.app.flags\ntf.flags.DEFINE_boolean(\n 'include_masks', False, 'Whether to include instance segmentations masks '\n '(PNG encoded) in the result. default: False.')\ntf.flags.DEFINE_string('train_image_dir', '', 'Training image directory.')\ntf.flags.DEFINE_string('val_image_dir', '', 'Validation image directory.')\ntf.flags.DEFINE_string('test_image_dir', '', 'Test image directory.')\ntf.flags.DEFINE_string('train_annotations_file', '',\n 'Training annotations JSON file.')\ntf.flags.DEFINE_string('val_annotations_file', '',\n 'Validation annotations JSON file.')\ntf.flags.DEFINE_string('testdev_annotations_file', '',\n 'Test-dev annotations JSON file.')\ntf.flags.DEFINE_string('train_keypoint_annotations_file', '',\n 'Training annotations JSON file.')\ntf.flags.DEFINE_string('val_keypoint_annotations_file', '',\n 'Validation annotations JSON file.')\n# DensePose is only available for coco 2014.\ntf.flags.DEFINE_string('train_densepose_annotations_file', '',\n 'Training annotations JSON file for DensePose.')\ntf.flags.DEFINE_string('val_densepose_annotations_file', '',\n 'Validation annotations JSON file for DensePose.')\ntf.flags.DEFINE_string('output_dir', '/tmp/', 'Output data directory.')\n# Whether to only produce images/annotations on person class (for keypoint /\n# densepose task).\ntf.flags.DEFINE_boolean('remove_non_person_annotations', False, 'Whether to '\n 'remove all annotations for non-person objects.')\ntf.flags.DEFINE_boolean('remove_non_person_images', False, 'Whether to '\n 'remove all examples that do not contain a person.')\n\nFLAGS = flags.FLAGS\n\nlogger = tf.get_logger()\nlogger.setLevel(logging.INFO)\n\n_COCO_KEYPOINT_NAMES = [\n b'nose', b'left_eye', b'right_eye', b'left_ear', b'right_ear',\n b'left_shoulder', b'right_shoulder', b'left_elbow', b'right_elbow',\n b'left_wrist', b'right_wrist', b'left_hip', b'right_hip',\n b'left_knee', b'right_knee', b'left_ankle', b'right_ankle'\n]\n\n_COCO_PART_NAMES = [\n b'torso_back', b'torso_front', b'right_hand', b'left_hand', b'left_foot',\n b'right_foot', b'right_upper_leg_back', b'left_upper_leg_back',\n b'right_upper_leg_front', b'left_upper_leg_front', b'right_lower_leg_back',\n b'left_lower_leg_back', b'right_lower_leg_front', b'left_lower_leg_front',\n b'left_upper_arm_back', b'right_upper_arm_back', b'left_upper_arm_front',\n b'right_upper_arm_front', b'left_lower_arm_back', b'right_lower_arm_back',\n b'left_lower_arm_front', b'right_lower_arm_front', b'right_face',\n b'left_face',\n]\n\n_DP_PART_ID_OFFSET = 1\n\n\ndef clip_to_unit(x):\n return min(max(x, 0.0), 1.0)\n\n\ndef create_tf_example(image,\n annotations_list,\n image_dir,\n category_index,\n include_masks=False,\n keypoint_annotations_dict=None,\n densepose_annotations_dict=None,\n remove_non_person_annotations=False,\n remove_non_person_images=False):\n \"\"\"Converts image and annotations to a tf.Example proto.\n\n Args:\n image: dict with keys: [u'license', u'file_name', u'coco_url', u'height',\n u'width', u'date_captured', u'flickr_url', u'id']\n annotations_list:\n list of dicts with keys: [u'segmentation', u'area', u'iscrowd',\n u'image_id', u'bbox', u'category_id', u'id'] Notice that bounding box\n coordinates in the official COCO dataset are given as [x, y, width,\n height] tuples using absolute coordinates where x, y represent the\n top-left (0-indexed) corner. This function converts to the format\n expected by the Tensorflow Object Detection API (which is which is\n [ymin, xmin, ymax, xmax] with coordinates normalized relative to image\n size).\n image_dir: directory containing the image files.\n category_index: a dict containing COCO category information keyed by the\n 'id' field of each category. See the label_map_util.create_category_index\n function.\n include_masks: Whether to include instance segmentations masks\n (PNG encoded) in the result. default: False.\n keypoint_annotations_dict: A dictionary that maps from annotation_id to a\n dictionary with keys: [u'keypoints', u'num_keypoints'] represeting the\n keypoint information for this person object annotation. If None, then\n no keypoint annotations will be populated.\n densepose_annotations_dict: A dictionary that maps from annotation_id to a\n dictionary with keys: [u'dp_I', u'dp_x', u'dp_y', 'dp_U', 'dp_V']\n representing part surface coordinates. For more information see\n http://densepose.org/.\n remove_non_person_annotations: Whether to remove any annotations that are\n not the \"person\" class.\n remove_non_person_images: Whether to remove any images that do not contain\n at least one \"person\" annotation.\n\n Returns:\n key: SHA256 hash of the image.\n example: The converted tf.Example\n num_annotations_skipped: Number of (invalid) annotations that were ignored.\n num_keypoint_annotation_skipped: Number of keypoint annotations that were\n skipped.\n num_densepose_annotation_skipped: Number of DensePose annotations that were\n skipped.\n\n Raises:\n ValueError: if the image pointed to by data['filename'] is not a valid JPEG\n \"\"\"\n image_height = image['height']\n image_width = image['width']\n filename = image['file_name']\n image_id = image['id']\n\n full_path = os.path.join(image_dir, filename)\n with tf.gfile.GFile(full_path, 'rb') as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = PIL.Image.open(encoded_jpg_io)\n key = hashlib.sha256(encoded_jpg).hexdigest()\n\n xmin = []\n xmax = []\n ymin = []\n ymax = []\n is_crowd = []\n category_names = []\n category_ids = []\n area = []\n encoded_mask_png = []\n keypoints_x = []\n keypoints_y = []\n keypoints_visibility = []\n keypoints_name = []\n num_keypoints = []\n include_keypoint = keypoint_annotations_dict is not None\n num_annotations_skipped = 0\n num_keypoint_annotation_used = 0\n num_keypoint_annotation_skipped = 0\n dp_part_index = []\n dp_x = []\n dp_y = []\n dp_u = []\n dp_v = []\n dp_num_points = []\n densepose_keys = ['dp_I', 'dp_U', 'dp_V', 'dp_x', 'dp_y', 'bbox']\n include_densepose = densepose_annotations_dict is not None\n num_densepose_annotation_used = 0\n num_densepose_annotation_skipped = 0\n for object_annotations in annotations_list:\n (x, y, width, height) = tuple(object_annotations['bbox'])\n if width <= 0 or height <= 0:\n num_annotations_skipped += 1\n continue\n if x + width > image_width or y + height > image_height:\n num_annotations_skipped += 1\n continue\n category_id = int(object_annotations['category_id'])\n category_name = category_index[category_id]['name'].encode('utf8')\n if remove_non_person_annotations and category_name != b'person':\n num_annotations_skipped += 1\n continue\n xmin.append(float(x) / image_width)\n xmax.append(float(x + width) / image_width)\n ymin.append(float(y) / image_height)\n ymax.append(float(y + height) / image_height)\n is_crowd.append(object_annotations['iscrowd'])\n category_ids.append(category_id)\n category_names.append(category_name)\n area.append(object_annotations['area'])\n\n if include_masks:\n run_len_encoding = mask.frPyObjects(object_annotations['segmentation'],\n image_height, image_width)\n binary_mask = mask.decode(run_len_encoding)\n if not object_annotations['iscrowd']:\n binary_mask = np.amax(binary_mask, axis=2)\n pil_image = PIL.Image.fromarray(binary_mask)\n output_io = io.BytesIO()\n pil_image.save(output_io, format='PNG')\n encoded_mask_png.append(output_io.getvalue())\n\n if include_keypoint:\n annotation_id = object_annotations['id']\n if annotation_id in keypoint_annotations_dict:\n num_keypoint_annotation_used += 1\n keypoint_annotations = keypoint_annotations_dict[annotation_id]\n keypoints = keypoint_annotations['keypoints']\n num_kpts = keypoint_annotations['num_keypoints']\n keypoints_x_abs = keypoints[::3]\n keypoints_x.extend(\n [float(x_abs) / image_width for x_abs in keypoints_x_abs])\n keypoints_y_abs = keypoints[1::3]\n keypoints_y.extend(\n [float(y_abs) / image_height for y_abs in keypoints_y_abs])\n keypoints_visibility.extend(keypoints[2::3])\n keypoints_name.extend(_COCO_KEYPOINT_NAMES)\n num_keypoints.append(num_kpts)\n else:\n keypoints_x.extend([0.0] * len(_COCO_KEYPOINT_NAMES))\n keypoints_y.extend([0.0] * len(_COCO_KEYPOINT_NAMES))\n keypoints_visibility.extend([0] * len(_COCO_KEYPOINT_NAMES))\n keypoints_name.extend(_COCO_KEYPOINT_NAMES)\n num_keypoints.append(0)\n\n if include_densepose:\n annotation_id = object_annotations['id']\n if (annotation_id in densepose_annotations_dict and\n all(key in densepose_annotations_dict[annotation_id]\n for key in densepose_keys)):\n dp_annotations = densepose_annotations_dict[annotation_id]\n num_densepose_annotation_used += 1\n dp_num_points.append(len(dp_annotations['dp_I']))\n dp_part_index.extend([int(i - _DP_PART_ID_OFFSET)\n for i in dp_annotations['dp_I']])\n # DensePose surface coordinates are defined on a [256, 256] grid\n # relative to each instance box (i.e. absolute coordinates in range\n # [0., 256.]). The following converts the coordinates\n # so that they are expressed in normalized image coordinates.\n dp_x_box_rel = [\n clip_to_unit(val / 256.) for val in dp_annotations['dp_x']]\n dp_x_norm = [(float(x) + x_box_rel * width) / image_width\n for x_box_rel in dp_x_box_rel]\n dp_y_box_rel = [\n clip_to_unit(val / 256.) for val in dp_annotations['dp_y']]\n dp_y_norm = [(float(y) + y_box_rel * height) / image_height\n for y_box_rel in dp_y_box_rel]\n dp_x.extend(dp_x_norm)\n dp_y.extend(dp_y_norm)\n dp_u.extend(dp_annotations['dp_U'])\n dp_v.extend(dp_annotations['dp_V'])\n else:\n dp_num_points.append(0)\n\n if (remove_non_person_images and\n not any(name == b'person' for name in category_names)):\n return (key, None, num_annotations_skipped,\n num_keypoint_annotation_skipped, num_densepose_annotation_skipped)\n feature_dict = {\n 'image/height': dataset_util.int64_feature(image_height),\n 'image/width': dataset_util.int64_feature(image_width),\n 'image/filename': dataset_util.bytes_feature(filename.encode('utf8')),\n 'image/source_id': dataset_util.bytes_feature(str(image_id).encode('utf8')),\n 'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),\n 'image/encoded': dataset_util.bytes_feature(encoded_jpg),\n 'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')),\n 'image/object/bbox/xmin': dataset_util.float_list_feature(xmin),\n 'image/object/bbox/xmax': dataset_util.float_list_feature(xmax),\n 'image/object/bbox/ymin': dataset_util.float_list_feature(ymin),\n 'image/object/bbox/ymax': dataset_util.float_list_feature(ymax),\n # 'image/object/class/text': dataset_util.bytes_list_feature(category_names),\n # The below 3 lines should fix the indices[0] = 0 is not in [0,0) problem.\n # At least according to https://github.com/tensorflow/tensorflow/issues/17353 \n 'image/object/bbox/class/label': dataset_util.int64_list_feature(category_ids),\n 'image/object/class/text': dataset_util.bytes_list_feature(category_names), \n 'image/object/class/label': dataset_util.int64_list_feature(category_ids),\n ##\n 'image/object/is_crowd': dataset_util.int64_list_feature(is_crowd),\n 'image/object/area': dataset_util.float_list_feature(area),\n }\n if include_masks:\n feature_dict['image/object/mask'] = (\n dataset_util.bytes_list_feature(encoded_mask_png))\n if include_keypoint:\n feature_dict['image/object/keypoint/x'] = (\n dataset_util.float_list_feature(keypoints_x))\n feature_dict['image/object/keypoint/y'] = (\n dataset_util.float_list_feature(keypoints_y))\n feature_dict['image/object/keypoint/num'] = (\n dataset_util.int64_list_feature(num_keypoints))\n feature_dict['image/object/keypoint/visibility'] = (\n dataset_util.int64_list_feature(keypoints_visibility))\n feature_dict['image/object/keypoint/text'] = (\n dataset_util.bytes_list_feature(keypoints_name))\n num_keypoint_annotation_skipped = (\n len(keypoint_annotations_dict) - num_keypoint_annotation_used)\n if include_densepose:\n feature_dict['image/object/densepose/num'] = (\n dataset_util.int64_list_feature(dp_num_points))\n feature_dict['image/object/densepose/part_index'] = (\n dataset_util.int64_list_feature(dp_part_index))\n feature_dict['image/object/densepose/x'] = (\n dataset_util.float_list_feature(dp_x))\n feature_dict['image/object/densepose/y'] = (\n dataset_util.float_list_feature(dp_y))\n feature_dict['image/object/densepose/u'] = (\n dataset_util.float_list_feature(dp_u))\n feature_dict['image/object/densepose/v'] = (\n dataset_util.float_list_feature(dp_v))\n num_densepose_annotation_skipped = (\n len(densepose_annotations_dict) - num_densepose_annotation_used)\n\n example = tf.train.Example(features=tf.train.Features(feature=feature_dict))\n return (key, example, num_annotations_skipped,\n num_keypoint_annotation_skipped, num_densepose_annotation_skipped)\n\n\ndef _create_tf_record_from_coco_annotations(annotations_file, image_dir,\n output_path, include_masks,\n num_shards,\n keypoint_annotations_file='',\n densepose_annotations_file='',\n remove_non_person_annotations=False,\n remove_non_person_images=False):\n \"\"\"Loads COCO annotation json files and converts to tf.Record format.\n\n Args:\n annotations_file: JSON file containing bounding box annotations.\n image_dir: Directory containing the image files.\n output_path: Path to output tf.Record file.\n include_masks: Whether to include instance segmentations masks\n (PNG encoded) in the result. default: False.\n num_shards: number of output file shards.\n keypoint_annotations_file: JSON file containing the person keypoint\n annotations. If empty, then no person keypoint annotations will be\n generated.\n densepose_annotations_file: JSON file containing the DensePose annotations.\n If empty, then no DensePose annotations will be generated.\n remove_non_person_annotations: Whether to remove any annotations that are\n not the \"person\" class.\n remove_non_person_images: Whether to remove any images that do not contain\n at least one \"person\" annotation.\n \"\"\"\n with contextlib2.ExitStack() as tf_record_close_stack, \\\n tf.gfile.GFile(annotations_file, 'r') as fid:\n output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords(\n tf_record_close_stack, output_path, num_shards)\n groundtruth_data = json.load(fid)\n images = groundtruth_data['images']\n category_index = label_map_util.create_category_index(\n groundtruth_data['categories'])\n\n annotations_index = {}\n if 'annotations' in groundtruth_data:\n logging.info('Found groundtruth annotations. Building annotations index.')\n for annotation in groundtruth_data['annotations']:\n image_id = annotation['image_id']\n if image_id not in annotations_index:\n annotations_index[image_id] = []\n annotations_index[image_id].append(annotation)\n missing_annotation_count = 0\n for image in images:\n image_id = image['id']\n if image_id not in annotations_index:\n missing_annotation_count += 1\n annotations_index[image_id] = []\n logging.info('%d images are missing annotations.',\n missing_annotation_count)\n\n keypoint_annotations_index = {}\n if keypoint_annotations_file:\n with tf.gfile.GFile(keypoint_annotations_file, 'r') as kid:\n keypoint_groundtruth_data = json.load(kid)\n if 'annotations' in keypoint_groundtruth_data:\n for annotation in keypoint_groundtruth_data['annotations']:\n image_id = annotation['image_id']\n if image_id not in keypoint_annotations_index:\n keypoint_annotations_index[image_id] = {}\n keypoint_annotations_index[image_id][annotation['id']] = annotation\n\n densepose_annotations_index = {}\n if densepose_annotations_file:\n with tf.gfile.GFile(densepose_annotations_file, 'r') as fid:\n densepose_groundtruth_data = json.load(fid)\n if 'annotations' in densepose_groundtruth_data:\n for annotation in densepose_groundtruth_data['annotations']:\n image_id = annotation['image_id']\n if image_id not in densepose_annotations_index:\n densepose_annotations_index[image_id] = {}\n densepose_annotations_index[image_id][annotation['id']] = annotation\n\n total_num_annotations_skipped = 0\n total_num_keypoint_annotations_skipped = 0\n total_num_densepose_annotations_skipped = 0\n for idx, image in enumerate(images):\n if idx % 100 == 0:\n logging.info('On image %d of %d', idx, len(images))\n annotations_list = annotations_index[image['id']]\n keypoint_annotations_dict = None\n if keypoint_annotations_file:\n keypoint_annotations_dict = {}\n if image['id'] in keypoint_annotations_index:\n keypoint_annotations_dict = keypoint_annotations_index[image['id']]\n densepose_annotations_dict = None\n if densepose_annotations_file:\n densepose_annotations_dict = {}\n if image['id'] in densepose_annotations_index:\n densepose_annotations_dict = densepose_annotations_index[image['id']]\n (_, tf_example, num_annotations_skipped, num_keypoint_annotations_skipped,\n num_densepose_annotations_skipped) = create_tf_example(\n image, annotations_list, image_dir, category_index, include_masks,\n keypoint_annotations_dict, densepose_annotations_dict,\n remove_non_person_annotations, remove_non_person_images)\n total_num_annotations_skipped += num_annotations_skipped\n total_num_keypoint_annotations_skipped += num_keypoint_annotations_skipped\n total_num_densepose_annotations_skipped += (\n num_densepose_annotations_skipped)\n shard_idx = idx % num_shards\n if tf_example:\n output_tfrecords[shard_idx].write(tf_example.SerializeToString())\n logging.info('Finished writing, skipped %d annotations.',\n total_num_annotations_skipped)\n if keypoint_annotations_file:\n logging.info('Finished writing, skipped %d keypoint annotations.',\n total_num_keypoint_annotations_skipped)\n if densepose_annotations_file:\n logging.info('Finished writing, skipped %d DensePose annotations.',\n total_num_densepose_annotations_skipped)\n\n\ndef main(_):\n assert FLAGS.train_image_dir, '`train_image_dir` missing.'\n assert FLAGS.val_image_dir, '`val_image_dir` missing.'\n assert FLAGS.test_image_dir, '`test_image_dir` missing.'\n assert FLAGS.train_annotations_file, '`train_annotations_file` missing.'\n assert FLAGS.val_annotations_file, '`val_annotations_file` missing.'\n assert FLAGS.testdev_annotations_file, '`testdev_annotations_file` missing.'\n\n if not tf.gfile.IsDirectory(FLAGS.output_dir):\n tf.gfile.MakeDirs(FLAGS.output_dir)\n train_output_path = os.path.join(FLAGS.output_dir, 'coco_train.record')\n val_output_path = os.path.join(FLAGS.output_dir, 'coco_val.record')\n testdev_output_path = os.path.join(FLAGS.output_dir, 'coco_testdev.record')\n\n _create_tf_record_from_coco_annotations(\n FLAGS.train_annotations_file,\n FLAGS.train_image_dir,\n train_output_path,\n FLAGS.include_masks,\n num_shards=100,\n keypoint_annotations_file=FLAGS.train_keypoint_annotations_file,\n densepose_annotations_file=FLAGS.train_densepose_annotations_file,\n remove_non_person_annotations=FLAGS.remove_non_person_annotations,\n remove_non_person_images=FLAGS.remove_non_person_images)\n _create_tf_record_from_coco_annotations(\n FLAGS.val_annotations_file,\n FLAGS.val_image_dir,\n val_output_path,\n FLAGS.include_masks,\n num_shards=50,\n keypoint_annotations_file=FLAGS.val_keypoint_annotations_file,\n densepose_annotations_file=FLAGS.val_densepose_annotations_file,\n remove_non_person_annotations=FLAGS.remove_non_person_annotations,\n remove_non_person_images=FLAGS.remove_non_person_images)\n _create_tf_record_from_coco_annotations(\n FLAGS.testdev_annotations_file,\n FLAGS.test_image_dir,\n testdev_output_path,\n FLAGS.include_masks,\n num_shards=50)\n\n\nif __name__ == '__main__':\n tf.app.run()\n" ]
[ [ "numpy.amax", "tensorflow.compat.v1.gfile.MakeDirs", "tensorflow.compat.v1.flags.DEFINE_string", "tensorflow.compat.v1.gfile.IsDirectory", "tensorflow.compat.v1.gfile.GFile", "tensorflow.compat.v1.flags.DEFINE_boolean", "tensorflow.compat.v1.get_logger", "tensorflow.compat.v1.train.Features", "tensorflow.compat.v1.app.run" ] ]
BaoWentz/AdvancedEAST-PyTorch
[ "a835c8cedce4ada1bc9580754245183d9f4aaa17" ]
[ "nms.py" ]
[ "# coding=utf-8\nimport numpy as np\n\nimport cfg\n\n\ndef should_merge(region, i, j):\n neighbor = {(i, j - 1)}\n return not region.isdisjoint(neighbor)\n\n\ndef region_neighbor(region_set):\n region_pixels = np.array(list(region_set))\n j_min = np.amin(region_pixels, axis=0)[1] - 1\n j_max = np.amax(region_pixels, axis=0)[1] + 1\n i_m = np.amin(region_pixels, axis=0)[0] + 1\n region_pixels[:, 0] += 1\n neighbor = {(region_pixels[n, 0], region_pixels[n, 1]) for n in\n range(len(region_pixels))}\n neighbor.add((i_m, j_min))\n neighbor.add((i_m, j_max))\n return neighbor\n\n\ndef region_group(region_list):\n S = [i for i in range(len(region_list))]\n D = []\n while len(S) > 0:\n m = S.pop(0)\n if len(S) == 0:\n # S has only one element, put it to D\n D.append([m])\n else:\n D.append(rec_region_merge(region_list, m, S))\n return D\n\n\ndef rec_region_merge(region_list, m, S):\n rows = [m]\n tmp = []\n for n in S:\n if not region_neighbor(region_list[m]).isdisjoint(region_list[n]) or \\\n not region_neighbor(region_list[n]).isdisjoint(region_list[m]):\n # 第m与n相交\n tmp.append(n)\n for d in tmp:\n S.remove(d)\n for e in tmp:\n rows.extend(rec_region_merge(region_list, e, S))\n return rows\n\n\ndef nms(predict, activation_pixels, threshold=cfg.side_vertex_pixel_threshold):\n region_list = []\n for i, j in zip(activation_pixels[0], activation_pixels[1]):\n merge = False\n for k in range(len(region_list)):\n if should_merge(region_list[k], i, j):\n region_list[k].add((i, j))\n merge = True\n # Fixme 重叠文本区域处理,存在和多个区域邻接的pixels,先都merge试试\n # break\n if not merge:\n region_list.append({(i, j)})\n D = region_group(region_list)\n quad_list = np.zeros((len(D), 4, 2))\n score_list = np.zeros((len(D), 4))\n for group, g_th in zip(D, range(len(D))):\n total_score = np.zeros((4, 2))\n for row in group:\n for ij in region_list[row]:\n score = predict[ij[0], ij[1], 1] # 边界像素\n if score >= threshold:\n ith_score = predict[ij[0], ij[1], 2:3] # 头还是尾\n if not (cfg.trunc_threshold <= ith_score < 1 -\n cfg.trunc_threshold): # 判断是否为头跟尾\n ith = int(np.around(ith_score))\n total_score[ith * 2:(ith + 1) * 2] += score\n px = (ij[1] + 0.5) * cfg.pixel_size\n py = (ij[0] + 0.5) * cfg.pixel_size\n p_v = [px, py] + np.reshape(predict[ij[0], ij[1], 3:7], (2, 2)) # 4位geo\n quad_list[g_th, ith * 2:(ith + 1) * 2] += score * p_v\n score_list[g_th] = total_score[:, 0]\n quad_list[g_th] /= (total_score + cfg.epsilon)\n return score_list, quad_list\n" ]
[ [ "numpy.amax", "numpy.amin", "numpy.around", "numpy.reshape", "numpy.zeros" ] ]
kakul/Article-Extraction
[ "a8a9a432fe86dd94a6108b08a64cb749b5db1df6" ]
[ "Image detection/imgtag.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mp\nfrom skimage.filter.rank import entropy,otsu\nfrom skimage.filter import threshold_otsu\nfrom skimage.morphology import square,rectangle,label,closing,disk,binary_erosion,opening\nfrom skimage.color import label2rgb,rgb2gray\nfrom skimage.segmentation import clear_border\nfrom skimage.measure import regionprops\nfrom skimage import io\ni=rgb2gray(io.imread('fog.jpg'))\nt=threshold_otsu(i)\ni=i>t\nz=binary_erosion(1-i,square(3))\nb=z.copy()\nclear_border(b)\nl=label(b)\nx=np.logical_xor(z,b)\nl[x]=-1\niol=label2rgb(l,image=i)\nfig,ax=plt.subplots(ncols=1,nrows=1,figsize=(6,6))\nax.imshow(iol)\nfor region in regionprops(l,['Area','BoundingBox']):\n if region['Area']<1500:\n continue\n minr,minc,maxr,maxc=region['BoundingBox']\n rect=mp.Rectangle((minc,minr),maxc-minc,maxr-minr,fill=False,edgecolor='red',linewidth=1)\n ax.add_patch(rect)\n\n\nplt.show()\n" ]
[ [ "numpy.logical_xor", "matplotlib.pyplot.show", "matplotlib.patches.Rectangle", "matplotlib.pyplot.subplots" ] ]
kangdh/hdmf
[ "680b68a1bbc9377590862574daea83579a3d52bc" ]
[ "src/hdmf/common/resources.py" ]
[ "import pandas as pd\nimport re\nfrom . import register_class, EXP_NAMESPACE\nfrom . import get_type_map\nfrom ..container import Table, Row, Container, AbstractContainer\nfrom ..utils import docval, popargs\nfrom ..build import TypeMap\n\n\nclass KeyTable(Table):\n \"\"\"\n A table for storing keys used to reference external resources.\n \"\"\"\n\n __defaultname__ = 'keys'\n\n __columns__ = (\n {'name': 'key', 'type': str,\n 'doc': 'The user key that maps to the resource term / registry symbol.'},\n )\n\n\nclass Key(Row):\n \"\"\"\n A Row class for representing rows in the KeyTable.\n \"\"\"\n\n __table__ = KeyTable\n\n\nclass ResourceTable(Table):\n \"\"\"\n A table for storing names and URIs of ontology sources.\n \"\"\"\n\n __defaultname__ = 'resources'\n\n __columns__ = (\n {'name': 'resource', 'type': str,\n 'doc': 'The resource/registry that the term/symbol comes from.'},\n {'name': 'resource_uri', 'type': str,\n 'doc': 'The URI for the resource term / registry symbol.'},\n )\n\n\nclass Resource(Row):\n \"\"\"\n A Row class for representing rows in the ResourceTable.\n \"\"\"\n\n __table__ = ResourceTable\n\n\nclass EntityTable(Table):\n \"\"\"\n A table for storing the external resources a key refers to.\n \"\"\"\n\n __defaultname__ = 'entities'\n\n __columns__ = (\n {'name': 'keys_idx', 'type': (int, Key),\n 'doc': ('The index into the keys table for the user key that '\n 'maps to the resource term / registry symbol.')},\n {'name': 'resources_idx', 'type': (int, Resource),\n 'doc': 'The index into the ResourceTable.'},\n {'name': 'entity_id', 'type': str,\n 'doc': 'The unique ID for the resource term / registry symbol.'},\n {'name': 'entity_uri', 'type': str,\n 'doc': 'The URI for the resource term / registry symbol.'},\n )\n\n\nclass Entity(Row):\n \"\"\"\n A Row class for representing rows in the EntityTable.\n \"\"\"\n\n __table__ = EntityTable\n\n\nclass ObjectTable(Table):\n \"\"\"\n A table for storing objects (i.e. Containers) that contain keys that refer to external resources.\n \"\"\"\n\n __defaultname__ = 'objects'\n\n __columns__ = (\n {'name': 'object_id', 'type': str,\n 'doc': 'The object ID for the Container/Data.'},\n {'name': 'relative_path', 'type': str,\n 'doc': ('The relative_path of the attribute of the object that uses ',\n 'an external resource reference key. Use an empty string if not applicable.')},\n {'name': 'field', 'type': str,\n 'doc': ('The field of the compound data type using an external resource. '\n 'Use an empty string if not applicable.')}\n )\n\n\nclass Object(Row):\n \"\"\"\n A Row class for representing rows in the ObjectTable.\n \"\"\"\n\n __table__ = ObjectTable\n\n\nclass ObjectKeyTable(Table):\n \"\"\"\n A table for identifying which keys are used by which objects for referring to external resources.\n \"\"\"\n\n __defaultname__ = 'object_keys'\n\n __columns__ = (\n {'name': 'objects_idx', 'type': (int, Object),\n 'doc': 'The index into the objects table for the Object that uses the Key.'},\n {'name': 'keys_idx', 'type': (int, Key),\n 'doc': 'The index into the keys table that is used to make an external resource reference.'}\n )\n\n\nclass ObjectKey(Row):\n \"\"\"\n A Row class for representing rows in the ObjectKeyTable.\n \"\"\"\n\n __table__ = ObjectKeyTable\n\n\n@register_class('ExternalResources', EXP_NAMESPACE)\nclass ExternalResources(Container):\n \"\"\"A table for mapping user terms (i.e. keys) to resource entities.\"\"\"\n\n __fields__ = (\n {'name': 'keys', 'child': True},\n {'name': 'resources', 'child': True},\n {'name': 'objects', 'child': True},\n {'name': 'object_keys', 'child': True},\n {'name': 'entities', 'child': True},\n )\n\n @docval({'name': 'name', 'type': str, 'doc': 'The name of this ExternalResources container.'},\n {'name': 'keys', 'type': KeyTable, 'default': None,\n 'doc': 'The table storing user keys for referencing resources.'},\n {'name': 'resources', 'type': ResourceTable, 'default': None,\n 'doc': 'The table for storing names and URIs of resources.'},\n {'name': 'entities', 'type': EntityTable, 'default': None,\n 'doc': 'The table storing entity information.'},\n {'name': 'objects', 'type': ObjectTable, 'default': None,\n 'doc': 'The table storing object information.'},\n {'name': 'object_keys', 'type': ObjectKeyTable, 'default': None,\n 'doc': 'The table storing object-resource relationships.'},\n {'name': 'type_map', 'type': TypeMap, 'default': None,\n 'doc': 'The type map. If None is provided, the HDMF-common type map will be used.'})\n def __init__(self, **kwargs):\n name = popargs('name', kwargs)\n super().__init__(name)\n self.keys = kwargs['keys'] or KeyTable()\n self.resources = kwargs['resources'] or ResourceTable()\n self.entities = kwargs['entities'] or EntityTable()\n self.objects = kwargs['objects'] or ObjectTable()\n self.object_keys = kwargs['object_keys'] or ObjectKeyTable()\n self.type_map = kwargs['type_map'] or get_type_map()\n\n @docval({'name': 'key_name', 'type': str, 'doc': 'The name of the key to be added.'})\n def _add_key(self, **kwargs):\n \"\"\"\n Add a key to be used for making references to external resources.\n\n It is possible to use the same *key_name* to refer to different resources so long as the *key_name* is not\n used within the same object, relative_path, and field. To do so, this method must be called for the\n two different resources.\n\n The returned Key objects must be managed by the caller so as to be appropriately passed to subsequent calls\n to methods for storing information about the different resources.\n \"\"\"\n key = kwargs['key_name']\n return Key(key, table=self.keys)\n\n @docval({'name': 'key', 'type': (str, Key), 'doc': 'The key to associate the entity with.'},\n {'name': 'resources_idx', 'type': (int, Resource), 'doc': 'The id of the resource.'},\n {'name': 'entity_id', 'type': str, 'doc': 'The unique entity id.'},\n {'name': 'entity_uri', 'type': str, 'doc': 'The URI for the entity.'})\n def _add_entity(self, **kwargs):\n \"\"\"\n Add an entity that will be referenced to using the given key.\n \"\"\"\n key = kwargs['key']\n resources_idx = kwargs['resources_idx']\n entity_id = kwargs['entity_id']\n entity_uri = kwargs['entity_uri']\n if not isinstance(key, Key):\n key = self._add_key(key)\n resource_entity = Entity(key, resources_idx, entity_id, entity_uri, table=self.entities)\n return resource_entity\n\n @docval({'name': 'resource', 'type': str, 'doc': 'The name of the ontology resource.'},\n {'name': 'uri', 'type': str, 'doc': 'The URI associated with ontology resource.'})\n def _add_resource(self, **kwargs):\n \"\"\"\n Add resource name and URI to ResourceTable that will be referenced by the ResourceTable idx.\n \"\"\"\n resource_name = kwargs['resource']\n uri = kwargs['uri']\n resource = Resource(resource_name, uri, table=self.resources)\n return resource\n\n @docval({'name': 'container', 'type': (str, AbstractContainer),\n 'doc': 'The Container/Data object to add or the object id of the Container/Data object to add.'},\n {'name': 'relative_path', 'type': str,\n 'doc': ('The relative_path of the attribute of the object that uses ',\n 'an external resource reference key. Use an empty string if not applicable.')},\n {'name': 'field', 'type': str, 'default': '',\n 'doc': ('The field of the compound data type using an external resource.')})\n def _add_object(self, **kwargs):\n \"\"\"\n Add an object that references an external resource.\n \"\"\"\n container, relative_path, field = popargs('container', 'relative_path', 'field', kwargs)\n if isinstance(container, AbstractContainer):\n container = container.object_id\n obj = Object(container, relative_path, field, table=self.objects)\n return obj\n\n @docval({'name': 'obj', 'type': (int, Object), 'doc': 'The Object that uses the Key.'},\n {'name': 'key', 'type': (int, Key), 'doc': 'The Key that the Object uses.'})\n def _add_object_key(self, **kwargs):\n \"\"\"\n Specify that an object (i.e. container and relative_path) uses a key to reference\n an external resource.\n \"\"\"\n obj, key = popargs('obj', 'key', kwargs)\n return ObjectKey(obj, key, table=self.object_keys)\n\n @docval({'name': 'container', 'type': (str, AbstractContainer),\n 'doc': ('The Container/Data object that uses the key or '\n 'the object id for the Container/Data object that uses the key.')},\n {'name': 'relative_path', 'type': str,\n 'doc': ('The relative_path of the attribute of the object that uses ',\n 'an external resource reference key. Use an empty string if not applicable.'),\n 'default': ''},\n {'name': 'field', 'type': str, 'default': '',\n 'doc': ('The field of the compound data type using an external resource.')})\n def _check_object_field(self, container, relative_path, field):\n \"\"\"\n Check if a container, relative path, and field have been added.\n\n The container can be either an object_id string or an AbstractContainer.\n\n If the container, relative_path, and field have not been added, add them\n and return the corresponding Object. Otherwise, just return the Object.\n \"\"\"\n if isinstance(container, str):\n objecttable_idx = self.objects.which(object_id=container)\n else:\n objecttable_idx = self.objects.which(object_id=container.object_id)\n\n if len(objecttable_idx) > 0:\n relative_path_idx = self.objects.which(relative_path=relative_path)\n field_idx = self.objects.which(field=field)\n objecttable_idx = list(set(objecttable_idx) & set(relative_path_idx) & set(field_idx))\n\n if len(objecttable_idx) == 1:\n return self.objects.row[objecttable_idx[0]]\n elif len(objecttable_idx) == 0:\n return self._add_object(container, relative_path, field)\n else:\n raise ValueError(\"Found multiple instances of the same object id, relative path, \"\n \"and field in objects table.\")\n\n @docval({'name': 'key_name', 'type': str, 'doc': 'The name of the Key to get.'},\n {'name': 'container', 'type': (str, AbstractContainer), 'default': None,\n 'doc': ('The Container/Data object that uses the key or '\n 'the object id for the Container/Data object that uses the key.')},\n {'name': 'relative_path', 'type': str,\n 'doc': ('The relative_path of the attribute of the object that uses ',\n 'an external resource reference key. Use an empty string if not applicable.'),\n 'default': ''},\n {'name': 'field', 'type': str, 'default': '',\n 'doc': ('The field of the compound data type using an external resource.')})\n def get_key(self, **kwargs):\n \"\"\"\n Return a Key or a list of Key objects that correspond to the given key.\n\n If container, relative_path, and field are provided, the Key that corresponds to the given name of the key\n for the given container, relative_path, and field is returned.\n \"\"\"\n key_name, container, relative_path, field = popargs('key_name', 'container', 'relative_path', 'field', kwargs)\n key_idx_matches = self.keys.which(key=key_name)\n\n if container is not None:\n # if same key is used multiple times, determine\n # which instance based on the Container\n object_field = self._check_object_field(container, relative_path, field)\n for row_idx in self.object_keys.which(objects_idx=object_field.idx):\n key_idx = self.object_keys['keys_idx', row_idx]\n if key_idx in key_idx_matches:\n return self.keys.row[key_idx]\n msg = (\"No key '%s' found for container '%s', relative_path '%s', and field '%s'\"\n % (key_name, container, relative_path, field))\n raise ValueError(msg)\n else:\n if len(key_idx_matches) == 0:\n # the key has never been used before\n raise ValueError(\"key '%s' does not exist\" % key_name)\n elif len(key_idx_matches) > 1:\n return [self.keys.row[i] for i in key_idx_matches]\n else:\n return self.keys.row[key_idx_matches[0]]\n\n @docval({'name': 'resource_name', 'type': str, 'doc': 'The name of the resource.'})\n def get_resource(self, **kwargs):\n \"\"\"\n Retrieve resource object with the given resource_name.\n \"\"\"\n resource_table_idx = self.resources.which(resource=kwargs['resource_name'])\n if len(resource_table_idx) == 0:\n # Resource hasn't been created\n msg = \"No resource '%s' exists. Use _add_resource to create a new resource\" % kwargs['resource_name']\n raise ValueError(msg)\n else:\n return self.resources.row[resource_table_idx[0]]\n\n @docval({'name': 'container', 'type': (str, AbstractContainer), 'default': None,\n 'doc': ('The Container/Data object that uses the key or '\n 'the object_id for the Container/Data object that uses the key.')},\n {'name': 'attribute', 'type': str,\n 'doc': 'The attribute of the container for the external reference.', 'default': None},\n {'name': 'field', 'type': str, 'default': '',\n 'doc': ('The field of the compound data type using an external resource.')},\n {'name': 'key', 'type': (str, Key), 'default': None,\n 'doc': 'The name of the key or the Key object from the KeyTable for the key to add a resource for.'},\n {'name': 'resources_idx', 'type': Resource, 'doc': 'The Resource from the ResourceTable.', 'default': None},\n {'name': 'resource_name', 'type': str, 'doc': 'The name of the resource to be created.', 'default': None},\n {'name': 'resource_uri', 'type': str, 'doc': 'The URI of the resource to be created.', 'default': None},\n {'name': 'entity_id', 'type': str, 'doc': 'The identifier for the entity at the resource.',\n 'default': None},\n {'name': 'entity_uri', 'type': str, 'doc': 'The URI for the identifier at the resource.', 'default': None}\n )\n def add_ref(self, **kwargs):\n \"\"\"\n Add information about an external reference used in this file.\n\n It is possible to use the same name of the key to refer to different resources\n so long as the name of the key is not used within the same object, relative_path, and\n field combination. This method does not support such functionality by default.\n \"\"\"\n ###############################################################\n container = kwargs['container']\n attribute = kwargs['attribute']\n key = kwargs['key']\n field = kwargs['field']\n entity_id = kwargs['entity_id']\n entity_uri = kwargs['entity_uri']\n add_entity = False\n\n if attribute is None: # Trivial Case\n relative_path = ''\n object_field = self._check_object_field(container, relative_path, field)\n else: # DataType Attribute Case\n attribute_object = getattr(container, attribute) # returns attribute object\n if isinstance(attribute_object, AbstractContainer):\n relative_path = ''\n object_field = self._check_object_field(attribute_object, relative_path, field)\n else: # Non-DataType Attribute Case:\n obj_mapper = self.type_map.get_map(container)\n spec = obj_mapper.get_attr_spec(attr_name=attribute)\n parent_spec = spec.parent # return the parent spec of the attribute\n if parent_spec.data_type is None:\n while parent_spec.data_type is None:\n parent_spec = parent_spec.parent # find the closest parent with a data_type\n parent_cls = self.type_map.get_dt_container_cls(data_type=parent_spec.data_type, autogen=False)\n if isinstance(container, parent_cls):\n parent_id = container.object_id\n # We need to get the path of the spec for relative_path\n absolute_path = spec.path\n relative_path = re.sub(\"^.+?(?=\"+container.data_type+\")\", \"\", absolute_path)\n object_field = self._check_object_field(parent_id, relative_path, field)\n else:\n msg = 'Container not the nearest data_type'\n raise ValueError(msg)\n else:\n parent_id = container.object_id # container needs to be the parent\n absolute_path = spec.path\n relative_path = re.sub(\"^.+?(?=\"+container.data_type+\")\", \"\", absolute_path)\n # this regex removes everything prior to the container on the absolute_path\n object_field = self._check_object_field(parent_id, relative_path, field)\n\n if not isinstance(key, Key):\n key_idx_matches = self.keys.which(key=key)\n # if same key is used multiple times, determine\n # which instance based on the Container\n for row_idx in self.object_keys.which(objects_idx=object_field.idx):\n key_idx = self.object_keys['keys_idx', row_idx]\n if key_idx in key_idx_matches:\n msg = \"Use Key Object when referencing an existing (container, relative_path, key)\"\n raise ValueError(msg)\n\n if not isinstance(key, Key):\n key = self._add_key(key)\n self._add_object_key(object_field, key)\n\n if kwargs['resources_idx'] is not None and kwargs['resource_name'] is None and kwargs['resource_uri'] is None:\n resource_table_idx = kwargs['resources_idx']\n elif (\n kwargs['resources_idx'] is not None\n and (kwargs['resource_name'] is not None\n or kwargs['resource_uri'] is not None)):\n msg = \"Can't have resource_idx with resource_name or resource_uri.\"\n raise ValueError(msg)\n elif len(self.resources.which(resource=kwargs['resource_name'])) == 0:\n resource_name = kwargs['resource_name']\n resource_uri = kwargs['resource_uri']\n resource_table_idx = self._add_resource(resource_name, resource_uri)\n else:\n idx = self.resources.which(resource=kwargs['resource_name'])\n resource_table_idx = self.resources.row[idx[0]]\n\n if (resource_table_idx is not None and entity_id is not None and entity_uri is not None):\n add_entity = True\n elif not (resource_table_idx is None and entity_id is None and resource_uri is None):\n msg = (\"Specify resource, entity_id, and entity_uri arguments.\"\n \"All three are required to create a reference\")\n raise ValueError(msg)\n\n if add_entity:\n entity = self._add_entity(key, resource_table_idx, entity_id, entity_uri)\n\n return key, resource_table_idx, entity\n\n @docval({'name': 'container', 'type': (str, AbstractContainer),\n 'doc': 'The Container/data object that is linked to resources/entities.'},\n {'name': 'relative_path', 'type': str,\n 'doc': ('The relative_path of the attribute of the object that uses ',\n 'an external resource reference key. Use an empty string if not applicable.'),\n 'default': ''},\n {'name': 'field', 'type': str, 'default': '',\n 'doc': ('The field of the compound data type using an external resource.')})\n def get_object_resources(self, **kwargs):\n \"\"\"\n Get all entities/resources associated with an object.\n \"\"\"\n container = kwargs['container']\n relative_path = kwargs['relative_path']\n field = kwargs['field']\n\n keys = []\n entities = []\n object_field = self._check_object_field(container, relative_path, field)\n # Find all keys associated with the object\n for row_idx in self.object_keys.which(objects_idx=object_field.idx):\n keys.append(self.object_keys['keys_idx', row_idx])\n # Find all the entities/resources for each key.\n for key_idx in keys:\n entity_idx = self.entities.which(keys_idx=key_idx)\n entities.append(self.entities.__getitem__(entity_idx[0]))\n df = pd.DataFrame(entities, columns=['keys_idx', 'resource_idx', 'entity_id', 'entity_uri'])\n return df\n\n @docval({'name': 'keys', 'type': (list, Key), 'default': None,\n 'doc': 'The Key(s) to get external resource data for.'},\n rtype=pd.DataFrame, returns='a DataFrame with keys and external resource data')\n def get_keys(self, **kwargs):\n \"\"\"\n Return a DataFrame with information about keys used to make references to external resources.\n The DataFrame will contain the following columns:\n - *key_name*: the key that will be used for referencing an external resource\n - *resources_idx*: the index for the resourcetable\n - *entity_id*: the index for the entity at the external resource\n - *entity_uri*: the URI for the entity at the external resource\n\n It is possible to use the same *key_name* to refer to different resources so long as the *key_name* is not\n used within the same object, relative_path, field. This method doesn't support such functionality by default. To\n select specific keys, use the *keys* argument to pass in the Key object(s) representing the desired keys. Note,\n if the same *key_name* is used more than once, multiple calls to this method with different Key objects will\n be required to keep the different instances separate. If a single call is made, it is left up to the caller to\n distinguish the different instances.\n \"\"\"\n keys = popargs('keys', kwargs)\n if keys is None:\n keys = [self.keys.row[i] for i in range(len(self.keys))]\n else:\n if not isinstance(keys, list):\n keys = [keys]\n data = list()\n for key in keys:\n rsc_ids = self.entities.which(keys_idx=key.idx)\n for rsc_id in rsc_ids:\n rsc_row = self.entities.row[rsc_id].todict()\n rsc_row.pop('keys_idx')\n rsc_row['key_name'] = key.key\n data.append(rsc_row)\n return pd.DataFrame(data=data, columns=['key_name', 'resources_idx',\n 'entity_id', 'entity_uri'])\n\n @docval({'name': 'use_categories', 'type': bool, 'default': False,\n 'doc': 'Use a multi-index on the columns to indicate which category each column belongs to.'},\n rtype=pd.DataFrame, returns='A DataFrame with all data merged into a flat, denormalized table.')\n def to_dataframe(self, **kwargs):\n \"\"\"\n Convert the data from the keys, resources, entities, objects, and object_keys tables\n to a single joint dataframe. I.e., here data is being denormalized, e.g., keys that\n are used across multiple enities or objects will duplicated across the corresponding\n rows.\n\n Returns: :py:class:`~pandas.DataFrame` with all data merged into a single, flat, denormalized table.\n\n \"\"\"\n use_categories = popargs('use_categories', kwargs)\n # Step 1: Combine the entities, keys, and resources,table\n entities_df = self.entities.to_dataframe()\n # Map the keys to the entities by 1) convert to dataframe, 2) select rows based on the keys_idx\n # from the entities table, expanding the dataframe to have the same number of rows as the\n # entities, and 3) reset the index to avoid duplicate values in the index, which causes errors when merging\n keys_mapped_df = self.keys.to_dataframe().iloc[entities_df['keys_idx']].reset_index(drop=True)\n # Map the resources to entities using the same strategy as for the keys\n resources_mapped_df = self.resources.to_dataframe().iloc[entities_df['resources_idx']].reset_index(drop=True)\n # Merge the mapped keys and resources with the entities tables\n entities_df = pd.concat(objs=[entities_df, keys_mapped_df, resources_mapped_df],\n axis=1, verify_integrity=False)\n # Add a column for the entity id (for consistency with the other tables and to facilitate query)\n entities_df['entities_idx'] = entities_df.index\n\n # Step 2: Combine the the object_keys and objects tables\n object_keys_df = self.object_keys.to_dataframe()\n objects_mapped_df = self.objects.to_dataframe().iloc[object_keys_df['objects_idx']].reset_index(drop=True)\n object_keys_df = pd.concat(objs=[object_keys_df, objects_mapped_df],\n axis=1,\n verify_integrity=False)\n\n # Step 3: merge the combined entities_df and object_keys_df DataFrames\n result_df = pd.concat(\n # Create for each row in the objects_keys table a DataFrame with all corresponding data from all tables\n objs=[pd.merge(\n # Find all entities that correspond to the row i of the object_keys_table\n entities_df[entities_df['keys_idx'] == object_keys_df['keys_idx'].iloc[i]].reset_index(drop=True),\n # Get a DataFrame for row i of the objects_keys_table\n object_keys_df.iloc[[i, ]],\n # Merge the entities and object_keys on the keys_idx column so that the values from the single\n # object_keys_table row are copied across all corresponding rows in the entities table\n on='keys_idx')\n for i in range(len(object_keys_df))],\n # Concatenate the rows of the objs\n axis=0,\n verify_integrity=False)\n\n # Step 4: Clean up the index and sort columns by table type and name\n result_df.reset_index(inplace=True, drop=True)\n column_labels = [('objects', 'objects_idx'), ('objects', 'object_id'), ('objects', 'field'),\n ('keys', 'keys_idx'), ('keys', 'key'),\n ('resources', 'resources_idx'), ('resources', 'resource'), ('resources', 'resource_uri'),\n ('entities', 'entities_idx'), ('entities', 'entity_id'), ('entities', 'entity_uri')]\n # sort the columns based on our custom order\n result_df = result_df.reindex(labels=[c[1] for c in column_labels],\n axis=1)\n # Add the categories if requested\n if use_categories:\n result_df.columns = pd.MultiIndex.from_tuples(column_labels)\n # return the result\n return result_df\n\n @docval({'name': 'db_file', 'type': str, 'doc': 'Name of the SQLite database file'},\n rtype=pd.DataFrame, returns='A DataFrame with all data merged into a flat, denormalized table.')\n def export_to_sqlite(self, db_file):\n \"\"\"\n Save the keys, resources, entities, objects, and object_keys tables using sqlite3 to the given db_file.\n\n The function will first create the tables (if they do not already exist) and then\n add the data from this ExternalResource object to the database. If the database file already\n exists, then the data will be appended as rows to the existing database tables.\n\n Note, the index values of foreign keys (e.g., keys_idx, objects_idx, resources_idx) in the tables\n will not match between the ExternalResources here and the exported database, but they are adjusted\n automatically here, to ensure the foreign keys point to the correct rows in the exported database.\n This is because: 1) ExternalResources uses 0-based indexing for foreign keys, whereas SQLite uses\n 1-based indexing and 2) if data is appended to existing tables then a corresponding additional\n offset must be applied to the relevant foreign keys.\n\n :raises: The function will raise errors if connection to the database fails. If\n the given db_file already exists, then there is also the possibility that\n certain updates may result in errors if there are collisions between the\n new and existing data.\n \"\"\"\n import sqlite3\n # connect to the database\n connection = sqlite3.connect(db_file)\n cursor = connection.cursor()\n # sql calls to setup the tables\n sql_create_keys_table = \"\"\" CREATE TABLE IF NOT EXISTS keys (\n id integer PRIMARY KEY,\n key text NOT NULL\n ); \"\"\"\n sql_create_objects_table = \"\"\" CREATE TABLE IF NOT EXISTS objects (\n id integer PRIMARY KEY,\n object_id text NOT NULL,\n relative_path text NOT NULL,\n field text\n ); \"\"\"\n sql_create_resources_table = \"\"\" CREATE TABLE IF NOT EXISTS resources (\n id integer PRIMARY KEY,\n resource text NOT NULL,\n resource_uri text NOT NULL\n ); \"\"\"\n sql_create_object_keys_table = \"\"\" CREATE TABLE IF NOT EXISTS object_keys (\n id integer PRIMARY KEY,\n objects_idx int NOT NULL,\n keys_idx int NOT NULL,\n FOREIGN KEY (objects_idx) REFERENCES objects (id),\n FOREIGN KEY (keys_idx) REFERENCES keys (id)\n ); \"\"\"\n sql_create_entities_table = \"\"\" CREATE TABLE IF NOT EXISTS entities (\n id integer PRIMARY KEY,\n keys_idx int NOT NULL,\n resources_idx int NOT NULL,\n entity_id text NOT NULL,\n entity_uri text NOT NULL,\n FOREIGN KEY (keys_idx) REFERENCES keys (id),\n FOREIGN KEY (resources_idx) REFERENCES resources (id)\n ); \"\"\"\n # execute setting up the tables\n cursor.execute(sql_create_keys_table)\n cursor.execute(sql_create_objects_table)\n cursor.execute(sql_create_resources_table)\n cursor.execute(sql_create_object_keys_table)\n cursor.execute(sql_create_entities_table)\n\n # NOTE: sqlite uses a 1-based row-index so we need to update all foreign key columns accordingly\n # NOTE: If we are adding to an existing sqlite database then we need to also adjust for he number of rows\n keys_offset = len(cursor.execute('select * from keys;').fetchall()) + 1\n objects_offset = len(cursor.execute('select * from objects;').fetchall()) + 1\n resources_offset = len(cursor.execute('select * from resources;').fetchall()) + 1\n\n # populate the tables and fix foreign keys during insert\n cursor.executemany(\" INSERT INTO keys(key) VALUES(?) \", self.keys[:])\n connection.commit()\n cursor.executemany(\" INSERT INTO objects(object_id, relative_path, field) VALUES(?, ?, ?) \", self.objects[:])\n connection.commit()\n cursor.executemany(\" INSERT INTO resources(resource, resource_uri) VALUES(?, ?) \", self.resources[:])\n connection.commit()\n cursor.executemany(\n \" INSERT INTO object_keys(objects_idx, keys_idx) VALUES(?+%i, ?+%i) \" % (objects_offset, keys_offset),\n self.object_keys[:])\n connection.commit()\n cursor.executemany(\n \" INSERT INTO entities(keys_idx, resources_idx, entity_id, entity_uri) VALUES(?+%i, ?+%i, ?, ?) \"\n % (keys_offset, resources_offset),\n self.entities[:])\n connection.commit()\n connection.close()\n" ]
[ [ "pandas.concat", "pandas.MultiIndex.from_tuples", "pandas.DataFrame" ] ]
luomingshuang/speechbrain
[ "f9d8f643e7ce56cd7dd20fd93be0acb15da3c499" ]
[ "recipes/LibriSpeech/ASR/inference-with-k2/utils/lm_rescore.py" ]
[ "# Copyright (c) 2021 Xiaomi Corporation (authors: Fangjun Kuang)\n\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\n\nimport math\n\nimport k2\nimport torch\n\n\ndef _intersect_device(a_fsas: k2.Fsa, b_fsas: k2.Fsa, b_to_a_map: torch.Tensor,\n sorted_match_a: bool):\n '''This is a wrapper of k2.intersect_device and its purpose is to split\n b_fsas into several batches and process each batch separately to avoid\n CUDA OOM error.\n\n The arguments and return value of this function are the same as\n k2.intersect_device.\n '''\n # NOTE: You can decrease batch_size in case of CUDA out of memory error.\n batch_size = 500\n num_fsas = b_fsas.shape[0]\n if num_fsas <= batch_size:\n return k2.intersect_device(a_fsas,\n b_fsas,\n b_to_a_map=b_to_a_map,\n sorted_match_a=sorted_match_a)\n\n num_batches = int(math.ceil(float(num_fsas) / batch_size))\n splits = []\n for i in range(num_batches):\n start = i * batch_size\n end = min(start + batch_size, num_fsas)\n splits.append((start, end))\n\n ans = []\n for start, end in splits:\n indexes = torch.arange(start, end).to(b_to_a_map)\n\n fsas = k2.index(b_fsas, indexes)\n b_to_a = k2.index(b_to_a_map, indexes)\n path_lats = k2.intersect_device(a_fsas,\n fsas,\n b_to_a_map=b_to_a,\n sorted_match_a=sorted_match_a)\n ans.append(path_lats)\n\n return k2.cat(ans)\n\n\ndef compute_am_scores(lats: k2.Fsa, word_fsas_with_epsilon_loops: k2.Fsa,\n path_to_seq_map: torch.Tensor) -> torch.Tensor:\n '''Compute AM scores of n-best lists (represented as word_fsas).\n\n Args:\n lats:\n An FsaVec, which is the output of `k2.intersect_dense_pruned`.\n It must have the attribute `lm_scores`.\n word_fsas_with_epsilon_loops:\n An FsaVec representing a n-best list. Note that it has been processed\n by `k2.add_epsilon_self_loops`.\n path_to_seq_map:\n A 1-D torch.Tensor with dtype torch.int32. path_to_seq_map[i] indicates\n which sequence the i-th Fsa in word_fsas_with_epsilon_loops belongs to.\n path_to_seq_map.numel() == word_fsas_with_epsilon_loops.arcs.dim0().\n Returns:\n Return a 1-D torch.Tensor containing the AM scores of each path.\n `ans.numel() == word_fsas_with_epsilon_loops.shape[0]`\n '''\n device = lats.device\n assert len(lats.shape) == 3\n assert hasattr(lats, 'lm_scores')\n\n # k2.compose() currently does not support b_to_a_map. To void\n # replicating `lats`, we use k2.intersect_device here.\n #\n # lats has phone IDs as `labels` and word IDs as aux_labels, so we\n # need to invert it here.\n inverted_lats = k2.invert(lats)\n\n # Now the `labels` of inverted_lats are word IDs (a 1-D torch.Tensor)\n # and its `aux_labels` are phone IDs ( a k2.RaggedInt with 2 axes)\n\n # Remove its `aux_labels` since it is not needed in the\n # following computation\n del inverted_lats.aux_labels\n inverted_lats = k2.arc_sort(inverted_lats)\n\n am_path_lats = _intersect_device(inverted_lats,\n word_fsas_with_epsilon_loops,\n b_to_a_map=path_to_seq_map,\n sorted_match_a=True)\n\n am_path_lats = k2.top_sort(k2.connect(am_path_lats.to('cpu')))\n\n # The `scores` of every arc consists of `am_scores` and `lm_scores`\n am_path_lats.scores = am_path_lats.scores - am_path_lats.lm_scores\n\n am_scores = am_path_lats.get_tot_scores(True, True)\n\n return am_scores\n\n\[email protected]_grad()\ndef rescore_with_n_best_list(lats: k2.Fsa, G: k2.Fsa, num_paths: int,\n lm_scale_list: List[float]) -> Dict[str, k2.Fsa]:\n '''Decode using n-best list with LM rescoring.\n\n `lats` is a decoding lattice, which has 3 axes. This function first\n extracts `num_paths` paths from `lats` for each sequence using\n `k2.random_paths`. The `am_scores` of these paths are computed.\n For each path, its `lm_scores` is computed using `G` (which is an LM).\n The final `tot_scores` is the sum of `am_scores` and `lm_scores`.\n The path with the greatest `tot_scores` within a sequence is used\n as the decoding output.\n\n Args:\n lats:\n An FsaVec. It can be the output of `k2.intersect_dense_pruned`.\n G:\n An FsaVec representing the language model (LM). Note that it\n is an FsaVec, but it contains only one Fsa.\n num_paths:\n It is the size `n` in `n-best` list.\n lm_scale_list:\n A list containing lm_scale values.\n Returns:\n A dict of FsaVec, whose key is a lm_scale and the value represents the\n best decoding path for each sequence in the lattice.\n '''\n device = lats.device\n\n assert len(lats.shape) == 3\n assert hasattr(lats, 'aux_labels')\n assert hasattr(lats, 'lm_scores')\n\n assert G.shape == (1, None, None)\n assert G.device == device\n assert hasattr(G, 'aux_labels') is False\n\n # First, extract `num_paths` paths for each sequence.\n # paths is a k2.RaggedInt with axes [seq][path][arc_pos]\n paths = k2.random_paths(lats, num_paths=num_paths, use_double_scores=True)\n if paths.shape().tot_size(1) == 0:\n print('Get None paths.')\n return None\n \n #print('Raggedint paths shape: ', paths.shape())\n # word_seqs is a k2.RaggedInt sharing the same shape as `paths`\n # but it contains word IDs. Note that it also contains 0s and -1s.\n # The last entry in each sublist is -1.\n word_seqs = k2.index(lats.aux_labels, paths)\n\n # Remove epsilons and -1 from word_seqs\n word_seqs = k2.ragged.remove_values_leq(word_seqs, 0)\n\n # Remove repeated sequences to avoid redundant computation later.\n #\n # unique_word_seqs is still a k2.RaggedInt with 3 axes [seq][path][word]\n # except that there are no repeated paths with the same word_seq\n # within a seq.\n #\n # num_repeats is also a k2.RaggedInt with 2 axes containing the\n # multiplicities of each path.\n # num_repeats.num_elements() == unique_word_seqs.num_elements()\n #\n # Since k2.ragged.unique_sequences will reorder paths within a seq,\n # `new2old` is a 1-D torch.Tensor mapping from the output path index\n # to the input path index.\n # new2old.numel() == unique_word_seqs.num_elements()\n unique_word_seqs, num_repeats, new2old = k2.ragged.unique_sequences(\n word_seqs, need_num_repeats=True, need_new2old_indexes=True)\n\n seq_to_path_shape = k2.ragged.get_layer(unique_word_seqs.shape(), 0)\n\n # path_to_seq_map is a 1-D torch.Tensor.\n # path_to_seq_map[i] is the seq to which the i-th path\n # belongs.\n path_to_seq_map = seq_to_path_shape.row_ids(1)\n\n # Remove the seq axis.\n # Now unique_word_seqs has only two axes [path][word]\n unique_word_seqs = k2.ragged.remove_axis(unique_word_seqs, 0)\n\n # word_fsas is an FsaVec with axes [path][state][arc]\n word_fsas = k2.linear_fsa(unique_word_seqs)\n\n word_fsas_with_epsilon_loops = k2.add_epsilon_self_loops(word_fsas)\n\n am_scores = compute_am_scores(lats, word_fsas_with_epsilon_loops,\n path_to_seq_map)\n\n # Now compute lm_scores\n b_to_a_map = torch.zeros_like(path_to_seq_map)\n lm_path_lats = _intersect_device(G,\n word_fsas_with_epsilon_loops,\n b_to_a_map=b_to_a_map,\n sorted_match_a=True)\n lm_path_lats = k2.top_sort(k2.connect(lm_path_lats))\n lm_scores = lm_path_lats.get_tot_scores(use_double_scores=True, log_semiring=False)\n\n ans = dict()\n for lm_scale in lm_scale_list:\n tot_scores = am_scores.to(device) / lm_scale + lm_scores.to(device)\n\n # Remember that we used `k2.ragged.unique_sequences` to remove repeated\n # paths to avoid redundant computation in `k2.intersect_device`.\n # Now we use `num_repeats` to correct the scores for each path.\n #\n # NOTE(fangjun): It is commented out as it leads to a worse WER\n # tot_scores = tot_scores * num_repeats.values()\n\n # TODO(fangjun): We may need to add `k2.RaggedDouble`\n ragged_tot_scores = k2.RaggedFloat(seq_to_path_shape,\n tot_scores.to(torch.float32))\n argmax_indexes = k2.ragged.argmax_per_sublist(ragged_tot_scores)\n\n # Use k2.index here since argmax_indexes' dtype is torch.int32\n best_path_indexes = k2.index(new2old, argmax_indexes)\n\n paths_2axes = k2.ragged.remove_axis(paths, 0)\n\n # best_path is a k2.RaggedInt with 2 axes [path][arc_pos]\n best_paths = k2.index(paths_2axes, best_path_indexes)\n\n # labels is a k2.RaggedInt with 2 axes [path][phone_id]\n # Note that it contains -1s.\n labels = k2.index(lats.labels.contiguous(), best_paths)\n\n labels = k2.ragged.remove_values_eq(labels, -1)\n\n # lats.aux_labels is a k2.RaggedInt tensor with 2 axes, so\n # aux_labels is also a k2.RaggedInt with 2 axes\n aux_labels = k2.index(lats.aux_labels, best_paths.values())\n\n best_path_fsas = k2.linear_fsa(labels)\n best_path_fsas.aux_labels = aux_labels\n\n key = f'lm_scale_{lm_scale}'\n ans[key] = best_path_fsas\n\n return ans\n\[email protected]_grad()\ndef rescore_with_whole_lattice(lats: k2.Fsa, G_with_epsilon_loops: k2.Fsa,\n lm_scale_list: List[float]\n ) -> Dict[str, k2.Fsa]:\n '''Use whole lattice to rescore.\n\n Args:\n lats:\n An FsaVec It can be the output of `k2.intersect_dense_pruned`.\n G_with_epsilon_loops:\n An FsaVec representing the language model (LM). Note that it\n is an FsaVec, but it contains only one Fsa.\n lm_scale_list:\n A list containing lm_scale values.\n Returns:\n A dict of FsaVec, whose key is a lm_scale and the value represents the\n best decoding path for each sequence in the lattice.\n '''\n assert len(lats.shape) == 3\n assert hasattr(lats, 'lm_scores')\n assert G_with_epsilon_loops.shape == (1, None, None)\n\n device = lats.device\n lats.scores = lats.scores - lats.lm_scores\n # We will use lm_scores from G, so remove lats.lm_scores here\n del lats.lm_scores\n assert hasattr(lats, 'lm_scores') is False\n\n # lats.scores = scores / lm_scale\n # Now, lats.scores contains only am_scores\n\n # inverted_lats has word IDs as labels.\n # Its aux_labels are phone IDs, which is a ragged tensor k2.RaggedInt\n inverted_lats = k2.invert(lats)\n num_seqs = lats.shape[0]\n\n b_to_a_map = torch.zeros(num_seqs, device=device, dtype=torch.int32)\n try:\n rescoring_lats = k2.intersect_device(G_with_epsilon_loops,\n inverted_lats,\n b_to_a_map,\n sorted_match_a=True)\n except RuntimeError as e:\n print(f'Caught exception:\\n{e}\\n')\n print(f'Number of FSAs: {inverted_lats.shape[0]}')\n print('num_arcs before pruning: ', inverted_lats.arcs.num_elements())\n\n # NOTE(fangjun): The choice of the threshold 0.01 is arbitrary here\n # to avoid OOM. We may need to fine tune it.\n inverted_lats = k2.prune_on_arc_post(inverted_lats, 0.001, True)\n print('num_arcs after pruning: ', inverted_lats.arcs.num_elements())\n\n rescoring_lats = k2.intersect_device(G_with_epsilon_loops,\n inverted_lats,\n b_to_a_map,\n sorted_match_a=True)\n\n rescoring_lats = k2.top_sort(k2.connect(rescoring_lats.to('cpu')))\n\n # inv_lats has phone IDs as labels\n # and word IDs as aux_labels.\n inv_lats = k2.invert(rescoring_lats)\n\n ans = dict()\n #\n # The following implements\n # scores = (scores - lm_scores)/lm_scale + lm_scores\n # = scores/lm_scale + lm_scores*(1 - 1/lm_scale)\n #\n saved_am_scores = inv_lats.scores - inv_lats.lm_scores\n for lm_scale in lm_scale_list:\n am_scores = saved_am_scores / lm_scale\n inv_lats.scores = am_scores + inv_lats.lm_scores\n\n best_paths = k2.shortest_path(inv_lats, use_double_scores=True)\n key = f'lm_scale_{lm_scale}'\n ans[key] = best_paths\n return ans\n" ]
[ [ "torch.zeros_like", "torch.no_grad", "torch.arange", "torch.zeros" ] ]
CarstenWalther/space-tyckiting
[ "8398f080332c78c7f246289947fdda49558e0f12" ]
[ "clients/python/tyckiting_client/ai/strategies/escaping.py" ]
[ "import random\nimport logging\n\nimport numpy as np\n\nfrom tyckiting_client import hexagon\nfrom tyckiting_client.messages import Pos\n\nfrom tyckiting_client.notifications import defaultNotificationCenter\nfrom tyckiting_client.notifications import ID_START_ROUND_NOTIFICATION\nfrom tyckiting_client.gameField import GameField\n\nclass Escaping(object):\n\n\tdef __init__(self, config):\n\t\tself.config = config\n\n\tdef getMove(self, bot):\n\t\tcoords = self.getPossibleMoves(bot)\n\t\tcoord = random.choice(list(coords))\n\t\tpos = Pos(coord[0], coord[1])\n\t\tlogging.info('Move %d from %s to %s', bot.bot_id, bot.pos, pos)\n\t\treturn pos\n\n\tdef getPossibleMoves(self, bot):\n\t\traise NotImplementedError()\n\nclass RandomEscaping(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = set()\n\t\tfor radius in range(1, self.config.move + 1):\n\t\t\tcoordinates |= hexagon.get_ring((bot.pos.x, bot.pos.y), radius)\n\t\tcoordinates = hexagon.extractValidCoordinates(coordinates, self.config.field_radius)\n\t\treturn coordinates\n\nclass StraightDistance2Escaping(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = set()\n\t\tcenter = (bot.pos.x, bot.pos.y)\n\t\tfor direction in range(6):\n\t\t\tcoord = hexagon.neighbor(center, direction)\n\t\t\tcoord = hexagon.neighbor(coord, direction)\n\t\t\tcoordinates.add(coord)\n\t\tcoordinates = hexagon.extractValidCoordinates(coordinates, self.config.field_radius)\n\t\treturn coordinates\n\nclass Distance1Escaping(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = set()\n\t\tcenter = (bot.pos.x, bot.pos.y)\n\t\tfor direction in range(6):\n\t\t\tcoord = hexagon.neighbor(center, direction)\n\t\t\tcoordinates.add(coord)\n\t\tcoordinates = hexagon.extractValidCoordinates(coordinates, self.config.field_radius)\n\t\treturn coordinates\n\nclass CurvedDistance2Escaping(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = set()\n\t\tcenter = (bot.pos.x, bot.pos.y)\n\t\tfor direction in range(6):\n\t\t\tcoord = hexagon.neighbor(center, direction)\n\t\t\tcoord = hexagon.neighbor(coord, (direction - 1) % 6)\n\t\t\tcoordinates.add(coord)\n\t\tcoordinates = hexagon.extractValidCoordinates(coordinates, self.config.field_radius)\n\t\treturn coordinates\n\nclass AvoidSelfhit(Escaping):\n\n\tdef setEnemy(self, enemy_pos):\n\t\tself.enemy_pos = enemy_pos\n\n\tdef getPossibleMoves(self, bot):\n\t\tlogging.info('AvoidSelfhit on bot %d from enemy in %s', bot.bot_id, self.enemy_pos)\n\t\tcoordinates = set()\n\t\tcenter = (bot.pos.x, bot.pos.y)\n\t\tmax_distance = 0\n\n\t\tfor direction in range(6):\n\t\t\tcoord = hexagon.neighbor(center, direction)\n\t\t\tcoord = hexagon.neighbor(coord, direction)\n\t\t\tdistance = hexagon.distance(coord, self.enemy_pos)\n\n\t\t\tif distance == max_distance:\n\t\t\t\tcoordinates.add(coord)\n\n\t\t\telif distance > max_distance:\n\t\t\t\tcoordinates.clear()\n\t\t\t\tcoordinates.add(coord)\n\t\t\t\tmax_distance = distance\n\n\t\tcoordinates = hexagon.extractValidCoordinates(coordinates, self.config.field_radius)\n\t\treturn coordinates\n\nclass AvoidGrouping(Escaping):\n\n\tdef __init__(self, config):\n\t\tself.config = config\n\t\tself.straight = StraightDistance2Escaping(self.config)\n\t\tself.curved = CurvedDistance2Escaping(self.config)\n\t\tself.teammates = None\n\n\tdef setTeammates(self, bots):\n\t\tself.teammates = bots\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = set()\n\t\tmax_distance = 0\n\n\t\tc1 = self.straight.getPossibleMoves(bot)\n\t\tc2 = self.curved.getPossibleMoves(bot)\n\t\tmoves = c1 | c2\n\t\tdistances = {}\n\n\t\tmax_distance = 0\n\t\tfor m in moves:\n\t\t\tdistance_to_team = 32\n\t\t\tfor own_bot in self.teammates:\n\t\t\t\tif hexagon.distance(own_bot.pos, m) < distance_to_team:\n\t\t\t\t\tdistance_to_team = hexagon.distance(own_bot.pos, m)\n\t\t\tdistances[m] = distance_to_team\n\t\t\tif distance_to_team > max_distance:\n\t\t\t\tcoordinates = set()\n\t\t\t\tcoordinates.add(m)\n\t\t\t\tmax_distance = distance_to_team\n\t\t\telif distance_to_team == max_distance:\n\t\t\t\tcoordinates.add(m)\n\n\t\treturn coordinates\n\n\nclass PretendToBeDead(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\treturn [(bot.pos.x, bot.pos.y)]\n\n# The following strategies return a sorted list with possible targetFields\n# starting with its proposed best target\n\nclass RunFromEnemy(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = hexagon.getCircle(self.config.move, bot.pos.x, bot.pos.y)\n\t\tgameField = GameField(self.config)\n\t\tposAndEnemyProb = sorted([(gameField.enemyProbability(c), c) for c in coordinates])\n\t\treturn list(zip(*posAndEnemyProb))[1]\n\n\nclass ChaseEnemy(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = hexagon.getCircle(self.config.move, bot.pos.x, bot.pos.y)\n\t\tgameField = GameField(self.config)\n\t\tposAndEnemyProb = sorted([(gameField.enemyProbability(c), c) for c in coordinates], reverse=True)\n\t\treturn list(zip(*posAndEnemyProb))[1]\n\n\nclass AvoidWalls(Escaping):\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = hexagon.getCircle(self.config.move, bot.pos.x, bot.pos.y)\n\t\tposAndEnemyProb = sorted([(hexagon.distance(c, (0, 0)), c) for c in coordinates], reverse=True)\n\t\treturn list(zip(*posAndEnemyProb))[1]\n\n\nclass AvoidWallsAdvanced(Escaping):\n\n\tdef __init__(self, config):\n\t\tself.config = config\n\t\tself.straight = StraightDistance2Escaping(self.config)\n\t\tself.curved = CurvedDistance2Escaping(self.config)\n\n\tdef getPossibleMoves(self, bot):\n\t\tc1 = self.straight.getPossibleMoves(bot)\n\t\tc2 = self.curved.getPossibleMoves(bot)\n\t\tmoves = c1 | c2\n\n\t\tcoordinates = set()\n\t\tfor c in moves:\n\t\t\tif hexagon.distance(c, (0,0)) <= 12:\n\t\t\t\tcoordinates.add(c)\n\t\treturn coordinates\n\n\nclass SpreadOwnBots(Escaping):\n\n\tdef __init__(self, config):\n\t\tself.config = config\n\t\tdefaultNotificationCenter.registerFunc(ID_START_ROUND_NOTIFICATION, self.updateOwnBotPositions)\n\t\tself.bots = []\n\n\tdef distanceToWall(self, pos):\n\t\tx = pos[0]\n\t\ty = pos[1]\n\t\tz = -x-y\n\n\t\tring = max(abs(x), abs(y), abs(z))\n\t\treturn self.config.field_radius - ring\n\n\tdef updateOwnBotPositions(self, notification):\n\t\tself.bots = notification.data['bots']\n\n\tdef getPossibleMoves(self, bot):\n\t\tcoordinates = hexagon.get_ring(coords=(bot.pos.x, bot.pos.y), radius=self.config.move )\n\t\tcoordinates = list(hexagon.extractValidCoordinates(coordinates,self.config.field_radius))\n\t\t\n\t\ttable = np.zeros((len(coordinates), 3))\n\t\tfor i, coordinate in enumerate(coordinates):\n\t\t\tdistToMid = hexagon.distance(coordinate, (0,0))\n\t\t\tdistToMid /= self.config.field_radius\n\t\t\tdistToInnerCircle = 16 * (distToMid - 0.5)**4\n\n\t\t\tgameField = GameField(self.config)\n\t\t\tenemyProbability = gameField.enemyProbability(coordinate)\n\n\t\t\tdistToClosestTeamMate = min([hexagon.distance( (b.pos.x,b.pos.y), (bot.pos.x, bot.pos.y) ) for b in self.bots if b.bot_id != bot.bot_id])\n\t\t\tdistToClosestTeamMate /= self.config.field_radius\n\n\t\t\ttable[i,:] = np.array([distToInnerCircle, enemyProbability, distToClosestTeamMate])\n\n\t\ttable[:,1] = table[:,1] / table[:,1].sum()\n\t\tscores = table[:,0] + 1-table[:,1] + 1-table[:,2]\n\t\treturn [coordinates[scores.argmin()]]\n\t\t" ]
[ [ "numpy.array" ] ]
shaytexel/python-pesq
[ "f591b77a25f35e58a11db3bccc2d082b2e15155f" ]
[ "tests/test.py" ]
[ "\nfrom scipy.io import wavfile\nfrom pathlib import Path\nfrom pesq import pesq\n\n\nfrom scipy.io import wavfile\nfrom pesq import pesq\n\nrate, deg = wavfile.read(\"./dgaudio/dgu_af1s01.wav\")\nrate, ref = wavfile.read(\"./audio/u_af1s01.wav\")\n\nprint(pesq(8000, ref, deg, 'wb'))" ]
[ [ "scipy.io.wavfile.read" ] ]
Oneflow-Inc/tvm
[ "81cc89b59085164f5c83a73a7010fd72a2d60c69" ]
[ "tests/python/frontend/oneflow/test_forward.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=import-self, invalid-name\n# pylint: disable=arguments-differ, unused-argument, unused-import\n\"\"\"Unit tests for various models and operators\"\"\"\nimport os\nimport sys\n\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay\nfrom tvm.contrib import graph_executor\n\nimport oneflow as flow\n\nMODEL_HOME = \"test_model\"\n\n\ndef mkdir(path):\n # init\n path = path.strip()\n path = path.rstrip(\"\\\\\")\n\n if not os.path.exists(path):\n os.makedirs(path)\n else:\n print(\"{} is already here\".format(path))\n\n\ndef rmdir(path):\n for root, dirs, files in os.walk(path, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n os.removedirs(path)\n\n\ndef assert_shape(out1, out2):\n if out1.shape != out2.shape:\n msg = \"Output shapes {} and {} don't match\"\n raise AssertionError(msg.format(out1.shape, out2.shape))\n\n\nclass OneFlowGraph(flow.nn.Graph):\n def __init__(self, module):\n super().__init__()\n self.m = module\n\n def build(self, x):\n out = self.m(x)\n return out\n\n\nclass OneFlowGraph_v2(flow.nn.Graph):\n def __init__(self, module):\n super().__init__()\n self.m = module\n\n def build(self, x1, x2, x3):\n out = self.m(x1, x2, x3)\n return out\n\n\ndef get_oneflow_output(model, inputs):\n flow_output = model(inputs)\n return flow_output.numpy()\n\n\ndef get_oneflow_concat_output(model, input1, input2, input3):\n flow_output = model(input1, input2, input3).numpy()\n return flow_output\n\n\ndef get_tvm_output(graph, model_path, inputs: flow.tensor, target=\"llvm\", dtype=\"float32\"):\n inputs_numpy = inputs.numpy()\n if target == \"llvm\":\n device = tvm.cpu(0)\n elif target == \"cuda\":\n device = tvm.cuda(0)\n\n mod, params = relay.frontend.from_oneflow(graph, model_path)\n with tvm.transform.PassContext(opt_level=10):\n intrp = relay.build_module.create_executor(\"graph\", mod, device, target)\n tvm_output = intrp.evaluate()(tvm.nd.array(inputs_numpy.astype(dtype)), **params).numpy()\n return tvm_output\n\n\ndef get_tvm_concat_output(\n graph, model_path,\n input1: flow.tensor,\n input2: flow.tensor,\n input3: flow.tensor,\n target=\"llvm\", dtype=\"float32\"\n):\n input1_numpy = input1.numpy()\n input2_numpy = input2.numpy()\n input3_numpy = input3.numpy()\n if target == \"llvm\":\n device = tvm.cpu(0)\n elif target == \"cuda\":\n device = tvm.cuda(0)\n\n mod, params = relay.frontend.from_oneflow(graph, model_path)\n with tvm.transform.PassContext(opt_level=10):\n intrp = relay.build_module.create_executor(\"graph\", mod, device, target)\n tvm_output = intrp.evaluate()(\n tvm.nd.array(input1_numpy.astype(dtype)),\n tvm.nd.array(input2_numpy.astype(dtype)),\n tvm.nd.array(input3_numpy.astype(dtype)),\n **params\n ).numpy()\n return tvm_output\n\n\ndef verify_conv(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs = flow.tensor(\n np.random.rand(1, 3, 224, 224),\n dtype=flow.float32,\n ),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs = inputs.to(device)\n \n graph = OneFlowGraph(model)\n graph._compile(inputs)\n\n\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n \n out_flow = get_oneflow_output(graph, inputs)\n out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_pool(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs = flow.tensor(\n np.random.rand(1, 3, 224, 224),\n dtype=flow.float32,\n ),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs = inputs.to(device)\n\n graph = OneFlowGraph(model)\n graph._compile(inputs)\n\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n\n out_flow = get_oneflow_output(graph, inputs)\n out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_normalization(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs = flow.tensor(\n np.random.rand(1, 3, 224, 224),\n dtype=flow.float32,\n ),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs = inputs.to(device)\n\n graph = OneFlowGraph(model)\n graph._compile(inputs)\n\n # write params\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n\n out_flow = get_oneflow_output(graph, inputs)\n out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_upsample(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs = flow.tensor(\n np.random.rand(1, 3, 50, 50),\n dtype=flow.float32,\n ),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs = inputs.to(device)\n\n graph = OneFlowGraph(model)\n graph._compile(inputs)\n\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n\n out_flow = get_oneflow_output(graph, inputs)\n out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_convtran(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs = flow.tensor(\n np.random.rand(1, 3, 50, 50),\n dtype=flow.float32,\n ),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs = inputs.to(device)\n\n graph = OneFlowGraph(model)\n graph._compile(inputs)\n\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n\n out_flow = get_oneflow_output(graph, inputs)\n out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_activation(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs = flow.tensor(\n np.random.rand(10, 10),\n dtype=flow.float32,\n ),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs = inputs.to(device)\n\n graph = OneFlowGraph(model)\n graph._compile(inputs)\n\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n\n out_flow = get_oneflow_output(graph, inputs)\n out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_math(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs = flow.tensor(\n np.random.rand(100, 1),\n dtype=flow.float32,\n ),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs = inputs.to(device)\n\n graph = OneFlowGraph(model)\n graph._compile(inputs)\n\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n\n out_flow = get_oneflow_output(graph, inputs)\n out_tvm = get_tvm_output(graph, MODEL_HOME, inputs, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\ndef verify_concat(\n model, name=\"\", rtol=1e-5, atol=1e-5,\n inputs1 = flow.tensor(np.random.randn(2, 5, 5, 4), dtype=flow.float32),\n inputs2 = flow.tensor(np.random.randn(2, 5, 5, 2), dtype=flow.float32),\n inputs3 = flow.tensor(np.random.randn(2, 5, 5, 3), dtype=flow.float32),\n device = \"llvm\"\n):\n if device == \"cuda\":\n model.to(device)\n inputs1 = inputs1.to(device)\n inputs2 = inputs2.to(device)\n inputs3 = inputs3.to(device)\n\n graph = OneFlowGraph_v2(model)\n graph._compile(inputs1, inputs2, inputs3)\n\n mkdir(MODEL_HOME)\n flow.save(model.state_dict(), MODEL_HOME)\n\n out_flow = get_oneflow_concat_output(graph, inputs1, inputs2, inputs3)\n out_tvm = get_tvm_concat_output(graph, MODEL_HOME, inputs1, inputs2, inputs3, target=device)\n rmdir(MODEL_HOME)\n\n assert_shape(out_flow, out_tvm)\n tvm.testing.assert_allclose(out_flow, out_tvm, rtol=rtol, atol=atol)\n\n\n# defs/nn\[email protected]_gpu\ndef test_conv2d():\n class Conv2dModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.conv = flow.nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)\n\n def forward(self, x):\n x = self.conv(x)\n return x\n\n if os.path.exists(MODEL_HOME):\n rmdir(MODEL_HOME)\n\n model = Conv2dModel()\n model.eval()\n\n for device in [\"llvm\"]:\n verify_conv(model, device=device)\n\n\[email protected]_gpu\ndef test_pool2d():\n class MaxPool2dModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.pool = flow.nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n def forward(self, x):\n x = self.pool(x)\n return x\n\n class AvgPool2dModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.pool = flow.nn.AvgPool2d(kernel_size=3, stride=2, padding=1)\n\n def forward(self, x):\n x = self.pool(x)\n return x\n\n class AdaptiveAvgPool2dModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.pool = flow.nn.AdaptiveAvgPool2d((None, 7))\n\n def forward(self, x):\n x = self.pool(x)\n return x\n \n if os.path.exists(MODEL_HOME):\n rmdir(MODEL_HOME)\n\n model1 = MaxPool2dModel().eval()\n model2 = AvgPool2dModel().eval()\n model3 = AdaptiveAvgPool2dModel().eval()\n\n for device in [\"llvm\"]:\n verify_pool(model1, device=device)\n verify_pool(model2, device=device)\n verify_pool(model3, device=device)\n\n\[email protected]_gpu\ndef test_normalization():\n class BatchNorm2dModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.normalization = flow.nn.BatchNorm2d(3)\n \n def forward(self, x):\n x = self.normalization(x)\n return x\n \n if os.path.exists(MODEL_HOME):\n rmdir(MODEL_HOME)\n \n model = BatchNorm2dModel().eval()\n\n for device in [\"llvm\"]:\n verify_normalization(model, device=device)\n\n\[email protected]_gpu\ndef test_upsample():\n class UpsampleModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.upsample = flow.nn.Upsample(scale_factor=2.0, mode=\"nearest\")\n \n def forward(self, x):\n x = self.upsample(x)\n return x\n\n class UpsampleBiliModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.upsample = flow.nn.UpsamplingBilinear2d(scale_factor=2.0)\n \n def forward(self, x):\n x = self.upsample(x)\n return x\n \n if os.path.exists(MODEL_HOME):\n rmdir(MODEL_HOME)\n\n model1 = UpsampleModel().eval()\n model2 = UpsampleBiliModel().eval()\n\n for device in [\"llvm\"]:\n verify_upsample(model1, device=device)\n verify_upsample(model2, device=device)\n\n\[email protected]_gpu\ndef test_convtran():\n class ConvTranModel(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.convtran = flow.nn.ConvTranspose2d(3, 4, (3, 5), stride=(2, 1), padding=(4, 2))\n\n def forward(self, x):\n x = self.convtran(x)\n return x\n \n if os.path.exists(MODEL_HOME):\n rmdir(MODEL_HOME)\n\n model = ConvTranModel().eval()\n\n for device in [\"llvm\"]:\n verify_convtran(model, device=device)\n\n\[email protected]_gpu\ndef test_activation():\n class Softmax(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.Softmax()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class Softplus(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.Softplus()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class Softsign(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.Softsign()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class Tanh(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.Tanh()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class ReLU(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.ReLU()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class ReLU6(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.ReLU6()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class PReLU(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.PReLU()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class SELU(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.SELU()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class SiLU(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.SiLU()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class LeakyReLU(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.LeakyReLU(0.1)\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n class GELU(flow.nn.Module):\n def __init__(self):\n super().__init__()\n self.active = flow.nn.GELU()\n\n def forward(self, x):\n x = self.active(x)\n return x\n\n if os.path.exists(MODEL_HOME):\n rmdir(MODEL_HOME)\n\n model1 = Softmax().eval()\n model2 = Softplus().eval()\n model3 = Softsign().eval()\n model4 = Tanh().eval()\n model5 = ReLU().eval()\n model6 = ReLU6().eval()\n model7 = PReLU().eval()\n model8 = SELU().eval()\n model9 = SiLU().eval()\n model10 = LeakyReLU().eval()\n model11 = GELU().eval()\n\n for device in [\"llvm\"]:\n verify_activation(model1, device=device)\n # verify_activation(model2, device=device) # NO PASS\n verify_activation(model3, device=device)\n verify_activation(model4, device=device)\n verify_activation(model5, device=device)\n verify_activation(model6, device=device)\n verify_activation(model7, device=device)\n verify_activation(model8, device=device)\n verify_activation(model9, device=device)\n verify_activation(model10, device=device)\n verify_activation(model11, device=device)\n\n\[email protected]_gpu\ndef test_math():\n class Sigmoid(flow.nn.Module):\n def forward(self, x):\n return flow.sigmoid(x)\n\n class Sign(flow.nn.Module):\n def forward(self, x):\n return flow.sign(x)\n\n class Reciprocal(flow.nn.Module):\n def forward(self, x):\n return flow.reciprocal(x)\n\n class Pow(flow.nn.Module):\n def forward(self, x):\n return flow.pow(x, 2.0)\n\n\n class Log(flow.nn.Module):\n def forward(self, x):\n return flow.log(x)\n\n class Log2(flow.nn.Module):\n def forward(self, x):\n return flow.log1p(x)\n\n class Exp(flow.nn.Module):\n def forward(self, x):\n return flow.exp(x)\n\n class Exp2(flow.nn.Module):\n def forward(self, x):\n return flow.expm1(x)\n\n model1 = Sigmoid().eval()\n model2 = Sign().eval()\n model3 = Log().eval()\n model4 = Log2().eval()\n model5 = Exp().eval()\n model6 = Exp2().eval()\n\n for device in [\"llvm\"]:\n verify_math(model1, device=device)\n verify_math(model2, device=device)\n verify_math(model3, device=device)\n verify_math(model4, device=device)\n verify_math(model5, device=device)\n verify_math(model6, device=device)\n\n\[email protected]_gpu\ndef test_slice():\n class Slice(flow.nn.Module):\n def forward(self, x):\n tup_list = [[None, None, None], [0, 5, 2], [0, 6, 3]]\n out = flow.slice(x, slice_tup_list=tup_list)\n return out\n \n model = Slice().eval()\n\n for device in [\"llvm\"]:\n verify_math(\n model, device=device,\n inputs=flow.tensor(np.random.randn(3, 6, 9).astype(np.float32))\n )\n\n\[email protected]_gpu\ndef test_concat():\n class Concat(flow.nn.Module):\n def forward(self, x1, x2, x3):\n out = flow.cat([x1, x2, x3], dim=-1)\n return out\n\n model = Concat().eval()\n\n for device in [\"llvm\"]:\n verify_concat(model, device=device)\n\n\n\nif __name__ == \"__main__\":\n test_conv2d()\n test_pool2d()\n test_normalization()\n test_upsample()\n test_convtran()\n test_activation()\n test_math()\n test_slice()\n test_concat()\n rmdir(\"log\")\n\n" ]
[ [ "numpy.random.randn", "numpy.random.rand" ] ]
tiberiuichim/nlp-service
[ "6bb641de532afb8c001d40bf30caadcbd227a91d" ]
[ "app/api/questiongeneration/lib/questiongeneration.py" ]
[ "# Code from https://github.com/AMontgomerie/question_generator\n\nimport json\nimport random\nimport re\n\nimport en_core_web_trf\nimport numpy as np\nimport torch\nfrom transformers import (AutoModelForSeq2SeqLM,\n AutoModelForSequenceClassification, AutoTokenizer)\n\n\nclass QuestionGenerator:\n def __init__(self, model_dir=None):\n\n QG_PRETRAINED = \"iarfmoose/t5-base-question-generator\"\n self.ANSWER_TOKEN = \"<answer>\"\n self.CONTEXT_TOKEN = \"<context>\"\n self.SEQ_LENGTH = 512\n\n self.device = torch.device(\n \"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.qg_tokenizer = AutoTokenizer.from_pretrained(\n QG_PRETRAINED, use_fast=False)\n self.qg_model = AutoModelForSeq2SeqLM.from_pretrained(QG_PRETRAINED)\n self.qg_model.to(self.device)\n\n self.qa_evaluator = QAEvaluator(model_dir)\n\n def generate(\n self, article, use_evaluator=True, num_questions=None,\n answer_style=\"all\"\n ):\n\n print(\"Generating questions...\\n\")\n\n qg_inputs, qg_answers = self.generate_qg_inputs(article, answer_style)\n generated_questions = self.generate_questions_from_inputs(qg_inputs)\n\n message = \"{} questions doesn't match {} answers\".format(\n len(generated_questions), len(qg_answers)\n )\n assert len(generated_questions) == len(qg_answers), message\n\n if use_evaluator:\n\n print(\"Evaluating QA pairs...\\n\")\n\n encoded_qa_pairs = self.qa_evaluator.encode_qa_pairs(\n generated_questions, qg_answers\n )\n scores = self.qa_evaluator.get_scores(encoded_qa_pairs)\n if num_questions:\n qa_list = self._get_ranked_qa_pairs(\n generated_questions, qg_answers, scores, num_questions\n )\n else:\n qa_list = self._get_ranked_qa_pairs(\n generated_questions, qg_answers, scores\n )\n\n else:\n print(\"Skipping evaluation step.\\n\")\n qa_list = self._get_all_qa_pairs(generated_questions, qg_answers)\n\n return qa_list\n\n def generate_qg_inputs(self, text, answer_style):\n\n VALID_ANSWER_STYLES = [\"all\", \"sentences\", \"multiple_choice\"]\n\n if answer_style not in VALID_ANSWER_STYLES:\n raise ValueError(\n \"Invalid answer style {}. Please choose from {}\".format(\n answer_style, VALID_ANSWER_STYLES\n )\n )\n\n inputs = []\n answers = []\n\n if answer_style == \"sentences\" or answer_style == \"all\":\n segments = self._split_into_segments(text)\n for segment in segments:\n sentences = self._split_text(segment)\n prepped_inputs, prepped_answers = self._prepare_qg_inputs(\n sentences, segment\n )\n inputs.extend(prepped_inputs)\n answers.extend(prepped_answers)\n\n if answer_style == \"multiple_choice\" or answer_style == \"all\":\n sentences = self._split_text(text)\n prepped_inputs, prepped_answers = self._prepare_qg_inputs_MC(\n sentences)\n inputs.extend(prepped_inputs)\n answers.extend(prepped_answers)\n\n return inputs, answers\n\n def generate_questions_from_inputs(self, qg_inputs):\n generated_questions = []\n\n for qg_input in qg_inputs:\n question = self._generate_question(qg_input)\n generated_questions.append(question)\n\n return generated_questions\n\n def _split_text(self, text):\n MAX_SENTENCE_LEN = 128\n\n sentences = re.findall(\".*?[.!\\?]\", text)\n\n cut_sentences = []\n for sentence in sentences:\n if len(sentence) > MAX_SENTENCE_LEN:\n cut_sentences.extend(re.split(\"[,;:)]\", sentence))\n # temporary solution to remove useless post-quote sentence fragments\n cut_sentences = [s for s in sentences if len(s.split(\" \")) > 5]\n sentences = sentences + cut_sentences\n\n return list(set([s.strip(\" \") for s in sentences]))\n\n def _split_into_segments(self, text):\n MAX_TOKENS = 490\n\n paragraphs = text.split(\"\\n\")\n tokenized_paragraphs = [\n self.qg_tokenizer(p)[\"input_ids\"] for p in paragraphs if len(p) > 0\n ]\n\n segments = []\n while len(tokenized_paragraphs) > 0:\n segment = []\n while len(segment) < MAX_TOKENS and len(tokenized_paragraphs) > 0:\n paragraph = tokenized_paragraphs.pop(0)\n segment.extend(paragraph)\n segments.append(segment)\n return [self.qg_tokenizer.decode(s) for s in segments]\n\n def _prepare_qg_inputs(self, sentences, text):\n inputs = []\n answers = []\n\n for sentence in sentences:\n qg_input = \"{} {} {} {}\".format(\n self.ANSWER_TOKEN, sentence, self.CONTEXT_TOKEN, text\n )\n inputs.append(qg_input)\n answers.append(sentence)\n\n return inputs, answers\n\n def _prepare_qg_inputs_MC(self, sentences):\n\n spacy_nlp = en_core_web_trf.load()\n docs = list(spacy_nlp.pipe(sentences, disable=[\"parser\"]))\n inputs_from_text = []\n answers_from_text = []\n\n for i in range(len(sentences)):\n entities = docs[i].ents\n if entities:\n for entity in entities:\n qg_input = \"{} {} {} {}\".format(\n self.ANSWER_TOKEN, entity, self.CONTEXT_TOKEN, sentences[i]\n )\n answers = self._get_MC_answers(entity, docs)\n inputs_from_text.append(qg_input)\n answers_from_text.append(answers)\n\n return inputs_from_text, answers_from_text\n\n def _get_MC_answers(self, correct_answer, docs):\n\n entities = []\n for doc in docs:\n entities.extend([{\"text\": e.text, \"label_\": e.label_}\n for e in doc.ents])\n\n # remove duplicate elements\n entities_json = [json.dumps(kv) for kv in entities]\n pool = set(entities_json)\n num_choices = (\n min(4, len(pool)) - 1\n ) # -1 because we already have the correct answer\n\n # add the correct answer\n final_choices = []\n correct_label = correct_answer.label_\n final_choices.append({\"answer\": correct_answer.text, \"correct\": True})\n pool.remove(\n json.dumps({\"text\": correct_answer.text,\n \"label_\": correct_answer.label_})\n )\n\n # find answers with the same NER label\n matches = [e for e in pool if correct_label in e]\n\n # if we don't have enough then add some other random answers\n if len(matches) < num_choices:\n choices = matches\n pool = pool.difference(set(choices))\n choices.extend(random.sample(pool, num_choices - len(choices)))\n else:\n choices = random.sample(matches, num_choices)\n\n choices = [json.loads(s) for s in choices]\n for choice in choices:\n final_choices.append({\"answer\": choice[\"text\"], \"correct\": False})\n random.shuffle(final_choices)\n return final_choices\n\n def _generate_question(self, qg_input):\n self.qg_model.eval()\n encoded_input = self._encode_qg_input(qg_input)\n with torch.no_grad():\n output = self.qg_model.generate(\n input_ids=encoded_input[\"input_ids\"])\n question = self.qg_tokenizer.decode(\n output[0], skip_special_tokens=True)\n return question\n\n def _encode_qg_input(self, qg_input):\n return self.qg_tokenizer(\n qg_input,\n padding='max_length',\n max_length=self.SEQ_LENGTH,\n truncation=True,\n return_tensors=\"pt\",\n ).to(self.device)\n\n def _get_ranked_qa_pairs(\n self, generated_questions, qg_answers, scores, num_questions=10\n ):\n if num_questions > len(scores):\n num_questions = len(scores)\n print(\n \"\\nWas only able to generate {} questions. For more questions, please input a longer text.\".format(\n num_questions\n )\n )\n\n qa_list = []\n for i in range(num_questions):\n index = scores[i]\n qa = self._make_dict(\n generated_questions[index].split(\n \"?\")[0] + \"?\", qg_answers[index]\n )\n qa_list.append(qa)\n return qa_list\n\n def _get_all_qa_pairs(self, generated_questions, qg_answers):\n qa_list = []\n for i in range(len(generated_questions)):\n qa = self._make_dict(\n generated_questions[i].split(\"?\")[0] + \"?\", qg_answers[i]\n )\n qa_list.append(qa)\n return qa_list\n\n def _make_dict(self, question, answer):\n qa = {}\n qa[\"question\"] = question\n qa[\"answer\"] = answer\n return qa\n\n\nclass QAEvaluator:\n def __init__(self, model_dir=None):\n\n QAE_PRETRAINED = \"iarfmoose/bert-base-cased-qa-evaluator\"\n self.SEQ_LENGTH = 512\n\n self.device = torch.device(\n \"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.qae_tokenizer = AutoTokenizer.from_pretrained(QAE_PRETRAINED)\n self.qae_model = AutoModelForSequenceClassification.from_pretrained(\n QAE_PRETRAINED\n )\n self.qae_model.to(self.device)\n\n def encode_qa_pairs(self, questions, answers):\n encoded_pairs = []\n for i in range(len(questions)):\n encoded_qa = self._encode_qa(questions[i], answers[i])\n encoded_pairs.append(encoded_qa.to(self.device))\n return encoded_pairs\n\n def get_scores(self, encoded_qa_pairs):\n scores = {}\n self.qae_model.eval()\n with torch.no_grad():\n for i in range(len(encoded_qa_pairs)):\n scores[i] = self._evaluate_qa(encoded_qa_pairs[i])\n\n return [\n k for k, v in sorted(scores.items(), key=lambda item: item[1], reverse=True)\n ]\n\n def _encode_qa(self, question, answer):\n if type(answer) is list:\n for a in answer:\n if a[\"correct\"]:\n correct_answer = a[\"answer\"]\n else:\n correct_answer = answer\n return self.qae_tokenizer(\n text=question,\n text_pair=correct_answer,\n padding=\"max_length\",\n max_length=self.SEQ_LENGTH,\n truncation=True,\n return_tensors=\"pt\",\n )\n\n def _evaluate_qa(self, encoded_qa_pair):\n output = self.qae_model(**encoded_qa_pair)\n return output[0][0][1]\n\n\ndef print_qa(qa_list, show_answers=True):\n for i in range(len(qa_list)):\n # wider space for 2 digit q nums\n space = \" \" * int(np.where(i < 9, 3, 4))\n\n print(\"{}) Q: {}\".format(i + 1, qa_list[i][\"question\"]))\n\n answer = qa_list[i][\"answer\"]\n\n # print a list of multiple choice answers\n if type(answer) is list:\n\n if show_answers:\n print(\n \"{}A: 1.\".format(space),\n answer[0][\"answer\"],\n np.where(answer[0][\"correct\"], \"(correct)\", \"\"),\n )\n for j in range(1, len(answer)):\n print(\n \"{}{}.\".format(space + \" \", j + 1),\n answer[j][\"answer\"],\n np.where(answer[j][\"correct\"] ==\n True, \"(correct)\", \"\"),\n )\n\n else:\n print(\"{}A: 1.\".format(space), answer[0][\"answer\"])\n for j in range(1, len(answer)):\n print(\"{}{}.\".format(space + \" \", j + 1),\n answer[j][\"answer\"])\n print(\"\")\n\n # print full sentence answers\n else:\n if show_answers:\n print(\"{}A:\".format(space), answer, \"\\n\")\n" ]
[ [ "torch.no_grad", "numpy.where", "torch.cuda.is_available" ] ]
jonghun-jeong/pytorch_VDSR
[ "514b021044018baf909e79f48392783daa592888" ]
[ "vdsr.py" ]
[ "import torch\r\nimport torch.nn as nn\r\nfrom math import sqrt\r\n\r\nclass Conv_ReLU_Block(nn.Module):\r\n def __init__(self):\r\n super(Conv_ReLU_Block, self).__init__()\r\n self.conv = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False)\r\n self.relu = nn.ReLU(inplace=True)\r\n \r\n def forward(self, x):\r\n return self.relu(self.conv(x))\r\n \r\nclass Net(nn.Module):\r\n def __init__(self):\r\n super(Net, self).__init__()\r\n self.residual_layer = self.make_layer(Conv_ReLU_Block, 18)\r\n self.input = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False)\r\n self.output = nn.Conv2d(in_channels=64, out_channels=1, kernel_size=3, stride=1, padding=1, bias=False)\r\n self.relu = nn.ReLU(inplace=True)\r\n \r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n m.weight.data.normal_(0, sqrt(2. / n))\r\n \r\n def make_layer(self, block, num_of_layer):\r\n layers = []\r\n for _ in range(num_of_layer):\r\n layers.append(block())\r\n return nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n residual = x\r\n out = self.relu(self.input(x))\r\n out = self.residual_layer(out)\r\n out = self.output(out)\r\n out = torch.add(out,residual)\r\n return out\r\n " ]
[ [ "torch.nn.Sequential", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.add" ] ]
Kolyan-1/MSc-Thesis-Code
[ "c651805b82a9e1087c1e18f80839c977a3ba2352" ]
[ "TF/dev_profilingTF2.py" ]
[ "import tensorflow as tf\nimport numpy as np\nx = tf.get_variable('a',initializer=tf.constant(np.array([[1.,2.,3.],[4.,5.,6.]])))\ny = tf.get_variable('b',initializer=tf.constant(np.array([[1],[4]])))\n\n\n\n\nsess = tf.Session()\n\nsess.run(tf.global_variables_initializer())\na = tf.reduce_mean(x, axis=0, keep_dims=True)\nc = x - a\nd = c - tf.reduce_mean(c, axis=1, keep_dims=True)\n\nprint(sess.run(c))\nprint(sess.run(d))\n\n# def tf_dot(x,y):\n# return tf.reduce_sum(x*y)\n#\n# x = tf.get_variable('a',initializer=tf.constant(np.array([1.0,2.0,3.0])))\n#\n# y = []\n#\n# y.append(tf_dot(x,x))\n# y.append(tf_dot(x,2*x))\n#\n# z = tf.contrib.distributions.percentile(y,q=96)\n#\n# print(y)\n#\n# sess = tf.Session()\n#\n# sess.run(tf.global_variables_initializer())\n#\n# k = x*x\n# print(k.eval(session=sess))\n# print(z.eval(session=sess))\n" ]
[ [ "tensorflow.global_variables_initializer", "numpy.array", "tensorflow.Session", "tensorflow.reduce_mean" ] ]
xin-alice/cs159_safe_learning
[ "44761774c38cec36f156b2978b5eb5ec1ca712e9" ]
[ "safe_learning/tests/test_functions.py" ]
[ "\"\"\"Unit tests for the functions file.\"\"\"\n\nfrom __future__ import division, print_function, absolute_import\n\nfrom numpy.testing import assert_equal, assert_allclose\nimport pytest\nimport numpy as np\nfrom scipy.optimize import check_grad\nimport tensorflow as tf\n\nfrom safe_learning.functions import (_Triangulation, Triangulation,\n ScipyDelaunay, GridWorld,\n PiecewiseConstant, DeterministicFunction,\n UncertainFunction, QuadraticFunction,\n DimensionError, GPRCached,\n GaussianProcess, NeuralNetwork)\nfrom safe_learning.utilities import concatenate_inputs\n\ntry:\n import gpflow\nexcept ImportError:\n gpflow = None\n\n\nclass TestFunction(object):\n \"\"\"Test the function class.\"\"\"\n\n @pytest.fixture(scope='class')\n def testing_class(self):\n class A(DeterministicFunction):\n def __init__(self, value, name='a'):\n super(A, self).__init__()\n with tf.variable_scope(self.scope_name):\n self.variable = tf.Variable(value)\n sess = tf.get_default_session()\n sess.run(tf.variables_initializer([self.variable]))\n\n def build_evaluation(self, point):\n return self.variable * point\n\n with tf.Session() as sess:\n return A, sess\n\n def test_class(self, testing_class):\n \"\"\"Test the the class is working.\"\"\"\n A, sess = testing_class\n with sess.as_default():\n a = A(2.)\n input = np.array(1.)\n\n output = a(input)\n assert_allclose(2. * input, output.eval())\n\n # Test double output\n output2 = a(input)\n assert_allclose(2. * input, output2.eval())\n\n def test_add(self, testing_class):\n \"\"\"Test adding functions.\"\"\"\n A, sess = testing_class\n with sess.as_default():\n a1 = A(3.)\n a2 = A(2.)\n\n a = a1 + a2\n\n input = np.array(1.)\n output = a(input)\n\n assert_allclose(5. * input, output.eval())\n\n assert a1.parameters[0] in a.parameters\n assert a2.parameters[0] in a.parameters\n\n def test_mult(self, testing_class):\n \"\"\"Test multiplying functions.\"\"\"\n A, sess = testing_class\n with sess.as_default():\n a1 = A(3.)\n a2 = A(2.)\n\n a = a1 * a2\n\n input = np.array(1.)\n output = a(input)\n\n assert_allclose(6. * input, output.eval())\n\n assert a1.parameters[0] in a.parameters\n assert a2.parameters[0] in a.parameters\n\n # Test multiplying with constant\n a = a1 * 2.\n output = a(input)\n assert_allclose(6. * input, output.eval())\n\n def test_neg(self, testing_class):\n \"\"\"Test multiplying functions.\"\"\"\n A, sess = testing_class\n with sess.as_default():\n a = A(3.)\n b = -a\n\n input = np.array(2.)\n output = b(input)\n\n assert_allclose(-3. * input, output.eval())\n\n assert a.parameters[0] is b.parameters[0]\n\n def test_copy(self, testing_class):\n \"\"\"Test copying\"\"\"\n A, sess = testing_class\n with sess.as_default():\n a = A(2.)\n b = A(3.)\n b.copy_parameters(a)\n\n p1 = a.parameters[0]\n p2 = b.parameters[0]\n\n assert p1.eval() == p2.eval()\n assert p1 is not p2\n\n\nclass TestDeterministicFuction(object):\n \"\"\"Test the base class.\"\"\"\n\n def test_errors(self):\n \"\"\"Check notImplemented error.\"\"\"\n f = DeterministicFunction()\n pytest.raises(NotImplementedError, f.build_evaluation, None)\n\n\nclass TestUncertainFunction(object):\n \"\"\"Test the base class.\"\"\"\n\n def test_errors(self):\n \"\"\"Check notImplemented error.\"\"\"\n f = UncertainFunction()\n pytest.raises(NotImplementedError, f.build_evaluation, None)\n\n def test_mean_function(self):\n \"\"\"Test the conversion to a deterministic function.\"\"\"\n f = UncertainFunction()\n f.build_evaluation = lambda x: (1, 2)\n fd = f.to_mean_function()\n assert(fd(None) == 1)\n\n\[email protected](gpflow is None, reason='gpflow module not installed')\nclass TestGPRCached(object):\n \"\"\"Test the GPR_cached class.\"\"\"\n\n @pytest.fixture(scope=\"class\")\n def gps(self):\n \"\"\"Create cached and uncached gpflow models and GPy model.\"\"\"\n x = np.array([[1, 0], [0, 1]], dtype=float)\n y = np.array([[0], [1]], dtype=float)\n kernel = gpflow.kernels.RBF(2)\n gp = gpflow.gpr.GPR(x, y, kernel)\n gp_cached = GPRCached(x, y, kernel)\n return gp, gp_cached\n\n def test_adding_data(self, gps):\n \"\"\"Test that adding data works.\"\"\"\n test_points = np.array([[0.9, 0.1], [3., 2]])\n\n gp, gp_cached = gps\n gpfun = GaussianProcess(gp)\n gpfun_cached = GaussianProcess(gp_cached)\n\n x = np.array([[1.2, 2.3]])\n y = np.array([[2.4]])\n\n gpfun.add_data_point(x, y)\n m1, v1 = gpfun(test_points)\n\n gpfun_cached.add_data_point(x, y)\n m2, v2 = gpfun_cached(test_points)\n\n feed_dict = gpfun.feed_dict.copy()\n feed_dict.update(gpfun_cached.feed_dict)\n\n with tf.Session() as sess:\n m1, v1, m2, v2 = sess.run([m1, v1, m2, v2], feed_dict=feed_dict)\n\n assert_allclose(m1, m2)\n assert_allclose(v1, v2)\n\n def test_predict_f(self, gps):\n \"\"\"Make sure predictions is same as in uncached case.\"\"\"\n # Note that this messes things up terribly due to caching. So this\n # must be the last test that we run.\n gp, gp_cached = gps\n test_points = np.array([[0.9, 0.1], [3., 2]])\n a1, b1 = gp_cached.predict_f(test_points)\n a2, b2 = gp.predict_f(test_points)\n assert_allclose(a1, a2)\n assert_allclose(b1, b2)\n\n\[email protected](gpflow is None, 'gpflow module not installed')\nclass Testgpflow(object):\n \"\"\"Test the GaussianProcess function class.\"\"\"\n\n @pytest.fixture(scope=\"class\")\n def setup(self):\n \"\"\"Create GP model with gpflow and GPy.\"\"\"\n with tf.Session() as sess:\n x = np.array([[1, 0], [0, 1]], dtype=float)\n y = np.array([[0], [1]], dtype=float)\n kernel = gpflow.kernels.RBF(2)\n gp = gpflow.gpr.GPR(x, y, kernel)\n yield sess, gp\n\n def test_evaluation(self, setup):\n \"\"\"Make sure evaluation works.\"\"\"\n test_points = np.array([[0.9, 0.1], [3., 2]])\n beta = 3.0\n sess, gp = setup\n\n ufun = GaussianProcess(gp, beta=beta)\n\n # Evaluate GP\n mean_1, error_1 = ufun(test_points)\n mean_1, error_1 = sess.run([mean_1, error_1],\n feed_dict=ufun.feed_dict)\n\n # Test multiple inputs\n mean_2, error_2 = ufun(test_points[:, [0]],\n test_points[:, [1]])\n mean_2, error_2 = sess.run([mean_2, error_2], feed_dict=ufun.feed_dict)\n\n assert_allclose(mean_1, mean_2)\n assert_allclose(error_1, error_2)\n\n def test_new_data(self, setup):\n \"\"\"Test adding data points to the GP.\"\"\"\n test_points = np.array([[0.9, 0.1], [3., 2]])\n sess, gp = setup\n\n ufun = GaussianProcess(gp)\n\n x = np.array([[1.2, 2.3]])\n y = np.array([[2.4]])\n\n ufun.add_data_point(x, y)\n\n assert_allclose(ufun.X, np.array([[1, 0],\n [0, 1],\n [1.2, 2.3]]))\n assert_allclose(ufun.Y, np.array([[0], [1], [2.4]]))\n\n # Check prediction is correct after adding data (cholesky update)\n a1, b1 = ufun(test_points)\n a1, b1 = sess.run([a1, b1], feed_dict=ufun.feed_dict)\n\n a1_true = np.array([[0.16371139], [0.22048311]])\n b1_true = np.array([[1.37678679], [1.98183191]])\n assert_allclose(a1, a1_true)\n assert_allclose(b1, b1_true)\n\n\nclass TestQuadraticFunction(object):\n \"\"\"Test the quadratic function.\"\"\"\n\n def test_evaluate(self):\n \"\"\"Setup testing environment for quadratic.\"\"\"\n points = np.array([[0, 0],\n [0, 1],\n [1, 0],\n [1, 1]], dtype=np.float)\n P = np.array([[1., 0.1],\n [0.2, 2.]])\n quad = QuadraticFunction(P)\n true_fval = np.array([[0., 2., 1., 3.3]]).T\n\n with tf.Session():\n tf_res = quad(points)\n res = tf_res.eval()\n\n assert_allclose(true_fval, res)\n\n\ndef test_scipy_delaunay():\n \"\"\"Test the fake replacement for Scipy.\"\"\"\n limits = [[-1, 1], [-1, 2]]\n num_points = [2, 6]\n discretization = GridWorld(limits, num_points)\n sp_delaunay = ScipyDelaunay(limits, num_points)\n delaunay = _Triangulation(discretization)\n\n assert_equal(delaunay.nsimplex, sp_delaunay.nsimplex)\n assert_equal(delaunay.input_dim, sp_delaunay.ndim)\n sp_delaunay.find_simplex(np.array([[0, 0]]))\n\n\nclass TestGridworld(object):\n \"\"\"Test the general GridWorld definitions.\"\"\"\n\n def test_dimensions_error(self):\n \"\"\"Test dimension errors.\"\"\"\n limits = [[-1.1, 1.5], [2.2, 2.4]]\n num_points = [7, 8]\n grid = GridWorld(limits, num_points)\n\n pytest.raises(DimensionError, grid._check_dimensions,\n np.array([[1, 2, 3]]))\n\n pytest.raises(DimensionError, grid._check_dimensions,\n np.array([[1]]))\n\n def test_index_state_conversion(self):\n \"\"\"Test all index conversions.\"\"\"\n limits = [[-1.1, 1.5], [2.2, 2.4]]\n num_points = [7, 8]\n grid = GridWorld(limits, num_points)\n\n # Forward and backwards convert all indeces\n indeces = np.arange(grid.nindex)\n states = grid.index_to_state(indeces)\n indeces2 = grid.state_to_index(states)\n assert_equal(indeces, indeces2)\n\n # test 1D input\n grid.state_to_index([0, 2.3])\n grid.index_to_state(1)\n\n # Test rectangles\n rectangles = np.arange(grid.nrectangles)\n states = grid.rectangle_to_state(rectangles)\n rectangles2 = grid.state_to_rectangle(states + grid.unit_maxes / 2)\n assert_equal(rectangles, rectangles2)\n\n rectangle = grid.state_to_rectangle(100 * np.ones((1, 2)))\n assert_equal(rectangle, grid.nrectangles - 1)\n\n rectangle = grid.state_to_rectangle(-100 * np.ones((1, 2)))\n assert_equal(rectangle, 0)\n\n # Test rectangle corners\n corners = grid.rectangle_corner_index(rectangles)\n corner_states = grid.rectangle_to_state(rectangles)\n corners2 = grid.state_to_index(corner_states)\n assert_equal(corners, corners2)\n\n # Test point outside grid\n test_point = np.array([[-1.2, 2.]])\n index = grid.state_to_index(test_point)\n assert_equal(index, 0)\n\n def test_integer_numpoints(self):\n \"\"\"Check integer numpoints argument.\"\"\"\n grid = GridWorld([[1, 2], [3, 4]], 2)\n assert_equal(grid.num_points, np.array([2, 2]))\n\n def test_0d(self):\n \"\"\"Check that initialization works for 1d-discretization.\"\"\"\n grid = GridWorld([[0, 1]], 3)\n\n test = np.array([[0.1, 0.4, 0.9]]).T\n res = np.array([0, 1, 2])\n assert_allclose(grid.state_to_index(test), res)\n\n res = np.array([0, 0, 1])\n assert_allclose(grid.state_to_rectangle(test), res)\n assert_allclose(grid.rectangle_to_state(res), res[:, None] * 0.5)\n\n\nclass TestConcatenateDecorator(object):\n \"\"\"Test the concatenate_input decorator.\"\"\"\n\n @concatenate_inputs(start=1)\n def fun(self, x):\n \"\"\"Test function.\"\"\"\n return x\n\n def test_concatenate_numpy(self):\n \"\"\"Test concatenation of inputs for numpy.\"\"\"\n x = np.arange(4).reshape(2, 2)\n y = x + 4\n true_res = np.hstack((x, y))\n res = self.fun(x, y)\n assert_allclose(res, true_res)\n assert_allclose(self.fun(x), x)\n\n def test_concatenate_tensorflow(self):\n \"\"\"Test concatenation of inputs for tensorflow.\"\"\"\n x_data = np.arange(4).reshape(2, 2).astype(np.float32)\n true_res = np.hstack((x_data, x_data + 4))\n x = tf.placeholder(dtype=tf.float32, shape=[2, 2])\n y = x + 4\n\n fun_x = self.fun(x)\n fun_xy = self.fun(x, y)\n\n assert isinstance(fun_x, tf.Tensor)\n assert isinstance(fun_xy, tf.Tensor)\n\n with tf.Session() as sess:\n res_x, res_both = sess.run([fun_x, fun_xy],\n {x: x_data})\n\n assert_allclose(res_both, true_res)\n assert_allclose(res_x, x_data)\n\n\nclass TestPiecewiseConstant(object):\n \"\"\"Test a piecewise constant function.\"\"\"\n\n def test_init(self):\n \"\"\"Test initialisation.\"\"\"\n limits = [[-1, 1], [-1, 1]]\n npoints = 4\n discretization = GridWorld(limits, npoints)\n pwc = PiecewiseConstant(discretization, np.arange(16))\n assert_allclose(pwc.parameters, np.arange(16)[:, None])\n\n def test_evaluation(self):\n \"\"\"Evaluation tests for piecewise constant function.\"\"\"\n limits = [[-1, 1], [-1, 1]]\n npoints = 3\n discretization = GridWorld(limits, npoints)\n pwc = PiecewiseConstant(discretization)\n\n vertex_points = pwc.discretization.index_to_state(\n np.arange(pwc.nindex))\n vertex_values = np.sum(vertex_points, axis=1, keepdims=True)\n pwc.parameters = vertex_values\n\n test = pwc(vertex_points)\n assert_allclose(test, vertex_values)\n\n outside_point = np.array([[-1.5, -1.5]])\n test1 = pwc(outside_point)\n assert_allclose(test1, np.array([[-2]]))\n\n # Test constraint evaluation\n test2 = pwc.parameter_derivative(vertex_points)\n test2 = test2.toarray().dot(vertex_values)\n assert_allclose(test2, vertex_values)\n\n def test_gradient(self):\n \"\"\"Test the gradient.\"\"\"\n limits = [[-1, 1], [-1, 1]]\n npoints = 3\n discretization = GridWorld(limits, npoints)\n pwc = PiecewiseConstant(discretization)\n test_points = pwc.discretization.index_to_state(np.arange(pwc.nindex))\n gradient = pwc.gradient(test_points)\n assert_allclose(gradient, 0)\n\n\nclass TestTriangulationNumpy(object):\n \"\"\"Test the generalized Delaunay triangulation in numpy.\"\"\"\n\n def test_find_simplex(self):\n \"\"\"Test the simplices on the grid.\"\"\"\n limits = [[-1, 1], [-1, 2]]\n num_points = [3, 7]\n discretization = GridWorld(limits, num_points)\n delaunay = _Triangulation(discretization)\n\n # Test the basic properties\n assert_equal(delaunay.discretization.nrectangles, 2 * 6)\n assert_equal(delaunay.input_dim, 2)\n assert_equal(delaunay.nsimplex, 2 * 2 * 6)\n assert_equal(delaunay.discretization.offset, np.array([-1, -1]))\n assert_equal(delaunay.discretization.unit_maxes,\n np.array([2, 3]) / (np.array(num_points) - 1))\n\n # test the simplex indices\n lower = delaunay.triangulation.find_simplex(np.array([0, 0])).squeeze()\n upper = 1 - lower\n\n test_points = np.array([[0, 0],\n [0.9, 0.45],\n [1.1, 0],\n [1.9, 2.9]])\n\n test_points += np.array(limits)[:, 0]\n\n true_result = np.array([lower, upper, 6 * 2 + lower, 11 * 2 + upper])\n result = delaunay.find_simplex(test_points)\n\n assert_allclose(result, true_result)\n\n # Test the ability to find simplices\n simplices = delaunay.simplices(result)\n true_simplices = np.array([[0, 1, 7],\n [1, 7, 8],\n [7, 8, 14],\n [13, 19, 20]])\n assert_equal(np.sort(simplices, axis=1), true_simplices)\n\n # Test point ouside domain (should map to bottom left and top right)\n assert_equal(lower, delaunay.find_simplex(np.array([[-100., -100.]])))\n assert_equal(delaunay.nsimplex - 1 - lower,\n delaunay.find_simplex(np.array([[100., 100.]])))\n\n def test_values(self):\n \"\"\"Test the evaluation function.\"\"\"\n eps = 1e-10\n\n discretization = GridWorld([[0, 1], [0, 1]], [2, 2])\n delaunay = _Triangulation(discretization)\n\n test_points = np.array([[0, 0],\n [1 - eps, 0],\n [0, 1 - eps],\n [0.5 - eps, 0.5 - eps],\n [0, 0.5],\n [0.5, 0]])\n nodes = delaunay.discretization.state_to_index(np.array([[0, 0],\n [1, 0],\n [0, 1]]))\n\n H = delaunay.parameter_derivative(test_points).toarray()\n\n true_H = np.zeros((len(test_points), delaunay.nindex),\n dtype=np.float)\n true_H[0, nodes[0]] = 1\n true_H[1, nodes[1]] = 1\n true_H[2, nodes[2]] = 1\n true_H[3, nodes[[1, 2]]] = 0.5\n true_H[4, nodes[[0, 2]]] = 0.5\n true_H[5, nodes[[0, 1]]] = 0.5\n\n assert_allclose(H, true_H, atol=1e-7)\n\n # Test value property\n values = np.random.rand(delaunay.nindex)\n delaunay.parameters = values\n v1 = H.dot(values)[:, None]\n v2 = delaunay(test_points)\n assert_allclose(v1, v2)\n\n # Test the projections\n test_point = np.array([[-0.5, -0.5]])\n delaunay.parameters = np.array([0, 1, 1, 1])\n unprojected = delaunay(test_point)\n delaunay.project = True\n projected = delaunay(test_point)\n\n assert_allclose(projected, np.array([[0]]))\n assert_allclose(unprojected, np.array([[-1]]))\n\n def test_multiple_dimensions(self):\n \"\"\"Test delaunay in three dimensions.\"\"\"\n limits = [[0, 1]] * 3\n discretization = GridWorld(limits, [2] * 3)\n delaunay = _Triangulation(discretization)\n assert_equal(delaunay.input_dim, 3)\n assert_equal(delaunay.discretization.nrectangles, 1)\n assert_equal(delaunay.nsimplex, np.math.factorial(3))\n\n corner_points = np.array([[0, 0, 0],\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n [0, 1, 1],\n [1, 1, 0],\n [1, 0, 1],\n [1, 1, 1]], dtype=np.float)\n\n values = np.sum(delaunay.discretization.index_to_state(np.arange(8)),\n axis=1) / 3\n\n test_points = np.vstack((corner_points,\n np.array([[0, 0, 0.5],\n [0.5, 0, 0],\n [0, 0.5, 0],\n [0.5, 0.5, 0.5]])))\n corner_values = np.sum(corner_points, axis=1) / 3\n true_values = np.hstack((corner_values,\n np.array([1 / 6, 1 / 6, 1 / 6, 1 / 2])))\n\n delaunay.parameters = values\n result = delaunay(test_points)\n assert_allclose(result, true_values[:, None], atol=1e-5)\n\n def test_gradient(self):\n \"\"\"Test the gradient_at function.\"\"\"\n discretization = GridWorld([[0, 1], [0, 1]], [2, 2])\n delaunay = _Triangulation(discretization)\n\n points = np.array([[0, 0],\n [1, 0],\n [0, 1],\n [1, 1]], dtype=np.int)\n nodes = delaunay.discretization.state_to_index(points)\n\n # Simplex with node values:\n # 3 - 1\n # | \\ |\n # 1 - 2\n # --> x\n\n values = np.zeros(delaunay.nindex)\n values[nodes] = [1, 2, 3, 1]\n\n test_points = np.array([[0.01, 0.01],\n [0.99, 0.99]])\n\n true_grad = np.array([[1, 2], [-2, -1]])\n\n # Construct true H (gradient as function of values)\n true_H = np.zeros((2 * delaunay.input_dim, delaunay.nindex))\n\n true_H[0, nodes[[0, 1]]] = [-1, 1]\n true_H[1, nodes[[0, 2]]] = [-1, 1]\n true_H[2, nodes[[2, 3]]] = [-1, 1]\n true_H[3, nodes[[1, 3]]] = [-1, 1]\n\n # Evaluate gradient with and without values\n H = delaunay.gradient_parameter_derivative(test_points).toarray()\n delaunay.parameters = values\n grad = delaunay.gradient(test_points)\n\n # Compare\n assert_allclose(grad, true_grad)\n assert_allclose(H, true_H)\n assert_allclose(true_grad,\n H.dot(values).reshape(-1, delaunay.input_dim))\n\n def test_1d(self):\n \"\"\"Test the triangulation for 1D inputs.\"\"\"\n discretization = GridWorld([[0, 1]], 3)\n delaunay = _Triangulation(discretization, vertex_values=[0, 0.5, 0])\n vertex_values = delaunay.parameters\n\n test_points = np.array([[0, 0.2, 0.5, 0.6, 0.9, 1.]]).T\n test_point = test_points[[0], :]\n\n simplices = delaunay.find_simplex(test_points)\n true_simplices = np.array([0, 0, 1, 1, 1, 1])\n assert_allclose(simplices, true_simplices)\n assert_allclose(delaunay.find_simplex(test_point),\n true_simplices[[0]])\n\n values = delaunay(test_points)\n true_values = np.array([0, 0.2, 0.5, 0.4, 0.1, 0])[:, None]\n assert_allclose(values, true_values)\n\n value_constraint = delaunay.parameter_derivative(test_points)\n values = value_constraint.toarray().dot(vertex_values)\n assert_allclose(values, true_values)\n\n gradient = delaunay.gradient(test_points)\n true_gradient = np.array([1, 1, -1, -1, -1, -1])[:, None]\n assert_allclose(gradient, true_gradient)\n\n gradient_deriv = delaunay.gradient_parameter_derivative(test_points)\n gradient = gradient_deriv.toarray().dot(vertex_values)\n assert_allclose(gradient.reshape(-1, 1), true_gradient)\n\n\nclass TestTriangulation(object):\n \"\"\"Test the tensorflow wrapper around the numpy triangulation.\"\"\"\n\n @pytest.fixture(scope=\"class\")\n def setup(self):\n \"\"\"Create testing environment.\"\"\"\n with tf.Session(graph=tf.Graph()) as sess:\n npoints = 3\n\n discretization = GridWorld([[0, 1], [0, 1]], npoints)\n parameters = np.sum(discretization.all_points ** 2,\n axis=1, keepdims=True)\n trinp = _Triangulation(discretization, vertex_values=parameters)\n\n tri = Triangulation(discretization, vertex_values=parameters)\n\n test_points = np.array([[-10, -10],\n [0.2, 0.7],\n [0, 0],\n [0, 1],\n [1, 1],\n [-0.2, 0.5],\n [0.43, 0.21]])\n\n sess.run(tf.global_variables_initializer())\n yield sess, tri, trinp, test_points\n\n def test_evaluate(self, setup):\n \"\"\"Test the evaluations.\"\"\"\n sess, tri, trinp, test_points = setup\n # with tf.Session() as sess:\n res = sess.run(tri(test_points))\n assert_allclose(res, trinp(test_points))\n\n def test_projected_evaluate(self, setup):\n \"\"\"Test evaluations with enabled projection.\"\"\"\n sess, tri, trinp, test_points = setup\n\n # Enable project\n trinp.project = True\n tri.project = True\n\n res = sess.run(tri(test_points))\n assert_allclose(res, trinp(test_points))\n\n def test_gradient_x(self, setup):\n \"\"\"Test the gradients with respect to the inputs.\"\"\"\n sess, tri, trinp, test_points = setup\n\n points = tf.placeholder(tf.float64, [None, None])\n feed_dict = {points: test_points}\n\n # Dsiable project\n trinp.project = False\n tri.project = False\n\n # Just another run test\n y = tri(points)\n res = sess.run(y, feed_dict=feed_dict)\n assert_allclose(res, trinp(test_points))\n\n # Test gradients\n grad = tf.gradients(y, points)\n res = sess.run(grad, feed_dict=feed_dict)[0]\n assert_allclose(res, trinp.gradient(test_points))\n\n # Enable project\n trinp.project = True\n tri.project = True\n\n # Results are different outside of the projection.\n inside = (np.all(test_points < trinp.limits[:, [1]].T, axis=1)\n & np.all(test_points > trinp.limits[:, [0]].T, axis=1))\n\n test_points = test_points[inside]\n\n # Test gradients projected\n y = tri(points)\n grad = tf.gradients(y, points)\n res = sess.run(grad, feed_dict=feed_dict)[0]\n assert_allclose(res[inside], trinp.gradient(test_points))\n\n def test_gradient_param(self, setup):\n \"\"\"Test the gradients with respect to the parameters.\"\"\"\n sess, tri, trinp, test_points = setup\n\n # Disable project\n trinp.project = True\n tri.project = True\n\n x = tf.placeholder(tf.float64, [1, 2])\n\n true_gradient = trinp.parameter_derivative(test_points)\n true_gradient = np.array(true_gradient.todense())\n\n y = tri(x)\n grad_tf = tf.gradients(y, tri.parameters)[0]\n dense_gradient = np.zeros(true_gradient[0].shape, dtype=np.float)\n\n for i, test in enumerate(test_points):\n gradient = sess.run(grad_tf, feed_dict={x: test[None, :]})\n dense_gradient[:] = 0.\n dense_gradient[gradient.indices] = gradient.values[:, 0]\n assert_allclose(dense_gradient, true_gradient[i])\n\n\ndef test_neural_network():\n \"\"\"Test the NeuralNetwork class init.\"\"\"\n relu = tf.nn.relu\n\n with tf.Session() as sess:\n nn = NeuralNetwork(layers=[2, 3, 1],\n nonlinearities=[relu, relu, None])\n\n # x = tf.placeholder()\n res = nn(np.random.rand(4, 2))\n sess.run(tf.global_variables_initializer())\n res, lipschitz = sess.run([res, nn.lipschitz()])\n\n assert lipschitz > 0.\n\n\nif __name__ == '__main__':\n pytest.main()\n" ]
[ [ "tensorflow.variables_initializer", "numpy.math.factorial", "numpy.all", "numpy.testing.assert_equal", "numpy.hstack", "tensorflow.Graph", "tensorflow.Variable", "numpy.arange", "tensorflow.gradients", "tensorflow.Session", "numpy.zeros", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.array", "numpy.sum", "tensorflow.get_default_session", "numpy.sort", "numpy.ones", "tensorflow.variable_scope" ] ]
felixriese/susi
[ "fa405e683eda30850900c14d214e732862ef4180" ]
[ "susi/SOMClustering.py" ]
[ "\"\"\"SOMClustering class.\n\nCopyright (c) 2019-2021 Felix M. Riese.\nAll rights reserved.\n\n\"\"\"\n\nimport itertools\nfrom typing import List, Optional, Sequence, Tuple\n\nimport numpy as np\nimport scipy.spatial.distance as dist\nfrom joblib import Parallel, delayed, effective_n_jobs\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import binarize\nfrom sklearn.utils.validation import check_array\nfrom tqdm import tqdm\n\nfrom .SOMUtils import decreasing_rate, modify_weight_matrix_online\n\n\nclass SOMClustering:\n \"\"\"Unsupervised self-organizing map for clustering.\n\n Parameters\n ----------\n n_rows : int, optional (default=10)\n Number of rows for the SOM grid\n\n n_columns : int, optional (default=10)\n Number of columns for the SOM grid\n\n init_mode_unsupervised : str, optional (default=\"random\")\n Initialization mode of the unsupervised SOM\n\n n_iter_unsupervised : int, optional (default=1000)\n Number of iterations for the unsupervised SOM\n\n train_mode_unsupervised : str, optional (default=\"online\")\n Training mode of the unsupervised SOM\n\n neighborhood_mode_unsupervised : str, optional (default=\"linear\")\n Neighborhood mode of the unsupervised SOM\n\n learn_mode_unsupervised : str, optional (default=\"min\")\n Learning mode of the unsupervised SOM\n\n distance_metric : str, optional (default=\"euclidean\")\n Distance metric to compare on feature level (not SOM grid).\n Possible metrics: {\"euclidean\", \"manhattan\", \"mahalanobis\",\n \"tanimoto\", \"spectralangle\"}. Note that \"tanimoto\" tends to be slow.\n\n .. versionadded:: 1.1.1\n Spectral angle metric.\n\n learning_rate_start : float, optional (default=0.5)\n Learning rate start value\n\n learning_rate_end : float, optional (default=0.05)\n Learning rate end value (only needed for some lr definitions)\n\n nbh_dist_weight_mode : str, optional (default=\"pseudo-gaussian\")\n Formula of the neighborhood distance weight. Possible formulas\n are: {\"pseudo-gaussian\", \"mexican-hat\"}.\n\n n_jobs : int or None, optional (default=None)\n The number of jobs to run in parallel.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n verbose : int, optional (default=0)\n Controls the verbosity.\n\n Attributes\n ----------\n node_list_ : np.ndarray of (int, int) tuples\n List of 2-dimensional coordinates of SOM nodes\n\n radius_max_ : float, int\n Maximum radius of the neighborhood function\n\n radius_min_ : float, int\n Minimum radius of the neighborhood function\n\n unsuper_som_ : np.ndarray\n Weight vectors of the unsupervised SOM\n shape = (self.n_rows, self.n_columns, X.shape[1])\n\n X_ : np.ndarray\n Input data\n\n fitted_ : boolean\n States if estimator is fitted to X\n\n max_iterations_ : int\n Maximum number of iterations for the current training\n\n bmus_ : list of (int, int) tuples\n List of best matching units (BMUs) of the dataset X\n\n variances_ : array of float\n Standard deviations of every feature\n\n \"\"\"\n\n def __init__(\n self,\n n_rows: int = 10,\n n_columns: int = 10,\n *,\n init_mode_unsupervised: str = \"random\",\n n_iter_unsupervised: int = 1000,\n train_mode_unsupervised: str = \"online\",\n neighborhood_mode_unsupervised: str = \"linear\",\n learn_mode_unsupervised: str = \"min\",\n distance_metric: str = \"euclidean\",\n learning_rate_start: float = 0.5,\n learning_rate_end: float = 0.05,\n nbh_dist_weight_mode: str = \"pseudo-gaussian\",\n n_jobs: Optional[int] = None,\n random_state=None,\n verbose: Optional[int] = 0,\n ) -> None:\n \"\"\"Initialize SOMClustering object.\"\"\"\n self.n_rows = n_rows\n self.n_columns = n_columns\n self.init_mode_unsupervised = init_mode_unsupervised\n self.n_iter_unsupervised = n_iter_unsupervised\n self.train_mode_unsupervised = train_mode_unsupervised\n self.neighborhood_mode_unsupervised = neighborhood_mode_unsupervised\n self.learn_mode_unsupervised = learn_mode_unsupervised\n self.distance_metric = distance_metric\n self.learning_rate_start = learning_rate_start\n self.learning_rate_end = learning_rate_end\n self.nbh_dist_weight_mode = nbh_dist_weight_mode\n self.n_jobs = n_jobs\n self.random_state = random_state\n self.verbose = verbose\n\n def _init_unsuper_som(self) -> None:\n \"\"\"Initialize map.\"\"\"\n # init node list\n self.node_list_ = np.array(\n list(itertools.product(range(self.n_rows), range(self.n_columns))),\n dtype=int,\n )\n\n self.max_iterations_ = self.n_iter_unsupervised\n\n # init radius parameter\n self.radius_max_ = max(self.n_rows, self.n_columns) / 2\n self.radius_min_ = 1\n\n # tqdm paramters\n self.tqdm_params_ = {\"disable\": not bool(self.verbose), \"ncols\": 100}\n\n # init unsupervised SOM in the feature space\n if self.init_mode_unsupervised == \"random\":\n som = np.random.rand(self.n_rows, self.n_columns, self.X_.shape[1])\n\n elif self.init_mode_unsupervised == \"random_data\":\n indices = np.random.randint(\n low=0, high=self.X_.shape[0], size=self.n_rows * self.n_columns\n )\n som_list = self.X_[indices]\n som = som_list.reshape(\n self.n_rows, self.n_columns, self.X_.shape[1]\n )\n\n elif self.init_mode_unsupervised == \"pca\":\n\n # fixed number of components\n pca = PCA(n_components=2, random_state=self.random_state)\n\n pca_comp = pca.fit(self.X_).components_\n\n a_row = np.linspace(-1.0, 1.0, self.n_rows)\n a_col = np.linspace(-1.0, 1.0, self.n_columns)\n\n som = np.zeros(\n shape=(self.n_rows, self.n_columns, self.X_.shape[1])\n )\n\n for node in self.node_list_:\n som[node[0], node[1], :] = np.add(\n np.multiply(a_row[node[0]], pca_comp[0]),\n np.multiply(a_col[node[1]], pca_comp[1]),\n )\n\n else:\n raise ValueError(\n f\"Invalid init_mode_unsupervised: {self.init_mode_unsupervised}.\"\n )\n\n self.unsuper_som_ = som\n\n def fit(self, X: Sequence, y: Optional[Sequence] = None):\n \"\"\"Fit unsupervised SOM to input data.\n\n Parameters\n ----------\n X : array-like matrix of shape = [n_samples, n_features]\n The training input samples.\n y : None\n Not used in this class.\n\n Returns\n -------\n self : object\n\n Examples\n --------\n Load the SOM and fit it to your input data `X` with:\n\n >>> import susi\n >>> som = susi.SOMClustering()\n >>> som.fit(X)\n\n \"\"\"\n np.random.seed(seed=self.random_state)\n self.X_ = check_array(X, dtype=np.float64) # TODO accept_sparse\n\n self.sample_weights_ = np.full(fill_value=1.0, shape=(len(self.X_), 1))\n\n self._train_unsupervised_som()\n self.fitted_ = True\n\n return self\n\n def _train_unsupervised_som(self) -> None:\n \"\"\"Train unsupervised SOM.\"\"\"\n self._init_unsuper_som()\n\n if self.train_mode_unsupervised == \"online\":\n for it in tqdm(\n range(self.n_iter_unsupervised),\n desc=\"unsuper\",\n **self.tqdm_params_,\n ):\n\n # select one input vector & calculate best matching unit (BMU)\n dp = np.random.randint(low=0, high=len(self.X_))\n bmu_pos = self.get_bmu(self.X_[dp], self.unsuper_som_)\n\n # calculate learning rate and neighborhood function\n learning_rate = self._calc_learning_rate(\n curr_it=it, mode=self.learn_mode_unsupervised\n )\n nbh_func = self._calc_neighborhood_func(\n curr_it=it, mode=self.neighborhood_mode_unsupervised\n )\n\n # calculate distance weight matrix and update weights\n dist_weight_matrix = self._get_nbh_distance_weight_matrix(\n nbh_func, bmu_pos\n )\n self.unsuper_som_ = modify_weight_matrix_online(\n som_array=self.unsuper_som_,\n dist_weight_matrix=dist_weight_matrix,\n true_vector=self.X_[dp],\n learning_rate=learning_rate * self.sample_weights_[dp],\n )\n\n elif self.train_mode_unsupervised == \"batch\":\n for it in tqdm(\n range(self.n_iter_unsupervised),\n desc=\"unsuper\",\n **self.tqdm_params_,\n ):\n\n # calculate BMUs\n bmus = self.get_bmus(self.X_)\n\n # calculate neighborhood function\n nbh_func = self._calc_neighborhood_func(\n curr_it=it, mode=self.neighborhood_mode_unsupervised\n )\n\n # calculate distance weight matrix for all datapoints\n dist_weight_block = self._get_nbh_distance_weight_block(\n nbh_func, bmus\n )\n\n # update weights\n self.unsuper_som_ = self._modify_weight_matrix_batch(\n self.unsuper_som_, dist_weight_block, self.X_\n )\n\n else:\n raise NotImplementedError(\n \"Unsupervised mode not implemented:\",\n self.train_mode_unsupervised,\n )\n\n self._set_bmus(self.X_)\n\n def _calc_learning_rate(self, curr_it: int, mode: str) -> float:\n \"\"\"Calculate learning rate alpha with 0 <= alpha <= 1.\n\n Parameters\n ----------\n curr_it : int\n Current iteration count\n mode : str\n Mode of the learning rate (min, exp, expsquare)\n\n Returns\n -------\n float\n Learning rate\n\n \"\"\"\n return decreasing_rate(\n self.learning_rate_start,\n self.learning_rate_end,\n iteration_max=self.max_iterations_,\n iteration=curr_it,\n mode=mode,\n )\n\n def _calc_neighborhood_func(self, curr_it: int, mode: str) -> float:\n \"\"\"Calculate neighborhood function (= radius).\n\n Parameters\n ----------\n curr_it : int\n Current number of iterations\n mode : str\n Mode of the decreasing rate\n\n Returns\n -------\n float\n Neighborhood function (= radius)\n\n \"\"\"\n return decreasing_rate(\n self.radius_max_,\n self.radius_min_,\n iteration_max=self.max_iterations_,\n iteration=curr_it,\n mode=mode,\n )\n\n def get_bmu(\n self, datapoint: np.ndarray, som_array: np.ndarray\n ) -> Tuple[int, int]:\n \"\"\"Get best matching unit (BMU) for datapoint.\n\n Parameters\n ----------\n datapoint : np.ndarray, shape=shape[1]\n Datapoint = one row of the dataset X\n som_array : np.ndarray\n Weight vectors of the SOM\n shape = (self.n_rows, self.n_columns, X.shape[1])\n\n Returns\n -------\n tuple, shape = (int, int)\n Position of best matching unit (row, column)\n\n \"\"\"\n a = self._get_node_distance_matrix(\n datapoint.astype(np.float64), som_array\n )\n\n return np.argwhere(a == np.min(a))[0]\n\n def get_bmus(\n self, X: np.ndarray, som_array: Optional[np.array] = None\n ) -> Optional[List[Tuple[int, int]]]:\n \"\"\"Get Best Matching Units for big datalist.\n\n Parameters\n ----------\n X : np.ndarray\n List of datapoints\n som_array : np.ndarray, optional (default=`None`)\n Weight vectors of the SOM\n shape = (self.n_rows, self.n_columns, X.shape[1])\n\n Returns\n -------\n bmus : list of (int, int) tuples\n Position of best matching units (row, column) for each datapoint\n\n Examples\n --------\n Load the SOM, fit it to your input data `X` and transform your input\n data with:\n\n >>> import susi\n >>> import matplotlib.pyplot as plt\n >>> som = susi.SOMClustering()\n >>> som.fit(X)\n >>> bmu_list = som.get_bmus(X)\n >>> plt.hist2d([x[0] for x in bmu_list], [x[1] for x in bmu_list]\n\n \"\"\"\n if som_array is None:\n som_array = self.unsuper_som_\n\n bmus = None\n if self.n_jobs == 1:\n bmus = [tuple(self.get_bmu(dp, som_array)) for dp in X]\n else:\n n_jobs, _, _ = self._partition_bmus(X)\n bmus = Parallel(n_jobs=n_jobs, verbose=self.verbose)(\n delayed(self.get_bmu)(dp, som_array) for dp in X\n )\n return bmus\n\n def _partition_bmus(\n self, X: np.ndarray\n ) -> Tuple[float, List[int], List[int]]:\n \"\"\"Private function used to partition bmus between jobs.\n\n Parameters\n ----------\n X : np.ndarray\n List of datapoints\n\n Returns\n -------\n n_jobs : int\n Number of jobs\n list of int\n List of number of datapoints per job\n list of int\n List of start values for every job list\n\n \"\"\"\n n_datapoints = len(X)\n n_jobs = min(effective_n_jobs(self.n_jobs), n_datapoints)\n\n n_datapoints_per_job = np.full(\n n_jobs, n_datapoints // n_jobs, dtype=int\n )\n\n n_datapoints_per_job[: n_datapoints % n_jobs] += 1\n starts = np.cumsum(n_datapoints_per_job)\n\n return n_jobs, n_datapoints_per_job.tolist(), [0] + starts.tolist()\n\n def _set_bmus(\n self, X: np.ndarray, som_array: Optional[np.array] = None\n ) -> None:\n \"\"\"Set BMUs in the current SOM object.\n\n Parameters\n ----------\n X : array-like matrix of shape = [n_samples, n_features]\n The input samples.\n som_array : np.ndarray\n Weight vectors of the SOM\n shape = (self.n_rows, self.n_columns, X.shape[1])\n\n \"\"\"\n self.bmus_ = self.get_bmus(X=X, som_array=som_array)\n\n def _get_node_distance_matrix(\n self, datapoint: np.ndarray, som_array: np.ndarray\n ) -> np.ndarray:\n \"\"\"Get distance of datapoint and node using Euclidean distance.\n\n Parameters\n ----------\n datapoint : np.ndarray, shape=(X.shape[1])\n Datapoint = one row of the dataset `X`\n som_array : np.ndarray\n Weight vectors of the SOM,\n shape = (self.n_rows, self.n_columns, X.shape[1])\n\n Returns\n -------\n distmat : np.ndarray of float\n Distance between datapoint and each SOM node\n\n \"\"\"\n # algorithms on the full matrix\n if self.distance_metric == \"euclidean\":\n return np.linalg.norm(som_array - datapoint, axis=2)\n\n # node-by-node algorithms\n distmat = np.zeros((self.n_rows, self.n_columns))\n if self.distance_metric == \"manhattan\":\n for node in self.node_list_:\n distmat[node] = dist.cityblock(\n som_array[node[0], node[1]], datapoint\n )\n\n elif self.distance_metric == \"mahalanobis\":\n for node in self.node_list_:\n som_node = som_array[node[0], node[1]]\n cov = np.cov(\n np.stack((datapoint, som_node), axis=0), rowvar=False\n )\n cov_pinv = np.linalg.pinv(cov) # pseudo-inverse\n distmat[node] = dist.mahalanobis(datapoint, som_node, cov_pinv)\n\n elif self.distance_metric == \"tanimoto\":\n # Note that this is a binary distance measure.\n # Therefore, the vectors have to be converted.\n # Source: Melssen 2006, Supervised Kohonen networks for\n # classification problems\n # VERY SLOW ALGORITHM!!!\n threshold = 0.5\n for node in self.node_list_:\n som_node = som_array[node[0], node[1]]\n distmat[node] = dist.rogerstanimoto(\n binarize(\n datapoint.reshape(1, -1),\n threshold=threshold,\n copy=True,\n ),\n binarize(\n som_node.reshape(1, -1), threshold=threshold, copy=True\n ),\n )\n\n elif self.distance_metric == \"spectralangle\":\n for node in self.node_list_:\n distmat[node] = np.arccos(\n np.divide(\n np.dot(som_array[node[0], node[1]], datapoint),\n np.multiply(\n np.linalg.norm(som_array),\n np.linalg.norm(datapoint),\n ),\n )\n )\n\n return distmat\n\n def _get_nbh_distance_weight_matrix(\n self, neighborhood_func: float, bmu_pos: Tuple[int, int]\n ) -> np.ndarray:\n \"\"\"Calculate neighborhood distance weight.\n\n Parameters\n ----------\n neighborhood_func : float\n Current neighborhood function\n bmu_pos : tuple, shape=(int, int)\n Position of calculated BMU of the current datapoint\n\n Returns\n -------\n np.array of float, shape=(n_rows, n_columns)\n Neighborhood distance weight matrix between SOM and BMU\n\n \"\"\"\n dist_mat = np.linalg.norm(self.node_list_ - bmu_pos, axis=1)\n\n pseudogaussian = np.exp(\n -np.divide(\n np.power(dist_mat, 2), (2 * np.power(neighborhood_func, 2))\n )\n )\n\n if self.nbh_dist_weight_mode == \"pseudo-gaussian\":\n return pseudogaussian.reshape((self.n_rows, self.n_columns, 1))\n\n if self.nbh_dist_weight_mode == \"mexican-hat\":\n mexicanhat = np.multiply(\n pseudogaussian,\n np.subtract(\n 1,\n np.divide(\n np.power(dist_mat, 2), np.power(neighborhood_func, 2)\n ),\n ),\n )\n return mexicanhat.reshape((self.n_rows, self.n_columns, 1))\n\n raise ValueError(\n \"Invalid nbh_dist_weight_mode: \" + str(self.nbh_dist_weight_mode)\n )\n\n def _get_nbh_distance_weight_block(\n self, nbh_func: float, bmus: List[Tuple[int, int]]\n ) -> np.ndarray:\n \"\"\"Calculate distance weight matrix for all datapoints.\n\n The combination of several distance weight matrices is called\n \"block\" in the following.\n\n Parameters\n ----------\n neighborhood_func : float\n Current neighborhood function\n bmus : list of tuple (int, int)\n Positions of calculated BMUs of the datapoints\n\n Returns\n -------\n dist_weight_block : np.ndarray of float, shape=(n_rows, n_columns)\n Neighborhood distance weight block between SOM and BMUs\n\n \"\"\"\n dist_weight_block = np.zeros((len(bmus), self.n_rows, self.n_columns))\n\n for i, bmu_pos in enumerate(bmus):\n dist_weight_block[i] = self._get_nbh_distance_weight_matrix(\n nbh_func, bmu_pos\n ).reshape((self.n_rows, self.n_columns))\n\n return dist_weight_block\n\n def _modify_weight_matrix_batch(\n self,\n som_array: np.ndarray,\n dist_weight_matrix: np.ndarray,\n data: np.ndarray,\n ) -> np.ndarray:\n \"\"\"Modify weight matrix of the SOM for the online algorithm.\n\n Parameters\n ----------\n som_array : np.ndarray\n Weight vectors of the SOM\n shape = (self.n_rows, self.n_columns, X.shape[1])\n dist_weight_matrix : np.ndarray of float\n Current distance weight of the SOM for the specific node\n data : np.ndarray\n True vector(s)\n learning_rate : float\n Current learning rate of the SOM\n\n Returns\n -------\n np.array\n Weight vector of the SOM after the modification\n\n \"\"\"\n # calculate numerator and divisor for the batch formula\n numerator = np.sum(\n [\n np.multiply(\n data[i],\n dist_weight_matrix[i].reshape(\n (self.n_rows, self.n_columns, 1)\n ),\n )\n for i in range(len(data))\n ],\n axis=0,\n )\n divisor = np.sum(dist_weight_matrix, axis=0).reshape(\n (self.n_rows, self.n_columns, 1)\n )\n\n # update weights\n old_som = np.copy(som_array)\n new_som = np.divide(\n numerator,\n divisor,\n out=np.full_like(numerator, np.nan),\n where=(divisor != 0),\n )\n\n # overwrite new nans with old entries\n new_som[np.isnan(new_som)] = old_som[np.isnan(new_som)]\n return new_som\n\n def transform(\n self, X: Sequence, y: Optional[Sequence] = None\n ) -> np.ndarray:\n \"\"\"Transform input data.\n\n Parameters\n ----------\n X : array-like matrix of shape = [n_samples, n_features]\n The prediction input samples.\n y : None, optional\n Ignored.\n\n Returns\n -------\n np.array of tuples (int, int)\n Predictions including the BMUs of each datapoint\n\n Examples\n --------\n Load the SOM, fit it to your input data `X` and transform your input\n data with:\n\n >>> import susi\n >>> som = susi.SOMClustering()\n >>> som.fit(X)\n >>> X_transformed = som.transform(X)\n\n \"\"\"\n # assert(self.fitted_ is True)\n self.X_ = check_array(X, dtype=np.float64)\n return np.array(self.get_bmus(self.X_))\n\n def fit_transform(\n self, X: Sequence, y: Optional[Sequence] = None\n ) -> np.ndarray:\n \"\"\"Fit to the input data and transform it.\n\n Parameters\n ----------\n X : array-like matrix of shape = [n_samples, n_features]\n The training and prediction input samples.\n y : None, optional\n Ignored.\n\n Returns\n -------\n np.array of tuples (int, int)\n Predictions including the BMUs of each datapoint\n\n Examples\n --------\n Load the SOM, fit it to your input data `X` and transform your input\n data with:\n\n >>> import susi\n >>> som = susi.SOMClustering()\n >>> X_transformed = som.fit_transform(X)\n\n \"\"\"\n self.fit(X)\n # assert(self.fitted_ is True)\n self.X_ = check_array(X, dtype=np.float64)\n return self.transform(X, y)\n\n def get_datapoints_from_node(self, node: Tuple[int, int]) -> List[int]:\n \"\"\"Get all datapoints of one node.\n\n Parameters\n ----------\n node : tuple, shape (int, int)\n Node for which the linked datapoints are calculated\n\n Returns\n -------\n datapoints : list of int\n List of indices of the datapoints that are linked to `node`\n\n \"\"\"\n datapoints = []\n for i in range(len(self.bmus_)):\n if np.array_equal(self.bmus_[i], node):\n datapoints.append(i)\n return datapoints\n\n def get_clusters(self, X: np.ndarray) -> Optional[List[Tuple[int, int]]]:\n \"\"\"Calculate the SOM nodes on the unsupervised SOM grid per datapoint.\n\n Parameters\n ----------\n X : np.ndarray\n Input data\n\n Returns\n -------\n list of tuples (int, int)\n List of SOM nodes, one for each input datapoint\n\n \"\"\"\n return self.get_bmus(X)\n\n def get_u_matrix(self, mode: str = \"mean\") -> np.ndarray:\n \"\"\"Calculate unified distance matrix (u-matrix).\n\n Parameters\n ----------\n mode : str, optional (default=\"mean)\n Choice of the averaging algorithm\n\n Returns\n -------\n u_matrix : np.ndarray\n U-matrix containing the distances between all nodes of the\n unsupervised SOM. Shape = (n_rows*2-1, n_columns*2-1)\n\n Examples\n --------\n Fit your SOM to input data `X` and then calculate the u-matrix with\n `get_u_matrix()`. You can plot the u-matrix then with e.g.\n `pyplot.imshow()`.\n\n >>> import susi\n >>> import numpy as np\n >>> import matplotlib.pyplot as plt\n >>> som = susi.SOMClustering()\n >>> som.fit(X)\n >>> umat = som.get_u_matrix()\n >>> plt.imshow(np.squeeze(umat))\n\n \"\"\"\n self.u_mean_mode_ = mode\n\n self.u_matrix = np.zeros(\n shape=(self.n_rows * 2 - 1, self.n_columns * 2 - 1, 1), dtype=float\n )\n\n # step 1: fill values between SOM nodes\n self._calc_u_matrix_distances()\n\n # step 2: fill values at SOM nodes and on diagonals\n self._calc_u_matrix_means()\n\n return self.u_matrix\n\n def _calc_u_matrix_distances(self) -> None:\n \"\"\"Calculate the Eucl. distances between all neighbored SOM nodes.\"\"\"\n for u_node in itertools.product(\n range(self.n_rows * 2 - 1), range(self.n_columns * 2 - 1)\n ):\n\n # neighbor vector\n nb = (0, 0)\n\n if not (u_node[0] % 2) and (u_node[1] % 2):\n # mean horizontally\n nb = (0, 1)\n\n elif (u_node[0] % 2) and not (u_node[1] % 2):\n # mean vertically\n nb = (1, 0)\n\n self.u_matrix[u_node] = np.linalg.norm(\n self.unsuper_som_[u_node[0] // 2][u_node[1] // 2]\n - self.unsuper_som_[u_node[0] // 2 + nb[0]][\n u_node[1] // 2 + nb[1]\n ],\n axis=0,\n )\n\n def _calc_u_matrix_means(self) -> None:\n \"\"\"Calculate the missing parts of the u-matrix.\n\n After `_calc_u_matrix_distances()`, there are two kinds of entries\n missing: the entries at the positions of the actual SOM nodes and the\n entries in between the distance nodes. Both types of entries are\n calculated in this function.\n\n \"\"\"\n for u_node in itertools.product(\n range(self.n_rows * 2 - 1), range(self.n_columns * 2 - 1)\n ):\n\n if not (u_node[0] % 2) and not (u_node[1] % 2):\n # SOM nodes -> mean over 2-4 values\n\n nodelist = []\n if u_node[0] > 0:\n nodelist.append((u_node[0] - 1, u_node[1]))\n if u_node[0] < self.n_rows * 2 - 2:\n nodelist.append((u_node[0] + 1, u_node[1]))\n if u_node[1] > 0:\n nodelist.append((u_node[0], u_node[1] - 1))\n if u_node[1] < self.n_columns * 2 - 2:\n nodelist.append((u_node[0], u_node[1] + 1))\n self.u_matrix[u_node] = self._get_u_mean(nodelist)\n\n elif (u_node[0] % 2) and (u_node[1] % 2):\n # mean over four\n\n self.u_matrix[u_node] = self._get_u_mean(\n [\n (u_node[0] - 1, u_node[1]),\n (u_node[0] + 1, u_node[1]),\n (u_node[0], u_node[1] - 1),\n (u_node[0], u_node[1] + 1),\n ]\n )\n\n def _get_u_mean(self, nodelist: List[Tuple[int, int]]) -> Optional[float]:\n \"\"\"Calculate a mean value of the node entries in `nodelist`.\n\n Parameters\n ----------\n nodelist : list of tuple (int, int)\n List of nodes on the u-matrix containing distance values\n\n Returns\n -------\n u_mean : float\n Mean value\n\n \"\"\"\n meanlist = [self.u_matrix[u_node] for u_node in nodelist]\n u_mean = None\n if self.u_mean_mode_ == \"mean\":\n u_mean = np.mean(meanlist)\n elif self.u_mean_mode_ == \"median\":\n u_mean = np.median(meanlist)\n elif self.u_mean_mode_ == \"min\":\n u_mean = np.min(meanlist)\n elif self.u_mean_mode_ == \"max\":\n u_mean = np.max(meanlist)\n return u_mean\n\n def _get_node_neighbors(\n self, node: Tuple[int, int], radius: int = 1\n ) -> List[Tuple[int, int]]:\n \"\"\"Get neighboring nodes (grid parameters) of `node`.\n\n .. versionadded:: 1.1.3\n\n Parameters\n ----------\n node : Tuple[int, int]\n Node position on the SOM grid.\n radius : int, optional (default=1)\n Radius to calculate the node radius. Is set arbitrarily to 1, can\n be changed in future versions.\n\n Returns\n -------\n [type]\n [description]\n \"\"\"\n row_range = range(\n max(node[0] - radius, 0),\n min(node[0] + radius, self.n_rows - 1) + 1,\n )\n column_range = range(\n max(node[1] - radius, 0),\n min(node[1] + radius, self.n_columns - 1) + 1,\n )\n return list(itertools.product(row_range, column_range))\n\n def get_quantization_error(self, X: Optional[Sequence] = None) -> float:\n \"\"\"Get quantization error for `X` (or the training data).\n\n Parameters\n ----------\n X : array-like matrix, optional (default=True)\n Samples of shape = [n_samples, n_features]. If `None`, the training\n data is used for the calculation.\n\n Returns\n -------\n float\n Mean quantization error over all datapoints.\n\n Raises\n ------\n RuntimeError\n Raised if the SOM is not fitted yet.\n\n \"\"\"\n if not self.fitted_:\n raise RuntimeError(\"SOM is not fitted!\")\n\n if X is None:\n X = self.X_\n\n weights_per_datapoint = [\n self.unsuper_som_[bmu[0], bmu[1]] for bmu in self.get_bmus(X)\n ]\n\n quantization_errors = np.linalg.norm(\n np.subtract(weights_per_datapoint, X)\n )\n\n return np.mean(quantization_errors)\n" ]
[ [ "numpy.dot", "numpy.linspace", "numpy.cumsum", "numpy.max", "scipy.spatial.distance.cityblock", "numpy.mean", "numpy.random.randint", "numpy.subtract", "numpy.stack", "numpy.full", "numpy.copy", "scipy.spatial.distance.mahalanobis", "numpy.zeros", "numpy.multiply", "numpy.min", "numpy.isnan", "numpy.power", "numpy.median", "numpy.full_like", "numpy.random.rand", "sklearn.decomposition.PCA", "numpy.sum", "sklearn.utils.validation.check_array", "numpy.random.seed", "numpy.array_equal", "numpy.linalg.norm", "numpy.linalg.pinv" ] ]
TSummersLab/Risk_Bounded_Nonlinear_Robot_Motion_Planning
[ "717b9f07f4ed625ee33ab8ec22ce78dc2907d759" ]
[ "Unicycle Simulation/scripts/tracking_controller.py" ]
[ "#!/usr/bin/env python3\n\"\"\"\nChangelog:\nNew in version 1_0:\n- Create script to run and test functions in `lqr.py`\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAuthor:\nBen Gravell\nEmail:\[email protected]\nGithub:\n@BenGravell\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis script does the following:\n- Provides sample trajectories used for debugging\n- Provide functions to generate filtered noise\n- Runs lqr and lqrm functions from `lqr.py` using a sample trajectory as the high-level trajectory\n(edit `use_robust_lqr` to switch between lqr and lqrm)\n\n\nTested platform:\n- Python 3.6.9 on Ubuntu 18.04 LTS (64 bit)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport math\nimport numpy as np\nimport numpy.linalg as la\nimport numpy.random as npr\nimport scipy.linalg as sla\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt\n\nfrom problem_domain import generate_disturbance_hist, transform_disturbance, update_disturbance\nfrom plotting import plot_hist, plot_gain_hist, animate, plot_paths\nfrom lqr import lqr, lqrm\nfrom utility.matrixmath import mdot, sympart\n\nfrom copy import copy\nimport time\nimport pickle\nfrom opt_path import load_pickle_file\nimport os\nimport sys\nsys.path.insert(0, '../utility')\n\nimport config\nSTEER_TIME = config.STEER_TIME # Maximum Steering Time Horizon\nDT = config.DT # timestep between controls\nSAVEPATH = config.SAVEPATH\nGOALAREA = config.GOALAREA #[xmin,xmax,ymin,ymax]\nVELMIN, VELMAX = config.VELMIN, config.VELMAX\nANGVELMIN, ANGVELMAX = config.ANGVELMIN, config.ANGVELMAX\nOBSTACLELIST = config.OBSTACLELIST\nROBRAD = config.ROBRAD\nQLL = config.QLL\nRLL = config.RLL\nQTLL = config.QTLL\n\n\n# State\n# x[0] = horizontal position\n# x[1] = vertical position\n# x[2] = angular position\n#\n# Input\n# u[0] = linear speed\n# u[1] = angular speed\n\nclass OpenLoopController:\n def __init__(self, u_ref_hist):\n self.u_ref_hist = u_ref_hist\n\n def compute_input(self, x, t):\n u_ref = self.u_ref_hist[t]\n return u_ref\n\n\nclass LQRController:\n def __init__(self, K_hist, L_hist, e_hist, z_hist, x_ref_hist, u_ref_hist):\n self.K_hist = K_hist\n self.L_hist = L_hist\n self.e_hist = e_hist\n self.z_hist = z_hist\n self.x_ref_hist = x_ref_hist\n self.u_ref_hist = u_ref_hist\n\n def compute_input(self, x, t):\n K = self.K_hist[t]\n L = self.L_hist[t]\n e = self.e_hist[t]\n z = self.z_hist[t]\n x_ref = self.x_ref_hist[t]\n u_ref = self.u_ref_hist[t]\n dx = x - x_ref\n u = np.dot(K, dx) + np.dot(L, z) + e + u_ref\n return u\n\n\ndef load_ref_traj(input_file):\n inputs_string = \"inputs\"\n states_file = input_file.replace(inputs_string, \"states\")\n\n input_file = os.path.join(SAVEPATH, input_file)\n states_file = os.path.join(SAVEPATH, states_file)\n\n # load inputs and states\n ref_inputs = load_pickle_file(input_file)\n ref_states = load_pickle_file(states_file)\n return ref_states, ref_inputs\n\n\ndef rollout(n, m, T, DT, x0=None, w_base_hist=None, controller=None, saturate_inputs=True, disturb=True, transform_disturbance_flag=True):\n # Initialize\n x_hist = np.zeros([T, n])\n if x0 is None:\n x0 = np.zeros(n)\n x_hist[0] = x0\n x = np.copy(x0)\n u_hist = np.zeros([T, m])\n w_hist = np.zeros([T, n])\n # Simulate\n for t in range(T-1):\n # Compute desired control inputs\n u = controller.compute_input(x, t)\n # Saturate inputs at actuator limits\n if saturate_inputs:\n u[0] = np.clip(u[0], VELMIN, VELMAX)\n u[1] = np.clip(u[1], ANGVELMIN, ANGVELMAX)\n # Generate state-dependent additive disturbance\n if disturb:\n if transform_disturbance_flag:\n w_base = w_base_hist[t]\n w = transform_disturbance(w_base, x)\n else:\n w = w_base_hist[t]\n else:\n w = np.zeros(n)\n # Transition the state\n x = dtime_dynamics(x, u, DT) + w\n # Record quantities\n x_hist[t+1] = x\n u_hist[t] = u\n w_hist[t+1] = w\n return x_hist, u_hist, w_hist\n\n\n# Continuous-time nonlinear dynamics\ndef ctime_dynamics(x, u):\n return np.array([u[0]*np.cos(x[2]), u[0]*np.sin(x[2]), u[1]])\n\n\n# Discrete-time nonlinear dynamics\ndef dtime_dynamics(x, u, DT):\n # Euler method\n return x + ctime_dynamics(x, u)*DT\n\n\n# Linearized continuous-time dynamics\ndef ctime_jacobian(x, u):\n A = np.array([[0, 0, -u[0]*np.sin(x[2])],\n [0, 0, u[0]*np.cos(x[2])],\n [0, 0, 0]])\n B = np.array([[np.cos(x[2]), 0],\n [np.sin(x[2]), 0],\n [0, 1]])\n return A, B\n\n\n# Linearized discrete-time dynamics\ndef dtime_jacobian(n, x, u, DT, method='zoh'):\n A, B = ctime_jacobian(x, u)\n Ad = np.eye(n) + A*DT\n Bd = B*DT\n # C, D = np.eye(n), np.zeros([n, m])\n # sysd = signal.cont2discrete((A, B, C, D), DT, method)\n # return sysd[0], sysd[1]\n return Ad, Bd\n\n\n# generate some example reference inputs\n# this is replaced by RRT* which actually does something useful\ndef generate_reference_inputs(pattern='rounded_arrow'):\n u_hist = np.zeros([T, m])\n for i in range(T):\n t = t_hist[i]\n if pattern == 'rounded_arrow':\n u_hist[i] = np.array([0.1*(2+0.5*np.cos(0.2*t)), 0.08*np.sin(0.05*t)])\n elif pattern == 'clover':\n u_hist[i] = np.array([0.01*(np.sin(0.2*t)+1)+0.05*(np.sin(0.05*t)+1)+0.05,\n 0.03*np.sin(0.05*t) + 0.02*np.tanh(4*np.sin(0.01*t)+1) - 0.005])\n return u_hist\n\n\ndef evaluate_trajectory(T, x_hist, u_hist, w_hist, x_ref_hist, Q, R, S):\n # Evaluate trajectory in terms of reference tracking, control effort, and disturbance energy\n dxtot = 0\n utot = 0\n wtot = 0\n for t in range(T):\n dx = x_hist[t] - x_ref_hist[t]\n u = u_hist[t]\n w = w_hist[t]\n dxtot += mdot(dx.T, Q, dx)\n utot += mdot(u.T, R, u)\n wtot += mdot(w.T, S, w)\n print('Total tracking error: %.3f' % dxtot)\n print('Total control effort: %.3f' % utot)\n print('Total disturbance energy: %.3f' % wtot)\n return dxtot, utot, wtot\n\n\ndef create_lqrm_controller(x_ref_hist, u_ref_hist, use_robust_lqr=True,\n delta_theta_max=1*(2*np.pi/360)):\n # delta_theta_max is the maximum assumed angle deviation in radians for robust control design\n\n T, n = x_ref_hist.shape\n T, m = u_ref_hist.shape\n # Compute linearized dynamics matrices along the reference trajectory\n A_hist = np.zeros([T, n, n])\n B_hist = np.zeros([T, n, m])\n for t in range(T):\n A_hist[t], B_hist[t] = dtime_jacobian(n, x_ref_hist[t], u_ref_hist[t], DT)\n\n E_hist = np.zeros([T, n, n]) # TODO - make this something more meaningful\n W_hist = np.zeros([T, n, n]) # TODO - make this something more meaningful\n\n # Construct multiplicative noises and additive adversary\n\n # TODO - move this somewhere else\n # Old robustness settings\n # c = 3\n # C_hist = np.zeros([T, n, c])\n # for t in range(T):\n # # Adversary can push robot around isotropically in xy plane position and twist the robot angle a little\n # C_hist[t] = np.array([[0.4, 0.0, 0.0],\n # [0.0, 0.4, 0.0],\n # [0.0, 0.0, 0.1]])\n #\n # num_alphas = 3\n # num_betas = 2\n # num_gammas = 2\n # alpha_var = robust_scale*0.1*np.array([1.0, 1.0, 0.5])\n # beta_var = robust_scale*0.5*np.array([1.0, 0.5])\n # gamma_var = np.array([0, 0])\n # alpha_var_hist = np.tile(alpha_var, (T, 1))\n # beta_var_hist = np.tile(beta_var, (T, 1))\n # gamma_var_hist = np.tile(gamma_var, (T, 1))\n #\n # Ai_hist = np.zeros([T, num_alphas, n, n])\n # Bi_hist = np.zeros([T, num_betas, n, m])\n # Ci_hist = np.zeros([T, num_gammas, n, c])\n # for t in range(T):\n # cos_theta = np.cos(x_ref_hist[t, 2])\n # sin_theta = np.sin(x_ref_hist[t, 2])\n # Ai_hist[t, 0] = np.array([[cos_theta, 0, 0],\n # [sin_theta, 0, 0],\n # [0, 0, 0]])\n # Ai_hist[t, 1] = np.array([[0, cos_theta, 0],\n # [0, sin_theta, 0],\n # [0, 0, 0]])\n # Ai_hist[t, 2] = np.array([[0, 0, 0],\n # [0, 0, 0],\n # [0, 0, 1]])\n # Bi_hist[t, 0] = np.array([[cos_theta, 0],\n # [sin_theta, 0],\n # [0, 0]])\n # Bi_hist[t, 1] = np.array([[0, 0],\n # [0, 0],\n # [0, 1]])\n #\n\n # New robustness settings\n c = 3\n C_hist = np.zeros([T, n, c])\n for t in range(T):\n # No adversary\n C_hist[t] = np.zeros([n, c])\n\n num_alphas = 2\n num_betas = 2\n num_gammas = 2\n alpha_var_hist = np.zeros([T, num_alphas])\n beta_var_hist = np.zeros([T, num_betas])\n gamma_var_hist = np.zeros([T, num_gammas])\n\n Ai_hist = np.zeros([T, num_alphas, n, n])\n Bi_hist = np.zeros([T, num_betas, n, m])\n Ci_hist = np.zeros([T, num_gammas, n, c])\n for t in range(T):\n v = u_ref_hist[t, 0]\n sin_theta = np.sin(x_ref_hist[t, 2])\n cos_theta = np.cos(x_ref_hist[t, 2])\n\n sin_delta_theta_max = np.sin(delta_theta_max)\n cos_delta_theta_max = np.cos(delta_theta_max)\n\n alpha_var_hist[t, 0] = v*DT*sin_delta_theta_max\n alpha_var_hist[t, 1] = v*DT*(1 - cos_delta_theta_max)\n beta_var_hist[t, 0] = sin_delta_theta_max\n beta_var_hist[t, 1] = 1 - cos_delta_theta_max\n\n Ai_hist[t, 0] = np.array([[0, 0, -sin_theta],\n [0, 0, cos_theta],\n [0, 0, 0]])\n Ai_hist[t, 1] = np.array([[0, 0, -cos_theta],\n [0, 0, -sin_theta],\n [0, 0, 0]])\n Bi_hist[t, 0] = np.array([[-sin_theta, 0],\n [cos_theta, 0],\n [0, 0]])\n Bi_hist[t, 1] = np.array([[cos_theta, 0],\n [sin_theta, 0],\n [0, 0]])\n\n # Construct cost matrices\n # We use the same cost matrices for all time steps, including the final time\n Qorg = np.diag([0, 0, 0]) # Penalty on state being far from origin\n # Qref = np.diag([100, 100, 10]) # Penalty on state deviating from reference\n # QTref = np.diag([100, 100, 10])\n Qref = QLL\n QTref = QTLL\n # Rorg = np.diag([1, 10]) # Penalty on control being far from origin (control effort)\n Rorg = RLL\n Rref = np.diag([0, 0]) # Penalty on input deviating from reference (deviation control effort)\n # Vorg = (1/robust_scale)*600*np.diag([2, 2, 1]) # Penalty on additive adversary\n Vorg = 1000 * np.diag([1, 1, 1]) # Penalty on additive adversary\n\n\n G_hist = np.zeros([T, n+m+c+n+m, n+m+c+n+m])\n for t in range(T):\n Znm, Zmn = np.zeros([n, m]), np.zeros([m, n])\n Znc, Zmc = np.zeros([n, c]), np.zeros([m, c])\n Zcn, Zcm = np.zeros([c, n]), np.zeros([c, m])\n\n G_hist[t] = np.block([[Qref+Qorg, Znm, Znc, Qorg, Znm],\n [Zmn, Rref+Rorg, Zmc, Zmn, Rorg],\n [Zcn, Zcm, -Vorg, Zcn, Zcm],\n [Qorg, Znm, Znc, Qorg, Znm],\n [Zmn, Rorg, Zmc, Zmn, Rorg]])\n\n # Terminal penalty\n G_hist[-1] = np.block([[QTref+Qorg, Znm, Znc, Qorg, Znm],\n [Zmn, Rref+Rorg, Zmc, Zmn, Rorg],\n [Zcn, Zcm, -Vorg, Zcn, Zcm],\n [Qorg, Znm, Znc, Qorg, Znm],\n [Zmn, Rorg, Zmc, Zmn, Rorg]])\n\n # Construct the exogenous signal\n z_hist = np.hstack([x_ref_hist, u_ref_hist])\n\n # Compute optimal control policies, backwards in time\n if not use_robust_lqr:\n # Truncate the G_hist[k] to match the expected format of lqr() i.e. with no adversary blocks\n G_hist_for_lqr = np.zeros([T, n+m+n+m, n+m+n+m])\n for t in range(T):\n Znm, Zmn = np.zeros([n, m]), np.zeros([m, n])\n G_hist_for_lqr[t] = np.block([[Qref+Qorg, Znm, Qorg, Znm],\n [Zmn, Rref+Rorg, Zmn, Rorg],\n [Qorg, Znm, Qorg, Znm],\n [Zmn, Rorg, Zmn, Rorg]])\n K_hist, L_hist, e_hist, P_hist, q_hist, r_hist = lqr(z_hist, A_hist, B_hist, G_hist_for_lqr)\n else:\n lqrm_args = {'z_hist': z_hist,\n 'A_hist': A_hist,\n 'B_hist': B_hist,\n 'C_hist': C_hist,\n 'Ai_hist': Ai_hist,\n 'Bi_hist': Bi_hist,\n 'Ci_hist': Ci_hist,\n 'alpha_var_hist': alpha_var_hist,\n 'beta_var_hist': beta_var_hist,\n 'gamma_var_hist': gamma_var_hist,\n 'G_hist': G_hist,\n 'E_hist': E_hist,\n 'W_hist': W_hist}\n lqrm_outs = lqrm(**lqrm_args)\n K_hist, L_hist, e_hist, Kv_hist, Lv_hist, ev_hist, P_hist, q_hist, r_hist = lqrm_outs\n\n return LQRController(K_hist, L_hist, e_hist, z_hist, x_ref_hist, u_ref_hist)\n\n\nif __name__ == \"__main__\":\n # # Open-loop control sequence\n # T = 500\n # t_hist = np.arange(T)*DT\n # n, m = 3, 2\n # u_ref_hist = generate_reference_inputs(pattern='rounded_arrow')\n # # Create open-loop controller object\n # ol_controller = OpenLoopController(u_ref_hist)\n # # Get reference trajectory by simulating open-loop control using nonlinear dynamics, forwards in time\n # x_ref_hist, u_ref_hist, w_ref_hist = rollout(n, m, T, DT, x0=np.array([-3, -4, 0]), w_base_hist=None, controller=ol_controller,\n # saturate_inputs=True, disturb=False)\n\n # input_file = \"OptTraj_short_v1_0_1607441105_inputs\"\n # input_file = \"OptTraj_v1_0_1607307033_inputs\"\n input_file = 'OptTraj_short_v1_0_1614486007_inputs'\n\n x_ref_hist, u_ref_hist = load_ref_traj(input_file)\n\n # Start in the reference initial state\n x0 = x_ref_hist[0]\n # Start in a different initial state to stress-test controllers\n # If only using linearization about reference trajectory, this may lead to catastrophic failure\n # since the actual trajectory will be different and thus the dynamics different and instability may result\n # x0 = np.array([-1, -1, 0.5])\n\n # Number of states, inputs\n T, n = x_ref_hist.shape\n T, m = u_ref_hist.shape\n\n t_hist = np.arange(T) * DT\n\n # Create open-loop controller object\n ol_controller = OpenLoopController(u_ref_hist)\n\n # Create LQR controller object\n lqr_controller = create_lqrm_controller(x_ref_hist, u_ref_hist, use_robust_lqr=False)\n lqrm_controller = create_lqrm_controller(x_ref_hist, u_ref_hist, use_robust_lqr=True)\n\n\n # Monte Carlo\n num_montecarlo_trials = 20\n x_cl_hist_all = np.zeros([num_montecarlo_trials, T, n])\n x_ol_hist_all = np.zeros([num_montecarlo_trials, T, n])\n for i in range(num_montecarlo_trials):\n\n w_base_hist = generate_disturbance_hist(T, DT, scale=0.2)\n\n # Simulate trajectory with noise and control, forwards in time\n x_cl_hist, u_cl_hist, w_cl_hist = rollout(n, m, T, DT, x0, w_base_hist, controller=lqrm_controller,\n saturate_inputs=True, disturb=True)\n\n x_ol_hist, u_ol_hist, w_ol_hist = rollout(n, m, T, DT, x0, w_base_hist, controller=ol_controller,\n saturate_inputs=True, disturb=True)\n\n x_cl_hist_all[i] = x_cl_hist\n x_ol_hist_all[i] = x_ol_hist\n\n # # Evaluate trajectory in terms of reference tracking, control effort, and disturbance energy\n # Qeval = np.diag([10, 10, 1])\n # Reval = np.diag([10, 100])\n # Seval = np.diag([10, 10, 1])\n # print('Evaluation under closed-loop control')\n # evaluate_trajectory(T, x_cl_hist, u_cl_hist, w_base_hist, x_ref_hist, Qeval, Reval, Seval)\n # print('')\n # print('Evaluation under open-loop control')\n # evaluate_trajectory(T, x_ol_hist, u_ol_hist, w_base_hist, x_ref_hist, Qeval, Reval, Seval)\n # print('')\n\n\n # Plotting\n plt.close('all')\n\n # Plot Monte Carlo paths\n ax_lim = [-5.2, 5.2, -5.2, 5.2]\n x_hist_all_dict = {'Open-loop': x_ol_hist_all, 'Closed-loop': x_cl_hist_all}\n plot_paths(t_hist, x_hist_all_dict, {}, x_ref_hist, title=None, fig_offset=None, axis_limits=ax_lim)\n\n\n\n\n\n # plot_hist(t_hist, [x_ref_hist, x_ol_hist, x_cl_hist], quantity='state')\n # plot_hist(t_hist, [u_ref_hist, u_ol_hist, u_cl_hist], quantity='input')\n # # plot_hist(t_hist, [w_ref_hist, w_ol_hist, w_cl_hist], quantity='disturbance')\n # plot_hist(t_hist, [w_base_hist, w_base_hist, w_base_hist], quantity='disturbance_base')\n # plot_gain_hist(lqrm_controller.K_hist)\n\n # ax_lim = [-6, 6, -6, 6]\n # robot_w = 0.2/2\n # robot_h = 0.5/2\n # wheel_w = 0.5/2\n # wheel_h = 0.005/2\n #\n # animate(t_hist, x_ref_hist, u_ref_hist, x_ref_hist, u_ref_hist, title='Open-loop, reference', fig_offset=(400, 400),\n # axis_limits = ax_lim, robot_w = robot_w, robot_h = robot_h, wheel_w = wheel_w, wheel_h = wheel_h)\n # animate(t_hist, x_cl_hist, u_cl_hist, x_ref_hist, u_ref_hist, title='Closed-loop, disturbed', fig_offset=(1000, 400),\n # axis_limits = ax_lim, robot_w = robot_w, robot_h = robot_h, wheel_w = wheel_w, wheel_h = wheel_h)\n # animate(t_hist, x_ol_hist, u_ol_hist, x_ref_hist, u_ref_hist, title='Open-loop, disturbed', fig_offset=(1600, 400),\n # axis_limits = ax_lim, robot_w = robot_w, robot_h = robot_h, wheel_w = wheel_w, wheel_h = wheel_h)\n" ]
[ [ "numpy.diag", "numpy.hstack", "numpy.dot", "numpy.clip", "numpy.arange", "numpy.eye", "numpy.cos", "numpy.sin", "numpy.copy", "numpy.block", "matplotlib.pyplot.close", "numpy.array", "numpy.zeros" ] ]
dingcheng0107/rnn_cnn_text_classify
[ "bc31651e050ea45264a32da51f756b789a2a33ad" ]
[ "cnn_model.py" ]
[ "# coding: utf-8\n\nimport tensorflow as tf\n\n\nclass TCNNConfig(object):\n \"\"\"CNN配置参数\"\"\"\n\n embedding_dim = 64 # 词向量维度,相当于图片的3通道数\n seq_length = 600 # 序列长度,句子的长度\n num_classes = 2 # 类别数\n num_filters = 256 # 卷积核数目\n kernel_size = 6 # 卷积核尺寸\n vocab_size = 5000 # 词汇表达小\n\n hidden_dim = 256 # 全连接层神经元\n\n dropout_keep_prob = 0.45 # dropout保留比例\n learning_rate = 1e-3 # 学习率\n\n batch_size = 256 # 每批训练大小\n num_epochs = 50 # 总迭代轮次\n\n print_per_batch = 50 # 每多少轮输出一次结果\n save_per_batch = 10 # 每多少轮存入tensorboard\n\n\nclass TextCNN(object):\n \"\"\"文本分类,CNN模型\"\"\"\n\n def __init__(self, config):\n self.config = config\n\n # 三个待输入的数据\n self.input_x = tf.placeholder(tf.int32, [None, self.config.seq_length], name='input_x')\n self.input_y = tf.placeholder(tf.float32, [None, self.config.num_classes], name='input_y')\n self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')\n\n self.cnn()\n\n def cnn(self):\n \"\"\"CNN模型\"\"\"\n # 词向量映射\n with tf.device('/cpu:0'):\n embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim]) # embedding shape is [5000,64],词汇表中有5000个词汇\n embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x) # 函数的用法主要是选取embedding里面索引(self.input_x)对应的元素\n # self.input的shape(?, 600),self.input是长度为600的索引值,返回shape(batch, 600, 64):batch+句子长度+词向量维度\n # 首先随机生成词汇表大小的张量,将输入的词汇(onehot编码过的)用索引映射到随机生成的词汇表张量每行数据,输入一一对应变成了词汇表的映射\n with tf.name_scope(\"cnn\"):\n # CNN layer\n conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, self.config.kernel_size, name='conv') # 600-5+1=596,(?, 596, 256)\n # global max pooling layer\n gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp') # (?, 256),对行的维度增长的方向(向下)axis=1整个列求最大值\n\n with tf.name_scope(\"score\"):\n # 全连接层,后面接dropout以及relu激活\n fc = tf.layers.dense(gmp, self.config.hidden_dim, name='fc1')\n fc = tf.contrib.layers.dropout(fc, self.keep_prob)\n fc = tf.nn.relu(fc)\n\n # 分类器\n self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2') # shape=(?, 10)\n self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1) # 归一化到[0,1],预测类别 shape=(?,)\n\n with tf.name_scope(\"optimize\"):\n # 损失函数,交叉熵\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.input_y)\n self.loss = tf.reduce_mean(cross_entropy)\n # 优化器\n self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss)\n\n with tf.name_scope(\"accuracy\"):\n # 准确率\n correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls) # 比较pred和label是否相等,计算准确率\n self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))" ]
[ [ "tensorflow.layers.conv1d", "tensorflow.nn.relu", "tensorflow.device", "tensorflow.get_variable", "tensorflow.reduce_max", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.nn.softmax", "tensorflow.reduce_mean", "tensorflow.cast", "tensorflow.placeholder", "tensorflow.layers.dense", "tensorflow.contrib.layers.dropout", "tensorflow.name_scope", "tensorflow.train.AdamOptimizer", "tensorflow.argmax", "tensorflow.nn.embedding_lookup" ] ]
rahulatrkm/Hippocampal-Volume-Quantification-in-Alzheimer-s-Progression
[ "21d78cbbda9edb0c215bcbb4cc9551f1734e08c0" ]
[ "section3/src/inference_dcm.py" ]
[ "\"\"\"\nHere we do inference on a DICOM volume, constructing the volume first, and then sending it to the\nclinical archive\n\nThis code will do the following:\n 1. Identify the series to run HippoCrop.AI algorithm on from a folder containing multiple studies\n 2. Construct a NumPy volume from a set of DICOM files\n 3. Run inference on the constructed volume\n 4. Create report from the inference\n 5. Call a shell script to push report to the storage archive\n\"\"\"\n\nimport os\nimport sys\nimport datetime\nimport time\nimport shutil\nimport subprocess\n\nimport numpy as np\nimport pydicom\n\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\nfrom inference.UNetInferenceAgent import UNetInferenceAgent\n\ndef load_dicom_volume_as_numpy_from_list(dcmlist):\n \"\"\"Loads a list of PyDicom objects a Numpy array.\n Assumes that only one series is in the array\n\n Arguments:\n dcmlist {list of PyDicom objects} -- path to directory\n\n Returns:\n tuple of (3D volume, header of the 1st image)\n \"\"\"\n\n # In the real world you would do a lot of validation here\n slices = [np.flip(dcm.pixel_array).T for dcm in sorted(dcmlist, key=lambda dcm: dcm.InstanceNumber)]\n\n # Make sure that you have correctly constructed the volume from your axial slices!\n hdr = dcmlist[0]\n\n # We return header so that we can inspect metadata properly.\n # Since for our purposes we are interested in \"Series\" header, we grab header of the\n # first file (assuming that any instance-specific values will be ighored - common approach)\n # We also zero-out Pixel Data since the users of this function are only interested in metadata\n hdr.PixelData = None\n return (np.stack(slices, 2), hdr)\n\ndef get_predicted_volumes(pred):\n \"\"\"Gets volumes of two hippocampal structures from the predicted array\n\n Arguments:\n pred {Numpy array} -- array with labels. Assuming 0 is bg, 1 is anterior, 2 is posterior\n\n Returns:\n A dictionary with respective volumes\n \"\"\"\n\n # TASK: Compute the volume of your hippocampal prediction\n # <YOUR CODE HERE>\n anterior_vol, posterior_vol = 0, 0\n for i in range(pred.shape[0]):\n for j in range(pred.shape[1]):\n for k in range(pred.shape[2]):\n if pred[i, j, k] == 1:\n anterior_vol += 1\n elif pred[i, j, k] == 2:\n posterior_vol += 1\n total_vol = anterior_vol + posterior_vol\n return {\"anterior\": anterior_vol, \"posterior\": posterior_vol, \"total\": total_vol}\n\ndef create_report(inference, header, orig_vol, pred_vol):\n \"\"\"Generates an image with inference report\n\n Arguments:\n inference {Dictionary} -- dict containing anterior, posterior and full volume values\n header {PyDicom Dataset} -- DICOM header\n orig_vol {Numpy array} -- original volume\n pred_vol {Numpy array} -- predicted label\n\n Returns:\n PIL image\n \"\"\"\n\n # The code below uses PIL image library to compose an RGB image that will go into the report\n # A standard way of storing measurement data in DICOM archives is creating such report and\n # sending them on as Secondary Capture IODs (http://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_A.8.html)\n # Essentially, our report is just a standard RGB image, with some metadata, packed into\n # DICOM format.\n\n pimg = Image.new(\"RGB\", (1000, 1000))\n draw = ImageDraw.Draw(pimg)\n\n header_font = ImageFont.truetype(\"assets/Roboto-Regular.ttf\", size=40)\n main_font = ImageFont.truetype(\"assets/Roboto-Regular.ttf\", size=20)\n\n slice_nums = [orig_vol.shape[2]//3, orig_vol.shape[2]//2, orig_vol.shape[2]*3//4] # is there a better choice?\n\n # TASK: Create the report here and show information that you think would be relevant to\n # clinicians. A sample code is provided below, but feel free to use your creative\n # genius to make if shine. After all, the is the only part of all our machine learning\n # efforts that will be visible to the world. The usefulness of your computations will largely\n # depend on how you present them.\n\n # SAMPLE CODE BELOW: UNCOMMENT AND CUSTOMIZE\n draw.text((10, 0), \"HippoVolume.AI\", (255, 255, 255), font=header_font)\n draw.multiline_text((10, 90),\n f\"Patient ID: {header.PatientID}\\n Hippocampal total volume: {inference['total']}\\n Anterior volume: {inference['anterior']}\\n Posterior volume: {inference['posterior']}\",\n (255, 255, 255), font=main_font)\n\n # STAND-OUT SUGGESTION:\n # In addition to text data in the snippet above, can you show some images?\n # Think, what would be relevant to show? Can you show an overlay of mask on top of original data?\n # Hint: here's one way to convert a numpy array into a PIL image and draw it inside our pimg object:\n #\n # Create a PIL image from array:\n # Numpy array needs to flipped, transposed and normalized to a matrix of values in the range of [0..255]\n nd_img = np.flip((orig_vol[slice_nums[0],:,:]/np.max(orig_vol))*0xff).T.astype(np.uint8)\n # This is how you create a PIL image from numpy array\n pil_i = Image.fromarray(nd_img, mode=\"L\").convert(\"RGBA\").resize(nd_img.shape)\n # Paste the PIL image into our main report image object (pimg)\n pimg.paste(pil_i, box=(10, 280))\n return pimg\n\ndef save_report_as_dcm(header, report, path):\n \"\"\"Writes the supplied image as a DICOM Secondary Capture file\n\n Arguments:\n header {PyDicom Dataset} -- original DICOM file header\n report {PIL image} -- image representing the report\n path {Where to save the report}\n\n Returns:\n N/A\n \"\"\"\n\n # Code below creates a DICOM Secondary Capture instance that will be correctly\n # interpreted by most imaging viewers including our OHIF\n # The code here is complete as it is unlikely that as a data scientist you will\n # have to dive that deep into generating DICOMs. However, if you still want to understand\n # the subject, there are some suggestions below\n\n # Set up DICOM metadata fields. Most of them will be the same as original file header\n out = pydicom.Dataset(header)\n\n out.file_meta = pydicom.Dataset()\n out.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian\n\n # STAND OUT SUGGESTION:\n # If you want to understand better the generation of valid DICOM, remove everything below\n # and try writing your own DICOM generation code from scratch.\n # Refer to this part of the standard to see what are the requirements for the valid\n # Secondary Capture IOD: http://dicom.nema.org/medical/dicom/2019e/output/html/part03.html#sect_A.8\n # The Modules table (A.8-1) contains a list of modules with a notice which ones are mandatory (M)\n # and which ones are conditional (C) and which ones are user-optional (U)\n # Note that we are building an RGB image which would have three 8-bit samples per pixel\n # Also note that writing code that generates valid DICOM has a very calming effect\n # on mind and body :)\n\n out.is_little_endian = True\n out.is_implicit_VR = False\n\n # We need to change class to Secondary Capture\n out.SOPClassUID = \"1.2.840.10008.5.1.4.1.1.7\"\n out.file_meta.MediaStorageSOPClassUID = out.SOPClassUID\n\n # Our report is a separate image series of one image\n out.SeriesInstanceUID = pydicom.uid.generate_uid()\n out.SOPInstanceUID = pydicom.uid.generate_uid()\n out.file_meta.MediaStorageSOPInstanceUID = out.SOPInstanceUID\n out.Modality = \"OT\" # Other\n out.SeriesDescription = \"HippoVolume.AI\"\n\n out.Rows = report.height\n out.Columns = report.width\n\n out.ImageType = r\"DERIVED\\PRIMARY\\AXIAL\" # We are deriving this image from patient data\n out.SamplesPerPixel = 3 # we are building an RGB image.\n out.PhotometricInterpretation = \"RGB\"\n out.PlanarConfiguration = 0 # means that bytes encode pixels as R1G1B1R2G2B2... as opposed to R1R2R3...G1G2G3...\n out.BitsAllocated = 8 # we are using 8 bits/pixel\n out.BitsStored = 8\n out.HighBit = 7\n out.PixelRepresentation = 0\n\n # Set time and date\n dt = datetime.date.today().strftime(\"%Y%m%d\")\n tm = datetime.datetime.now().strftime(\"%H%M%S\")\n out.StudyDate = dt\n out.StudyTime = tm\n out.SeriesDate = dt\n out.SeriesTime = tm\n\n out.ImagesInAcquisition = 1\n\n # We empty these since most viewers will then default to auto W/L\n out.WindowCenter = \"\"\n out.WindowWidth = \"\"\n\n # Data imprinted directly into image pixels is called \"burned in annotation\"\n out.BurnedInAnnotation = \"YES\"\n\n out.PixelData = report.tobytes()\n\n pydicom.filewriter.dcmwrite(path, out, write_like_original=False)\n\ndef get_series_for_inference(path):\n \"\"\"Reads multiple series from one folder and picks the one\n to run inference on.\n\n Arguments:\n path {string} -- location of the DICOM files\n\n Returns:\n Numpy array representing the series\n \"\"\"\n\n # Here we are assuming that path is a directory that contains a full study as a collection\n # of files\n # We are reading all files into a list of PyDicom objects so that we can filter them later\n #dicoms = [pydicom.dcmread(os.path.join(path, f)) for f in os.listdir(path)]\n dicoms = []\n for _ , subdirs, _ in os.walk(path):\n for subdir in subdirs:\n dicoms.extend([pydicom.dcmread(os.path.join(path, subdir, f)) for f in os.listdir(os.path.join(path, subdir))])\n\n # TASK: create a series_for_inference variable that will contain a list of only\n # those PyDicom objects that represent files that belong to the series that you\n # will run inference on.\n # It is important to note that radiological modalities most often operate in terms\n # of studies, and it will most likely be on you to establish criteria for figuring\n # out which one of the multiple series sent by the scanner is the one you need to feed to\n # your algorithm. In our case it's rather easy - we have reached an agreement with\n # people who configured the HippoCrop tool and they label the output of their tool in a\n # certain way. Can you figure out which is that?\n # Hint: inspect the metadata of HippoCrop series\n\n # <YOUR CODE HERE>\n series_for_inference = [d for d in dicoms if d.SeriesDescription==\"HippoCrop\"]\n\n # Check if there are more than one series (using set comprehension).\n if len({f.SeriesInstanceUID for f in series_for_inference}) != 1:\n print(\"Error: can not figure out what series to run inference on\")\n return []\n\n return series_for_inference\n\ndef os_command(command):\n # Comment this if running under Windows\n sp = subprocess.Popen([\"/bin/bash\", \"-i\", \"-c\", command])\n sp.communicate()\n\n # Uncomment this if running under Windows\n # os.system(command)\n\nif __name__ == \"__main__\":\n # This code expects a single command line argument with link to the directory containing\n # routed studies\n if len(sys.argv) != 2:\n print(\"You should supply one command line argument pointing to the routing folder. Exiting.\")\n sys.exit()\n\n # Find all subdirectories within the supplied directory. We assume that\n # one subdirectory contains a full study\n subdirs = [os.path.join(sys.argv[1], d) for d in os.listdir(sys.argv[1]) if\n os.path.isdir(os.path.join(sys.argv[1], d))]\n\n # Get the latest directory\n study_dir = sorted(subdirs, key=lambda dir: os.stat(dir).st_mtime, reverse=True)[0]\n\n print(f\"Looking for series to run inference on in directory {study_dir}...\")\n\n # TASK: get_series_for_inference is not complete. Go and complete it\n volume, header = load_dicom_volume_as_numpy_from_list(get_series_for_inference(study_dir))\n print(f\"Found series of {volume.shape[2]} axial slices\")\n\n print(\"HippoVolume.AI: Running inference...\")\n # TASK: Use the UNetInferenceAgent class and model parameter file from the previous section\n inference_agent = UNetInferenceAgent(\n device=\"cpu\",\n parameter_file_path=r\"../../section2/out/2020-05-23_1212_Basic_unet/model.pth\")\n\n # Run inference\n # TASK: single_volume_inference_unpadded takes a volume of arbitrary size\n # and reshapes y and z dimensions to the patch size used by the model before\n # running inference. Your job is to implement it.\n pred_label = inference_agent.single_volume_inference_unpadded(np.array(volume))\n # TASK: get_predicted_volumes is not complete. Go and complete it\n pred_volumes = get_predicted_volumes(pred_label)\n\n # Create and save the report\n print(\"Creating and pushing report...\")\n report_save_path = r\"../out/report.dcm\"\n # TASK: create_report is not complete. Go and complete it.\n # STAND OUT SUGGESTION: save_report_as_dcm has some suggestions if you want to expand your\n # knowledge of DICOM format\n report_img = create_report(pred_volumes, header, volume, pred_label)\n save_report_as_dcm(header, report_img, report_save_path)\n\n # Send report to our storage archive\n # TASK: Write a command line string that will issue a DICOM C-STORE request to send our report\n # to our Orthanc server (that runs on port 4242 of the local machine), using storescu tool\n os_command(\"storescu localhost 4242 -v -aec HIPPOAI +r +sd ../out/report.dcm\")\n\n # This line will remove the study dir if run as root user\n # Sleep to let our StoreSCP server process the report (remember - in our setup\n # the main archive is routing everyting that is sent to it, including our freshly generated\n # report) - we want to give it time to save before cleaning it up\n time.sleep(2)\n shutil.rmtree(study_dir, onerror=lambda f, p, e: print(f\"Error deleting: {e[1]}\"))\n\n print(f\"Inference successful on {header['SOPInstanceUID'].value}, out: {pred_label.shape}\",\n f\"volume ant: {pred_volumes['anterior']}, \",\n f\"volume post: {pred_volumes['posterior']}, total volume: {pred_volumes['total']}\")" ]
[ [ "numpy.max", "numpy.array", "numpy.flip", "numpy.stack" ] ]
airicbear/calculus-homework
[ "a765d3ba35b2b3794b9b2cce038152682eeb2cb8" ]
[ "2019-05/figures/595_25.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Plot the function\nf = lambda x: x ** 3 - 3 * x + 1\nxp = np.linspace(-2, 2, 100)\nplt.plot(xp, f(xp))\nplt.xlabel('x')\nplt.ylabel('f(x)')\n\n# Plot extrema and points of inflection\nx = np.array([-1, 0, 1])\ny = np.array([f(i) for i in x])\nplt.scatter(x, y)\nfor i in x:\n plt.annotate('({}, {})'.format(i, f(i)), [i, f(i)])\n\nplt.savefig('595_25')\nplt.show()\n\n" ]
[ [ "matplotlib.pyplot.scatter", "numpy.linspace", "matplotlib.pyplot.savefig", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
saketkattu/Handwritting-to-Text-Converter
[ "854203eec564f4620aa9d8870d7e4bcd449c45c1" ]
[ "text-convertor/text_recoginzer/models/transformer_util.py" ]
[ "\"\"\"Position Encoding and other utilities for Tranformers\"\"\"\nimport math\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\n\n\n\n\nclass PositionalEncoding(torch.nn.Module):\n \"\"\"Classic Attention-is-all-you-need positional encoding.\"\"\"\n\n def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000) -> None:\n super().__init__()\n self.dropout = torch.nn.Dropout(p=dropout)\n pe = self.make_pe(d_model=d_model, max_len=max_len) # (max_len, 1, d_model)\n self.register_buffer(\"pe\", pe)\n\n @staticmethod\n def make_pe(d_model: int, max_len: int) -> torch.Tensor:\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(1)\n return pe\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n # x.shape = (S, B, d_model)\n assert x.shape[2] == self.pe.shape[2] # type: ignore\n x = x + self.pe[: x.size(0)] # type: ignore\n return self.dropout(x)\n\n\ndef generate_square_subsequent_mask(size: int) -> torch.Tensor:\n \"\"\"Generate a triangular (size, size) mask.\"\"\"\n mask = (torch.triu(torch.ones(size, size)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float(\"-inf\")).masked_fill(mask == 1, float(0.0))\n return mask" ]
[ [ "torch.nn.Dropout", "torch.ones", "torch.sin", "torch.zeros", "torch.arange", "torch.cos" ] ]
imnotk/Octave-convolution-sonnet
[ "fe040ae8752a6cbba27300ef44d6a8d8195ee4a3" ]
[ "resnet.py" ]
[ "import tensorflow as tf \nimport sonnet as snt \n\nfrom octave_conv import OctaveUnit2d\nfrom octave_conv import unit2d\n\nclass basicblock(snt.AbstractModule):\n\n expansion = 1\n def __init__(self,depth=64,stride=(1,1),ratio=0.5, is_first = False,name='bottleneck'):\n super(basicblock,self).__init__(name=name)\n self._depth = depth\n self._stride = stride\n self._ratio = ratio\n self._is_first = is_first\n\n def _build(self,inputs,is_training):\n \n if self._is_first is False:\n shortcut = inputs\n else:\n shortcut = OctaveUnit2d(output_channels=self._depth,kernel_shape=(1,1),ratio=self._ratio,stride=self._stride,activation_fn=None,name='shortcut')(inputs,is_training=is_training)\n\n residual = OctaveUnit2d(output_channels=self._depth,kernel_shape=(3,3),ratio=self._ratio,stride=self._stride,name='conv1')(inputs,is_training=is_training)\n residual = OctaveUnit2d(output_channels=self._depth,kernel_shape=(3,3),ratio=self._ratio,activation_fn=None,name='conv2')(residual,is_training=is_training)\n\n shortcut_h, shortcut_l = shortcut if type(shortcut) is tuple else (shortcut, None)\n residual_h, residual_l = shortcut if type(residual) is tuple else (residual, None)\n\n out_h = tf.nn.relu(shortcut_h + residual_h)\n out_l = tf.nn.relu(shortcut_l + residual_l) if shortcut_l is not None and residual_l is not None else None\n\n return out_h if out_l is None else (out_h, out_l)\n\nclass bottleneck(snt.AbstractModule):\n\n expansion = 4\n def __init__(self,depth=64,tride=(1,1),ratio=0.5,is_first = False,name='bottleneck'):\n super(bottleneck,self).__init__(name=name)\n self._depth = depth\n self._stride = stride\n self._ratio = ratio\n self._is_fisrt = is_first\n\n def _build(self,inputs,is_training):\n \n if self._is_fisrt is False:\n shortcut = inputs\n else:\n shortcut = OctaveUnit2d(output_channels=self._depth * self.expansion,kernel_shape=(1,1),ratio=self._ratio,stride=self._stride,activation_fn=None,name='shortcut')(inputs,is_training=is_training)\n\n residual = OctaveUnit2d(output_channels=self._depth,kernel_shape=(1,1),ratio=self._ratio,stride=self._stride,name='conv1')(inputs,is_training=is_training)\n residual = OctaveUnit2d(output_channels=self._depth,kernel_shape=(3,3),ratio=self._ratio,name='conv2')(residual,is_training=is_training)\n residual = OctaveUnit2d(output_channels=self._depth * self.expansion,kernel_shape=(1,1),ratio=self._ratio,activation_fn=None,name='conv3')(residual,is_training=is_training)\n\n out = tf.nn.relu(shortcut + residual)\n return out\n\nclass Resnet(snt.AbstractModule):\n\n VALID_ENDPOINTS = (\n 'conv1',\n 'pool1',\n 'block1',\n 'block2',\n 'block3',\n 'block4',\n 'logits',\n 'Predictions'\n )\n\n def __init__(self,num_classes = 1000, block = basicblock, ratio=0.25,spatia_squeeze = True,unit_num = [2,2,2,2],\n final_endpoint = 'logits',name = 'resnet_v1_18'):\n if final_endpoint not in self.VALID_ENDPOINTS:\n raise ValueError('Unknown final endpoint %s' % final_endpoint)\n\n super(Resnet, self).__init__(name = name)\n self._num_classes = num_classes\n self._spatia_squeeze = spatia_squeeze\n self._final_endpoint = final_endpoint\n self._unit_num = unit_num\n self._block = block\n self._ratio = ratio\n\n def _build(self, inputs ,is_training ,dropout_keep_prob = 0.5):\n if self._final_endpoint not in self.VALID_ENDPOINTS:\n raise ValueError('Unknown final endpoint %s' % self._final_endpoint)\n\n net = inputs\n end_points = {}\n end_point = 'conv1'\n net = unit2d(output_channels=64,kernel_shape=[7,7],\n stride=[2,2],name = end_point)(net,is_training=is_training)\n\n end_points[end_point] = net\n if self._final_endpoint == end_point: return net,end_points\n end_point = 'pool1'\n net = tf.nn.max_pool(net,ksize=(1,3,3,1),strides=(1,2,2,1),\n padding=snt.SAME,name=end_point)\n end_points[end_point] = net\n if self._final_endpoint == end_point: return net, end_points\n \n end_point = 'block1'\n with tf.variable_scope(end_point):\n num_units = self._unit_num[0]\n for i in range(num_units):\n with tf.variable_scope('unit_%d' % (i+1)):\n if i != 0:\n net = self._block(depth=64,stride=1,ratio=self._ratio )(net,is_training=is_training )\n\n else:\n net = self._block(depth=64,stride=1,ratio=self._ratio, is_first=True )(net,is_training=is_training )\n\n end_points[end_point] = net\n if self._final_endpoint == end_point: return net,end_points\n\n end_point = 'block2'\n with tf.variable_scope(end_point):\n num_units = self._unit_num[1]\n for i in range (num_units):\n with tf.variable_scope ('unit_%d' % (i + 1)):\n if i != 0:\n net = self._block (depth=128, stride=1, ratio=self._ratio ) (net, is_training=is_training )\n \n else:\n net = self._block (depth=128, stride=2,ratio=self._ratio, is_first=True ) (net, is_training=is_training )\n \n end_points[end_point] = net\n if self._final_endpoint == end_point: return net, end_points\n\n end_point = 'block3'\n with tf.variable_scope(end_point):\n num_units = self._unit_num[2]\n for i in range (num_units):\n with tf.variable_scope ('unit_%d' % (i + 1)):\n if i != 0:\n net = self._block (depth=256,stride=1,ratio=self._ratio ) (net, is_training=is_training )\n \n else:\n net = self._block (depth=256, stride=2,ratio=self._ratio, is_first=True ) (net, is_training=is_training )\n \n end_points[end_point] = net\n if self._final_endpoint == end_point: return net, end_points\n\n end_point = 'block4'\n with tf.variable_scope(end_point):\n num_units = self._unit_num[3]\n for i in range (num_units):\n with tf.variable_scope ('unit_%d' % (i + 1)):\n if i != 0:\n net = self._block (depth=512, stride=1, ratio=0 ) (net, is_training=is_training )\n \n else:\n net = self._block (depth=512, stride=2, is_first=True, ratio=0 ) (net, is_training=is_training )\n \n end_points[end_point] = net\n if self._final_endpoint == end_point: return net, end_points\n \n \n _,h,w,_ = net.shape.as_list()\n net = tf.nn.avg_pool(net,(1,h,w,1),strides=(1,1,1,1),padding=snt.VALID)\n\n with tf.variable_scope('logits'):\n logits = snt.Conv2D(self._num_classes,kernel_shape=(1,1),use_bias=True)(net)\n \n logits = tf.squeeze(logits,axis=[1,2])\n\n return logits, end_points\n\ndef Resnet18(num_classes = 1000, block = basicblock, ratio=0.25,unit_num = [2,2,2,2],name='resnet_v1_18'):\n\n return Resnet(num_classes=num_classes,block=block,ratio=ratio,unit_num=unit_num,name=name)\n\ndef Resnet18(num_classes = 1000, block = basicblock, ratio=0.25,unit_num = [3,4,6,3],name='resnet_v1_34'):\n\n return Resnet(num_classes=num_classes,block=block,ratio=ratio,unit_num=unit_num,name=name)\n\ndef Resnet50(num_classes = 1000, block = bottleneck, ratio=0.25,unit_num = [3,4,6,3],name='resnet_v1_50'):\n\n return Resnet(num_classes=num_classes,block=block,ratio=ratio,unit_num=unit_num,name=name)\n\ndef Resnet101(num_classes = 1000, block = bottleneck, ratio=0.25,unit_num = [3,4,23,3],name='resnet_v1_101'):\n\n return Resnet(num_classes=num_classes,block=block,ratio=ratio,unit_num=unit_num,name=name)\n\ndef Resnet152(num_classes = 1000, block = bottleneck, ratio=0.25,unit_num = [3,8,36,3],name='resnet_v1_152'):\n\n return Resnet(num_classes=num_classes,block=block,ratio=ratio,unit_num=unit_num,name=name)\n\nif __name__ == \"__main__\":\n a = tf.placeholder(tf.float32, [None,224,224,3])\n Resnet()(a,True)\n\n for i in tf.global_variables():\n print(i)" ]
[ [ "tensorflow.nn.relu", "tensorflow.nn.max_pool", "tensorflow.global_variables", "tensorflow.placeholder", "tensorflow.squeeze", "tensorflow.nn.avg_pool", "tensorflow.variable_scope" ] ]
diazona/pandas
[ "af7bdd3883c8d61e9d9388d3aa699930eee7fff8" ]
[ "pandas/tools/tests/test_util.py" ]
[ "import os\nimport locale\nimport codecs\nimport nose\n\nimport numpy as np\nfrom numpy.testing import assert_equal\n\nimport pandas as pd\nfrom pandas import date_range, Index\nimport pandas.util.testing as tm\nfrom pandas.tools.util import cartesian_product, to_numeric\n\nCURRENT_LOCALE = locale.getlocale()\nLOCALE_OVERRIDE = os.environ.get('LOCALE_OVERRIDE', None)\n\n\nclass TestCartesianProduct(tm.TestCase):\n\n def test_simple(self):\n x, y = list('ABC'), [1, 22]\n result = cartesian_product([x, y])\n expected = [np.array(['A', 'A', 'B', 'B', 'C', 'C']),\n np.array([1, 22, 1, 22, 1, 22])]\n assert_equal(result, expected)\n\n def test_datetimeindex(self):\n # regression test for GitHub issue #6439\n # make sure that the ordering on datetimeindex is consistent\n x = date_range('2000-01-01', periods=2)\n result = [Index(y).day for y in cartesian_product([x, x])]\n expected = [np.array([1, 1, 2, 2]), np.array([1, 2, 1, 2])]\n assert_equal(result, expected)\n\n\nclass TestLocaleUtils(tm.TestCase):\n\n @classmethod\n def setUpClass(cls):\n super(TestLocaleUtils, cls).setUpClass()\n cls.locales = tm.get_locales()\n\n if not cls.locales:\n raise nose.SkipTest(\"No locales found\")\n\n tm._skip_if_windows()\n\n @classmethod\n def tearDownClass(cls):\n super(TestLocaleUtils, cls).tearDownClass()\n del cls.locales\n\n def test_get_locales(self):\n # all systems should have at least a single locale\n assert len(tm.get_locales()) > 0\n\n def test_get_locales_prefix(self):\n if len(self.locales) == 1:\n raise nose.SkipTest(\"Only a single locale found, no point in \"\n \"trying to test filtering locale prefixes\")\n first_locale = self.locales[0]\n assert len(tm.get_locales(prefix=first_locale[:2])) > 0\n\n def test_set_locale(self):\n if len(self.locales) == 1:\n raise nose.SkipTest(\"Only a single locale found, no point in \"\n \"trying to test setting another locale\")\n\n if LOCALE_OVERRIDE is not None:\n lang, enc = LOCALE_OVERRIDE.split('.')\n else:\n lang, enc = 'it_CH', 'UTF-8'\n\n enc = codecs.lookup(enc).name\n new_locale = lang, enc\n\n if not tm._can_set_locale(new_locale):\n with tm.assertRaises(locale.Error):\n with tm.set_locale(new_locale):\n pass\n else:\n with tm.set_locale(new_locale) as normalized_locale:\n new_lang, new_enc = normalized_locale.split('.')\n new_enc = codecs.lookup(enc).name\n normalized_locale = new_lang, new_enc\n self.assertEqual(normalized_locale, new_locale)\n\n current_locale = locale.getlocale()\n self.assertEqual(current_locale, CURRENT_LOCALE)\n\n\nclass TestToNumeric(tm.TestCase):\n\n def test_series(self):\n s = pd.Series(['1', '-3.14', '7'])\n res = to_numeric(s)\n expected = pd.Series([1, -3.14, 7])\n tm.assert_series_equal(res, expected)\n\n s = pd.Series(['1', '-3.14', 7])\n res = to_numeric(s)\n tm.assert_series_equal(res, expected)\n\n def test_series_numeric(self):\n s = pd.Series([1, 3, 4, 5], index=list('ABCD'), name='XXX')\n res = to_numeric(s)\n tm.assert_series_equal(res, s)\n\n s = pd.Series([1., 3., 4., 5.], index=list('ABCD'), name='XXX')\n res = to_numeric(s)\n tm.assert_series_equal(res, s)\n\n # bool is regarded as numeric\n s = pd.Series([True, False, True, True],\n index=list('ABCD'), name='XXX')\n res = to_numeric(s)\n tm.assert_series_equal(res, s)\n\n def test_error(self):\n s = pd.Series([1, -3.14, 'apple'])\n with tm.assertRaises(ValueError):\n to_numeric(s, errors='raise')\n\n res = to_numeric(s, errors='ignore')\n expected = pd.Series([1, -3.14, 'apple'])\n tm.assert_series_equal(res, expected)\n\n res = to_numeric(s, errors='coerce')\n expected = pd.Series([1, -3.14, np.nan])\n tm.assert_series_equal(res, expected)\n\n def test_error_seen_bool(self):\n s = pd.Series([True, False, 'apple'])\n with tm.assertRaises(ValueError):\n to_numeric(s, errors='raise')\n\n res = to_numeric(s, errors='ignore')\n expected = pd.Series([True, False, 'apple'])\n tm.assert_series_equal(res, expected)\n\n # coerces to float\n res = to_numeric(s, errors='coerce')\n expected = pd.Series([1., 0., np.nan])\n tm.assert_series_equal(res, expected)\n\n def test_list(self):\n s = ['1', '-3.14', '7']\n res = to_numeric(s)\n expected = np.array([1, -3.14, 7])\n tm.assert_numpy_array_equal(res, expected)\n\n def test_list_numeric(self):\n s = [1, 3, 4, 5]\n res = to_numeric(s)\n tm.assert_numpy_array_equal(res, np.array(s, dtype=np.int64))\n\n s = [1., 3., 4., 5.]\n res = to_numeric(s)\n tm.assert_numpy_array_equal(res, np.array(s))\n\n # bool is regarded as numeric\n s = [True, False, True, True]\n res = to_numeric(s)\n tm.assert_numpy_array_equal(res, np.array(s))\n\n def test_numeric(self):\n s = pd.Series([1, -3.14, 7], dtype='O')\n res = to_numeric(s)\n expected = pd.Series([1, -3.14, 7])\n tm.assert_series_equal(res, expected)\n\n s = pd.Series([1, -3.14, 7])\n res = to_numeric(s)\n tm.assert_series_equal(res, expected)\n\n def test_all_nan(self):\n s = pd.Series(['a', 'b', 'c'])\n res = to_numeric(s, errors='coerce')\n expected = pd.Series([np.nan, np.nan, np.nan])\n tm.assert_series_equal(res, expected)\n\n def test_type_check(self):\n # GH 11776\n df = pd.DataFrame({'a': [1, -3.14, 7], 'b': ['4', '5', '6']})\n with tm.assertRaisesRegexp(TypeError, \"1-d array\"):\n to_numeric(df)\n for errors in ['ignore', 'raise', 'coerce']:\n with tm.assertRaisesRegexp(TypeError, \"1-d array\"):\n to_numeric(df, errors=errors)\n\n def test_scalar(self):\n self.assertEqual(pd.to_numeric(1), 1)\n self.assertEqual(pd.to_numeric(1.1), 1.1)\n\n self.assertEqual(pd.to_numeric('1'), 1)\n self.assertEqual(pd.to_numeric('1.1'), 1.1)\n\n with tm.assertRaises(ValueError):\n to_numeric('XX', errors='raise')\n\n self.assertEqual(to_numeric('XX', errors='ignore'), 'XX')\n self.assertTrue(np.isnan(to_numeric('XX', errors='coerce')))\n\n def test_numeric_dtypes(self):\n idx = pd.Index([1, 2, 3], name='xxx')\n res = pd.to_numeric(idx)\n tm.assert_index_equal(res, idx)\n\n res = pd.to_numeric(pd.Series(idx, name='xxx'))\n tm.assert_series_equal(res, pd.Series(idx, name='xxx'))\n\n res = pd.to_numeric(idx.values)\n tm.assert_numpy_array_equal(res, idx.values)\n\n idx = pd.Index([1., np.nan, 3., np.nan], name='xxx')\n res = pd.to_numeric(idx)\n tm.assert_index_equal(res, idx)\n\n res = pd.to_numeric(pd.Series(idx, name='xxx'))\n tm.assert_series_equal(res, pd.Series(idx, name='xxx'))\n\n res = pd.to_numeric(idx.values)\n tm.assert_numpy_array_equal(res, idx.values)\n\n def test_str(self):\n idx = pd.Index(['1', '2', '3'], name='xxx')\n exp = np.array([1, 2, 3], dtype='int64')\n res = pd.to_numeric(idx)\n tm.assert_index_equal(res, pd.Index(exp, name='xxx'))\n\n res = pd.to_numeric(pd.Series(idx, name='xxx'))\n tm.assert_series_equal(res, pd.Series(exp, name='xxx'))\n\n res = pd.to_numeric(idx.values)\n tm.assert_numpy_array_equal(res, exp)\n\n idx = pd.Index(['1.5', '2.7', '3.4'], name='xxx')\n exp = np.array([1.5, 2.7, 3.4])\n res = pd.to_numeric(idx)\n tm.assert_index_equal(res, pd.Index(exp, name='xxx'))\n\n res = pd.to_numeric(pd.Series(idx, name='xxx'))\n tm.assert_series_equal(res, pd.Series(exp, name='xxx'))\n\n res = pd.to_numeric(idx.values)\n tm.assert_numpy_array_equal(res, exp)\n\n def test_datetimelike(self):\n for tz in [None, 'US/Eastern', 'Asia/Tokyo']:\n idx = pd.date_range('20130101', periods=3, tz=tz, name='xxx')\n res = pd.to_numeric(idx)\n tm.assert_index_equal(res, pd.Index(idx.asi8, name='xxx'))\n\n res = pd.to_numeric(pd.Series(idx, name='xxx'))\n tm.assert_series_equal(res, pd.Series(idx.asi8, name='xxx'))\n\n res = pd.to_numeric(idx.values)\n tm.assert_numpy_array_equal(res, idx.asi8)\n\n def test_timedelta(self):\n idx = pd.timedelta_range('1 days', periods=3, freq='D', name='xxx')\n res = pd.to_numeric(idx)\n tm.assert_index_equal(res, pd.Index(idx.asi8, name='xxx'))\n\n res = pd.to_numeric(pd.Series(idx, name='xxx'))\n tm.assert_series_equal(res, pd.Series(idx.asi8, name='xxx'))\n\n res = pd.to_numeric(idx.values)\n tm.assert_numpy_array_equal(res, idx.asi8)\n\n def test_period(self):\n idx = pd.period_range('2011-01', periods=3, freq='M', name='xxx')\n res = pd.to_numeric(idx)\n tm.assert_index_equal(res, pd.Index(idx.asi8, name='xxx'))\n\n # ToDo: enable when we can support native PeriodDtype\n # res = pd.to_numeric(pd.Series(idx, name='xxx'))\n # tm.assert_series_equal(res, pd.Series(idx.asi8, name='xxx'))\n\n\nif __name__ == '__main__':\n nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],\n exit=False)\n" ]
[ [ "pandas.util.testing._can_set_locale", "pandas.Series", "pandas.util.testing._skip_if_windows", "pandas.DataFrame", "pandas.util.testing.set_locale", "pandas.util.testing.assert_index_equal", "numpy.testing.assert_equal", "pandas.util.testing.get_locales", "pandas.util.testing.assert_numpy_array_equal", "pandas.util.testing.assert_series_equal", "pandas.Index", "pandas.tools.util.to_numeric", "pandas.to_numeric", "pandas.tools.util.cartesian_product", "pandas.date_range", "numpy.array", "pandas.timedelta_range", "pandas.period_range", "pandas.util.testing.assertRaisesRegexp", "pandas.util.testing.assertRaises" ] ]
mtar/heat
[ "35aac8c0aaafa2dcb350ad86514e61da9ee05a50" ]
[ "heat/core/tests/test_tiling.py" ]
[ "import torch\n\nimport heat as ht\nfrom .test_suites.basic_test import TestCase\n\n\nclass TestSplitTiles(TestCase):\n # most of the cases are covered by the resplit tests\n def test_raises(self):\n length = torch.tensor([i + 20 for i in range(2)], device=self.device.torch_device)\n test = torch.arange(\n torch.prod(length), dtype=torch.float64, device=self.device.torch_device\n ).reshape([i + 20 for i in range(2)])\n a = ht.array(test, split=1)\n tiles = ht.tiling.SplitTiles(a)\n with self.assertRaises(TypeError):\n tiles[\"p\"]\n with self.assertRaises(TypeError):\n tiles[0] = \"p\"\n with self.assertRaises(TypeError):\n tiles[\"p\"] = \"p\"\n\n def test_misc_coverage(self):\n length = torch.tensor([i + 5 for i in range(3)], device=self.device.torch_device)\n test = torch.arange(\n torch.prod(length), dtype=torch.float64, device=self.device.torch_device\n ).reshape([i + 5 for i in range(3)])\n a = ht.array(test, split=None)\n tiles = ht.tiling.SplitTiles(a)\n self.assertTrue(torch.all(tiles.tile_locations == a.comm.rank))\n a = ht.resplit(a, 0)\n tiles = ht.tiling.SplitTiles(a)\n if a.comm.size == 3:\n # definition of adjusting tests is he same logic as the code itself,\n # therefore, fixed tests are issued for one process confic\n tile_dims = torch.tensor(\n [[2.0, 2.0, 1.0], [2.0, 2.0, 2.0], [3.0, 2.0, 2.0]], device=self.device.torch_device\n )\n res = tiles.tile_dimensions\n self.assertTrue(torch.equal(tile_dims, res))\n testing_tensor = torch.tensor(\n [\n [\n [168.0, 169.0, 170.0, 171.0, 172.0, 173.0, 174.0],\n [175.0, 176.0, 177.0, 178.0, 179.0, 180.0, 181.0],\n [182.0, 183.0, 184.0, 185.0, 186.0, 187.0, 188.0],\n [189.0, 190.0, 191.0, 192.0, 193.0, 194.0, 195.0],\n [196.0, 197.0, 198.0, 199.0, 200.0, 201.0, 202.0],\n [203.0, 204.0, 205.0, 206.0, 207.0, 208.0, 209.0],\n ]\n ],\n dtype=torch.float64,\n )\n if a.comm.rank == 2:\n self.assertTrue(torch.equal(tiles[2], testing_tensor))\n tiles[2] = 1000\n sl = tiles[2]\n if a.comm.rank == 2:\n self.assertEqual(torch.Size([1, 6, 7]), sl.shape)\n self.assertTrue(torch.all(sl == 1000))\n else:\n self.assertTrue(sl is None)\n\n\nclass TestSquareDiagTiles(TestCase):\n # arrs = (m_eq_n_s0, m_eq_n_s1, m_gr_n_s0, m_gr_n_s1, m_ls_n_s0, m_ls_n_s1)\n if ht.MPI_WORLD.size > 1:\n\n def test_init_raises(self):\n # need to test the raises here\n with self.assertRaises(TypeError):\n ht.core.tiling.SquareDiagTiles(\"sdkd\", tiles_per_proc=1)\n with self.assertRaises(TypeError):\n ht.core.tiling.SquareDiagTiles(ht.arange(2), tiles_per_proc=\"sdf\")\n with self.assertRaises(ValueError):\n ht.core.tiling.SquareDiagTiles(ht.arange(2), tiles_per_proc=0)\n with self.assertRaises(ValueError):\n ht.core.tiling.SquareDiagTiles(ht.arange(2), tiles_per_proc=1)\n\n def test_properties(self):\n # ---- m = n ------------- properties ------ s0 -----------\n m_eq_n_s0 = ht.random.randn(47, 47, split=0)\n # m_eq_n_s0.create_square_diag_tiles(tiles_per_proc=1)\n m_eq_n_s0_t1 = ht.tiling.SquareDiagTiles(m_eq_n_s0, tiles_per_proc=1)\n m_eq_n_s0_t2 = ht.tiling.SquareDiagTiles(m_eq_n_s0, tiles_per_proc=2)\n # arr\n self.assertTrue(ht.equal(m_eq_n_s0_t1.arr, m_eq_n_s0))\n self.assertTrue(ht.equal(m_eq_n_s0_t2.arr, m_eq_n_s0))\n # lshape_map\n self.assertTrue(torch.equal(m_eq_n_s0_t1.lshape_map, m_eq_n_s0.create_lshape_map()))\n self.assertTrue(torch.equal(m_eq_n_s0_t2.lshape_map, m_eq_n_s0.create_lshape_map()))\n\n if m_eq_n_s0.comm.size == 3:\n # col_inds\n self.assertEqual(m_eq_n_s0_t1.col_indices, [0, 16, 32])\n self.assertEqual(m_eq_n_s0_t2.col_indices, [0, 8, 16, 24, 32, 40])\n # row inds\n self.assertEqual(m_eq_n_s0_t1.row_indices, [0, 16, 32])\n self.assertEqual(m_eq_n_s0_t2.row_indices, [0, 8, 16, 24, 32, 40])\n # tile cols per proc\n self.assertEqual(m_eq_n_s0_t1.tile_columns_per_process, [3, 3, 3])\n self.assertEqual(m_eq_n_s0_t2.tile_columns_per_process, [6, 6, 6])\n # tile rows per proc\n self.assertEqual(m_eq_n_s0_t1.tile_rows_per_process, [1, 1, 1])\n self.assertEqual(m_eq_n_s0_t2.tile_rows_per_process, [2, 2, 2])\n # last diag pr\n self.assertEqual(m_eq_n_s0_t1.last_diagonal_process, m_eq_n_s0.comm.size - 1)\n self.assertEqual(m_eq_n_s0_t2.last_diagonal_process, m_eq_n_s0.comm.size - 1)\n # tile cols\n self.assertEqual(m_eq_n_s0_t1.tile_columns, m_eq_n_s0.comm.size)\n self.assertEqual(m_eq_n_s0_t2.tile_columns, m_eq_n_s0.comm.size * 2)\n # tile rows\n self.assertEqual(m_eq_n_s0_t1.tile_rows, m_eq_n_s0.comm.size)\n self.assertEqual(m_eq_n_s0_t2.tile_rows, m_eq_n_s0.comm.size * 2)\n\n # ---- m = n ------------- properties ------ s1 -----------\n m_eq_n_s1 = ht.random.randn(47, 47, split=1)\n m_eq_n_s1_t1 = ht.core.tiling.SquareDiagTiles(m_eq_n_s1, tiles_per_proc=1)\n m_eq_n_s1_t2 = ht.core.tiling.SquareDiagTiles(m_eq_n_s1, tiles_per_proc=2)\n # lshape_map\n self.assertTrue(torch.equal(m_eq_n_s1_t1.lshape_map, m_eq_n_s1.create_lshape_map()))\n self.assertTrue(torch.equal(m_eq_n_s1_t2.lshape_map, m_eq_n_s1.create_lshape_map()))\n\n if m_eq_n_s1.comm.size == 3:\n # col_inds\n self.assertEqual(m_eq_n_s1_t1.col_indices, [0, 16, 32])\n self.assertEqual(m_eq_n_s1_t2.col_indices, [0, 8, 16, 24, 32, 40])\n # row inds\n self.assertEqual(m_eq_n_s1_t1.row_indices, [0, 16, 32])\n self.assertEqual(m_eq_n_s1_t2.row_indices, [0, 8, 16, 24, 32, 40])\n # tile cols per proc\n self.assertEqual(m_eq_n_s1_t1.tile_columns_per_process, [1, 1, 1])\n self.assertEqual(m_eq_n_s1_t2.tile_columns_per_process, [2, 2, 2])\n # tile rows per proc\n self.assertEqual(m_eq_n_s1_t1.tile_rows_per_process, [3, 3, 3])\n self.assertEqual(m_eq_n_s1_t2.tile_rows_per_process, [6, 6, 6])\n # last diag pr\n self.assertEqual(m_eq_n_s1_t1.last_diagonal_process, m_eq_n_s1.comm.size - 1)\n self.assertEqual(m_eq_n_s1_t2.last_diagonal_process, m_eq_n_s1.comm.size - 1)\n # tile cols\n self.assertEqual(m_eq_n_s1_t1.tile_columns, m_eq_n_s1.comm.size)\n self.assertEqual(m_eq_n_s1_t2.tile_columns, m_eq_n_s1.comm.size * 2)\n # tile rows\n self.assertEqual(m_eq_n_s1_t1.tile_rows, m_eq_n_s1.comm.size)\n self.assertEqual(m_eq_n_s1_t2.tile_rows, m_eq_n_s1.comm.size * 2)\n\n # ---- m > n ------------- properties ------ s0 -----------\n m_gr_n_s0 = ht.random.randn(38, 128, split=0)\n m_gr_n_s0_t1 = ht.core.tiling.SquareDiagTiles(m_gr_n_s0, tiles_per_proc=1)\n m_gr_n_s0_t2 = ht.core.tiling.SquareDiagTiles(m_gr_n_s0, tiles_per_proc=2)\n if m_eq_n_s1.comm.size == 3:\n # col_inds\n self.assertEqual(m_gr_n_s0_t1.col_indices, [0, 13, 26])\n self.assertEqual(m_gr_n_s0_t2.col_indices, [0, 7, 13, 20, 26, 32])\n # row inds\n self.assertEqual(m_gr_n_s0_t1.row_indices, [0, 13, 26])\n self.assertEqual(m_gr_n_s0_t2.row_indices, [0, 7, 13, 20, 26, 32])\n # tile cols per proc\n self.assertEqual(m_gr_n_s0_t1.tile_columns_per_process, [3, 3, 3])\n self.assertEqual(m_gr_n_s0_t2.tile_columns_per_process, [6, 6, 6])\n # tile rows per proc\n self.assertEqual(m_gr_n_s0_t1.tile_rows_per_process, [1, 1, 1])\n self.assertEqual(m_gr_n_s0_t2.tile_rows_per_process, [2, 2, 2])\n # last diag pr\n self.assertEqual(m_gr_n_s0_t1.last_diagonal_process, m_eq_n_s1.comm.size - 1)\n self.assertEqual(m_gr_n_s0_t2.last_diagonal_process, m_eq_n_s1.comm.size - 1)\n # tile cols\n self.assertEqual(m_gr_n_s0_t1.tile_columns, m_eq_n_s1.comm.size)\n self.assertEqual(m_gr_n_s0_t2.tile_columns, m_eq_n_s1.comm.size * 2)\n # tile rows\n self.assertEqual(m_gr_n_s0_t1.tile_rows, m_eq_n_s1.comm.size)\n self.assertEqual(m_gr_n_s0_t2.tile_rows, m_eq_n_s1.comm.size * 2)\n\n # ---- m > n ------------- properties ------ s1 -----------\n m_gr_n_s1 = ht.random.randn(38, 128, split=1)\n m_gr_n_s1_t1 = ht.core.tiling.SquareDiagTiles(m_gr_n_s1, tiles_per_proc=1)\n m_gr_n_s1_t2 = ht.core.tiling.SquareDiagTiles(m_gr_n_s1, tiles_per_proc=2)\n if m_eq_n_s1.comm.size == 3:\n # col_inds\n self.assertEqual(m_gr_n_s1_t1.col_indices, [0, 38, 43, 86, 128, 171])\n self.assertEqual(m_gr_n_s1_t2.col_indices, [0, 19, 38, 43, 86, 128, 171])\n # row inds\n self.assertEqual(m_gr_n_s1_t1.row_indices, [0])\n self.assertEqual(m_gr_n_s1_t2.row_indices, [0, 19])\n # tile cols per proc\n self.assertEqual(m_gr_n_s1_t1.tile_columns_per_process, [2, 1, 1])\n self.assertEqual(m_gr_n_s1_t2.tile_columns_per_process, [3, 1, 1])\n # tile rows per proc\n self.assertEqual(m_gr_n_s1_t1.tile_rows_per_process, [1, 1, 1])\n self.assertEqual(m_gr_n_s1_t2.tile_rows_per_process, [2, 2, 2])\n # last diag pr\n self.assertEqual(m_gr_n_s1_t1.last_diagonal_process, 0)\n self.assertEqual(m_gr_n_s1_t2.last_diagonal_process, 0)\n # tile cols\n self.assertEqual(m_gr_n_s1_t1.tile_columns, 6)\n self.assertEqual(m_gr_n_s1_t2.tile_columns, 7)\n # tile rows\n self.assertEqual(m_gr_n_s1_t1.tile_rows, 1)\n self.assertEqual(m_gr_n_s1_t2.tile_rows, 2)\n\n # ---- m < n ------------- properties ------ s0 -----------\n m_ls_n_s0 = ht.random.randn(323, 49, split=0)\n m_ls_n_s0_t1 = ht.core.tiling.SquareDiagTiles(m_ls_n_s0, tiles_per_proc=1)\n m_ls_n_s0_t2 = ht.core.tiling.SquareDiagTiles(m_ls_n_s0, tiles_per_proc=2)\n if m_eq_n_s1.comm.size == 3:\n # col_inds\n self.assertEqual(m_ls_n_s0_t1.col_indices, [0])\n self.assertEqual(m_ls_n_s0_t2.col_indices, [0, 25])\n # row inds\n self.assertEqual(m_ls_n_s0_t1.row_indices, [0, 49, 109, 216])\n self.assertEqual(m_ls_n_s0_t2.row_indices, [0, 25, 49, 110, 163, 216, 270])\n # tile cols per proc\n self.assertEqual(m_ls_n_s0_t1.tile_columns_per_process, [1])\n self.assertEqual(m_ls_n_s0_t2.tile_columns_per_process, [2])\n # tile rows per proc\n self.assertEqual(m_ls_n_s0_t1.tile_rows_per_process, [2, 1, 1])\n self.assertEqual(m_ls_n_s0_t2.tile_rows_per_process, [3, 2, 2])\n # last diag pr\n self.assertEqual(m_ls_n_s0_t1.last_diagonal_process, 0)\n self.assertEqual(m_ls_n_s0_t2.last_diagonal_process, 0)\n # tile cols\n self.assertEqual(m_ls_n_s0_t1.tile_columns, 1)\n self.assertEqual(m_ls_n_s0_t2.tile_columns, 2)\n # tile rows\n self.assertEqual(m_ls_n_s0_t1.tile_rows, 4)\n self.assertEqual(m_ls_n_s0_t2.tile_rows, 7)\n\n # ---- m < n ------------- properties ------ s1 -----------\n m_ls_n_s1 = ht.random.randn(323, 49, split=1)\n m_ls_n_s1_t1 = ht.core.tiling.SquareDiagTiles(m_ls_n_s1, tiles_per_proc=1)\n m_ls_n_s1_t2 = ht.core.tiling.SquareDiagTiles(m_ls_n_s1, tiles_per_proc=2)\n if m_eq_n_s1.comm.size == 3:\n # col_inds\n self.assertEqual(m_ls_n_s1_t1.col_indices, [0, 17, 33])\n self.assertEqual(m_ls_n_s1_t2.col_indices, [0, 9, 17, 25, 33, 41])\n # row inds\n self.assertEqual(m_ls_n_s1_t1.row_indices, [0, 17, 33, 49])\n self.assertEqual(m_ls_n_s1_t2.row_indices, [0, 9, 17, 25, 33, 41, 49])\n # tile cols per proc\n self.assertEqual(m_ls_n_s1_t1.tile_columns_per_process, [1, 1, 1])\n self.assertEqual(m_ls_n_s1_t2.tile_columns_per_process, [2, 2, 2])\n # tile rows per proc\n self.assertEqual(m_ls_n_s1_t1.tile_rows_per_process, [4, 4, 4])\n self.assertEqual(m_ls_n_s1_t2.tile_rows_per_process, [7, 7, 7])\n # last diag pr\n self.assertEqual(m_ls_n_s1_t1.last_diagonal_process, 2)\n self.assertEqual(m_ls_n_s1_t2.last_diagonal_process, 2)\n # tile cols\n self.assertEqual(m_ls_n_s1_t1.tile_columns, 3)\n self.assertEqual(m_ls_n_s1_t2.tile_columns, 6)\n # tile rows\n self.assertEqual(m_ls_n_s1_t1.tile_rows, 4)\n self.assertEqual(m_ls_n_s1_t2.tile_rows, 7)\n\n def test_local_set_get(self):\n # this function will also test all of the start_stop functions and the\n # --------------------- local ----------- s0 ----------------\n # (int), (int, int), (slice, int), (slice, slice), (int, slice)\n m_eq_n_s0 = ht.zeros((25, 25), split=0)\n m_eq_n_s0_t2 = ht.core.tiling.SquareDiagTiles(m_eq_n_s0, tiles_per_proc=2)\n k = (slice(0, 10), slice(2, None))\n m_eq_n_s0_t2.local_set(key=k, value=1)\n lcl_key = m_eq_n_s0_t2.local_to_global(key=k, rank=m_eq_n_s0.comm.rank)\n st_sp = m_eq_n_s0_t2.get_start_stop(key=lcl_key)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n lcl_shape = m_eq_n_s0_t2.local_get(key=(slice(None), slice(None))).shape\n self.assertEqual(lcl_shape, m_eq_n_s0.lshape)\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n k = (1, 1)\n m_eq_n_s0_t2.local_set(key=k, value=1)\n lcl_key = m_eq_n_s0_t2.local_to_global(key=k, rank=m_eq_n_s0.comm.rank)\n st_sp = m_eq_n_s0_t2.get_start_stop(key=lcl_key)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n k = 1\n m_eq_n_s0_t2.local_set(key=k, value=1)\n lcl_key = m_eq_n_s0_t2.local_to_global(key=k, rank=m_eq_n_s0.comm.rank)\n st_sp = m_eq_n_s0_t2.get_start_stop(key=lcl_key)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n # --------------------- local ----------- s1 ----------------\n m_eq_n_s1 = ht.zeros((25, 25), split=1)\n m_eq_n_s1_t2 = ht.core.tiling.SquareDiagTiles(m_eq_n_s1, tiles_per_proc=2)\n k = (slice(0, 2), slice(0, None))\n m_eq_n_s1_t2.local_set(key=k, value=1)\n lcl_key = m_eq_n_s1_t2.local_to_global(key=k, rank=m_eq_n_s1.comm.rank)\n st_sp = m_eq_n_s1_t2.get_start_stop(key=lcl_key)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n lcl_shape = m_eq_n_s1_t2.local_get(key=(slice(None), slice(None))).shape\n self.assertEqual(lcl_shape, m_eq_n_s1.lshape)\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n if ht.MPI_WORLD.size > 2:\n k = (5, 1)\n m_eq_n_s1_t2.local_set(key=k, value=1)\n lcl_key = m_eq_n_s1_t2.local_to_global(key=k, rank=m_eq_n_s1.comm.rank)\n st_sp = m_eq_n_s1_t2.get_start_stop(key=lcl_key)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n k = 2\n m_eq_n_s1_t2.local_set(key=k, value=1)\n lcl_key = m_eq_n_s1_t2.local_to_global(key=k, rank=m_eq_n_s1.comm.rank)\n st_sp = m_eq_n_s1_t2.get_start_stop(key=lcl_key)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n # --------------------- global ---------- s0 ----------------\n m_eq_n_s0 = ht.zeros((25, 25), split=0)\n m_eq_n_s0_t2 = ht.core.tiling.SquareDiagTiles(m_eq_n_s0, tiles_per_proc=2)\n k = 2\n m_eq_n_s0_t2[k] = 1\n if m_eq_n_s0_t2[k] is not None:\n st_sp = m_eq_n_s0_t2.get_start_stop(key=k)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n if ht.MPI_WORLD.size > 2:\n k = (5, 5)\n m_eq_n_s0_t2[k] = 1\n if m_eq_n_s0_t2[k] is not None:\n st_sp = m_eq_n_s0_t2.get_start_stop(key=k)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n k = (slice(0, 2), slice(1, 5))\n m_eq_n_s0_t2[k] = 1\n if m_eq_n_s0_t2[k] is not None:\n st_sp = m_eq_n_s0_t2.get_start_stop(key=k)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s0._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n # --------------------- global ---------- s1 ----------------\n m_eq_n_s1 = ht.zeros((25, 25), split=1)\n m_eq_n_s1_t2 = ht.core.tiling.SquareDiagTiles(m_eq_n_s1, tiles_per_proc=2)\n k = (slice(0, 3), slice(0, 2))\n m_eq_n_s1_t2[k] = 1\n if m_eq_n_s1_t2[k] is not None:\n st_sp = m_eq_n_s1_t2.get_start_stop(key=k)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n # k = (slice(0, 3), slice(0, 2))\n if ht.MPI_WORLD.size > 2:\n k = (5, 5)\n m_eq_n_s1_t2[k] = 1\n if m_eq_n_s1_t2[k] is not None:\n st_sp = m_eq_n_s1_t2.get_start_stop(key=k)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n\n k = (slice(0, 3), 3)\n m_eq_n_s1_t2[k] = 1\n if m_eq_n_s1_t2[k] is not None:\n st_sp = m_eq_n_s1_t2.get_start_stop(key=k)\n sz = st_sp[1] - st_sp[0], st_sp[3] - st_sp[2]\n lcl_slice = m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]]\n self.assertTrue(torch.all(lcl_slice - torch.ones(sz) == 0))\n # reset base\n m_eq_n_s1._DNDarray__array[st_sp[0] : st_sp[1], st_sp[2] : st_sp[3]] = 0\n with self.assertRaises(ValueError):\n m_eq_n_s1_t2[1, :]\n with self.assertRaises(TypeError):\n m_eq_n_s1_t2[\"asdf\"]\n with self.assertRaises(TypeError):\n m_eq_n_s1_t2[1, \"asdf\"]\n with self.assertRaises(ValueError):\n m_eq_n_s1_t2[1, :] = 2\n with self.assertRaises(ValueError):\n m_eq_n_s1_t2.get_start_stop(key=(1, slice(None)))\n with self.assertRaises(ValueError):\n m_eq_n_s1_t2.get_start_stop(key=(1, slice(None)))\n" ]
[ [ "torch.all", "torch.Size", "torch.ones", "torch.equal", "torch.tensor", "torch.prod" ] ]