repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
TianWuYuJiangHenShou/horovod_pretraining | [
"c05b282ad0710521fbea237bad905470b25ddfc3"
] | [
"run_classifier_hvd.py"
] | [
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport csv\nimport os\nimport modeling\nimport optimization_hvd\nimport tokenization\nimport tensorflow as tf\n\nimport horovod.tensorflow as hvd\n\nflags = tf.compat.v1.flags\n\nFLAGS = flags.FLAGS\n\n## Required parameters\nflags.DEFINE_string(\n \"data_dir\", None,\n \"The input data dir. Should contain the .tsv files (or other data files) \"\n \"for the task.\")\n\nflags.DEFINE_string(\n \"bert_config_file\", None,\n \"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\")\n\nflags.DEFINE_string(\"vocab_file\", None,\n \"The vocabulary file that the BERT model was trained on.\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\n## Other parameters\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 128,\n \"The maximum total input sequence length after WordPiece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_bool(\n \"do_predict\", False,\n \"Whether to run the model in inference mode on the test set.\")\n\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\n\nflags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\")\n\nflags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\")\n\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\n \"Total number of training epochs to perform.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 1000,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\ntf.compat.v1.flags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\ntf.compat.v1.flags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.compat.v1.flags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.compat.v1.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_integer(\n \"num_tpu_cores\", 8,\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass PaddingInputExample(object):\n \"\"\"Fake example so the num input examples is a multiple of the batch size.\n\n When running eval/predict on the TPU, we need to pad the number of examples\n to be a multiple of the batch size, because the TPU requires a fixed batch\n size. The alternative is to drop the last batch, which is bad because it means\n the entire output data won't be generated.\n\n We use this class instead of `None` because treating `None` as padding\n battches could cause silent errors.\n \"\"\"\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n input_ids,\n input_mask,\n segment_ids,\n label_id,\n is_real_example=True):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n self.is_real_example = is_real_example\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_test_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for prediction.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with tf.io.gfile.GFile(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\n\nclass XnliProcessor(DataProcessor):\n \"\"\"Processor for the XNLI data set.\"\"\"\n\n def __init__(self):\n self.language = \"zh\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n lines = self._read_tsv(\n os.path.join(data_dir, \"multinli\",\n \"multinli.train.%s.tsv\" % self.language))\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"train-%d\" % (i)\n text_a = tokenization.convert_to_unicode(line[0])\n text_b = tokenization.convert_to_unicode(line[1])\n label = tokenization.convert_to_unicode(line[2])\n if label == tokenization.convert_to_unicode(\"contradictory\"):\n label = tokenization.convert_to_unicode(\"contradiction\")\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n lines = self._read_tsv(os.path.join(data_dir, \"xnli.dev.tsv\"))\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"dev-%d\" % (i)\n language = tokenization.convert_to_unicode(line[0])\n if language != tokenization.convert_to_unicode(self.language):\n continue\n text_a = tokenization.convert_to_unicode(line[6])\n text_b = tokenization.convert_to_unicode(line[7])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n\nclass MnliProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")),\n \"dev_matched\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test_matched.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, tokenization.convert_to_unicode(line[0]))\n text_a = tokenization.convert_to_unicode(line[8])\n text_b = tokenization.convert_to_unicode(line[9])\n if set_type == \"test\":\n label = \"contradiction\"\n else:\n label = tokenization.convert_to_unicode(line[-1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MrpcProcessor(DataProcessor):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[3])\n text_b = tokenization.convert_to_unicode(line[4])\n if set_type == \"test\":\n label = \"0\"\n else:\n label = tokenization.convert_to_unicode(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass ColaProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # Only the test set has a header\n if set_type == \"test\" and i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n if set_type == \"test\":\n text_a = tokenization.convert_to_unicode(line[1])\n label = \"0\"\n else:\n text_a = tokenization.convert_to_unicode(line[3])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\ndef convert_single_example(ex_index, example, label_list, max_seq_length,\n tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n\n if isinstance(example, PaddingInputExample):\n return InputFeatures(\n input_ids=[0] * max_seq_length,\n input_mask=[0] * max_seq_length,\n segment_ids=[0] * max_seq_length,\n label_id=0,\n is_real_example=False)\n\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n if ex_index < 5:\n tf.compat.v1.logging.info(\"*** Example ***\")\n tf.compat.v1.logging.info(\"guid: %s\" % (example.guid))\n tf.compat.v1.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.compat.v1.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.compat.v1.logging.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.compat.v1.logging.info(\"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n tf.compat.v1.logging.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id,\n is_real_example=True)\n return feature\n\n\ndef file_based_convert_examples_to_features(\n examples, label_list, max_seq_length, tokenizer, output_file):\n \"\"\"Convert a set of `InputExample`s to a TFRecord file.\"\"\"\n\n writer = tf.io.TFRecordWriter(output_file)\n\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.compat.v1.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n features = collections.OrderedDict()\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"label_ids\"] = create_int_feature([feature.label_id])\n features[\"is_real_example\"] = create_int_feature(\n [int(feature.is_real_example)])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n writer.close()\n\n\ndef file_based_input_fn_builder(input_file, seq_length, is_training,\n drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n name_to_features = {\n \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),\n \"label_ids\": tf.io.FixedLenFeature([], tf.int64),\n \"is_real_example\": tf.io.FixedLenFeature([], tf.int64),\n }\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.io.parse_single_example(serialized=record, features=name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.cast(t, dtype=tf.int32)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n labels, num_labels, use_one_hot_embeddings):\n \"\"\"Creates a classification model.\"\"\"\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # In the demo, we are doing a simple classification task on the entire\n # segment.\n #\n # If you want to use the token-level output, use model.get_sequence_output()\n # instead.\n output_layer = model.get_pooled_output()\n\n hidden_size = output_layer.shape[-1].value\n\n output_weights = tf.compat.v1.get_variable(\n \"output_weights\", [num_labels, hidden_size],\n initializer=tf.compat.v1.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.compat.v1.get_variable(\n \"output_bias\", [num_labels], initializer=tf.compat.v1.zeros_initializer())\n\n with tf.compat.v1.variable_scope(\"loss\"):\n if is_training:\n # I.e., 0.1 dropout\n output_layer = tf.nn.dropout(output_layer, rate=1 - (0.9))\n\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n probabilities = tf.nn.softmax(logits, axis=-1)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n per_example_loss = -tf.reduce_sum(input_tensor=one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(input_tensor=per_example_loss)\n\n return (loss, per_example_loss, logits, probabilities)\n\n\ndef model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n tf.compat.v1.logging.info(\"*** Features ***\")\n for name in sorted(features.keys()):\n tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n label_ids = features[\"label_ids\"]\n is_real_example = None\n if \"is_real_example\" in features:\n is_real_example = tf.cast(features[\"is_real_example\"], dtype=tf.float32)\n else:\n is_real_example = tf.ones(tf.shape(input=label_ids), dtype=tf.float32)\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n (total_loss, per_example_loss, logits, probabilities) = create_model(\n bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,\n num_labels, use_one_hot_embeddings)\n\n tvars = tf.compat.v1.trainable_variables()\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map, initialized_variable_names\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n if use_tpu:\n\n def tpu_scaffold():\n tf.compat.v1.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.compat.v1.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.compat.v1.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n tf.compat.v1.logging.info(\"**** Trainable Variables ****\")\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n init_string)\n\n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n\n train_op = optimization_hvd.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tf.compat.v1.estimator.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n elif mode == tf.estimator.ModeKeys.EVAL:\n\n def metric_fn(per_example_loss, label_ids, logits, is_real_example):\n predictions = tf.argmax(input=logits, axis=-1, output_type=tf.int32)\n accuracy = tf.compat.v1.metrics.accuracy(\n labels=label_ids, predictions=predictions, weights=is_real_example)\n loss = tf.compat.v1.metrics.mean(values=per_example_loss, weights=is_real_example)\n return {\n \"eval_accuracy\": accuracy,\n \"eval_loss\": loss,\n }\n\n eval_metrics = (metric_fn,\n [per_example_loss, label_ids, logits, is_real_example])\n output_spec = tf.compat.v1.estimator.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n eval_metrics=eval_metrics,\n scaffold_fn=scaffold_fn)\n else:\n output_spec = tf.compat.v1.estimator.tpu.TPUEstimatorSpec(\n mode=mode,\n predictions={\"probabilities\": probabilities},\n scaffold_fn=scaffold_fn)\n return output_spec\n\n return model_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef input_fn_builder(features, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n all_input_ids = []\n all_input_mask = []\n all_segment_ids = []\n all_label_ids = []\n\n for feature in features:\n all_input_ids.append(feature.input_ids)\n all_input_mask.append(feature.input_mask)\n all_segment_ids.append(feature.segment_ids)\n all_label_ids.append(feature.label_id)\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n num_examples = len(features)\n\n # This is for demo purposes and does NOT scale to large data sets. We do\n # not use Dataset.from_generator() because that uses tf.py_func which is\n # not TPU compatible. The right way to load data is with TFRecordReader.\n d = tf.data.Dataset.from_tensor_slices({\n \"input_ids\":\n tf.constant(\n all_input_ids, shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input_mask\":\n tf.constant(\n all_input_mask,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"segment_ids\":\n tf.constant(\n all_segment_ids,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"label_ids\":\n tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),\n })\n\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)\n return d\n\n return input_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer):\n \"\"\"Convert a set of `InputExample`s to a list of `InputFeatures`.\"\"\"\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.compat.v1.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n features.append(feature)\n return features\n\n\ndef main(_):\n hvd.init()\n FLAGS.output_dir = FLAGS.output_dir if hvd.rank() == 0 else os.path.join(FLAGS.output_dir, str(hvd.rank()))\n\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)\n\n processors = {\n \"cola\": ColaProcessor,\n \"mnli\": MnliProcessor,\n \"mrpc\": MrpcProcessor,\n \"xnli\": XnliProcessor,\n }\n\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\n FLAGS.init_checkpoint)\n\n if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:\n raise ValueError(\n \"At least one of `do_train`, `do_eval` or `do_predict' must be True.\")\n\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n tf.io.gfile.makedirs(FLAGS.output_dir)\n\n task_name = FLAGS.task_name.lower()\n\n if task_name not in processors:\n raise ValueError(\"Task not found: %s\" % (task_name))\n\n processor = processors[task_name]()\n\n label_list = processor.get_labels()\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tf.compat.v1.estimator.tpu.InputPipelineConfig.PER_HOST_V2\n\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.visible_device_list = str(hvd.local_rank())\n\n run_config = tf.compat.v1.estimator.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tf.compat.v1.estimator.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host),\n log_step_count_steps=25,\n session_config=config)\n\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n if FLAGS.do_train:\n train_examples = processor.get_train_examples(FLAGS.data_dir)\n num_train_steps = int(\n len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n num_train_steps = num_train_steps // hvd.size()\n num_warmup_steps = num_warmup_steps // hvd.size()\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=len(label_list),\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf.compat.v1.estimator.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=FLAGS.train_batch_size,\n eval_batch_size=FLAGS.eval_batch_size,\n predict_batch_size=FLAGS.predict_batch_size)\n\n if FLAGS.do_train:\n train_file = os.path.join(FLAGS.output_dir, \"train.tf_record\")\n file_based_convert_examples_to_features(\n train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)\n tf.compat.v1.logging.info(\"***** Running training *****\")\n tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples))\n tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\n tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps)\n train_input_fn = file_based_input_fn_builder(\n input_file=train_file,\n seq_length=FLAGS.max_seq_length,\n is_training=True,\n drop_remainder=True)\n hooks = [hvd.BroadcastGlobalVariablesHook(0)]\n\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=hooks)\n\n if FLAGS.do_eval:\n eval_examples = processor.get_dev_examples(FLAGS.data_dir)\n num_actual_eval_examples = len(eval_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on. These do NOT count towards the metric (all tf.metrics\n # support a per-instance weight, and these get a weight of 0.0).\n while len(eval_examples) % FLAGS.eval_batch_size != 0:\n eval_examples.append(PaddingInputExample())\n\n eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\")\n file_based_convert_examples_to_features(\n eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)\n\n tf.compat.v1.logging.info(\"***** Running evaluation *****\")\n tf.compat.v1.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(eval_examples), num_actual_eval_examples,\n len(eval_examples) - num_actual_eval_examples)\n tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)\n\n # This tells the estimator to run through the entire set.\n eval_steps = None\n # However, if running eval on the TPU, you will need to specify the\n # number of steps.\n if FLAGS.use_tpu:\n assert len(eval_examples) % FLAGS.eval_batch_size == 0\n eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)\n\n eval_drop_remainder = True if FLAGS.use_tpu else False\n eval_input_fn = file_based_input_fn_builder(\n input_file=eval_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=eval_drop_remainder)\n\n result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)\n\n output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\")\n with tf.io.gfile.GFile(output_eval_file, \"w\") as writer:\n tf.compat.v1.logging.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n if FLAGS.do_predict:\n predict_examples = processor.get_test_examples(FLAGS.data_dir)\n num_actual_predict_examples = len(predict_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on.\n while len(predict_examples) % FLAGS.predict_batch_size != 0:\n predict_examples.append(PaddingInputExample())\n\n predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\")\n file_based_convert_examples_to_features(predict_examples, label_list,\n FLAGS.max_seq_length, tokenizer,\n predict_file)\n\n tf.compat.v1.logging.info(\"***** Running prediction*****\")\n tf.compat.v1.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(predict_examples), num_actual_predict_examples,\n len(predict_examples) - num_actual_predict_examples)\n tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n predict_drop_remainder = True if FLAGS.use_tpu else False\n predict_input_fn = file_based_input_fn_builder(\n input_file=predict_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=predict_drop_remainder)\n\n result = estimator.predict(input_fn=predict_input_fn)\n\n output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\")\n with tf.io.gfile.GFile(output_predict_file, \"w\") as writer:\n num_written_lines = 0\n tf.compat.v1.logging.info(\"***** Predict results *****\")\n for (i, prediction) in enumerate(result):\n probabilities = prediction[\"probabilities\"]\n if i >= num_actual_predict_examples:\n break\n output_line = \"\\t\".join(\n str(class_probability)\n for class_probability in probabilities) + \"\\n\"\n writer.write(output_line)\n num_written_lines += 1\n assert num_written_lines == num_actual_predict_examples\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"data_dir\")\n flags.mark_flag_as_required(\"task_name\")\n flags.mark_flag_as_required(\"vocab_file\")\n flags.mark_flag_as_required(\"bert_config_file\")\n flags.mark_flag_as_required(\"output_dir\")\n tf.compat.v1.app.run()\n"
] | [
[
"tensorflow.io.TFRecordWriter",
"tensorflow.compat.v1.metrics.mean",
"tensorflow.nn.log_softmax",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.distribute.cluster_resolver.TPUClusterResolver",
"tensorflow.compat.v1.zeros_initializer",
"tensorflow.compat.v1.train.Scaffold",
"tensorflow.compat.v1.app.run",
"tensorflow.compat.v1.truncated_normal_initializer",
"tensorflow.data.TFRecordDataset",
"tensorflow.io.gfile.GFile",
"tensorflow.compat.v1.trainable_variables",
"tensorflow.compat.v1.flags.DEFINE_string",
"tensorflow.compat.v1.estimator.tpu.TPUConfig",
"tensorflow.argmax",
"tensorflow.compat.v1.variable_scope",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.compat.v1.metrics.accuracy",
"tensorflow.io.gfile.makedirs",
"tensorflow.one_hot",
"tensorflow.compat.v1.estimator.tpu.TPUEstimatorSpec",
"tensorflow.train.Features",
"tensorflow.compat.v1.train.init_from_checkpoint",
"tensorflow.nn.bias_add",
"tensorflow.compat.v1.estimator.tpu.TPUEstimator",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.io.parse_single_example",
"tensorflow.compat.v1.logging.set_verbosity",
"tensorflow.io.FixedLenFeature",
"tensorflow.compat.v1.logging.info"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DengBoCong/text-sim | [
"2c6c323649aa259a7b3d5c6d3714bd1860114826"
] | [
"sim/bert_base/torch/transformers/modeling_nezha.py"
] | [
"#! -*- coding: utf-8 -*-\n\"\"\" NeZha Model, Base Transformers\n\"\"\"\n# Author: DengBoCong <[email protected]>\n# https://arxiv.org/pdf/1909.00204.pdf\n#\n# License: MIT License\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport numpy as np\nimport math\nimport sys\nimport torch\nimport torch.nn as nn\nfrom sim.bert_base.torch.transformers.modeling_bert import BertPreTrainedModel\nfrom sim.tools.settings import RUNTIME_LOG_FILE_PATH\nfrom sim.tools.tools import get_logger\n\nlogger = get_logger(name=\"actuator\", file_path=RUNTIME_LOG_FILE_PATH)\n\nCONFIG_NAME = 'bert_config.json'\nWEIGHTS_NAME = 'pytorch_model.bin'\nPRETRAINED_MODEL_ARCHIVE_MAP = {\n 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz\",\n 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz\",\n 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz\",\n 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased.tar.gz\",\n 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased.tar.gz\",\n 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased.tar.gz\",\n 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz\",\n}\nBERT_CONFIG_NAME = 'bert_config.json'\n\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n \"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n\ndef swish(x):\n return x * torch.sigmoid(x)\n\n\nACT2FN = {\"gelu\": gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish}\n\ntry:\n from apex.normalization.fused_layer_norm import FusedLayerNorm as BertLayerNorm\nexcept ImportError:\n logger.info(\"Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .\")\n\n\n class BertLayerNorm(nn.Module):\n def __init__(self, hidden_size, eps=1e-12):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(BertLayerNorm, self).__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.bias = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.weight * x + self.bias\n\n\nclass BertEmbeddings(nn.Module):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\n \"\"\"\n\n def __init__(self, config):\n super(BertEmbeddings, self).__init__()\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0)\n try:\n self.use_relative_position = config.use_relative_position\n except:\n self.use_relative_position = False\n if not self.use_relative_position:\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)\n self.diff_token_type_embeddings = nn.Embedding(5, config.hidden_size)\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, input_ids, token_type_ids=None):\n seq_length = input_ids.size(1)\n position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids)\n embeddings = words_embeddings\n if not self.use_relative_position:\n position_embeddings = self.position_embeddings(position_ids)\n embeddings += position_embeddings\n segment_token_type_ids = token_type_ids % 10\n diff_token_type_ids = token_type_ids // 10\n segment_token_type_embeddings = self.token_type_embeddings(segment_token_type_ids)\n diff_token_type_embeddings = self.diff_token_type_embeddings(diff_token_type_ids)\n # token_type_embeddings = segment_token_type_embeddings + diff_token_type_embeddings\n token_type_embeddings = segment_token_type_embeddings\n embeddings += token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BertSelfAttention(nn.Module):\n def __init__(self, config):\n super(BertSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads))\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n context_layer = torch.matmul(attention_probs, value_layer)\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n return context_layer, attention_scores\n\n\ndef _generate_relative_positions_matrix(length, max_relative_position,\n cache=False):\n \"\"\"Generates matrix of relative positions between inputs.\"\"\"\n if not cache:\n range_vec = torch.arange(length)\n range_mat = range_vec.repeat(length).view(length, length)\n distance_mat = range_mat - torch.t(range_mat)\n else:\n distance_mat = torch.arange(-length + 1, 1, 1).unsqueeze(0)\n\n distance_mat_clipped = torch.clamp(distance_mat, -max_relative_position, max_relative_position)\n final_mat = distance_mat_clipped + max_relative_position\n\n return final_mat\n\n\ndef _generate_relative_positions_embeddings(length, depth, max_relative_position=127):\n vocab_size = max_relative_position * 2 + 1\n range_vec = torch.arange(length)\n range_mat = range_vec.repeat(length).view(length, length)\n distance_mat = range_mat - torch.t(range_mat)\n distance_mat_clipped = torch.clamp(distance_mat, -max_relative_position, max_relative_position)\n final_mat = distance_mat_clipped + max_relative_position\n embeddings_table = np.zeros([vocab_size, depth])\n for pos in range(vocab_size):\n for i in range(depth // 2):\n embeddings_table[pos, 2 * i] = np.sin(pos / np.power(10000, 2 * i / depth))\n embeddings_table[pos, 2 * i + 1] = np.cos(pos / np.power(10000, 2 * i / depth))\n\n embeddings_table_tensor = torch.tensor(embeddings_table).float()\n flat_relative_positions_matrix = final_mat.view(-1)\n one_hot_relative_positions_matrix = torch.nn.functional.one_hot(flat_relative_positions_matrix,\n num_classes=vocab_size).float()\n embeddings = torch.matmul(one_hot_relative_positions_matrix, embeddings_table_tensor)\n my_shape = list(final_mat.size())\n my_shape.append(depth)\n embeddings = embeddings.view(my_shape)\n return embeddings\n\n\nclass NeZhaSelfAttention(nn.Module):\n def __init__(self, config):\n super(NeZhaSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads))\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n self.relative_positions_embeddings = _generate_relative_positions_embeddings(\n length=512, depth=self.attention_head_size, max_relative_position=config.max_relative_position).cuda()\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask):\n device = 'cpu'\n if hidden_states.is_cuda:\n device = hidden_states.get_device()\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n batch_size, num_attention_heads, from_seq_length, to_seq_length = attention_scores.size()\n\n relations_keys = self.relative_positions_embeddings.detach().clone()[:to_seq_length, :to_seq_length, :].to(\n device)\n # relations_keys = embeddings.clone().detach().to(device)\n query_layer_t = query_layer.permute(2, 0, 1, 3)\n query_layer_r = query_layer_t.contiguous().view(from_seq_length, batch_size * num_attention_heads,\n self.attention_head_size)\n key_position_scores = torch.matmul(query_layer_r, relations_keys.permute(0, 2, 1))\n key_position_scores_r = key_position_scores.view(from_seq_length, batch_size,\n num_attention_heads, from_seq_length)\n key_position_scores_r_t = key_position_scores_r.permute(1, 2, 0, 3)\n attention_scores = attention_scores + key_position_scores_r_t\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n context_layer = torch.matmul(attention_probs, value_layer)\n\n relations_values = self.relative_positions_embeddings.clone()[:to_seq_length, :to_seq_length, :].to(\n device)\n attention_probs_t = attention_probs.permute(2, 0, 1, 3)\n attentions_probs_r = attention_probs_t.contiguous().view(from_seq_length, batch_size * num_attention_heads,\n to_seq_length)\n value_position_scores = torch.matmul(attentions_probs_r, relations_values)\n value_position_scores_r = value_position_scores.view(from_seq_length, batch_size,\n num_attention_heads, self.attention_head_size)\n value_position_scores_r_t = value_position_scores_r.permute(1, 2, 0, 3)\n context_layer = context_layer + value_position_scores_r_t\n\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n return context_layer, attention_scores\n\n\nclass BertSelfOutput(nn.Module):\n def __init__(self, config):\n super(BertSelfOutput, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertAttention(nn.Module):\n def __init__(self, config):\n super(BertAttention, self).__init__()\n try:\n self.use_relative_position = config.use_relative_position\n except:\n self.use_relative_position = False\n if self.use_relative_position:\n self.self = NeZhaSelfAttention(config)\n else:\n self.self = BertSelfAttention(config)\n\n self.output = BertSelfOutput(config)\n\n def forward(self, input_tensor, attention_mask):\n self_output = self.self(input_tensor, attention_mask)\n self_output, layer_att = self_output\n attention_output = self.output(self_output, input_tensor)\n return attention_output, layer_att\n\n\nclass BertIntermediate(nn.Module):\n def __init__(self, config):\n super(BertIntermediate, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, str)):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\nclass BertOutput(nn.Module):\n def __init__(self, config):\n super(BertOutput, self).__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertLayer(nn.Module):\n def __init__(self, config):\n super(BertLayer, self).__init__()\n self.attention = BertAttention(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self, hidden_states, attention_mask):\n attention_output = self.attention(hidden_states, attention_mask)\n attention_output, layer_att = attention_output\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n return layer_output, layer_att\n\n\nclass BertEncoder(nn.Module):\n def __init__(self, config):\n super(BertEncoder, self).__init__()\n layer = BertLayer(config)\n self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])\n\n def forward(self, hidden_states, attention_mask):\n all_encoder_layers = []\n all_encoder_att = []\n for i, layer_module in enumerate(self.layer):\n all_encoder_layers.append(hidden_states)\n hidden_states = layer_module(all_encoder_layers[i], attention_mask)\n hidden_states, layer_att = hidden_states\n all_encoder_att.append(layer_att)\n all_encoder_layers.append(hidden_states)\n return all_encoder_layers, all_encoder_att\n\n\nclass BertPooler(nn.Module):\n def __init__(self, config):\n super(BertPooler, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\nclass NeZhaModel(BertPreTrainedModel):\n def __init__(self, config):\n super(NeZhaModel, self).__init__(config)\n self.embeddings = BertEmbeddings(config)\n self.encoder = BertEncoder(config)\n self.pooler = BertPooler(config)\n\n self.init_weights()\n\n def set_input_embeddings(self, value):\n self.embeddings.word_embeddings = value\n\n def forward(self, input_ids,\n token_type_ids=None,\n position_ids=None,\n attention_mask=None,\n head_mask=None,\n **kwargs):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n embedding_output = self.embeddings(input_ids, token_type_ids)\n encoded_layers = self.encoder(embedding_output,\n extended_attention_mask)\n encoded_layers, attention_layers = encoded_layers\n sequence_output = encoded_layers[-1]\n pooled_output = self.pooler(sequence_output)\n return sequence_output, pooled_output, None\n\n\nclass BertPredictionHeadTransform(nn.Module):\n def __init__(self, config):\n super(BertPredictionHeadTransform, self).__init__()\n # Need to unty it when we separate the dimensions of hidden and emb\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, str)):\n self.transform_act_fn = ACT2FN[config.hidden_act]\n else:\n self.transform_act_fn = config.hidden_act\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12)\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass BertLMPredictionHead(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertLMPredictionHead, self).__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(bert_model_embedding_weights.size(1),\n bert_model_embedding_weights.size(0),\n bias=False)\n self.decoder.weight = bert_model_embedding_weights\n self.bias = nn.Parameter(torch.zeros(bert_model_embedding_weights.size(0)))\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states) + self.bias\n return hidden_states\n\n\nclass BertOnlyMLMHead(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertOnlyMLMHead, self).__init__()\n self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)\n\n def forward(self, sequence_output):\n prediction_scores = self.predictions(sequence_output)\n return prediction_scores\n\n\nclass BertOnlyNSPHead(nn.Module):\n def __init__(self, config):\n super(BertOnlyNSPHead, self).__init__()\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, pooled_output):\n seq_relationship_score = self.seq_relationship(pooled_output)\n return seq_relationship_score\n\n\nclass BertPreTrainingHeads(nn.Module):\n def __init__(self, config, bert_model_embedding_weights):\n super(BertPreTrainingHeads, self).__init__()\n self.predictions = BertLMPredictionHead(config, bert_model_embedding_weights)\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, sequence_output, pooled_output):\n prediction_scores = self.predictions(sequence_output)\n seq_relationship_score = self.seq_relationship(pooled_output)\n return prediction_scores, seq_relationship_score\n\n\nclass BertForPreTraining(BertPreTrainedModel):\n \"\"\"BERT model with pre-training heads.\n This module comprises the BERT model followed by the two pre-training heads:\n - the masked language modeling head, and\n - the next sentence classification head.\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `masked_lm_labels`: optional masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss\n is only computed for the labels set in [0, ..., vocab_size]\n `next_sentence_label`: optional next sentence classification loss: torch.LongTensor of shape [batch_size]\n with indices selected in [0, 1].\n 0 => next sentence is the continuation, 1 => next sentence is a random sentence.\n\n Outputs:\n if `masked_lm_labels` and `next_sentence_label` are not `None`:\n Outputs the total_loss which is the sum of the masked language modeling loss and the next\n sentence classification loss.\n if `masked_lm_labels` or `next_sentence_label` is `None`:\n Outputs a tuple comprising\n - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and\n - the next sentence classification logits of shape [batch_size, 2].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n model = BertForPreTraining(config)\n masked_lm_logits_scores, seq_relationship_logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n\n def __init__(self, config):\n super(BertForPreTraining, self).__init__(config)\n self.bert = NeZhaModel(config)\n self.cls = BertPreTrainingHeads(config, self.bert.embeddings.word_embeddings.weight)\n self.init_weights()\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None,\n masked_lm_labels=None, next_sentence_label=None):\n sequence_output, pooled_output = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)\n\n if masked_lm_labels is not None and next_sentence_label is not None:\n loss_fct = nn.CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n total_loss = masked_lm_loss + next_sentence_loss\n return total_loss\n elif masked_lm_labels is not None:\n loss_fct = nn.CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n total_loss = masked_lm_loss\n return total_loss\n else:\n return prediction_scores, seq_relationship_score\n\n\nclass NeZhaForMaskedLM(BertPreTrainedModel):\n \"\"\"BERT model with the masked language modeling head.\n This module comprises the BERT model followed by the masked language modeling head.\n\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss\n is only computed for the labels set in [0, ..., vocab_size]\n\n Outputs:\n if `masked_lm_labels` is not `None`:\n Outputs the masked language modeling loss.\n if `masked_lm_labels` is `None`:\n Outputs the masked language modeling logits of shape [batch_size, sequence_length, vocab_size].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n model = BertForMaskedLM(config)\n masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n\n def __init__(self, config):\n super(NeZhaForMaskedLM, self).__init__(config)\n self.bert = NeZhaModel(config)\n self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)\n self.init_weights()\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None,\n output_attention=False, **kwargs):\n sequence_output, _, _ = self.bert(input_ids,\n token_type_ids=token_type_ids,\n attention_mask=attention_mask)\n\n prediction_scores = self.cls(sequence_output)\n\n masked_lm_loss = None\n if labels is not None:\n loss_fct = nn.CrossEntropyLoss() # -100 index = padding token\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))\n return masked_lm_loss, masked_lm_loss\n\n\nclass BertForSequenceClassification(BertPreTrainedModel):\n \"\"\"BERT model for classification.\n This module is composed of the BERT model with a linear layer on top of\n the pooled output.\n\n Params:\n `config`: a BertConfig class instance with the configuration to build a new model.\n `num_labels`: the number of classes for the classifier. Default = 2.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]\n with indices selected in [0, ..., num_labels].\n\n Outputs:\n if `labels` is not `None`:\n Outputs the CrossEntropy classification loss of the output with the labels.\n if `labels` is `None`:\n Outputs the classification logits of shape [batch_size, num_labels].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n num_labels = 2\n\n model = BertForSequenceClassification(config, num_labels)\n logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n\n def __init__(self, config, num_labels):\n super(BertForSequenceClassification, self).__init__(config)\n self.num_labels = num_labels\n self.bert = NeZhaModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, num_labels)\n self.init_weights()\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):\n _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n task_output = self.dropout(pooled_output)\n logits = self.classifier(task_output)\n if labels is not None:\n loss_fct = nn.CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n return loss\n else:\n return logits\n\n\nclass NeZhaForMultipleChoice(BertPreTrainedModel):\n def __init__(self, config, num_choices=2):\n super(NeZhaForMultipleChoice, self).__init__(config)\n self.num_choices = num_choices\n self.bert = NeZhaModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, 1)\n self.init_weights()\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None, return_logits=False):\n # input_ids: [bs,num_choice,seq_l]\n flat_input_ids = input_ids.view(-1, input_ids.size(-1)) # flat_input_ids: [bs*num_choice,seq_l]\n flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1))\n flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1))\n _, pooled_output = self.bert(flat_input_ids, flat_token_type_ids, flat_attention_mask,\n output_all_encoded_layers=False)\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output) # logits: (bs*num_choice,1)\n reshaped_logits = logits.view(-1, self.num_choices) # logits: (bs, num_choice)\n\n if labels is not None:\n loss_fct = nn.CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n if return_logits:\n return loss, reshaped_logits\n else:\n return loss\n else:\n return reshaped_logits\n\n\nclass NeZhaForQuestionAnswering(BertPreTrainedModel):\n def __init__(self, config):\n super(NeZhaForQuestionAnswering, self).__init__(config)\n self.bert = NeZhaModel(config)\n # TODO check with Google if it's normal there is no dropout on the token classifier of SQuAD in the TF version\n # self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.qa_outputs = nn.Linear(config.hidden_size, 2)\n self.init_weights()\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, start_positions=None, end_positions=None):\n sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n return total_loss\n else:\n return start_logits, end_logits\n\n\nclass BertForJointLSTM(BertPreTrainedModel):\n def __init__(self, config, num_intent_labels, num_slot_labels):\n super(BertForJointLSTM, self).__init__(config)\n self.num_intent_labels = num_intent_labels\n self.num_slot_labels = num_slot_labels\n self.bert = NeZhaModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.intent_classifier = nn.Linear(config.hidden_size, num_intent_labels)\n self.lstm = nn.LSTM(\n input_size=config.hidden_size,\n hidden_size=300,\n batch_first=True,\n bidirectional=True\n\n )\n self.slot_classifier = nn.Linear(300 * 2, num_slot_labels)\n self.init_weights()\n\n def forward(self, input_ids, token_type_ids=None,\n attention_mask=None, intent_labels=None, slot_labels=None):\n encoded_layers, attention_layers, pooled_output = self.bert(input_ids, token_type_ids, attention_mask)\n intent_logits = self.intent_classifier(self.dropout(pooled_output))\n\n last_encoded_layer = encoded_layers[-1]\n slot_logits, _ = self.lstm(last_encoded_layer)\n slot_logits = self.slot_classifier(slot_logits)\n tmp = []\n if intent_labels is not None and slot_labels is not None:\n loss_fct = nn.CrossEntropyLoss()\n intent_loss = loss_fct(intent_logits.view(-1, self.num_intent_labels), intent_labels.view(-1))\n if attention_mask is not None:\n active_slot_loss = attention_mask.view(-1) == 1\n active_slot_logits = slot_logits.view(-1, self.num_slot_labels)[active_slot_loss]\n active_slot_labels = slot_labels.view(-1)[active_slot_loss]\n slot_loss = loss_fct(active_slot_logits, active_slot_labels)\n else:\n slot_loss = loss_fct(slot_logits.view(-1, self.num_slot_labels), slot_labels.view(-1))\n\n return intent_loss, slot_loss\n else:\n return intent_logits, slot_logits\n"
] | [
[
"torch.nn.Softmax",
"torch.zeros",
"torch.nn.Embedding",
"torch.t",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.sqrt",
"torch.tensor",
"torch.arange",
"numpy.zeros",
"torch.ones_like",
"torch.sigmoid",
"numpy.power",
"torch.zeros_like",
"torch.nn.Linear",
"torch.nn.LSTM",
"torch.nn.Tanh",
"torch.matmul",
"torch.nn.functional.one_hot",
"torch.clamp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
naver-ai/neuralwoz | [
"89f10904256c0df33e14c05e8581421d52b63105"
] | [
"SUMBT/code/BeliefTrackerSlotQueryMultiSlot.py"
] | [
"import os.path\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.nn import CrossEntropyLoss\nfrom torch.nn import CosineEmbeddingLoss\n\nfrom pytorch_pretrained_bert.modeling import BertModel\nfrom pytorch_pretrained_bert.modeling import BertPreTrainedModel\n\nclass BertForUtteranceEncoding(BertPreTrainedModel):\n def __init__(self, config):\n super(BertForUtteranceEncoding, self).__init__(config)\n\n self.config = config\n self.bert = BertModel(config)\n\n def forward(self, input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False):\n return self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers)\n\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self, heads, d_model, dropout=0.1):\n super().__init__()\n\n self.d_model = d_model\n self.d_k = d_model // heads\n self.h = heads\n\n self.q_linear = nn.Linear(d_model, d_model)\n self.v_linear = nn.Linear(d_model, d_model)\n self.k_linear = nn.Linear(d_model, d_model)\n self.dropout = nn.Dropout(dropout)\n self.out = nn.Linear(d_model, d_model)\n\n self.scores = None\n\n def attention(self, q, k, v, d_k, mask=None, dropout=None):\n\n scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k)\n\n if mask is not None:\n mask = mask.unsqueeze(1)\n scores = scores.masked_fill(mask == 0, -1e9)\n scores = F.softmax(scores, dim=-1)\n\n if dropout is not None:\n scores = dropout(scores)\n\n self.scores = scores\n output = torch.matmul(scores, v)\n return output\n\n def forward(self, q, k, v, mask=None):\n bs = q.size(0)\n\n # perform linear operation and split into h heads\n k = self.k_linear(k).view(bs, -1, self.h, self.d_k)\n q = self.q_linear(q).view(bs, -1, self.h, self.d_k)\n v = self.v_linear(v).view(bs, -1, self.h, self.d_k)\n\n # transpose to get dimensions bs * h * sl * d_model\n k = k.transpose(1, 2)\n q = q.transpose(1, 2)\n v = v.transpose(1, 2)\n\n scores = self.attention(q, k, v, self.d_k, mask, self.dropout)\n\n # concatenate heads and put through final linear layer\n concat = scores.transpose(1, 2).contiguous().view(bs, -1, self.d_model)\n output = self.out(concat)\n return output\n\n def get_scores(self):\n return self.scores\n\nclass BeliefTracker(nn.Module):\n def __init__(self, args, num_labels, device):\n super(BeliefTracker, self).__init__()\n\n self.hidden_dim = args.hidden_dim\n self.rnn_num_layers = args.num_rnn_layers\n self.zero_init_rnn = args.zero_init_rnn\n self.max_seq_length = args.max_seq_length\n self.max_label_length = args.max_label_length\n self.num_labels = num_labels\n self.num_slots = len(num_labels)\n self.attn_head = args.attn_head\n self.device = device\n\n ### Utterance Encoder\n self.utterance_encoder = BertForUtteranceEncoding.from_pretrained(\n \"bert-base-uncased\"\n #os.path.join(args.bert_dir, 'bert-base-uncased.model')\n )\n self.bert_output_dim = self.utterance_encoder.config.hidden_size\n self.hidden_dropout_prob = self.utterance_encoder.config.hidden_dropout_prob\n if args.fix_utterance_encoder:\n for p in self.utterance_encoder.bert.pooler.parameters():\n p.requires_grad = False\n\n ### slot, slot-value Encoder (not trainable)\n self.sv_encoder = BertForUtteranceEncoding.from_pretrained(\n \"bert-base-uncased\")\n #os.path.join(args.bert_dir, 'bert-base-uncased.model'))\n for p in self.sv_encoder.bert.parameters():\n p.requires_grad = False\n\n self.slot_lookup = nn.Embedding(self.num_slots, self.bert_output_dim)\n self.value_lookup = nn.ModuleList([nn.Embedding(num_label, self.bert_output_dim) for num_label in num_labels])\n\n ### Attention layer\n self.attn = MultiHeadAttention(self.attn_head, self.bert_output_dim, dropout=0)\n\n ### RNN Belief Tracker\n self.nbt = None\n if args.task_name.find(\"gru\") != -1:\n self.nbt = nn.GRU(input_size=self.bert_output_dim,\n hidden_size=self.hidden_dim,\n num_layers=self.rnn_num_layers,\n dropout=self.hidden_dropout_prob,\n batch_first=True)\n self.init_parameter(self.nbt)\n elif args.task_name.find(\"lstm\") != -1:\n self.nbt = nn.LSTM(input_size=self.bert_output_dim,\n hidden_size=self.hidden_dim,\n num_layers=self.rnn_num_layers,\n dropout=self.hidden_dropout_prob,\n batch_first=True)\n self.init_parameter(self.nbt)\n if not self.zero_init_rnn:\n self.rnn_init_linear = nn.Sequential(\n nn.Linear(self.bert_output_dim, self.hidden_dim),\n nn.ReLU(),\n nn.Dropout(self.hidden_dropout_prob)\n )\n\n self.linear = nn.Linear(self.hidden_dim, self.bert_output_dim)\n self.layer_norm = nn.LayerNorm(self.bert_output_dim)\n\n ### Measure\n self.distance_metric = args.distance_metric\n if self.distance_metric == \"cosine\":\n self.metric = torch.nn.CosineSimilarity(dim=-1, eps=1e-08)\n elif self.distance_metric == \"euclidean\":\n self.metric = torch.nn.PairwiseDistance(p=2.0, eps=1e-06, keepdim=False)\n\n ### Classifier\n self.nll = CrossEntropyLoss(ignore_index=-1)\n\n ### Etc.\n self.dropout = nn.Dropout(self.hidden_dropout_prob)\n\n def initialize_slot_value_lookup(self, label_ids, slot_ids):\n\n self.sv_encoder.eval()\n\n # Slot encoding\n slot_type_ids = torch.zeros(slot_ids.size(), dtype=torch.long).to(self.device)\n slot_mask = slot_ids > 0\n hid_slot, _ = self.sv_encoder(slot_ids.view(-1, self.max_label_length),\n slot_type_ids.view(-1, self.max_label_length),\n slot_mask.view(-1, self.max_label_length),\n output_all_encoded_layers=False)\n hid_slot = hid_slot[:, 0, :]\n hid_slot = hid_slot.detach()\n self.slot_lookup = nn.Embedding.from_pretrained(hid_slot, freeze=True)\n\n for s, label_id in enumerate(label_ids):\n label_type_ids = torch.zeros(label_id.size(), dtype=torch.long).to(self.device)\n label_mask = label_id > 0\n hid_label, _ = self.sv_encoder(label_id.view(-1, self.max_label_length),\n label_type_ids.view(-1, self.max_label_length),\n label_mask.view(-1, self.max_label_length),\n output_all_encoded_layers=False)\n hid_label = hid_label[:, 0, :]\n hid_label = hid_label.detach()\n self.value_lookup[s] = nn.Embedding.from_pretrained(hid_label, freeze=True)\n self.value_lookup[s].padding_idx = -1\n\n print(\"Complete initialization of slot and value lookup\")\n\n def _make_aux_tensors(self, ids, len):\n token_type_ids = torch.zeros(ids.size(), dtype=torch.long).to(self.device)\n for i in range(len.size(0)):\n for j in range(len.size(1)):\n if len[i,j,0] == 0: # padding\n break\n elif len[i,j,1] > 0: # escape only text_a case\n start = len[i,j,0]\n ending = len[i,j,0] + len[i,j,1]\n token_type_ids[i, j, start:ending] = 1\n attention_mask = ids > 0\n return token_type_ids, attention_mask\n\n def forward(self, input_ids, input_len, labels, n_gpu=1, target_slot=None):\n\n # if target_slot is not specified, output values corresponding all slot-types\n if target_slot is None:\n target_slot = list(range(0, self.num_slots))\n\n ds = input_ids.size(0) # dialog size\n ts = input_ids.size(1) # turn size\n bs = ds*ts\n slot_dim = len(target_slot)\n\n # Utterance encoding\n token_type_ids, attention_mask = self._make_aux_tensors(input_ids, input_len)\n\n hidden, _ = self.utterance_encoder(input_ids.view(-1, self.max_seq_length),\n token_type_ids.view(-1, self.max_seq_length),\n attention_mask.view(-1, self.max_seq_length),\n output_all_encoded_layers=False)\n hidden = torch.mul(hidden, attention_mask.view(-1, self.max_seq_length, 1).expand(hidden.size()).float())\n hidden = hidden.repeat(slot_dim, 1, 1) #[(slot_dim*ds*ts), bert_seq, hid_size]\n\n hid_slot = self.slot_lookup.weight[target_slot, :] # Select target slot embedding\n hid_slot = hid_slot.repeat(1, bs).view(bs*slot_dim, -1) #[(slot_dim*ds*ts), bert_seq, hid_size]\n\n # Attended utterance vector\n hidden = self.attn(hid_slot, hidden, hidden, mask=attention_mask.view(-1, 1, self.max_seq_length).repeat(slot_dim, 1, 1))\n hidden = hidden.squeeze() # [slot_dim*ds*ts, bert_dim]\n hidden = hidden.view(slot_dim, ds, ts, -1).view(-1,ts,self.bert_output_dim)\n\n # NBT\n if self.zero_init_rnn:\n h = torch.zeros(self.rnn_num_layers, input_ids.shape[0] * slot_dim, self.hidden_dim).to(self.device) # [1, slot_dim*ds, hidden]\n else:\n h = hidden[:, 0, :].unsqueeze(0).repeat(self.rnn_num_layers, 1, 1)\n h = self.rnn_init_linear(h)\n\n if isinstance(self.nbt, nn.GRU):\n rnn_out, _ = self.nbt(hidden, h) # [slot_dim*ds, turn, hidden]\n elif isinstance(self.nbt, nn.LSTM):\n c = torch.zeros(self.rnn_num_layers, input_ids.shape[0]*slot_dim, self.hidden_dim).to(self.device) # [1, slot_dim*ds, hidden]\n rnn_out, _ = self.nbt(hidden, (h, c)) # [slot_dim*ds, turn, hidden]\n rnn_out = self.layer_norm(self.linear(self.dropout(rnn_out)))\n\n hidden = rnn_out.view(slot_dim, ds, ts, -1)\n\n # Label (slot-value) encoding\n loss = 0\n loss_slot =[]\n pred_slot = []\n output = []\n for s, slot_id in enumerate(target_slot): ## note: target_slots are successive\n # loss calculation\n hid_label = self.value_lookup[slot_id].weight\n num_slot_labels = hid_label.size(0)\n\n _hid_label = hid_label.unsqueeze(0).unsqueeze(0).repeat(ds, ts, 1, 1).view(ds*ts*num_slot_labels, -1)\n _hidden = hidden[s,:,:,:].unsqueeze(2).repeat(1, 1, num_slot_labels, 1).view(ds*ts*num_slot_labels, -1)\n _dist = self.metric(_hid_label, _hidden).view(ds, ts, num_slot_labels)\n\n if self.distance_metric == \"euclidean\":\n _dist = -_dist\n _, pred = torch.max(_dist, -1)\n pred_slot.append(pred.view(ds, ts, 1))\n output.append(_dist)\n\n if labels is not None:\n _loss = self.nll(_dist.view(ds*ts, -1), labels[:,:,s].view(-1))\n loss_slot.append(_loss.item())\n loss += _loss\n\n if labels is None:\n return output\n\n # calculate joint accuracy\n pred_slot = torch.cat(pred_slot, 2)\n accuracy = (pred_slot == labels).view(-1, slot_dim)\n acc_slot = torch.sum(accuracy,0).float() \\\n / torch.sum(labels.view(-1, slot_dim) > -1, 0).float()\n acc = sum(torch.sum(accuracy, 1) / slot_dim).float() \\\n / torch.sum(labels[:,:,0].view(-1) > -1, 0).float() # joint accuracy\n\n if n_gpu == 1:\n return loss, loss_slot, acc, acc_slot, pred_slot\n else:\n return loss.unsqueeze(0), None, acc.unsqueeze(0), acc_slot.unsqueeze(0), pred_slot.unsqueeze(0)\n\n @staticmethod\n def init_parameter(module):\n if isinstance(module, nn.Linear):\n torch.nn.init.xavier_normal_(module.weight)\n torch.nn.init.constant_(module.bias, 0.0)\n elif isinstance(module, nn.GRU) or isinstance(module, nn.LSTM):\n torch.nn.init.xavier_normal_(module.weight_ih_l0)\n torch.nn.init.xavier_normal_(module.weight_hh_l0)\n torch.nn.init.constant_(module.bias_ih_l0, 0.0)\n torch.nn.init.constant_(module.bias_hh_l0, 0.0)\n\n\n"
] | [
[
"torch.nn.functional.softmax",
"torch.max",
"torch.cat",
"torch.zeros",
"torch.nn.GRU",
"torch.sum",
"torch.nn.Embedding",
"torch.nn.Embedding.from_pretrained",
"torch.nn.PairwiseDistance",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.nn.CosineSimilarity",
"torch.nn.init.constant_",
"torch.nn.init.xavier_normal_",
"torch.nn.Linear",
"torch.nn.LSTM",
"torch.nn.LayerNorm",
"torch.matmul",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
domrim/bachelorarbeit-code | [
"56df0e2ab9b91c76a0f3f25d745316863ee4f275"
] | [
"jupyter-notebooks/eval/steps_sweep_error_bpsk.py"
] | [
"#!/usr/bin/env python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tikzplotlib\n\nget_ipython().run_line_magic('run', \"'./../split_step_fourier.ipynb'\")\nDEBUG = False\n\n# showing figures inline\nget_ipython().run_line_magic('matplotlib', 'inline')\n# plotting options \nfigure_size = (16, 9)\nplt.rcParams.update({\n 'font.family': 'serif',\n 'text.usetex': True,\n 'pgf.rcfonts': False,\n})\n\n\n# parameters of the filters\nf_symbol = 32e9 # symbol rate (Baud) (Symbols per second)\nn_up = 10 # samples per symbol (>1 => oversampling)\n\nr_rc = .33\nsyms_per_filt = 4 # symbols per filter (plus minus in both directions)\nt_sample_rc, rc = get_rc_ir(syms_per_filt, r_rc, f_symbol, n_up)\n\n# modulation scheme and constellation points for bpsk\nM = 2\nmodulation = {'0': -1, '1': 1}\nn_symbol = 1000 # number of symbols\n\n\n# Signalfolge generieren\nsend_bits = np.random.choice([symbol for symbol in modulation.keys()], size=n_symbol)\n\n\n## Global Transmission parameters\nz_length = 70 # [km]\n\nalpha = 0.2 # Dämpfung [dB/km]\nD = 17 # [ps/nm/km]\nbeta2 = - (D * np.square(1550e-9)) / (2 * np.pi * 3e8) * 1e-3 # [s^2/km] propagation constant, lambda=1550nm is standard single-mode wavelength\ngamma = 1.3 # [1/W/km]\n\n\n# simulate channel for multiple power inputs\nsims ={}\nfor power in np.arange(-5,10):\n send_rc = generate_signal(modulation, t_sample_rc, 1/f_symbol, send_bits, rc, syms_per_filt, n_symbol, power)\n send = add_zeros(send_rc, 100 * int(1/f_symbol/t_sample_rc))\n\n ## Simulation of reference transmission (dz = 0.1 km)\n nz_ref = 100 # steps\n dz_ref = z_length / nz_ref # [km]\n\n output_ref = splitstepfourier(send, t_sample_rc, dz_ref, nz_ref, alpha, beta2, gamma)\n\n d_nz = 1 # d_nz to use in loop\n ## Simulation of fibers with different step sizes\n step_sweep_sim = []\n for nz in np.arange(1, nz_ref+d_nz, step=d_nz):\n dz = z_length / nz\n output = splitstepfourier(send, t_sample_rc, dz, nz, alpha, beta2, gamma)\n step_sweep_sim.append((nz, output))\n \n sims[f\"{power}\"] = (output_ref, step_sweep_sim)\n\n\n## Plots\nfig1 = plt.figure(figsize=figure_size)\nplot1 = fig1.add_subplot()\nfig2 = plt.figure(figsize=figure_size)\nplot2 = fig2.add_subplot()\nfor key, data in sims.items():\n ref = data[0]\n signal = data[1]\n x_vals = []\n y_vals = []\n for n_steps, sim_out in signal:\n x_vals.append(n_steps)\n y_vals.append(abs(calc_relerr(sim_out, ref)))\n\n plot1.plot(x_vals, y_vals, label=key)\n if key in ['-5', '0', '3', '5', '6', '7', '8', '9']:\n plot2.plot(x_vals, y_vals, label=key)\n\nxmin = np.amin(x_vals)\nxmax = np.amax(x_vals)\n\nplot1.legend(loc='upper right', title='$P_{in}$', ncol=2)\nplot1.set_xlim(xmin, 20)\nplot1.set_ylabel(\"Relativer Fehler\")\nplot1.set_xlabel(\"Anzahl simulierter Schritte (nz)\")\n\nplot2.legend(loc='upper right', title='$P_{in}$', ncol=2)\nplot2.grid()\nplot2.set_xlim(xmin, 10)\nplot2.set_ylabel(\"Relativer Fehler\")\nplot2.set_xlabel(\"Anzahl simulierter Schritte (nz)\")\n\n\n# simulate channel for multiple power inputs without alpha\nsims2 ={}\nfor power in np.arange(-5,10):\n send_rc = generate_signal(modulation, t_sample_rc, 1/f_symbol, send_bits, rc, syms_per_filt, n_symbol, power)\n send = add_zeros(send_rc, 100 * int(1/f_symbol/t_sample_rc))\n\n ## Simulation of reference transmission (dz = 0.1 km)\n nz_ref = 100 # steps\n dz_ref = z_length / nz_ref # [km]\n\n output_ref = splitstepfourier(send, t_sample_rc, dz_ref, nz_ref, 0, beta2, gamma)\n\n d_nz = 1 # d_nz to use in loop\n ## Simulation of fibers with different step sizes\n step_sweep_sim = []\n for nz in np.arange(1, nz_ref+d_nz, step=d_nz):\n dz = z_length / nz\n output = splitstepfourier(send, t_sample_rc, dz, nz, 0, beta2, gamma)\n step_sweep_sim.append((nz, output))\n \n sims2[f\"{power}\"] = (output_ref, step_sweep_sim)\n\n\n## Plots\nfig3 = plt.figure(figsize=figure_size)\nplot3 = fig3.add_subplot()\nfig4 = plt.figure(figsize=figure_size)\nplot4 = fig4.add_subplot()\nfor key, data in sims2.items():\n ref = data[0]\n signal = data[1]\n x_vals = []\n y_vals = []\n for n_steps, sim_out in signal:\n x_vals.append(n_steps)\n y_vals.append(abs(calc_relerr(sim_out, ref)))\n\n plot3.plot(x_vals, y_vals, label=key)\n if key in ['-5', '0', '3', '5', '6', '7', '8', '9']:\n plot4.plot(x_vals, y_vals, label=key)\n\nxmin = np.amin(x_vals)\nxmax = np.amax(x_vals)\n\nplot3.legend(loc='upper right', title='$P_{in}$', ncol=2)\nplot3.set_xlim(xmin, 20)\nplot3.set_ylabel(\"Relativer Fehler\")\nplot3.set_xlabel(\"Anzahl simulierter Schritte (nz)\")\n\nplot4.legend(loc='upper right', title='$P_{in}$', ncol=2)\nplot4.grid()\nplot4.set_xlim(xmin, 10)\nplot4.set_ylabel(\"Relativer Fehler\")\nplot4.set_xlabel(\"Anzahl simulierter Schritte (nz)\")\n\n\noutput_fname = \"steps_sweep_bpsk\"\noutput_path = \"../../../bachelorarbeit-ausarbeitung/figures/plots/\"\n\ntikzplotlib.save(f'{output_path}{output_fname}_full.tex', figure=fig1, wrap=False, add_axis_environment=False, externalize_tables=True, override_externals=True)\ntikzplotlib.save(f'{output_path}{output_fname}_zoom.tex', figure=fig2, wrap=False, add_axis_environment=False, externalize_tables=True, override_externals=True)\ntikzplotlib.save(f'{output_path}{output_fname}_full_noalpha.tex', figure=fig3, wrap=False, add_axis_environment=False, externalize_tables=True, override_externals=True)\ntikzplotlib.save(f'{output_path}{output_fname}_zoom_noalpha.tex', figure=fig4, wrap=False, add_axis_environment=False, externalize_tables=True, override_externals=True)\n\nfig1.savefig(f\"{output_path}{output_fname}_full.pdf\", bbox_inches='tight')\nfig2.savefig(f\"{output_path}{output_fname}_zoom.pdf\", bbox_inches='tight')\nfig3.savefig(f\"{output_path}{output_fname}_full_noalpha.pdf\", bbox_inches='tight')\nfig4.savefig(f\"{output_path}{output_fname}_zoom_noalpha.pdf\", bbox_inches='tight')\n\n"
] | [
[
"numpy.square",
"numpy.amax",
"numpy.amin",
"numpy.arange",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
victorkich/MA-GRID | [
"386e323796b80ed8dac027e916e15a4fa3bf45ef"
] | [
"ddpg.py"
] | [
"import pickle\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom ddpg_step import ddpg_step\nfrom models.Policy_ddpg import Policy\nfrom models.Value_ddpg import Value\nfrom replay_memory import Memory\nfrom torch.utils.tensorboard import SummaryWriter\nfrom utils.file_util import check_path\nfrom utils.torch_util import device, FLOAT\nfrom utils.zfilter import ZFilter\nfrom environment import MAGRID\nfrom tqdm import tqdm\nprint(\"Using:\", device)\n\n\nclass DDPG:\n def __init__(self, render=False, num_process=6, memory_size=1000000, lr_p=1e-3, lr_v=1e-3, gamma=0.99, polyak=0.995,\n explore_size=30000, step_per_iter=3000, batch_size=100, min_update_step=1000, update_step=10,\n action_noise=0.1, seed=1, model_path=None, env_gamma=0.2, num_agents=3, env_grid=20):\n self.gamma = gamma\n self.polyak = polyak\n self.memory = Memory(memory_size)\n self.explore_size = explore_size\n self.step_per_iter = step_per_iter\n self.render = render\n self.num_process = num_process\n self.lr_p = lr_p\n self.lr_v = lr_v\n self.batch_size = batch_size\n self.min_update_step = min_update_step\n self.update_step = update_step\n self.action_noise = action_noise\n self.model_path = model_path\n self.seed = seed\n self.env_gamma = env_gamma\n self.num_agents = num_agents\n self.env_grid = env_grid\n self._init_model()\n\n def _init_model(self):\n self.env = MAGRID(self.num_agents, self.env_grid, self.env_gamma)\n self.num_states = self.env.num_states\n self.num_actions = self.env.num_actions\n\n self.action_low, self.action_high = 0, 5\n # seeding\n np.random.seed(self.seed)\n torch.manual_seed(self.seed)\n self.env.seed(self.seed)\n\n self.policy_net = Policy(self.num_states, self.num_actions, self.action_high).to(device)\n self.policy_net_target = Policy(self.num_states, self.num_actions, self.action_high).to(device)\n\n self.value_net = Value(self.num_states, self.num_actions).to(device)\n self.value_net_target = Value(self.num_states, self.num_actions).to(device)\n\n self.running_state = ZFilter((self.num_states,), clip=5)\n\n if self.model_path:\n print(\"Loading Saved Model {}_ddpg.p\".format('MAGRID'))\n self.policy_net, self.value_net, self.running_state = pickle.load(\n open('{}/{}_ddpg.p'.format(self.model_path, 'MAGRID'), \"rb\"))\n\n self.policy_net_target.load_state_dict(self.policy_net.state_dict())\n self.value_net_target.load_state_dict(self.value_net.state_dict())\n\n self.optimizer_p = optim.Adam(self.policy_net.parameters(), lr=self.lr_p)\n self.optimizer_v = optim.Adam(self.value_net.parameters(), lr=self.lr_v)\n\n def choose_action(self, state, noise_scale):\n \"\"\"select action\"\"\"\n state = FLOAT(state).unsqueeze(0).to(device)\n with torch.no_grad():\n action, log_prob = self.policy_net.get_action_log_prob(state)\n action = action.cpu().numpy()[0]\n # add noise\n noise = noise_scale * np.random.randn(self.num_actions)\n action += noise\n action = np.clip(action, self.action_low, self.action_high)\n return action \n\n def eval(self, i_iter, render=False):\n \"\"\"evaluate model\"\"\"\n state = self.env.reset()\n test_reward = 0\n while True:\n if render:\n self.env.render()\n # state = self.running_state(state)\n action = self.choose_action(state, 0)\n filtered_action = self.filter_action(action)\n state, reward, done = self.env.step(filtered_action)\n\n test_reward += reward\n if done:\n break\n print(f\"Iter: {i_iter}, test Reward: {test_reward}\")\n self.env.close()\n\n def filter_action(self, action):\n for i in range(round(action.size / 3)):\n aux = i * 3\n if abs(action[aux]) > abs(action[aux + 1]) and abs(action[aux]) > abs(action[aux + 2]):\n action[aux] = -1 if action[aux] < 0 else 1\n action[aux + 1] = 0\n action[aux + 2] = 0\n elif abs(action[aux]) < abs(action[aux + 1]) and abs(action[aux + 1]) > abs(action[aux + 2]):\n action[aux] = 0\n action[aux + 1] = -1 if action[aux + 1] < 0 else 1\n action[aux + 2] = 0\n else:\n action[aux] = 0\n action[aux + 1] = 0\n action[aux + 2] = -1 if action[aux + 2] < 0 else 1\n return action.astype(np.int32)\n\n def learn(self, writer, i_iter):\n \"\"\"interact\"\"\"\n global_steps = (i_iter - 1) * self.step_per_iter\n log = dict()\n num_steps = 0\n num_episodes = 0\n total_reward = 0.\n min_episode_reward = float('inf')\n max_episode_reward = float('-inf')\n\n for _ in tqdm(range(self.step_per_iter)):\n state = self.env.reset()\n episode_reward = 0\n for t in range(10000):\n if self.render:\n self.env.render()\n\n if global_steps < self.explore_size: # explore\n action = self.env.get_action_space_sample()\n #filtered_action = action\n else: # action with noise\n action = self.choose_action(state, self.action_noise)\n #filtered_action = self.filter_action(action)\n\n next_state, reward, done = self.env.step(action)\n mask = 0 if done else 1\n # ('state', 'action', 'reward', 'next_state', 'mask', 'log_prob')\n self.memory.push(state, action, reward, next_state, mask, None)\n\n episode_reward += reward\n global_steps += 1\n num_steps += 1\n\n if global_steps >= self.min_update_step and global_steps % self.update_step == 0:\n for _ in range(self.update_step):\n batch = self.memory.sample(\n self.batch_size) # random sample batch\n self.update(batch)\n\n if done or num_steps >= self.step_per_iter:\n break\n\n state = next_state\n\n num_episodes += 1\n total_reward += episode_reward\n min_episode_reward = min(episode_reward, min_episode_reward)\n max_episode_reward = max(episode_reward, max_episode_reward)\n\n # self.env.close()\n log['num_steps'] = num_steps\n log['num_episodes'] = num_episodes\n log['total_reward'] = total_reward\n log['avg_reward'] = total_reward / num_episodes\n log['max_episode_reward'] = max_episode_reward\n log['min_episode_reward'] = min_episode_reward\n\n print(f\"Iter: {i_iter}, num steps: {log['num_steps']}, total reward: {log['total_reward']: .4f}, \"\n f\"min reward: {log['min_episode_reward']: .4f}, max reward: {log['max_episode_reward']: .4f}, \"\n f\"average reward: {log['avg_reward']: .4f}\")\n\n # record reward information\n writer.add_scalar(\"total reward\", log['total_reward'], i_iter)\n writer.add_scalar(\"average reward\", log['avg_reward'], i_iter)\n writer.add_scalar(\"min reward\", log['min_episode_reward'], i_iter)\n writer.add_scalar(\"max reward\", log['max_episode_reward'], i_iter)\n writer.add_scalar(\"num steps\", log['num_steps'], i_iter)\n\n def update(self, batch):\n \"\"\"learn model\"\"\"\n batch_state = FLOAT(batch.state).to(device)\n batch_action = FLOAT(batch.action).to(device)\n batch_reward = FLOAT(batch.reward).to(device)\n batch_next_state = FLOAT(batch.next_state).to(device)\n batch_mask = FLOAT(batch.mask).to(device)\n\n # update by DDPG\n alg_step_stats = ddpg_step(self.policy_net, self.policy_net_target, self.value_net, self.value_net_target,\n self.optimizer_p, self.optimizer_v, batch_state, batch_action, batch_reward,\n batch_next_state, batch_mask, self.gamma, self.polyak)\n\n def save(self, save_path):\n \"\"\"save model\"\"\"\n check_path(save_path)\n pickle.dump((self.policy_net, self.value_net, self.running_state), open('{}/{}_ddpg.p'.format(save_path, 'MAGRID'), 'wb'))\n\n\nif __name__ == '__main__':\n log_path = \"../log/\"\n seed = 1\n base_dir = log_path + \"/DDPG_exp{}\".format(seed)\n writer = SummaryWriter(base_dir)\n max_iter = 500\n model_path = 'trained_models'\n save_iter = 50\n render = False\n eval_iter = 50\n ddpg = DDPG()\n\n for i_iter in range(1, max_iter + 1):\n ddpg.learn(writer, i_iter)\n if i_iter % eval_iter == 0:\n ddpg.eval(i_iter, render=render)\n if i_iter % save_iter == 0:\n ddpg.save(model_path)\n torch.cuda.empty_cache()\n"
] | [
[
"numpy.random.seed",
"numpy.clip",
"torch.manual_seed",
"torch.cuda.empty_cache",
"torch.no_grad",
"torch.utils.tensorboard.SummaryWriter",
"numpy.random.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
soominok/cheese-api | [
"6188b114c89f5aa0f83d92d25e7a5ebda379805e"
] | [
"com_cheese_api/cop/ord/order/model/order_service.py"
] | [
"import os\n\nfrom com_cheese_api.util.file_handler import FileReader\nimport pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier # rforest\nfrom sklearn.tree import DecisionTreeClassifier # dtree\nfrom sklearn.naive_bayes import GaussianNB # nb(Naive Bayes)\nfrom sklearn.neighbors import KNeighborsClassifier # knn(K-Nearest Neighbors algorithm)\nfrom sklearn.svm import SVC # svm(Support Vector Machine)\nfrom sklearn.model_selection import KFold # k value is understood as count\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\n\nfrom pathlib import Path\n# dtree, rforest, nb, knn, svm,\n\n\"\"\"\ncontext: /Users/bitcamp/emp_ai\nfname: \nPassengerId\nSurvived: The answer that a machine learning model should match \nPclass: Boarding Pass 1 = 1st-class seat, 2 = 2nd, 3 = 3rd,\nName,\nSex,\nAge,\nSibSp accompanying brothers, sisters, spouses\nParch accompanying parents, children,\nTicket : Ticket Number\nFare : Boarding Charges\nCabin : Room number\nEmbarked : a Port Name on Board C = Cherbourg, Q = Queenstown, S = Southhampton\n\"\"\"\n\n\nclass OrderService:\n def __init__(self):\n self.fileReader = FileReader()\n self.data = os.path.abspath(\"com_cheese_api\\\\user\\\\data\")\n\n self.odf = None\n\n def hook(self):\n train = 'train.csv'\n test = 'test.csv'\n this = self.fileReader\n this.train = self.new_model(train) # payload\n this.test = self.new_model(test) # payload\n\n '''\n Original Model Generation\n '''\n self.odf = pd.DataFrame(\n\n {\n 'userid': this.train.PassengerId,\n 'password': '1',\n 'name': this.train.Name\n }\n )\n\n this.id = this.test['PassengerId'] # This becomes a question.\n # print(f'Preprocessing Train Variable : {this.train.columns}')\n # print(f'Preprocessing Test Variable : {this.test.columns}')\n this = self.drop_feature(this, 'Cabin')\n this = self.drop_feature(this, 'Ticket')\n # print(f'Post-Drop Variable : {this.train.columns}')\n this = self.embarked_nominal(this)\n # print(f'Preprocessing Embarked Variable : {this.train.head()}')\n this = self.title_nominal(this)\n # print(f'Preprocessing Title Variable : {this.train.head()}')\n '''\n The name is unnecessary because we extracted the Title from the name variable.\n '''\n this = self.drop_feature(this, 'Name')\n this = self.drop_feature(this, 'PassengerId')\n this = self.age_ordinal(this)\n # print(f'Preprocessing Age Variable : {this.train.head()}')\n this = self.drop_feature(this, 'SibSp')\n this = self.sex_nominal(this)\n # print(f'Preprocessing Sex Variable : {this.train.head()}')\n this = self.fareBand_nominal(this)\n # print(f'Preprocessing Fare Variable : {this.train.head()}')\n this = self.drop_feature(this, 'Fare')\n # print(f'Preprocessing Train Result : {this.train.head()}')\n # print(f'Preprocessing Test Result : {this.test.head()}')\n # print(f'Train Na Check : {this.train.isnull().sum()}')\n # print(f'Test Na Check : {this.test.isnull().sum()}')\n this.label = self.create_label(this) # payload\n this.train = self.create_train(this) # payload\n # print(f'Train Variable : {this.train.columns}')\n # print(f'Test Variable : {this.test.columns}')\n clf = RandomForestClassifier()\n clf.fit(this.train, this.label)\n prediction = clf.predict(this.test)\n\n # print(this)\n df = pd.DataFrame(\n \n {\n 'pclass': this.train.Pclass,\n 'gender': this.train.Sex,\n 'age_group': this.train.AgeGroup,\n 'embarked': this.train.Embarked,\n 'rank': this.train.Title\n }\n )\n\n # print(self.odf)\n # print(df)\n sumdf = pd.concat([self.odf, df], axis=1)\n\n# '''\n# userid password name pclass gender age_group embarked rank\n# 0 1 1 Braund, Mr. Owen Harris 3 0 4 1 1\n# 1 2 1 Cumings, Mrs. John Bradley (Florence Briggs Th... 1 1 6 2 3\n# 2 3 1 Heikkinen, Miss. Laina 3 1 5 1 2\n# 3 4 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) 1 1 5 1 3\n# 4 5 1 Allen, Mr. William Henry 3 0 5 1 1\n# .. ... ... ... ... ... ... ... ...\n# 886 887 1 Montvila, Rev. Juozas 2 0 5 1 6\n# 887 888 1 Graham, Miss. Margaret Edith 1 1 4 1 2\n# 888 889 1 Johnston, Miss. Catherine Helen \"Carrie\" 3 1 2 1 2\n# 889 890 1 Behr, Mr. Karl Howell 1 0 5 2 1\n# 890 891 1 Dooley, Mr. Patrick 3 0 5 3 1\n\n# [891 rows x 8 columns]\n# '''\n return sumdf\n\n\n def new_model(self, payload) -> object:\n this = self.fileReader\n this.data = self.data\n this.fname = payload\n print(f'{self.data}')\n print(f'{this.fname}')\n return pd.read_csv(Path(self.data, this.fname))\n\n @staticmethod\n def create_train(this) -> object:\n return this.train.drop('Survived', axis=1) # Train is a dataset in which the answer is removed.\n\n @staticmethod\n def create_label(this) -> object:\n return this.train['Survived'] # Label is the answer.\n\n @staticmethod\n def drop_feature(this, feature) -> object:\n this.train = this.train.drop([feature], axis = 1)\n this.test = this.test.drop([feature], axis = 1)\n return this\n\n\n @staticmethod\n def pclass_ordinal(this) -> object:\n return this\n\n @staticmethod\n def sex_nominal(this) -> object:\n combine = [this.train, this.test] # Train and test are bound.\n sex_mapping = {'male': 0, 'female': 1}\n for dataset in combine:\n dataset['Sex'] = dataset['Sex'].map(sex_mapping)\n this.train = this.train # overriding\n this.test = this.test\n return this\n\n @staticmethod\n def age_ordinal(this) -> object:\n train = this.train\n test = this.test\n train['Age'] = train['Age'].fillna(-0.5)\n test['Age'] = test['Age'].fillna(-0.5)\n '''\n It's ambiguous to put an average, and it's too baseless to put a majority.\n the age is significant in determining survival rates and requires a detailed approach.\n If you don't know your age, \n you have to deal with it without knowing it to reduce the distortion of the price\n -0.5 is the middle value.\n '''\n bins = [-1, 0, 5, 12, 18, 24, 35, 60, np.inf]\n '''\n This part represents a range.\n -1 and more than 0....60 and more...\n [] This must be a variable name here.If you think so, you've got it right.\n '''\n\n labels = ['Unknown', 'Baby', 'Child', 'Teenager', 'Student', 'Young Adult', 'Adult', 'Senior']\n # [] This must be a variable name here.\n train['AgeGroup'] = pd.cut(train['Age'], bins, labels = labels)\n test['AgeGroup'] = pd.cut(train['Age'], bins, labels = labels)\n age_title_mapping = {\n 0: 'Unknown',\n 1: 'Baby',\n 2: 'Child',\n 3: 'Teenager',\n 4: 'Student',\n 5: 'Young Adult',\n 6: 'Adult',\n 7: 'Senior'\n } # If you treat it from [] to {} like this, you will treat Labs as a value.\n for x in range(len(train['AgeGroup'])):\n if train['AgeGroup'][x] == 'Unknown':\n train['AgeGroup'][x] = age_title_mapping[train['Title'][x]]\n for x in range(len(test['AgeGroup'])):\n if test['AgeGroup'][x] == 'Unknown':\n test['AgeGroup'][x] = age_title_mapping[test['Title'][x]]\n\n age_mapping = {\n 'Unknown': 0,\n 'Baby': 1,\n 'Child': 2,\n 'Teenager': 3,\n 'Student': 4,\n 'Young Adult': 5,\n 'Adult': 6,\n 'Senior': 7\n }\n train['AgeGroup'] = train['AgeGroup'].map(age_mapping)\n test['AgeGroup'] = test['AgeGroup'].map(age_mapping)\n this.train = train\n this.test = test\n return this\n\n @staticmethod\n def sibsp_numeric(this) -> object:\n return this\n\n @staticmethod\n def parch_numeric(this) -> object:\n return this\n\n @staticmethod\n def fare_ordinal(this) -> object:\n this.train['FareBand'] = pd.qcut(this['Fare'], 4, labels={1, 2, 3, 4})\n this.train['FareBand'] = pd.qcut(this['Fare'], 4, labels={1, 2, 3, 4})\n return this\n\n\n @staticmethod\n def fareBand_nominal(this) -> object: # Rates vary, so prepare for clustering\n this.train = this.train.fillna({'FareBand': 1}) # FareBand is a non-existent variable added\n this.test = this.test.fillna({'FareBand': 1}) # fillna 함수: 결측값 채울때 사용\n return this\n\n @staticmethod\n def embarked_nominal(this) -> object:\n this.train = this.train.fillna({'Embarked': 'S'}) # S is the most common, filling in empty spaces.\n this.test = this.test.fillna({'Embarked': 'S'})\n '''\n Many machine learning libraries expect class labels to be encoded as * integer*\n mapping: blue = 0, green = 1, red = 2\n '''\n this.train['Embarked'] = this.train['Embarked'].map({'S': 1, 'C': 2, 'Q': 3})\n this.test['Embarked'] = this.test['Embarked'].map({'S': 1, 'C': 2, 'Q': 3})\n return this\n\n @staticmethod\n def title_nominal(this) -> object:\n combine = [this.train, this.test]\n for dataset in combine:\n dataset['Title'] = dataset.Name.str.extract('([A-Za-z]+\\.', expand = False)\n for dataset in combine:\n dataset['Title'] = dataset['Title'].replace(['Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev',\\\n 'Jonkheer', 'Dona', 'Mme'], 'Rare')\n dataset['Title'] = dataset['Title'].replace(['Countess', 'Lady', 'Sir'], 'Royal')\n dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')\n dataset['Title'] = dataset['Title'].replace('Mlle', 'Mr')\n title_mapping = {'Mr': 1, 'Miss': 2, 'Mrs': 3, 'Master': 4, 'Royal': 5, 'Rare': 6}\n for dataset in combine:\n dataset['Title'] = dataset['Title'].map(title_mapping)\n dataset['Title'] = dataset['Title'].fillna(0) # Unknown\n this.train = this.train\n this.test = this.test\n return this\n\n # Dtree, Rforest, NB, Knn, SVM among Learning Algorithms use this as a representative\n\n @staticmethod\n def create_k_fold():\n return KFold(n_splits=10, shuffle=True, random_state=0)\n\n\n def accuracy_by_dtree(self, this):\n dtree = DecisionTreeClassifier()\n score = cross_val_score(dtree, this.train, this.label, cv=UserService.create_k_fold(),\\\n n_jobs=1, scoring='accuracy')\n return round(np.mean(score) * 100, 2)\n\n def accuracy_by_rforest(self, this):\n rforest = RandomForestClassifier()\n score = cross_val_score(rforest, this.train, this.label, cv=UserService.create_k_fold(),\\\n n_jobs=1, scoring='accuracy')\n return round(np.mean(score) * 100, 2)\n\n def accuracy_by_nb(self, this):\n nb = GaussianNB()\n score = cross_val_score(nb, this.train, this.label, cv=UserService.create_k_fold(),\\\n n_jobs=1, scoring='accuracy')\n return round(np.mean(score) * 100, 2)\n\n def accuracy_by_knn(self, this):\n knn = KNeighborsClassifier()\n score = cross_val_score(knn, this.train, this.label, cv=UserService.create_k_fold(),\\\n n_jobs=1, scoring='accuracy')\n return round(np.mean(score) * 100, 2)\n\n def accuracy_by_svm(self, this):\n svm = SVC()\n score = cross_val_score(svm, this.train, this.label, cv=UserService.create_k_fold(),\\\n n_jobs=1, scoring='accuracy')\n return round(np.mean(score) * 100, 2)\n\n def learning(self, train, test):\n service = self.service\n this = self.modeling(train, test)\n print(f'Dtree verification result: {service.accuracy_by_dtree(this)}')\n print(f'RForest verification result: {service.accuracy_by_rforest(this)}')\n print(f'Naive Bayes verification result: {service.accuracy_by_nb(this)}')\n print(f'KNN verification result: {service.accuracy_by_knn(this)}')\n print(f'SVM verification result: {service.accuracy_by_svm(this)}')\n\n def submit(self, train, test):\n this = self.modeling(train, test)\n clf = RandomForestClassifier()\n clf.fit(this.train, this.label)\n prediction = clf.predict(this.test)\n\n print(this)\n # Pclass Sex Age Parch Embarked Title AgeGroup\n df = pd.DataFrame(\n\n {\n 'pclass': this.train.Pclass,\n 'gender': this.train.Sex,\n 'age_group': this.train.AgeGroup,\n 'embarked': this.train.Embarked,\n 'rank': this.train.Title\n }\n )\n \n # print(self.odf)\n # print(df)\n sumdf = pd.concat([self.odf, df], axis=1)\n print(sumdf)\n return sumdf\n'''\nservice = UserService()\nservice.hook()\n'''"
] | [
[
"pandas.concat",
"sklearn.naive_bayes.GaussianNB",
"sklearn.ensemble.RandomForestClassifier",
"pandas.DataFrame",
"sklearn.model_selection.KFold",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.tree.DecisionTreeClassifier",
"numpy.mean",
"pandas.cut",
"sklearn.svm.SVC",
"pandas.qcut"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
tueimage/meta-segmentation-msc-2018 | [
"d497e6ea99b89fdb54e11568452894f022269043"
] | [
"archive/metafeature_extraction/meta_get_features.py"
] | [
"from MetaFeatureExtraction import MetaFeatureExtraction\nfrom tqdm import tqdm\nimport numpy as np\nimport os\nfrom keras.applications.vgg19 import VGG19\nfrom keras.models import Model, model_from_json\nfrom networks import EncoderDecoderNetwork\nfrom keras.applications.mobilenet import relu6\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\ndef main():\n tasks_list=['Task11_CHAOSLiver']\n#\n\n dataset_xlsx = ['braintumor', 'heart', 'liver', 'hippocampus', 'prostate', 'lung', 'pancreas', 'hepaticvessel', 'spleen', 'colon']\n meta_feature_names = ['nr of instances', 'mean pixel value', 'std pixel value', 'coefficient of variation', 'mean correlation coefficient', 'mean skewness', 'mean kurtosis', 'nomalized class entropy', 'mean normalized feature entropy', 'mean mutual inf', 'max mutual inf', 'equivalent nr of features', 'noise signal ratio']\n participants = ['BCVuniandes', 'beomheep', 'CerebriuDIKU', 'EdwardMa12593', 'ildoo', 'iorism82', 'isarasua', 'Isensee', 'jiafucang', 'lesswire1', 'lupin', 'oldrich.kodym', 'ORippler', 'phil666', 'rzchen_xmu', 'ubilearn', 'whale', '17111010008', 'allan.kim01']\n nr_of_subsets = 1\n feature_extractors = ['STAT','VGG16','ResNet50','MobileNetV1']\n filters = {'VGG16': 512, 'MobileNetV1': 1024, 'ResNet50': 2048}\n subset_size_5 = {'Task01_BrainTumour': 5,'Task02_Heart': 5,'Task03_Liver': 5,'Task04_Hippocampus': 5, 'Task05_Prostate': 5, 'Task06_Lung': 5, 'Task07_Pancreas': 5, 'Task08_HepaticVessel': 5, 'Task09_Spleen': 5, 'Task10_Colon': 5}\n subset_size_10 = {'Task01_BrainTumour': 10,'Task02_Heart': 6,'Task03_Liver': 10,'Task04_Hippocampus': 10, 'Task05_Prostate': 10, 'Task06_Lung': 10, 'Task07_Pancreas': 10, 'Task08_HepaticVessel': 10, 'Task09_Spleen': 10, 'Task10_Colon': 10}\n subset_size_20 = {'Task01_BrainTumour': 20,'Task02_Heart': 7,'Task03_Liver': 20,'Task04_Hippocampus': 20, 'Task05_Prostate': 11, 'Task06_Lung': 20, 'Task07_Pancreas': 20, 'Task08_HepaticVessel': 20, 'Task09_Spleen': 16, 'Task10_Colon': 20}\n\n dataset_size = {'Task01_BrainTumour': 266,'Task02_Heart': 10,'Task03_Liver': 60,'Task04_Hippocampus': 130, 'Task05_Prostate': 16, 'Task06_Lung': 32, 'Task07_Pancreas': 139, 'Task08_HepaticVessel': 139, 'Task09_Spleen': 20, 'Task10_Colon': 64}\n for task_id, task in enumerate(tasks_list):\n for fe in feature_extractors:\n meta_subset_size = 5#subset_size_5[task]\n #nr_of_subsets = dataset_size[task]\n labels = np.zeros((nr_of_subsets, meta_subset_size, len(participants)))\n if fe == 'STAT':\n features = np.zeros((nr_of_subsets,meta_subset_size, 33))\n model = None\n nr_of_filters = None\n else:\n nr_of_filters = filters[fe]\n features = np.zeros((nr_of_subsets,meta_subset_size, 7,7,nr_of_filters))\n model = EncoderDecoderNetwork(fe,task_id)\n model.task = task\n model.build_encoder()\n model.build_decoder()\n model.load_weights()\n model.update_encoder_weights()\n\n for subset in tqdm(range(nr_of_subsets)):\n m = MetaFeatureExtraction(task, meta_subset_size, fe, model, nr_of_filters)\n if fe != 'STAT': m.load_model(model.feature_extractor)\n m.gather_random_addresses()\n #m.gather_address(subset)\n # m.gather_list_meta_labels()\n m.gather_meta_features()\n if fe == 'STAT':\n features[subset,:] = m.meta_features\n else:\n features[subset,:,:,:,:] = m.meta_features\n # print(np.count_nonzero(m.meta_labels))\n # labels[subset,:,:] = m.meta_labels\n\n # np.save('metadata/meta_regressor_labels_{}_{}.npy'.format(task, fe), labels)\n np.save('metadata/meta_regressor_features_{}_{}.npy'.format(task, fe), features)\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ashutoshvarma/scipy | [
"46de4f0851991109c83592ee9e8dc59eb6541470"
] | [
"scipy/stats/tests/test_continuous_basic.py"
] | [
"import pickle\nimport numpy as np\nimport numpy.testing as npt\nimport pytest\nfrom pytest import raises as assert_raises\nfrom scipy.integrate import IntegrationWarning\n\nfrom scipy import stats\nfrom scipy.special import betainc\nfrom. common_tests import (check_normalization, check_moment, check_mean_expect,\n check_var_expect, check_skew_expect,\n check_kurt_expect, check_entropy,\n check_private_entropy, check_entropy_vect_scale,\n check_edge_support, check_named_args,\n check_random_state_property,\n check_meth_dtype, check_ppf_dtype, check_cmplx_deriv,\n check_pickling, check_rvs_broadcast, check_freezing)\nfrom scipy.stats._distr_params import distcont\n\n\"\"\"\nTest all continuous distributions.\n\nParameters were chosen for those distributions that pass the\nKolmogorov-Smirnov test. This provides safe parameters for each\ndistributions so that we can perform further testing of class methods.\n\nThese tests currently check only/mostly for serious errors and exceptions,\nnot for numerically exact results.\n\"\"\"\n\n# Note that you need to add new distributions you want tested\n# to _distr_params\n\nDECIMAL = 5 # specify the precision of the tests # increased from 0 to 5\n\n# Last three of these fail all around. Need to be checked\ndistcont_extra = [\n ['betaprime', (100, 86)],\n ['fatiguelife', (5,)],\n ['invweibull', (0.58847112119264788,)],\n # burr: sample mean test fails still for c<1\n ['burr', (0.94839838075366045, 4.3820284068855795)],\n # genextreme: sample mean test, sf-logsf test fail\n ['genextreme', (3.3184017469423535,)],\n]\n\n\ndistslow = ['kstwo', 'genexpon', 'ksone', 'recipinvgauss', 'vonmises',\n 'kappa4', 'vonmises_line', 'gausshyper', 'norminvgauss',\n 'geninvgauss']\n# distslow are sorted by speed (very slow to slow)\n\n# skip check_fit_args (test is slow)\nskip_fit_test = ['exponpow', 'exponweib', 'gausshyper', 'genexpon',\n 'halfgennorm', 'gompertz', 'johnsonsb', 'johnsonsu',\n 'kappa4', 'ksone', 'kstwo', 'kstwobign', 'mielke', 'ncf', 'nct',\n 'powerlognorm', 'powernorm', 'recipinvgauss', 'trapezoid',\n 'vonmises', 'vonmises_line',\n 'levy_stable', 'rv_histogram_instance']\n\n# skip check_fit_args_fix (test is slow)\nskip_fit_fix_test = ['burr', 'exponpow', 'exponweib',\n 'gausshyper', 'genexpon', 'halfgennorm',\n 'gompertz', 'johnsonsb', 'johnsonsu', 'kappa4',\n 'ksone', 'kstwo', 'kstwobign', 'levy_stable', 'mielke', 'ncf',\n 'ncx2', 'powerlognorm', 'powernorm', 'rdist',\n 'recipinvgauss', 'trapezoid', 'vonmises', 'vonmises_line']\n\n# These distributions fail the complex derivative test below.\n# Here 'fail' mean produce wrong results and/or raise exceptions, depending\n# on the implementation details of corresponding special functions.\n# cf https://github.com/scipy/scipy/pull/4979 for a discussion.\nfails_cmplx = set(['beta', 'betaprime', 'chi', 'chi2', 'dgamma', 'dweibull',\n 'erlang', 'f', 'gamma', 'gausshyper', 'gengamma',\n 'geninvgauss', 'gennorm', 'genpareto',\n 'halfgennorm', 'invgamma',\n 'ksone', 'kstwo', 'kstwobign', 'levy_l', 'loggamma', 'logistic',\n 'loguniform', 'maxwell', 'nakagami',\n 'ncf', 'nct', 'ncx2', 'norminvgauss', 'pearson3', 'rdist',\n 'reciprocal', 'rice', 'skewnorm', 't', 'tukeylambda',\n 'vonmises', 'vonmises_line', 'rv_histogram_instance'])\n\n_h = np.histogram([1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,\n 6, 6, 6, 7, 7, 7, 8, 8, 9], bins=8)\nhistogram_test_instance = stats.rv_histogram(_h)\n\n\ndef cases_test_cont_basic():\n for distname, arg in distcont[:] + [(histogram_test_instance, tuple())]:\n if distname == 'levy_stable':\n continue\n elif distname in distslow:\n yield pytest.param(distname, arg, marks=pytest.mark.slow)\n else:\n yield distname, arg\n\n\[email protected]('distname,arg', cases_test_cont_basic())\ndef test_cont_basic(distname, arg):\n # this test skips slow distributions\n\n if distname == 'truncnorm':\n pytest.xfail(reason=distname)\n\n try:\n distfn = getattr(stats, distname)\n except TypeError:\n distfn = distname\n distname = 'rv_histogram_instance'\n\n rng = np.random.RandomState(765456)\n sn = 500\n rvs = distfn.rvs(size=sn, *arg, random_state=rng)\n sm = rvs.mean()\n sv = rvs.var()\n m, v = distfn.stats(*arg)\n\n check_sample_meanvar_(distfn, arg, m, v, sm, sv, sn, distname + 'sample mean test')\n check_cdf_ppf(distfn, arg, distname)\n check_sf_isf(distfn, arg, distname)\n check_pdf(distfn, arg, distname)\n check_pdf_logpdf(distfn, arg, distname)\n check_pdf_logpdf_at_endpoints(distfn, arg, distname)\n check_cdf_logcdf(distfn, arg, distname)\n check_sf_logsf(distfn, arg, distname)\n check_ppf_broadcast(distfn, arg, distname)\n\n alpha = 0.01\n if distname == 'rv_histogram_instance':\n check_distribution_rvs(distfn.cdf, arg, alpha, rvs)\n elif distname != 'geninvgauss':\n # skip kstest for geninvgauss since cdf is too slow; see test for\n # rv generation in TestGenInvGauss in test_distributions.py\n check_distribution_rvs(distname, arg, alpha, rvs)\n\n locscale_defaults = (0, 1)\n meths = [distfn.pdf, distfn.logpdf, distfn.cdf, distfn.logcdf,\n distfn.logsf]\n # make sure arguments are within support\n spec_x = {'weibull_max': -0.5, 'levy_l': -0.5,\n 'pareto': 1.5, 'tukeylambda': 0.3,\n 'rv_histogram_instance': 5.0}\n x = spec_x.get(distname, 0.5)\n if distname == 'invweibull':\n arg = (1,)\n elif distname == 'ksone':\n arg = (3,)\n\n check_named_args(distfn, x, arg, locscale_defaults, meths)\n check_random_state_property(distfn, arg)\n check_pickling(distfn, arg)\n check_freezing(distfn, arg)\n\n # Entropy\n if distname not in ['kstwobign', 'kstwo']:\n check_entropy(distfn, arg, distname)\n\n if distfn.numargs == 0:\n check_vecentropy(distfn, arg)\n\n if (distfn.__class__._entropy != stats.rv_continuous._entropy\n and distname != 'vonmises'):\n check_private_entropy(distfn, arg, stats.rv_continuous)\n\n with npt.suppress_warnings() as sup:\n sup.filter(IntegrationWarning, \"The occurrence of roundoff error\")\n sup.filter(IntegrationWarning, \"Extremely bad integrand\")\n sup.filter(RuntimeWarning, \"invalid value\")\n check_entropy_vect_scale(distfn, arg)\n\n check_retrieving_support(distfn, arg)\n check_edge_support(distfn, arg)\n\n check_meth_dtype(distfn, arg, meths)\n check_ppf_dtype(distfn, arg)\n\n if distname not in fails_cmplx:\n check_cmplx_deriv(distfn, arg)\n\n if distname != 'truncnorm':\n check_ppf_private(distfn, arg, distname)\n\n if distname not in skip_fit_test:\n check_fit_args(distfn, arg, rvs[0:200])\n\n if distname not in skip_fit_fix_test:\n check_fit_args_fix(distfn, arg, rvs[0:200])\n\[email protected]('distname,arg', cases_test_cont_basic())\ndef test_rvs_scalar(distname, arg):\n # rvs should return a scalar when given scalar arguments (gh-12428)\n try:\n distfn = getattr(stats, distname)\n except TypeError:\n distfn = distname\n distname = 'rv_histogram_instance'\n\n assert np.isscalar(distfn.rvs(*arg))\n assert np.isscalar(distfn.rvs(*arg, size=()))\n assert np.isscalar(distfn.rvs(*arg, size=None))\n\n\ndef test_levy_stable_random_state_property():\n # levy_stable only implements rvs(), so it is skipped in the\n # main loop in test_cont_basic(). Here we apply just the test\n # check_random_state_property to levy_stable.\n check_random_state_property(stats.levy_stable, (0.5, 0.1))\n\n\ndef cases_test_moments():\n fail_normalization = set(['vonmises'])\n fail_higher = set(['vonmises', 'ncf'])\n\n for distname, arg in distcont[:] + [(histogram_test_instance, tuple())]:\n if distname == 'levy_stable':\n continue\n\n cond1 = distname not in fail_normalization\n cond2 = distname not in fail_higher\n\n yield distname, arg, cond1, cond2, False\n\n if not cond1 or not cond2:\n # Run the distributions that have issues twice, once skipping the\n # not_ok parts, once with the not_ok parts but marked as knownfail\n yield pytest.param(distname, arg, True, True, True,\n marks=pytest.mark.xfail)\n\n\[email protected]\[email protected]('distname,arg,normalization_ok,higher_ok,is_xfailing',\n cases_test_moments())\ndef test_moments(distname, arg, normalization_ok, higher_ok, is_xfailing):\n try:\n distfn = getattr(stats, distname)\n except TypeError:\n distfn = distname\n distname = 'rv_histogram_instance'\n\n with npt.suppress_warnings() as sup:\n sup.filter(IntegrationWarning,\n \"The integral is probably divergent, or slowly convergent.\")\n if is_xfailing:\n sup.filter(IntegrationWarning)\n\n m, v, s, k = distfn.stats(*arg, moments='mvsk')\n\n if normalization_ok:\n check_normalization(distfn, arg, distname)\n\n if higher_ok:\n check_mean_expect(distfn, arg, m, distname)\n check_skew_expect(distfn, arg, m, v, s, distname)\n check_var_expect(distfn, arg, m, v, distname)\n check_kurt_expect(distfn, arg, m, v, k, distname)\n\n check_loc_scale(distfn, arg, m, v, distname)\n check_moment(distfn, arg, m, v, distname)\n\n\[email protected]('dist,shape_args', distcont)\ndef test_rvs_broadcast(dist, shape_args):\n if dist in ['gausshyper', 'genexpon']:\n pytest.skip(\"too slow\")\n\n # If shape_only is True, it means the _rvs method of the\n # distribution uses more than one random number to generate a random\n # variate. That means the result of using rvs with broadcasting or\n # with a nontrivial size will not necessarily be the same as using the\n # numpy.vectorize'd version of rvs(), so we can only compare the shapes\n # of the results, not the values.\n # Whether or not a distribution is in the following list is an\n # implementation detail of the distribution, not a requirement. If\n # the implementation the rvs() method of a distribution changes, this\n # test might also have to be changed.\n shape_only = dist in ['argus', 'betaprime', 'dgamma', 'dweibull',\n 'exponnorm', 'geninvgauss', 'levy_stable', 'nct',\n 'norminvgauss', 'rice', 'skewnorm', 'semicircular']\n\n distfunc = getattr(stats, dist)\n loc = np.zeros(2)\n scale = np.ones((3, 1))\n nargs = distfunc.numargs\n allargs = []\n bshape = [3, 2]\n # Generate shape parameter arguments...\n for k in range(nargs):\n shp = (k + 4,) + (1,)*(k + 2)\n allargs.append(shape_args[k]*np.ones(shp))\n bshape.insert(0, k + 4)\n allargs.extend([loc, scale])\n # bshape holds the expected shape when loc, scale, and the shape\n # parameters are all broadcast together.\n\n check_rvs_broadcast(distfunc, dist, allargs, bshape, shape_only, 'd')\n\n\ndef test_rvs_gh2069_regression():\n # Regression tests for gh-2069. In scipy 0.17 and earlier,\n # these tests would fail.\n #\n # A typical example of the broken behavior:\n # >>> norm.rvs(loc=np.zeros(5), scale=np.ones(5))\n # array([-2.49613705, -2.49613705, -2.49613705, -2.49613705, -2.49613705])\n rng = np.random.RandomState(123)\n vals = stats.norm.rvs(loc=np.zeros(5), scale=1, random_state=rng)\n d = np.diff(vals)\n npt.assert_(np.all(d != 0), \"All the values are equal, but they shouldn't be!\")\n vals = stats.norm.rvs(loc=0, scale=np.ones(5), random_state=rng)\n d = np.diff(vals)\n npt.assert_(np.all(d != 0), \"All the values are equal, but they shouldn't be!\")\n vals = stats.norm.rvs(loc=np.zeros(5), scale=np.ones(5), random_state=rng)\n d = np.diff(vals)\n npt.assert_(np.all(d != 0), \"All the values are equal, but they shouldn't be!\")\n vals = stats.norm.rvs(loc=np.array([[0], [0]]), scale=np.ones(5),\n random_state=rng)\n d = np.diff(vals.ravel())\n npt.assert_(np.all(d != 0), \"All the values are equal, but they shouldn't be!\")\n\n assert_raises(ValueError, stats.norm.rvs, [[0, 0], [0, 0]],\n [[1, 1], [1, 1]], 1)\n assert_raises(ValueError, stats.gamma.rvs, [2, 3, 4, 5], 0, 1, (2, 2))\n assert_raises(ValueError, stats.gamma.rvs, [1, 1, 1, 1], [0, 0, 0, 0],\n [[1], [2]], (4,))\n\ndef test_nomodify_gh9900_regression():\n # Regression test for gh-9990\n # Prior to gh-9990, calls to stats.truncnorm._cdf() use what ever was\n # set inside the stats.truncnorm instance during stats.truncnorm.cdf().\n # This could cause issues wth multi-threaded code.\n # Since then, the calls to cdf() are not permitted to modify the global\n # stats.truncnorm instance.\n tn = stats.truncnorm\n # Use the right-half truncated normal\n # Check that the cdf and _cdf return the same result.\n npt.assert_almost_equal(tn.cdf(1, 0, np.inf), 0.6826894921370859)\n npt.assert_almost_equal(tn._cdf(1, 0, np.inf), 0.6826894921370859)\n\n # Now use the left-half truncated normal\n npt.assert_almost_equal(tn.cdf(-1, -np.inf, 0), 0.31731050786291415)\n npt.assert_almost_equal(tn._cdf(-1, -np.inf, 0), 0.31731050786291415)\n\n # Check that the right-half truncated normal _cdf hasn't changed\n npt.assert_almost_equal(tn._cdf(1, 0, np.inf), 0.6826894921370859) # NOT 1.6826894921370859\n npt.assert_almost_equal(tn.cdf(1, 0, np.inf), 0.6826894921370859)\n\n # Check that the left-half truncated normal _cdf hasn't changed\n npt.assert_almost_equal(tn._cdf(-1, -np.inf, 0), 0.31731050786291415) # Not -0.6826894921370859\n npt.assert_almost_equal(tn.cdf(1, -np.inf, 0), 1) # Not 1.6826894921370859\n npt.assert_almost_equal(tn.cdf(-1, -np.inf, 0), 0.31731050786291415) # Not -0.6826894921370859\n\n\ndef test_broadcast_gh9990_regression():\n # Regression test for gh-9990\n # The x-value 7 only lies within the support of 4 of the supplied\n # distributions. Prior to 9990, one array passed to\n # stats.reciprocal._cdf would have 4 elements, but an array\n # previously stored by stats.reciprocal_argcheck() would have 6, leading\n # to a broadcast error.\n a = np.array([1, 2, 3, 4, 5, 6])\n b = np.array([8, 16, 1, 32, 1, 48])\n ans = [stats.reciprocal.cdf(7, _a, _b) for _a, _b in zip(a,b)]\n npt.assert_array_almost_equal(stats.reciprocal.cdf(7, a, b), ans)\n\n ans = [stats.reciprocal.cdf(1, _a, _b) for _a, _b in zip(a,b)]\n npt.assert_array_almost_equal(stats.reciprocal.cdf(1, a, b), ans)\n\n ans = [stats.reciprocal.cdf(_a, _a, _b) for _a, _b in zip(a,b)]\n npt.assert_array_almost_equal(stats.reciprocal.cdf(a, a, b), ans)\n\n ans = [stats.reciprocal.cdf(_b, _a, _b) for _a, _b in zip(a,b)]\n npt.assert_array_almost_equal(stats.reciprocal.cdf(b, a, b), ans)\n\ndef test_broadcast_gh7933_regression():\n # Check broadcast works\n stats.truncnorm.logpdf(\n np.array([3.0, 2.0, 1.0]),\n a=(1.5 - np.array([6.0, 5.0, 4.0])) / 3.0,\n b=np.inf,\n loc=np.array([6.0, 5.0, 4.0]),\n scale=3.0\n )\n\ndef test_gh2002_regression():\n # Add a check that broadcast works in situations where only some\n # x-values are compatible with some of the shape arguments.\n x = np.r_[-2:2:101j]\n a = np.r_[-np.ones(50), np.ones(51)]\n expected = [stats.truncnorm.pdf(_x, _a, np.inf) for _x, _a in zip(x, a)]\n ans = stats.truncnorm.pdf(x, a, np.inf)\n npt.assert_array_almost_equal(ans, expected)\n\ndef test_gh1320_regression():\n # Check that the first example from gh-1320 now works.\n c = 2.62\n stats.genextreme.ppf(0.5, np.array([[c], [c + 0.5]]))\n # The other examples in gh-1320 appear to have stopped working\n # some time ago.\n # ans = stats.genextreme.moment(2, np.array([c, c + 0.5]))\n # expected = np.array([25.50105963, 115.11191437])\n # stats.genextreme.moment(5, np.array([[c], [c + 0.5]]))\n # stats.genextreme.moment(5, np.array([c, c + 0.5]))\n\ndef check_sample_meanvar_(distfn, arg, m, v, sm, sv, sn, msg):\n # this did not work, skipped silently by nose\n if np.isfinite(m):\n check_sample_mean(sm, sv, sn, m)\n if np.isfinite(v):\n check_sample_var(sv, sn, v)\n\n\ndef check_sample_mean(sm, v, n, popmean):\n # from stats.stats.ttest_1samp(a, popmean):\n # Calculates the t-obtained for the independent samples T-test on ONE group\n # of scores a, given a population mean.\n #\n # Returns: t-value, two-tailed prob\n df = n-1\n svar = ((n-1)*v) / float(df) # looks redundant\n t = (sm-popmean) / np.sqrt(svar*(1.0/n))\n prob = betainc(0.5*df, 0.5, df/(df + t*t))\n\n # return t,prob\n npt.assert_(prob > 0.01, 'mean fail, t,prob = %f, %f, m, sm=%f,%f' %\n (t, prob, popmean, sm))\n\n\ndef check_sample_var(sv, n, popvar):\n # two-sided chisquare test for sample variance equal to\n # hypothesized variance\n df = n-1\n chi2 = (n - 1)*sv/popvar\n pval = stats.distributions.chi2.sf(chi2, df) * 2\n npt.assert_(pval > 0.01, 'var fail, t, pval = %f, %f, v, sv=%f, %f' %\n (chi2, pval, popvar, sv))\n\n\ndef check_cdf_ppf(distfn, arg, msg):\n values = [0.001, 0.5, 0.999]\n npt.assert_almost_equal(distfn.cdf(distfn.ppf(values, *arg), *arg),\n values, decimal=DECIMAL, err_msg=msg +\n ' - cdf-ppf roundtrip')\n\n\ndef check_sf_isf(distfn, arg, msg):\n npt.assert_almost_equal(distfn.sf(distfn.isf([0.1, 0.5, 0.9], *arg), *arg),\n [0.1, 0.5, 0.9], decimal=DECIMAL, err_msg=msg +\n ' - sf-isf roundtrip')\n npt.assert_almost_equal(distfn.cdf([0.1, 0.9], *arg),\n 1.0 - distfn.sf([0.1, 0.9], *arg),\n decimal=DECIMAL, err_msg=msg +\n ' - cdf-sf relationship')\n\n\ndef check_pdf(distfn, arg, msg):\n # compares pdf at median with numerical derivative of cdf\n median = distfn.ppf(0.5, *arg)\n eps = 1e-6\n pdfv = distfn.pdf(median, *arg)\n if (pdfv < 1e-4) or (pdfv > 1e4):\n # avoid checking a case where pdf is close to zero or\n # huge (singularity)\n median = median + 0.1\n pdfv = distfn.pdf(median, *arg)\n cdfdiff = (distfn.cdf(median + eps, *arg) -\n distfn.cdf(median - eps, *arg))/eps/2.0\n # replace with better diff and better test (more points),\n # actually, this works pretty well\n msg += ' - cdf-pdf relationship'\n npt.assert_almost_equal(pdfv, cdfdiff, decimal=DECIMAL, err_msg=msg)\n\n\ndef check_pdf_logpdf(distfn, args, msg):\n # compares pdf at several points with the log of the pdf\n points = np.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])\n vals = distfn.ppf(points, *args)\n vals = vals[np.isfinite(vals)]\n pdf = distfn.pdf(vals, *args)\n logpdf = distfn.logpdf(vals, *args)\n pdf = pdf[(pdf != 0) & np.isfinite(pdf)]\n logpdf = logpdf[np.isfinite(logpdf)]\n msg += \" - logpdf-log(pdf) relationship\"\n npt.assert_almost_equal(np.log(pdf), logpdf, decimal=7, err_msg=msg)\n\n\ndef check_pdf_logpdf_at_endpoints(distfn, args, msg):\n # compares pdf with the log of the pdf at the (finite) end points\n points = np.array([0, 1])\n vals = distfn.ppf(points, *args)\n vals = vals[np.isfinite(vals)]\n with npt.suppress_warnings() as sup:\n # Several distributions incur divide by zero or encounter invalid values when computing\n # the pdf or logpdf at the endpoints.\n suppress_messsages = [\n \"divide by zero encountered in true_divide\", # multiple distributions\n \"divide by zero encountered in log\", # multiple distributions\n \"divide by zero encountered in power\", # gengamma\n \"invalid value encountered in add\", # genextreme\n \"invalid value encountered in subtract\", # gengamma\n \"invalid value encountered in multiply\" # recipinvgauss\n ]\n for msg in suppress_messsages:\n sup.filter(category=RuntimeWarning, message=msg)\n\n pdf = distfn.pdf(vals, *args)\n logpdf = distfn.logpdf(vals, *args)\n pdf = pdf[(pdf != 0) & np.isfinite(pdf)]\n logpdf = logpdf[np.isfinite(logpdf)]\n msg += \" - logpdf-log(pdf) relationship\"\n npt.assert_almost_equal(np.log(pdf), logpdf, decimal=7, err_msg=msg)\n\n\ndef check_sf_logsf(distfn, args, msg):\n # compares sf at several points with the log of the sf\n points = np.array([0.0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0])\n vals = distfn.ppf(points, *args)\n vals = vals[np.isfinite(vals)]\n sf = distfn.sf(vals, *args)\n logsf = distfn.logsf(vals, *args)\n sf = sf[sf != 0]\n logsf = logsf[np.isfinite(logsf)]\n msg += \" - logsf-log(sf) relationship\"\n npt.assert_almost_equal(np.log(sf), logsf, decimal=7, err_msg=msg)\n\n\ndef check_cdf_logcdf(distfn, args, msg):\n # compares cdf at several points with the log of the cdf\n points = np.array([0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0])\n vals = distfn.ppf(points, *args)\n vals = vals[np.isfinite(vals)]\n cdf = distfn.cdf(vals, *args)\n logcdf = distfn.logcdf(vals, *args)\n cdf = cdf[cdf != 0]\n logcdf = logcdf[np.isfinite(logcdf)]\n msg += \" - logcdf-log(cdf) relationship\"\n npt.assert_almost_equal(np.log(cdf), logcdf, decimal=7, err_msg=msg)\n\n\ndef check_ppf_broadcast(distfn, arg, msg):\n # compares ppf for multiple argsets.\n num_repeats = 5\n args = [] * num_repeats\n if arg:\n args = [np.array([_] * num_repeats) for _ in arg]\n\n median = distfn.ppf(0.5, *arg)\n medians = distfn.ppf(0.5, *args)\n msg += \" - ppf multiple\"\n npt.assert_almost_equal(medians, [median] * num_repeats, decimal=7, err_msg=msg)\n\n\ndef check_distribution_rvs(dist, args, alpha, rvs):\n # dist is either a cdf function or name of a distribution in scipy.stats.\n # args are the args for scipy.stats.dist(*args)\n # alpha is a significance level, ~0.01\n # rvs is array_like of random variables\n # test from scipy.stats.tests\n # this version reuses existing random variables\n D, pval = stats.kstest(rvs, dist, args=args, N=1000)\n if (pval < alpha):\n # The rvs passed in failed the K-S test, which _could_ happen\n # but is unlikely if alpha is small enough.\n # Repeat the the test with a new sample of rvs.\n # Generate 1000 rvs, perform a K-S test that the new sample of rvs\n # are distributed according to the distribution.\n D, pval = stats.kstest(dist, dist, args=args, N=1000)\n npt.assert_(pval > alpha, \"D = \" + str(D) + \"; pval = \" + str(pval) +\n \"; alpha = \" + str(alpha) + \"\\nargs = \" + str(args))\n\n\ndef check_vecentropy(distfn, args):\n npt.assert_equal(distfn.vecentropy(*args), distfn._entropy(*args))\n\n\ndef check_loc_scale(distfn, arg, m, v, msg):\n loc, scale = 10.0, 10.0\n mt, vt = distfn.stats(loc=loc, scale=scale, *arg)\n npt.assert_allclose(m*scale + loc, mt)\n npt.assert_allclose(v*scale*scale, vt)\n\n\ndef check_ppf_private(distfn, arg, msg):\n # fails by design for truncnorm self.nb not defined\n ppfs = distfn._ppf(np.array([0.1, 0.5, 0.9]), *arg)\n npt.assert_(not np.any(np.isnan(ppfs)), msg + 'ppf private is nan')\n\n\ndef check_retrieving_support(distfn, args):\n loc, scale = 1, 2\n supp = distfn.support(*args)\n supp_loc_scale = distfn.support(*args, loc=loc, scale=scale)\n npt.assert_almost_equal(np.array(supp)*scale + loc,\n np.array(supp_loc_scale))\n\n\ndef check_fit_args(distfn, arg, rvs):\n with np.errstate(all='ignore'), npt.suppress_warnings() as sup:\n sup.filter(category=RuntimeWarning,\n message=\"The shape parameter of the erlang\")\n sup.filter(category=RuntimeWarning,\n message=\"floating point number truncated\")\n vals = distfn.fit(rvs)\n vals2 = distfn.fit(rvs, optimizer='powell')\n\n # Only check the length of the return\n # FIXME: should check the actual results to see if we are 'close'\n # to what was created --- but what is 'close' enough\n npt.assert_(len(vals) == 2+len(arg))\n npt.assert_(len(vals2) == 2+len(arg))\n\n\ndef check_fit_args_fix(distfn, arg, rvs):\n with np.errstate(all='ignore'), npt.suppress_warnings() as sup:\n sup.filter(category=RuntimeWarning,\n message=\"The shape parameter of the erlang\")\n\n vals = distfn.fit(rvs, floc=0)\n vals2 = distfn.fit(rvs, fscale=1)\n npt.assert_(len(vals) == 2+len(arg))\n npt.assert_(vals[-2] == 0)\n npt.assert_(vals2[-1] == 1)\n npt.assert_(len(vals2) == 2+len(arg))\n if len(arg) > 0:\n vals3 = distfn.fit(rvs, f0=arg[0])\n npt.assert_(len(vals3) == 2+len(arg))\n npt.assert_(vals3[0] == arg[0])\n if len(arg) > 1:\n vals4 = distfn.fit(rvs, f1=arg[1])\n npt.assert_(len(vals4) == 2+len(arg))\n npt.assert_(vals4[1] == arg[1])\n if len(arg) > 2:\n vals5 = distfn.fit(rvs, f2=arg[2])\n npt.assert_(len(vals5) == 2+len(arg))\n npt.assert_(vals5[2] == arg[2])\n\n\[email protected]('method', ['pdf', 'logpdf', 'cdf', 'logcdf',\n 'sf', 'logsf', 'ppf', 'isf'])\[email protected]('distname, args', distcont)\ndef test_methods_with_lists(method, distname, args):\n # Test that the continuous distributions can accept Python lists\n # as arguments.\n dist = getattr(stats, distname)\n f = getattr(dist, method)\n if distname == 'invweibull' and method.startswith('log'):\n x = [1.5, 2]\n else:\n x = [0.1, 0.2]\n\n shape2 = [[a]*2 for a in args]\n loc = [0, 0.1]\n scale = [1, 1.01]\n result = f(x, *shape2, loc=loc, scale=scale)\n npt.assert_allclose(result,\n [f(*v) for v in zip(x, *shape2, loc, scale)],\n rtol=1e-14, atol=5e-14)\n\n\ndef test_burr_fisk_moment_gh13234_regression():\n vals0 = stats.burr.moment(1, 5, 4)\n assert isinstance(vals0, float)\n\n vals1 = stats.fisk.moment(1, 8)\n assert isinstance(vals1, float)\n"
] | [
[
"numpy.sqrt",
"scipy.stats.rv_histogram",
"scipy.stats.reciprocal.cdf",
"numpy.all",
"numpy.histogram",
"numpy.testing.suppress_warnings",
"numpy.testing.assert_almost_equal",
"numpy.diff",
"scipy.special.betainc",
"numpy.zeros",
"numpy.testing.assert_array_almost_equal",
"numpy.log",
"numpy.isnan",
"scipy.stats.truncnorm.pdf",
"numpy.testing.assert_",
"numpy.testing.assert_allclose",
"numpy.errstate",
"numpy.array",
"numpy.random.RandomState",
"scipy.stats.kstest",
"numpy.isfinite",
"scipy.stats.burr.moment",
"numpy.ones",
"scipy.stats.fisk.moment",
"scipy.stats.distributions.chi2.sf"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Edison1847/Mask_RCNN_Thy | [
"af8e9a97121825a12601f56cc4d57cd4e08ffcc0"
] | [
"samples/demo2.py"
] | [
"import os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport skimage.io\nimport time\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport cv2\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\n# Import COCO config\nsys.path.append(os.path.join(ROOT_DIR, \"samples/coco/\")) # To find local version\nimport coco\n\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n# Local path to trained weights file\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"model.h5\")\n# Download COCO trained weights from Releases if needed\nif not os.path.exists(COCO_MODEL_PATH):\n utils.download_trained_weights(COCO_MODEL_PATH)\n\n# Directory of images to run detection on\nIMAGE_DIR = os.path.join(ROOT_DIR, \"images\")\n\nclass InferenceConfig(coco.CocoConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n NUM_CLASSES = 1+1\n IMAGES_MIN_DIM = 256\n IMAGES_MAX_DIM = 256\n\nconfig = InferenceConfig()\nconfig.display()\n\n\n\n\n\n\n\"\"\"\nMask R-CNN\nDisplay and Visualization Functions.\n\nCopyright (c) 2017 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\n\"\"\"\n\nimport os\nimport sys\nimport random\nimport itertools\nimport colorsys\n\nimport numpy as np\nfrom skimage.measure import find_contours\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches, lines\nfrom matplotlib.patches import Polygon\nimport IPython.display\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\n\n\n############################################################\n# Visualization\n############################################################\n\ndef display_images(images, titles=None, cols=4, cmap=None, norm=None,\n interpolation=None):\n \"\"\"Display the given set of images, optionally with titles.\n images: list or array of image tensors in HWC format.\n titles: optional. A list of titles to display with each image.\n cols: number of images per row\n cmap: Optional. Color map to use. For example, \"Blues\".\n norm: Optional. A Normalize instance to map values to colors.\n interpolation: Optional. Image interpolation to use for display.\n \"\"\"\n titles = titles if titles is not None else [\"\"] * len(images)\n rows = len(images) // cols + 1\n plt.figure(figsize=(14, 14 * rows // cols))\n i = 1\n for image, title in zip(images, titles):\n plt.subplot(rows, cols, i)\n plt.title(title, fontsize=9)\n plt.axis('off')\n plt.imshow(image.astype(np.uint8), cmap=cmap,\n norm=norm, interpolation=interpolation)\n i += 1\n plt.show()\n\n\ndef random_colors(N, bright=True):\n \"\"\"\n Generate random colors.\n To get visually distinct colors, generate them in HSV space then\n convert to RGB.\n \"\"\"\n brightness = 1.0 if bright else 0.7\n hsv = [(i / N, 1, brightness) for i in range(N)]\n colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))\n random.shuffle(colors)\n return colors\n\n\ndef apply_mask(image, mask, color, alpha=0.15):\n \"\"\"Apply the given mask to the image.\n \"\"\"\n for c in range(3):\n image[:, :, c] = np.where(mask == 1,\n image[:, :, c] *\n (1 - alpha) + alpha * color[c] * 255,\n image[:, :, c])\n return image\n\n\ndef display_instances(image, boxes, masks, class_ids, class_names,\n scores=None, title=\"\",\n figsize=(16, 16), ax=None,\n show_mask=False, show_bbox=True,\n colors=None, captions=None):\n \"\"\"\n boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates.\n masks: [height, width, num_instances]\n class_ids: [num_instances]\n class_names: list of class names of the dataset\n scores: (optional) confidence scores for each box\n title: (optional) Figure title\n show_mask, show_bbox: To show masks and bounding boxes or not\n figsize: (optional) the size of the image\n colors: (optional) An array or colors to use with each object\n captions: (optional) A list of strings to use as captions for each object\n \"\"\"\n no_of_masks = []\n print(\"inside_last_func\")\n # Number of instances\n N = boxes.shape[0]\n if not N:\n print(\"\\n*** No instances to display *** \\n\")\n else:\n assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]\n\n # If no axis is passed, create one and automatically call show()\n auto_show = False\n if not ax:\n _, ax = plt.subplots(1, figsize=figsize)\n auto_show = True\n\n # Generate random colors\n colors = colors or random_colors(N)\n\n # Show area outside image boundaries.\n height, width = image.shape[:2]\n ax.set_ylim(height + 10, -10)\n ax.set_xlim(-10, width + 10)\n ax.axis('off')\n ax.set_title(title)\n\n masked_image = image.astype(np.uint32).copy()\n for i in range(N):\n color = colors[i]\n\n # Bounding box\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in image cropping.\n continue\n y1, x1, y2, x2 = boxes[i]\n if show_bbox:\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n alpha=0.7, linestyle=\"dashed\",\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n\n # Label\n if not captions:\n class_id = class_ids[i]\n score = scores[i] if scores is not None else None\n label = class_names[class_id]\n caption = \"{} {:.3f}\".format(label, score) if score else label\n # print(caption)\n else:\n caption = captions[i]\n ax.text(x1, y1 + 8, caption,\n color='b', size=11, backgroundcolor=\"none\")\n\n # Mask\n mask = masks[:, :, i]\n mask_for_area = mask.astype(np.uint8)*255\n contours, hierachy= cv2.findContours(mask_for_area, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n mask_area = cv2.contourArea(contours[0])\n # print(mask_area)\n if show_mask:\n masked_image = apply_mask(masked_image, mask, color)\n\n # Mask Polygon\n # Pad to ensure proper polygons for masks that touch image edges.\n padded_mask = np.zeros(\n (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)\n padded_mask[1:-1, 1:-1] = mask\n contours = find_contours(padded_mask, 0.5)\n for verts in contours:\n # Subtract the padding and flip (y, x) to (x, y)\n verts = np.fliplr(verts) - 1\n p = Polygon(verts, facecolor=\"none\", edgecolor=color)\n ax.add_patch(p)\n ax.imshow(masked_image.astype(np.uint8))\n # plt.imsave(\"uploads/Masked_Image1.jpg\", masked_image.astype(np.uint8))\n # to save file in local directory for n no of input images with date and time\n fig = ax.get_figure()\n fig.savefig(\"uploads/file.jpg\")\n if auto_show:\n\n # plt.imsave(\"uploads/Masked_Image.jpg\", masked_image.astype(np.uint8))\n plt.savefig('uploads/Masked_Image.jpg'.format(time.strftime(\"%Y%m%d-%H%M%S\")), bbox_inches='tight', pad_inches=-0.5)\n\n plt.show()\n return \"done\"\n\n\ndef display_differences(image,\n gt_box, gt_class_id, gt_mask,\n pred_box, pred_class_id, pred_score, pred_mask,\n class_names, title=\"\", ax=None,\n show_mask=True, show_box=True,\n iou_threshold=0.5, score_threshold=0.5):\n \"\"\"Display ground truth and prediction instances on the same image.\"\"\"\n # Match predictions to ground truth\n gt_match, pred_match, overlaps = utils.compute_matches(\n gt_box, gt_class_id, gt_mask,\n pred_box, pred_class_id, pred_score, pred_mask,\n iou_threshold=iou_threshold, score_threshold=score_threshold)\n # Ground truth = green. Predictions = red\n colors = [(0, 1, 0, .8)] * len(gt_match)\\\n + [(1, 0, 0, 1)] * len(pred_match)\n # Concatenate GT and predictions\n class_ids = np.concatenate([gt_class_id, pred_class_id])\n scores = np.concatenate([np.zeros([len(gt_match)]), pred_score])\n boxes = np.concatenate([gt_box, pred_box])\n masks = np.concatenate([gt_mask, pred_mask], axis=-1)\n # Captions per instance show score/IoU\n captions = [\"\" for m in gt_match] + [\"{:.2f} / {:.2f}\".format(\n pred_score[i],\n (overlaps[i, int(pred_match[i])]\n if pred_match[i] > -1 else overlaps[i].max()))\n for i in range(len(pred_match))]\n # Set title if not provided\n title = title or \"Ground Truth and Detections\\n GT=green, pred=red, captions: score/IoU\"\n # Display\n display_instances(\n image,\n boxes, masks, class_ids,\n class_names, scores, ax=ax,\n show_bbox=show_box, show_mask=show_mask,\n colors=colors, captions=captions,\n title=title)\n\n\ndef draw_rois(image, rois, refined_rois, mask, class_ids, class_names, limit=10):\n \"\"\"\n anchors: [n, (y1, x1, y2, x2)] list of anchors in image coordinates.\n proposals: [n, 4] the same anchors but refined to fit objects better.\n \"\"\"\n masked_image = image.copy()\n\n # Pick random anchors in case there are too many.\n ids = np.arange(rois.shape[0], dtype=np.int32)\n ids = np.random.choice(\n ids, limit, replace=False) if ids.shape[0] > limit else ids\n\n fig, ax = plt.subplots(1, figsize=(12, 12))\n if rois.shape[0] > limit:\n plt.title(\"Showing {} random ROIs out of {}\".format(\n len(ids), rois.shape[0]))\n else:\n plt.title(\"{} ROIs\".format(len(ids)))\n\n # Show area outside image boundaries.\n ax.set_ylim(image.shape[0] + 20, -20)\n ax.set_xlim(-50, image.shape[1] + 20)\n ax.axis('off')\n\n for i, id in enumerate(ids):\n color = np.random.rand(3)\n class_id = class_ids[id]\n # ROI\n y1, x1, y2, x2 = rois[id]\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n edgecolor=color if class_id else \"gray\",\n facecolor='none', linestyle=\"dashed\")\n ax.add_patch(p)\n # Refined ROI\n if class_id:\n ry1, rx1, ry2, rx2 = refined_rois[id]\n p = patches.Rectangle((rx1, ry1), rx2 - rx1, ry2 - ry1, linewidth=2,\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n # Connect the top-left corners of the anchor and proposal for easy visualization\n ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))\n\n # Label\n label = class_names[class_id]\n ax.text(rx1, ry1 + 8, \"{}\".format(label),\n color='w', size=11, backgroundcolor=\"none\")\n\n # Mask\n m = utils.unmold_mask(mask[id], rois[id]\n [:4].astype(np.int32), image.shape)\n masked_image = apply_mask(masked_image, m, color)\n\n ax.imshow(masked_image)\n\n # Print stats\n print(\"Positive ROIs: \", class_ids[class_ids > 0].shape[0])\n print(\"Negative ROIs: \", class_ids[class_ids == 0].shape[0])\n print(\"Positive Ratio: {:.2f}\".format(\n class_ids[class_ids > 0].shape[0] / class_ids.shape[0]))\n\n\n# TODO: Replace with matplotlib equivalent?\ndef draw_box(image, box, color):\n \"\"\"Draw 3-pixel width bounding boxes on the given image array.\n color: list of 3 int values for RGB.\n \"\"\"\n y1, x1, y2, x2 = box\n image[y1:y1 + 2, x1:x2] = color\n image[y2:y2 + 2, x1:x2] = color\n image[y1:y2, x1:x1 + 2] = color\n image[y1:y2, x2:x2 + 2] = color\n return image\n\n\ndef display_top_masks(image, mask, class_ids, class_names, limit=4):\n \"\"\"Display the given image and the top few class masks.\"\"\"\n to_display = []\n titles = []\n to_display.append(image)\n titles.append(\"H x W={}x{}\".format(image.shape[0], image.shape[1]))\n # Pick top prominent classes in this image\n unique_class_ids = np.unique(class_ids)\n mask_area = [np.sum(mask[:, :, np.where(class_ids == i)[0]])\n for i in unique_class_ids]\n top_ids = [v[0] for v in sorted(zip(unique_class_ids, mask_area),\n key=lambda r: r[1], reverse=True) if v[1] > 0]\n # Generate images and titles\n for i in range(limit):\n class_id = top_ids[i] if i < len(top_ids) else -1\n # Pull masks of instances belonging to the same class.\n m = mask[:, :, np.where(class_ids == class_id)[0]]\n m = np.sum(m * np.arange(1, m.shape[-1] + 1), -1)\n to_display.append(m)\n titles.append(class_names[class_id] if class_id != -1 else \"-\")\n display_images(to_display, titles=titles, cols=limit + 1, cmap=\"Blues_r\")\n\n\ndef plot_precision_recall(AP, precisions, recalls):\n \"\"\"Draw the precision-recall curve.\n\n AP: Average precision at IoU >= 0.5\n precisions: list of precision values\n recalls: list of recall values\n \"\"\"\n # Plot the Precision-Recall curve\n _, ax = plt.subplots(1)\n ax.set_title(\"Precision-Recall Curve. AP@50 = {:.3f}\".format(AP))\n ax.set_ylim(0, 1.1)\n ax.set_xlim(0, 1.1)\n _ = ax.plot(recalls, precisions)\n\n\ndef plot_overlaps(gt_class_ids, pred_class_ids, pred_scores,\n overlaps, class_names, threshold=0.5):\n \"\"\"Draw a grid showing how ground truth objects are classified.\n gt_class_ids: [N] int. Ground truth class IDs\n pred_class_id: [N] int. Predicted class IDs\n pred_scores: [N] float. The probability scores of predicted classes\n overlaps: [pred_boxes, gt_boxes] IoU overlaps of predictions and GT boxes.\n class_names: list of all class names in the dataset\n threshold: Float. The prediction probability required to predict a class\n \"\"\"\n gt_class_ids = gt_class_ids[gt_class_ids != 0]\n pred_class_ids = pred_class_ids[pred_class_ids != 0]\n\n plt.figure(figsize=(12, 10))\n plt.imshow(overlaps, interpolation='nearest', cmap=plt.cm.Blues)\n plt.yticks(np.arange(len(pred_class_ids)),\n [\"{} ({:.2f})\".format(class_names[int(id)], pred_scores[i])\n for i, id in enumerate(pred_class_ids)])\n plt.xticks(np.arange(len(gt_class_ids)),\n [class_names[int(id)] for id in gt_class_ids], rotation=90)\n\n thresh = overlaps.max() / 2.\n for i, j in itertools.product(range(overlaps.shape[0]),\n range(overlaps.shape[1])):\n text = \"\"\n if overlaps[i, j] > threshold:\n text = \"match\" if gt_class_ids[j] == pred_class_ids[i] else \"wrong\"\n color = (\"white\" if overlaps[i, j] > thresh\n else \"black\" if overlaps[i, j] > 0\n else \"grey\")\n plt.text(j, i, \"{:.3f}\\n{}\".format(overlaps[i, j], text),\n horizontalalignment=\"center\", verticalalignment=\"center\",\n fontsize=9, color=color)\n\n plt.tight_layout()\n plt.xlabel(\"Ground Truth\")\n plt.ylabel(\"Predictions\")\n\n\ndef draw_boxes(image, boxes=None, refined_boxes=None,\n masks=None, captions=None, visibilities=None,\n title=\"\", ax=None):\n \"\"\"Draw bounding boxes and segmentation masks with different\n customizations.\n\n boxes: [N, (y1, x1, y2, x2, class_id)] in image coordinates.\n refined_boxes: Like boxes, but draw with solid lines to show\n that they're the result of refining 'boxes'.\n masks: [N, height, width]\n captions: List of N titles to display on each box\n visibilities: (optional) List of values of 0, 1, or 2. Determine how\n prominent each bounding box should be.\n title: An optional title to show over the image\n ax: (optional) Matplotlib axis to draw on.\n \"\"\"\n # Number of boxes\n assert boxes is not None or refined_boxes is not None\n N = boxes.shape[0] if boxes is not None else refined_boxes.shape[0]\n\n # Matplotlib Axis\n if not ax:\n _, ax = plt.subplots(1, figsize=(12, 12))\n\n # Generate random colors\n colors = random_colors(N)\n\n # Show area outside image boundaries.\n margin = image.shape[0] // 10\n ax.set_ylim(image.shape[0] + margin, -margin)\n ax.set_xlim(-margin, image.shape[1] + margin)\n ax.axis('off')\n\n ax.set_title(title)\n\n masked_image = image.astype(np.uint32).copy()\n for i in range(N):\n # Box visibility\n visibility = visibilities[i] if visibilities is not None else 1\n if visibility == 0:\n color = \"gray\"\n style = \"dotted\"\n alpha = 0.5\n elif visibility == 1:\n color = colors[i]\n style = \"dotted\"\n alpha = 1\n elif visibility == 2:\n color = colors[i]\n style = \"solid\"\n alpha = 1\n\n # Boxes\n if boxes is not None:\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in cropping.\n continue\n y1, x1, y2, x2 = boxes[i]\n p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,\n alpha=alpha, linestyle=style,\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n\n # Refined boxes\n if refined_boxes is not None and visibility > 0:\n ry1, rx1, ry2, rx2 = refined_boxes[i].astype(np.int32)\n p = patches.Rectangle((rx1, ry1), rx2 - rx1, ry2 - ry1, linewidth=2,\n edgecolor=color, facecolor='none')\n ax.add_patch(p)\n # Connect the top-left corners of the anchor and proposal\n if boxes is not None:\n ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))\n\n # Captions\n if captions is not None:\n caption = captions[i]\n # If there are refined boxes, display captions on them\n if refined_boxes is not None:\n y1, x1, y2, x2 = ry1, rx1, ry2, rx2\n ax.text(x1, y1, caption, size=11, verticalalignment='top',\n color='w', backgroundcolor=\"none\",\n bbox={'facecolor': color, 'alpha': 0.5,\n 'pad': 2, 'edgecolor': 'none'})\n\n # Masks\n if masks is not None:\n mask = masks[:, :, i]\n masked_image = apply_mask(masked_image, mask, color)\n # Mask Polygon\n # Pad to ensure proper polygons for masks that touch image edges.\n padded_mask = np.zeros(\n (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)\n padded_mask[1:-1, 1:-1] = mask\n contours = find_contours(padded_mask, 0.5)\n for verts in contours:\n # Subtract the padding and flip (y, x) to (x, y)\n verts = np.fliplr(verts) - 1\n p = Polygon(verts, facecolor=\"none\", edgecolor=color)\n ax.add_patch(p)\n ax.imshow(masked_image.astype(np.uint8))\n\n\ndef display_table(table):\n \"\"\"Display values in a table format.\n table: an iterable of rows, and each row is an iterable of values.\n \"\"\"\n html = \"\"\n for row in table:\n row_html = \"\"\n for col in row:\n row_html += \"<td>{:40}</td>\".format(str(col))\n html += \"<tr>\" + row_html + \"</tr>\"\n html = \"<table>\" + html + \"</table>\"\n IPython.display.display(IPython.display.HTML(html))\n\n\ndef display_weight_stats(model):\n \"\"\"Scans all the weights in the model and returns a list of tuples\n that contain stats about each weight.\n \"\"\"\n layers = model.get_trainable_layers()\n table = [[\"WEIGHT NAME\", \"SHAPE\", \"MIN\", \"MAX\", \"STD\"]]\n for l in layers:\n weight_values = l.get_weights() # list of Numpy arrays\n weight_tensors = l.weights # list of TF tensors\n for i, w in enumerate(weight_values):\n weight_name = weight_tensors[i].name\n # Detect problematic layers. Exclude biases of conv layers.\n alert = \"\"\n if w.min() == w.max() and not (l.__class__.__name__ == \"Conv2D\" and i == 1):\n alert += \"<span style='color:red'>*** dead?</span>\"\n if np.abs(w.min()) > 1000 or np.abs(w.max()) > 1000:\n alert += \"<span style='color:red'>*** Overflow?</span>\"\n # Add row\n table.append([\n weight_name + alert,\n str(w.shape),\n \"{:+9.4f}\".format(w.min()),\n \"{:+10.4f}\".format(w.max()),\n \"{:+9.4f}\".format(w.std()),\n ])\n display_table(table)\n\n\ndef execute(filename):\n # ## Create Model and Load Trained Weights\n # Create model object in inference mode.\n model = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n # Load weights trained on MS-COCO\n model.load_weights(COCO_MODEL_PATH, by_name=True)\n class_names = ['BG', 'Nuclear crowding']\n\n\n # Load a random image from the images folder\n # file_names = next(os.walk(IMAGE_DIR))[2]\n image = skimage.io.imread(os.path.join(IMAGE_DIR, filename))\n\n # Run detection\n results = model.detect([image], verbose=1)\n\n # Visualize results\n r = results[0]\n\n # noClasses = len(r[\"rois\"])\n # write to file\n\n\n\n print(\"worked.....!!!!\")\n\n final_image = display_instances(image, r['rois'], r['masks'], r['class_ids'],\n class_names, r['scores'])\n\n print (\"done\")\n return final_image\n\n\n\n\n\n\n"
] | [
[
"matplotlib.pyplot.imshow",
"numpy.concatenate",
"numpy.any",
"numpy.where",
"matplotlib.patches.Polygon",
"matplotlib.pyplot.tight_layout",
"numpy.unique",
"numpy.fliplr",
"numpy.arange",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.axis",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.random.choice",
"matplotlib.patches.Rectangle",
"numpy.random.rand",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.lines.Line2D",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.xlabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
choco9966/Semantic-Segmentation-Review | [
"2518a0ca39bf9f6459f8fbf9c8dc26b6572abdf1"
] | [
"DeepLab Semantic Image Segmentation with Deep Convolutional Nets, Atrous Convolution, and Fully Connected CRFs (DeepLabv2) Review/code/DeepLabv2.py"
] | [
"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\"\"\"\nlast few max pooling layers를 없애고, 대신에 이후 convolution layers에 atrous convolution을 함. \nVGG16 or ResNet101 in fully convolutional fashion + using Atrous conv for downsampling\nbilinear interpolation to original resolution\nvgg16 based ASPP-L (4 branches : 6, 12, 18, 24)\n\"\"\"\n\ndef conv3x3_relu(in_ch, out_ch, rate=1):\n conv3x3_relu = nn.Sequential(nn.Conv2d(in_ch, out_ch, kernel_size=3, \n stride=1, padding=rate, dilation=rate),\n nn.ReLU())\n return conv3x3_relu\n\nclass VGG16(nn.Module):\n def __init__(self):\n super(VGG16, self).__init__()\n self.features = nn.Sequential(conv3x3_relu(3, 64),\n conv3x3_relu(64, 64),\n nn.MaxPool2d(3, stride=2, padding=1),\n conv3x3_relu(64, 128),\n conv3x3_relu(128, 128),\n nn.MaxPool2d(3, stride=2, padding=1),\n conv3x3_relu(128, 256),\n conv3x3_relu(256, 256),\n conv3x3_relu(256, 256),\n nn.MaxPool2d(3, stride=2, padding=1),\n conv3x3_relu(256, 512),\n conv3x3_relu(512, 512),\n conv3x3_relu(512, 512),\n nn.MaxPool2d(3, stride=1, padding=1), # 마지막 stride=1로 해서 두 layer 크기 유지 \n # and replace subsequent conv layer r=2\n conv3x3_relu(512, 512, rate=2),\n conv3x3_relu(512, 512, rate=2),\n conv3x3_relu(512, 512, rate=2),\n nn.MaxPool2d(3, stride=1, padding=1)) # 마지막 stride=1로 해서 두 layer 크기 유지 \n def forward(self, x):\n return self.features(x)\n\nclass ASPP(nn.Module):\n def __init__(self, in_channels, out_channels=1024, num_classes=21):\n super(ASPP, self).__init__()\n # atrous 3x3, rate=6\n self.conv_3x3_r6 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=6, dilation=6)\n # atrous 3x3, rate=12\n self.conv_3x3_r12 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=12, dilation=12)\n # atrous 3x3, rate=18\n self.conv_3x3_r18 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=18, dilation=18)\n # atrous 3x3, rate=24\n self.conv_3x3_r24 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=24, dilation=24)\n self.drop_conv_3x3 = nn.Dropout2d(0.5)\n\n self.conv_1x1 = nn.Conv2d(out_channels, out_channels, kernel_size=1)\n self.drop_conv_1x1 = nn.Dropout2d(0.5)\n\n self.conv_1x1_out = nn.Conv2d(out_channels, num_classes, kernel_size=1)\n\n def forward(self, feature_map):\n # 1번 branch\n # shape: (batch_size, out_channels, height/output_stride, width/output_stride)\n out_3x3_r6 = self.drop_conv_3x3(F.relu(self.conv_3x3_r6(feature_map)))\n out_img_r6 = self.drop_conv_1x1(F.relu(self.conv_1x1(out_3x3_r6)))\n out_img_r6 = self.conv_1x1_out(out_img_r6)\n # 2번 branch\n # shape: (batch_size, out_channels, height/output_stride, width/output_stride)\n out_3x3_r12 = self.drop_conv_3x3(F.relu(self.conv_3x3_r12(feature_map)))\n out_img_r12 = self.drop_conv_1x1(F.relu(self.conv_1x1(out_3x3_r12)))\n out_img_r12 = self.conv_1x1_out(out_img_r12)\n # 3번 branch\n # shape: (batch_size, out_channels, height/output_stride, width/output_stride)\n out_3x3_r18 = self.drop_conv_3x3(F.relu(self.conv_3x3_r18(feature_map)))\n out_img_r18 = self.drop_conv_1x1(F.relu(self.conv_1x1(out_3x3_r18)))\n out_img_r18 = self.conv_1x1_out(out_img_r18)\n # 4번 branch\n # shape: (batch_size, out_channels, height/output_stride, width/output_stride)\n out_3x3_r24 = self.drop_conv_3x3(F.relu(self.conv_3x3_r24(feature_map)))\n out_img_r24 = self.drop_conv_1x1(F.relu(self.conv_1x1(out_3x3_r24)))\n out_img_r24 = self.conv_1x1_out(out_img_r24)\n\n out = sum([out_img_r6, out_img_r12, out_img_r18, out_img_r24])\n \n return out\n\nclass DeepLabV2(nn.Module):\n ## VGG 위에 ASPP 쌓기\n def __init__(self, backbone, classifier, upsampling=8):\n super(DeepLabV2, self).__init__()\n self.backbone = backbone\n self.classifier = classifier\n self.upsampling = upsampling\n\n def forward(self, x):\n x = self.backbone(x)\n _, _, feature_map_h, feature_map_w = x.size()\n x = self.classifier(x)\n x = F.interpolate(x, size=(feature_map_h * self.upsampling, feature_map_w * self.upsampling), mode=\"bilinear\")\n return x\n\nif __name__=='__main__':\n backbone = VGG16()\n\n in_channels = 512\n out_channels = 256\n num_classes = 21\n aspp_module = ASPP(in_channels, out_channels, num_classes)\n\n model = DeepLabV2(backbone=backbone, classifier=aspp_module)\n #print(model)\n\n model.eval()\n image = torch.randn(1, 3, 1024, 512)\n print(\"input:\", image.shape)\n print(\"output:\", model(image).shape)\n"
] | [
[
"torch.nn.Dropout2d",
"torch.randn",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.functional.interpolate",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kastnerkyle/exploring_species_counterpoint | [
"dda762463e64036adeba7efd46c51daaaf906019"
] | [
"pvnet_mcts/generate_buffer_data_net_mcts.py"
] | [
"from net_mcts import NetMCTS\nfrom networks import PolicyValueNetwork\nfrom env_managers import MusicStateManager\nimport numpy as np\nimport torch as th\nfrom torch.autograd import Variable\nimport copy\n\nrandom_state = np.random.RandomState(9)\nmove_validator = MusicStateManager(random_state=random_state)\npv = PolicyValueNetwork(lower_size=len(move_validator.guide_map), prev_size=len(move_validator.original_map),\n policy_size=move_validator.valid_action_size)\n\ndef policy_value_fn(state):\n p, l = state[0][None, None], state[1:][None]\n p_, l_ = Variable(th.FloatTensor(p)), Variable(th.FloatTensor(l))\n policy_log_probs, value_est = pv(p_, l_)\n policy_log_probs = policy_log_probs.data.numpy()\n value_est = value_est.data.numpy()\n policy_probs = np.exp(policy_log_probs).flatten()\n actions = move_validator.valid_actions(state)\n assert len(actions) == len(policy_probs)\n comb = tuple(zip(actions, policy_probs))\n return comb, float(value_est.ravel())\n\ndef get_trace(random_state):\n state_mgr = MusicStateManager(random_state=random_state)\n mcts = NetMCTS(policy_value_fn, state_mgr, random_state=random_state)\n state = mcts.state_manager.init_state_\n temp = 1.\n states, moves, mcts_probs = [], [], []\n step = 0\n while True:\n move, move_probs = mcts.get_action(state, temp=temp)\n states.append(state)\n moves.append(move)\n mcts_probs.append(move_probs)\n mcts.update_to_move(move)\n state = mcts.state_manager.next_state(state, move)\n winner, end = mcts.state_manager.finished(state)\n step += 1\n if end:\n states.append(state)\n # add some flourish to the end / close it off\n full_seq = mcts.make_full_sequence(list(states))\n try:\n midi = mcts.state_manager.reconstruct_sequence(full_seq)\n except:\n print(\"Error in midi gen\")\n from IPython import embed; embed(); raise ValueError()\n\n try:\n musical_check = mcts.state_manager.evaluate_sequence(midi)\n except:\n print(\"Error in trace musical check\")\n from IPython import embed; embed(); raise ValueError()\n\n break\n return states, mcts_probs, moves, midi, musical_check\n\nif __name__ == \"__main__\":\n from visualization import pitches_and_durations_to_pretty_midi\n from visualization import plot_pitches_and_durations\n from analysis import fixup_parts_durations\n from analysis import intervals_from_midi\n\n from collections import deque\n import cPickle as pickle\n import os\n import shutil\n import gzip\n import time\n\n from shared_config import save_path, tmp_save_path, lockfile, model_path\n from shared_utils import creation_date\n\n boundary = 1000\n deque_max_size = 100000\n data_buffer = deque(maxlen=deque_max_size)\n\n seed = 1999\n if os.path.exists(save_path):\n with gzip.open(save_path, \"rb\") as f:\n old_data = pickle.load(f)\n data_buffer.extend(old_data)\n print(\"Loaded {} datapoints from previous save buffer {}\".format(len(data_buffer), save_path))\n rewards = [od[-1] for od in old_data]\n seed = int(10000 * sum([abs(r) for r in rewards])) % 223145\n print(\"Setting new seed {}\".format(seed))\n\n random_state = np.random.RandomState(seed)\n n_traces = 0\n\n last_param_info = None\n while True:\n ncd = creation_date(model_path)\n if last_param_info is None or ncd != last_param_info:\n print(\"Detected new model parameters in {}, reloading\".format(model_path))\n pv.load_state_dict(th.load(model_path, map_location=lambda storage, loc: storage))\n last_param_info = ncd\n\n start_time = time.time()\n trace_data = []\n n_traces += 1\n i = 1\n ss = 0\n while True:\n print(\"Trace {}, step {}, total length {}\".format(n_traces, i, ss))\n trace_random_state = np.random.RandomState(random_state.randint(1000000000))\n trace_results = get_trace(trace_random_state)\n trace_data.append(trace_results)\n ss = sum([len(td[1]) for td in trace_data])\n i += 1\n if ss > boundary:\n break\n stop_time = time.time()\n\n try:\n # this hackery mainly to avoid empty sequence edge cases\n # tf[-1][1][\"True\"] cannot be 0 length if tf[-1][1][\"False\"] is len 0\n failed = [min(td[-1][1][\"False\"] + [len(td[-2][0])]) for td in trace_data]\n reward = [[1. if ni < failed[n] else -1. for ni in range(len(td[-2][0]))]\n for n, td in enumerate(trace_data)]\n except:\n print(\"Issue in scaled reward calculation\")\n from IPython import embed; embed(); raise ValueError()\n\n flat_reward = [ri for r in reward for ri in r]\n\n print(\"Average scaled rewards: {}\".format(np.mean(flat_reward)))\n print(\"Min scaled rewards: {}\".format(np.min(flat_reward)))\n print(\"Max scaled rewards: {}\".format(np.max(flat_reward)))\n # cut off the end state, since it has no prob transition (it was terminal)\n trace_mcts_states = [td[0][:-1] for td in trace_data]\n trace_mcts_probs = [td[1] for td in trace_data]\n # cut off the end reward, since it has no prob transition (it was terminal)\n trace_mcts_rewards = [reward[n][:len(trace_mcts_probs[n])] for n, td in enumerate(trace_data)]\n\n def safezip(a, b, c=None):\n assert len(a) == len(b)\n if c:\n assert len(a) == len(c)\n return list(zip(a, b, c))\n else:\n return list(zip(a, b))\n\n for tms, tmp, tmr in safezip(trace_mcts_states, trace_mcts_probs, trace_mcts_rewards):\n data_buffer.extend(safezip(tms, tmp, tmr))\n\n with gzip.open(tmp_save_path, \"wb\") as f:\n pickle.dump(list(data_buffer), f)\n\n if os.path.exists(lockfile):\n while True:\n print(\"Buffer lockfile {} found, sleeping...\".format(lockfile))\n time.sleep(10)\n if not os.path.exists(lockfile):\n break\n\n shutil.move(tmp_save_path, save_path)\n print(\"Wrote buffer data of length {} to {}, time to generate {} seconds\".format(len(data_buffer), save_path, int(stop_time - start_time)))\n\n # plot the best and worst output trace\n argmax = [n for n, sr in enumerate(reward) if sr == max(reward)][0]\n argmin = [n for n, sr in enumerate(reward) if sr == min(reward)][0]\n all_parts = []\n all_durations = []\n for ai in [argmax, argmin]:\n if ai == argmax:\n print(\"Plotting best example {}\".format(ai))\n else:\n print(\"Plotting worst example {}\".format(ai))\n #parts = trace_data[0][-2]\n parts = trace_data[ai][-2]\n durations = [['4'] * len(p) for p in parts]\n interval_figures = intervals_from_midi(parts, durations)\n _, interval_durations = fixup_parts_durations(parts, durations)\n interval_durations = [interval_durations[0]]\n durations = [[int(di) for di in d] for d in durations]\n all_parts.append(parts)\n all_durations.append(durations)\n\n key_signature = \"C\"\n time_signature = \"4/4\"\n clefs = [\"treble\", \"bass\"]\n plot_pitches_and_durations(all_parts, all_durations,\n save_dir=\"mcts_plots\",\n name_tag=\"mcts_plot_{}.ly\")\n #interval_figures=interval_figures,\n #interval_durations=interval_durations,\n #use_clefs=clefs)\n\n # now dump samples\n pitches_and_durations_to_pretty_midi(all_parts, all_durations,\n save_dir=\"mcts_samples\",\n name_tag=\"mcts_sample_{}.mid\",\n default_quarter_length=240,\n voice_params=\"piano\")\n print(\"Trace {} completed\".format(n_traces))\n"
] | [
[
"torch.load",
"numpy.min",
"numpy.max",
"torch.FloatTensor",
"numpy.mean",
"numpy.exp",
"numpy.random.RandomState"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dyy0205/VisTR | [
"f1fe95680734f327be262b2a9e6566507ab5608f"
] | [
"net/models/adaptive_avgmax_pool.py"
] | [
"\"\"\" PyTorch selectable adaptive pooling\nAdaptive pooling with the ability to select the type of pooling from:\n * 'avg' - Average pooling\n * 'max' - Max pooling\n * 'avgmax' - Sum of average and max pooling re-scaled by 0.5\n * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles feature dim\n\nBoth a functional and a nn.Module version of the pooling is provided.\n\nAuthor: Ross Wightman (rwightman)\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef adaptive_pool_feat_mult(pool_type='avg'):\n if pool_type == 'catavgmax':\n return 2\n else:\n return 1\n\n\ndef adaptive_avgmax_pool2d(x, output_size=1):\n x_avg = F.adaptive_avg_pool2d(x, output_size)\n x_max = F.adaptive_max_pool2d(x, output_size)\n return 0.5 * (x_avg + x_max)\n\n\ndef adaptive_catavgmax_pool2d(x, output_size=1):\n x_avg = F.adaptive_avg_pool2d(x, output_size)\n x_max = F.adaptive_max_pool2d(x, output_size)\n return torch.cat((x_avg, x_max), 1)\n\n\ndef select_adaptive_pool2d(x, pool_type='avg', output_size=1):\n \"\"\"Selectable global pooling function with dynamic input kernel size\n \"\"\"\n if pool_type == 'avg':\n x = F.adaptive_avg_pool2d(x, output_size)\n elif pool_type == 'avgmax':\n x = adaptive_avgmax_pool2d(x, output_size)\n elif pool_type == 'catavgmax':\n x = adaptive_catavgmax_pool2d(x, output_size)\n elif pool_type == 'max':\n x = F.adaptive_max_pool2d(x, output_size)\n else:\n assert False, 'Invalid pool type: %s' % pool_type\n return x\n\n\nclass AdaptiveAvgMaxPool2d(nn.Module):\n def __init__(self, output_size=1):\n super(AdaptiveAvgMaxPool2d, self).__init__()\n self.output_size = output_size\n\n def forward(self, x):\n return adaptive_avgmax_pool2d(x, self.output_size)\n\n\nclass AdaptiveCatAvgMaxPool2d(nn.Module):\n def __init__(self, output_size=1):\n super(AdaptiveCatAvgMaxPool2d, self).__init__()\n self.output_size = output_size\n\n def forward(self, x):\n return adaptive_catavgmax_pool2d(x, self.output_size)\n\n\nclass SelectAdaptivePool2d(nn.Module):\n \"\"\"Selectable global pooling layer with dynamic input kernel size\n \"\"\"\n def __init__(self, output_size=1, pool_type='avg'):\n super(SelectAdaptivePool2d, self).__init__()\n self.output_size = output_size\n self.pool_type = pool_type\n if pool_type == 'avgmax':\n self.pool = AdaptiveAvgMaxPool2d(output_size)\n elif pool_type == 'catavgmax':\n self.pool = AdaptiveCatAvgMaxPool2d(output_size)\n elif pool_type == 'max':\n self.pool = nn.AdaptiveMaxPool2d(output_size)\n else:\n if pool_type != 'avg':\n print('Invalid pool type %s specified. Defaulting to average pooling.' % pool_type)\n self.pool = nn.AdaptiveAvgPool2d(output_size)\n # self.pool2 = lambda x: x.sumz(dim=1, keepdim=True)\n\n def forward(self, x):\n return self.pool(x)\n\n def feat_mult(self):\n return adaptive_pool_feat_mult(self.pool_type)\n\n def __repr__(self):\n return self.__class__.__name__ + ' (' \\\n + 'output_size=' + str(self.output_size) \\\n + ', pool_type=' + self.pool_type + ')'\n"
] | [
[
"torch.nn.AdaptiveMaxPool2d",
"torch.cat",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.functional.adaptive_max_pool2d",
"torch.nn.AdaptiveAvgPool2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Parskatt/mmdetection | [
"ee4cfa29e7f479b2454b1f1355f8c05be62d8466"
] | [
"mmdet/models/detectors/base.py"
] | [
"# Copyright (c) OpenMMLab. All rights reserved.\nfrom abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict\n\nimport mmcv\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nfrom mmcv.runner import BaseModule, auto_fp16\n\nfrom mmdet.core.visualization import imshow_det_bboxes\n\n\nclass BaseDetector(BaseModule, metaclass=ABCMeta):\n \"\"\"Base class for detectors.\"\"\"\n\n def __init__(self, init_cfg=None):\n super(BaseDetector, self).__init__(init_cfg)\n self.fp16_enabled = False\n\n @property\n def with_neck(self):\n \"\"\"bool: whether the detector has a neck\"\"\"\n return hasattr(self, 'neck') and self.neck is not None\n\n # TODO: these properties need to be carefully handled\n # for both single stage & two stage detectors\n @property\n def with_shared_head(self):\n \"\"\"bool: whether the detector has a shared head in the RoI Head\"\"\"\n return hasattr(self, 'roi_head') and self.roi_head.with_shared_head\n\n @property\n def with_bbox(self):\n \"\"\"bool: whether the detector has a bbox head\"\"\"\n return ((hasattr(self, 'roi_head') and self.roi_head.with_bbox)\n or (hasattr(self, 'bbox_head') and self.bbox_head is not None))\n\n @property\n def with_mask(self):\n \"\"\"bool: whether the detector has a mask head\"\"\"\n return ((hasattr(self, 'roi_head') and self.roi_head.with_mask)\n or (hasattr(self, 'mask_head') and self.mask_head is not None))\n\n @abstractmethod\n def extract_feat(self, imgs):\n \"\"\"Extract features from images.\"\"\"\n pass\n\n def extract_feats(self, imgs):\n \"\"\"Extract features from multiple images.\n\n Args:\n imgs (list[torch.Tensor]): A list of images. The images are\n augmented from the same image but in different ways.\n\n Returns:\n list[torch.Tensor]: Features of different images\n \"\"\"\n assert isinstance(imgs, list)\n return [self.extract_feat(img) for img in imgs]\n\n def forward_train(self, imgs, img_metas, **kwargs):\n \"\"\"\n Args:\n img (list[Tensor]): List of tensors of shape (1, C, H, W).\n Typically these should be mean centered and std scaled.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys, see\n :class:`mmdet.datasets.pipelines.Collect`.\n kwargs (keyword arguments): Specific to concrete implementation.\n \"\"\"\n # NOTE the batched image size information may be useful, e.g.\n # in DETR, this is needed for the construction of masks, which is\n # then used for the transformer_head.\n batch_input_shape = tuple(imgs[0].size()[-2:])\n for img_meta in img_metas:\n img_meta['batch_input_shape'] = batch_input_shape\n\n async def async_simple_test(self, img, img_metas, **kwargs):\n raise NotImplementedError\n\n @abstractmethod\n def simple_test(self, img, img_metas, **kwargs):\n pass\n\n @abstractmethod\n def aug_test(self, imgs, img_metas, **kwargs):\n \"\"\"Test function with test time augmentation.\"\"\"\n pass\n\n async def aforward_test(self, *, img, img_metas, **kwargs):\n for var, name in [(img, 'img'), (img_metas, 'img_metas')]:\n if not isinstance(var, list):\n raise TypeError(f'{name} must be a list, but got {type(var)}')\n\n num_augs = len(img)\n if num_augs != len(img_metas):\n raise ValueError(f'num of augmentations ({len(img)}) '\n f'!= num of image metas ({len(img_metas)})')\n # TODO: remove the restriction of samples_per_gpu == 1 when prepared\n samples_per_gpu = img[0].size(0)\n assert samples_per_gpu == 1\n\n if num_augs == 1:\n return await self.async_simple_test(img[0], img_metas[0], **kwargs)\n else:\n raise NotImplementedError\n\n def forward_test(self, imgs, img_metas, **kwargs):\n \"\"\"\n Args:\n imgs (List[Tensor]): the outer list indicates test-time\n augmentations and inner Tensor should have a shape NxCxHxW,\n which contains all images in the batch.\n img_metas (List[List[dict]]): the outer list indicates test-time\n augs (multiscale, flip, etc.) and the inner list indicates\n images in a batch.\n \"\"\"\n for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]:\n if not isinstance(var, list):\n raise TypeError(f'{name} must be a list, but got {type(var)}')\n\n num_augs = len(imgs)\n if num_augs != len(img_metas):\n raise ValueError(f'num of augmentations ({len(imgs)}) '\n f'!= num of image meta ({len(img_metas)})')\n\n # NOTE the batched image size information may be useful, e.g.\n # in DETR, this is needed for the construction of masks, which is\n # then used for the transformer_head.\n for img, img_meta in zip(imgs, img_metas):\n batch_size = len(img_meta)\n for img_id in range(batch_size):\n img_meta[img_id]['batch_input_shape'] = tuple(img.size()[-2:])\n\n if num_augs == 1:\n # proposals (List[List[Tensor]]): the outer list indicates\n # test-time augs (multiscale, flip, etc.) and the inner list\n # indicates images in a batch.\n # The Tensor should have a shape Px4, where P is the number of\n # proposals.\n if 'proposals' in kwargs:\n kwargs['proposals'] = kwargs['proposals'][0]\n return self.simple_test(imgs[0], img_metas[0], **kwargs)\n else:\n assert imgs[0].size(0) == 1, 'aug test does not support ' \\\n 'inference with batch size ' \\\n f'{imgs[0].size(0)}'\n # TODO: support test augmentation for predefined proposals\n assert 'proposals' not in kwargs\n return self.aug_test(imgs, img_metas, **kwargs)\n\n @auto_fp16(apply_to=('img', ))\n def forward(self, img, img_metas, return_loss=True, **kwargs):\n \"\"\"Calls either :func:`forward_train` or :func:`forward_test` depending\n on whether ``return_loss`` is ``True``.\n\n Note this setting will change the expected inputs. When\n ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor\n and List[dict]), and when ``resturn_loss=False``, img and img_meta\n should be double nested (i.e. List[Tensor], List[List[dict]]), with\n the outer list indicating test time augmentations.\n \"\"\"\n if torch.onnx.is_in_onnx_export():\n assert len(img_metas) == 1\n return self.onnx_export(img[0], img_metas[0])\n if return_loss:\n return self.forward_train(img, img_metas, **kwargs)\n else:\n return self.forward_test(img, img_metas, **kwargs)\n\n def _parse_losses(self, losses):\n \"\"\"Parse the raw outputs (losses) of the network.\n\n Args:\n losses (dict): Raw output of the network, which usually contain\n losses and other necessary information.\n\n Returns:\n tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor \\\n which may be a weighted sum of all losses, log_vars contains \\\n all the variables to be sent to the logger.\n \"\"\"\n log_vars = OrderedDict()\n for loss_name, loss_value in losses.items():\n if isinstance(loss_value, torch.Tensor):\n log_vars[loss_name] = loss_value.mean()\n elif isinstance(loss_value, list):\n log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)\n else:\n raise TypeError(\n f'{loss_name} is not a tensor or list of tensors')\n\n loss = sum(_value for _key, _value in log_vars.items()\n if 'loss' in _key)\n\n # If the loss_vars has different length, GPUs will wait infinitely\n if dist.is_available() and dist.is_initialized():\n log_var_length = torch.tensor(len(log_vars), device=loss.device)\n dist.all_reduce(log_var_length)\n message = (f'rank {dist.get_rank()}' +\n f' len(log_vars): {len(log_vars)}' + ' keys: ' +\n ','.join(log_vars.keys()))\n assert log_var_length == len(log_vars) * dist.get_world_size(), \\\n 'loss log variables are different across GPUs!\\n' + message\n\n log_vars['loss'] = loss\n for loss_name, loss_value in log_vars.items():\n # reduce loss when distributed training\n if dist.is_available() and dist.is_initialized():\n loss_value = loss_value.data.clone()\n dist.all_reduce(loss_value.div_(dist.get_world_size()))\n log_vars[loss_name] = loss_value.item()\n\n return loss, log_vars\n\n def train_step(self, data, optimizer):\n \"\"\"The iteration step during training.\n\n This method defines an iteration step during training, except for the\n back propagation and optimizer updating, which are done in an optimizer\n hook. Note that in some complicated cases or models, the whole process\n including back propagation and optimizer updating is also defined in\n this method, such as GAN.\n\n Args:\n data (dict): The output of dataloader.\n optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of\n runner is passed to ``train_step()``. This argument is unused\n and reserved.\n\n Returns:\n dict: It should contain at least 3 keys: ``loss``, ``log_vars``, \\\n ``num_samples``.\n\n - ``loss`` is a tensor for back propagation, which can be a\n weighted sum of multiple losses.\n - ``log_vars`` contains all the variables to be sent to the\n logger.\n - ``num_samples`` indicates the batch size (when the model is\n DDP, it means the batch size on each GPU), which is used for\n averaging the logs.\n \"\"\"\n losses = self(**data)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss, log_vars=log_vars, num_samples=len(data['img_metas']))\n\n return outputs\n\n def val_step(self, data, optimizer=None):\n \"\"\"The iteration step during validation.\n\n This method shares the same signature as :func:`train_step`, but used\n during val epochs. Note that the evaluation after training epochs is\n not implemented with this method, but an evaluation hook.\n \"\"\"\n losses = self(**data)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss, log_vars=log_vars, num_samples=len(data['img_metas']))\n\n return outputs\n\n def show_result(self,\n img,\n result,\n score_thr=0.3,\n bbox_color=(72, 101, 241),\n text_color=(72, 101, 241),\n mask_color=None,\n thickness=2,\n font_size=13,\n win_name='',\n show=False,\n wait_time=0,\n out_file=None):\n \"\"\"Draw `result` over `img`.\n\n Args:\n img (str or Tensor): The image to be displayed.\n result (Tensor or tuple): The results to draw over `img`\n bbox_result or (bbox_result, segm_result).\n score_thr (float, optional): Minimum score of bboxes to be shown.\n Default: 0.3.\n bbox_color (str or tuple(int) or :obj:`Color`):Color of bbox lines.\n The tuple of color should be in BGR order. Default: 'green'\n text_color (str or tuple(int) or :obj:`Color`):Color of texts.\n The tuple of color should be in BGR order. Default: 'green'\n mask_color (None or str or tuple(int) or :obj:`Color`):\n Color of masks. The tuple of color should be in BGR order.\n Default: None\n thickness (int): Thickness of lines. Default: 2\n font_size (int): Font size of texts. Default: 13\n win_name (str): The window name. Default: ''\n wait_time (float): Value of waitKey param.\n Default: 0.\n show (bool): Whether to show the image.\n Default: False.\n out_file (str or None): The filename to write the image.\n Default: None.\n\n Returns:\n img (Tensor): Only if not `show` or `out_file`\n \"\"\"\n img = mmcv.imread(img)\n img = img.copy()\n if isinstance(result, tuple):\n bbox_result, segm_result = result\n if isinstance(segm_result, tuple):\n segm_result = segm_result[0] # ms rcnn\n else:\n bbox_result, segm_result = result, None\n bboxes = np.vstack(bbox_result)\n labels = [\n np.full(bbox.shape[0], i, dtype=np.int32)\n for i, bbox in enumerate(bbox_result)\n ]\n labels = np.concatenate(labels)\n # draw segmentation masks\n segms = None\n if segm_result is not None and len(labels) > 0: # non empty\n segms = mmcv.concat_list(segm_result)\n if isinstance(segms[0], torch.Tensor):\n segms = torch.stack(segms, dim=0).detach().cpu().numpy()\n else:\n segms = np.stack(segms, axis=0)\n # if out_file specified, do not show image in window\n if out_file is not None:\n show = False\n # draw bounding boxes\n img = imshow_det_bboxes(\n img,\n bboxes,\n labels,\n segms,\n class_names=self.CLASSES,\n score_thr=score_thr,\n bbox_color=bbox_color,\n text_color=text_color,\n mask_color=mask_color,\n thickness=thickness,\n font_size=font_size,\n win_name=win_name,\n show=show,\n wait_time=wait_time,\n out_file=out_file)\n\n if not (show or out_file):\n return img\n\n def onnx_export(self, img, img_metas):\n raise NotImplementedError(f'{self.__class__.__name__} does '\n f'not support ONNX EXPORT')\n"
] | [
[
"torch.distributed.all_reduce",
"torch.distributed.is_initialized",
"numpy.stack",
"numpy.full",
"numpy.concatenate",
"torch.distributed.is_available",
"torch.stack",
"torch.distributed.get_rank",
"torch.distributed.get_world_size",
"torch.onnx.is_in_onnx_export",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xssstory/STAS | [
"ba4286e839069e43c2eac95d14a5f2816d90332e",
"ba4286e839069e43c2eac95d14a5f2816d90332e"
] | [
"fairseq/tasks/extractive_summarization_recovery_dev.py",
"fairseq/models/extract_sum_roberta_long_transformer_rank.py"
] | [
"\r\nimport os\r\nimport numpy as np\r\nimport torch\r\nfrom fairseq import options\r\nfrom fairseq.data import (\r\n data_utils, GPT2Dictionary, FlexibleDictionary, LanguagePairDataset, indexed_dataset,\r\n # ExtractSumRecoveryDataset,\r\n IndexedRawTextDataset,\r\n IndexedCachedDataset,\r\n)\r\nfrom fairseq.data.bert_dictionary import BertDictionary\r\nfrom . import FairseqTask, register_task\r\nfrom fairseq.data.extract_sum_recovery_dataset_dev import ExtractSumRecoveryDevDataset\r\n\r\n@register_task('extractive_summarization_recovery_dev')\r\nclass ExtractiveSummarizationRecoveryDevTask(FairseqTask):\r\n\r\n @staticmethod\r\n def add_args(parser):\r\n \"\"\"Add task-specific arguments to the parser.\"\"\"\r\n parser.add_argument('data', metavar='DIR', help='path to data directory')\r\n parser.add_argument('-s', '--source-lang', default=None, metavar='SRC',\r\n help='source language')\r\n parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET',\r\n help='target language')\r\n parser.add_argument('--raw-text', action='store_true',\r\n help='load raw text dataset')\r\n parser.add_argument('--left-pad-source', default='True', type=str, metavar='BOOL',\r\n help='pad the source on the left (default: True)')\r\n parser.add_argument('--left-pad-target', default='False', type=str, metavar='BOOL',\r\n help='pad the target on the left (default: False)')\r\n parser.add_argument('--max-source-positions', default=40960, type=int, metavar='N',\r\n help='max number of tokens in the source sequence')\r\n parser.add_argument('--max-target-positions', default=40960, type=int, metavar='N',\r\n help='max number of tokens in the target sequence')\r\n parser.add_argument('--ncpu-eval', default=2, type=int, metavar='N',\r\n help='number of CPUs during rouge evaluation')\r\n parser.add_argument('--topk-sent-eval', default=3, type=int, metavar='N',\r\n help='number of sentences selected during rouge evaluation')\r\n parser.add_argument('--raw-valid', default=None, metavar='RAW_VALID',\r\n help='raw valid set')\r\n parser.add_argument('--raw-test', default=None, metavar='RAW_TEST',\r\n help='raw test set')\r\n parser.add_argument('--max-sent-length', default=50, type=int, metavar='N',\r\n help='max number of tokens a source document sentence can have')\r\n parser.add_argument('--max-doc-length', default=30, type=int, metavar='N',\r\n help='max number of sentences a source document can have')\r\n\r\n parser.add_argument('--masked-sent-prob', default=0.15, type=float, help='prob to predict masked lm')\r\n parser.add_argument('--max-predictions-per-doc', default=5, type=int, help='maximum number of masked sentences per doc')\r\n\r\n parser.add_argument('--init-from-pretrained-doc-model', default='False', type=str, metavar='BOOL',\r\n help='init model from a pretrained model')\r\n parser.add_argument('--pretrained-doc-model-path', default=None, metavar='PRETRAINED_PATH',\r\n help='pretrained doc model path')\r\n parser.add_argument('--trigram-block', default='True', type=str)\r\n parser.add_argument('--mask-other-sents', default='False', type=str)\r\n\r\n def __init__(self, args, src_dict, tgt_dict):\r\n super().__init__(args)\r\n self.src_dict = src_dict\r\n self.tgt_dict = tgt_dict\r\n self.max_src_size = 0\r\n self.max_tgt_size = 0\r\n self.run_dummy_batch = True\r\n # self.run_dummy_batch = False # just for test\r\n\r\n @classmethod\r\n def setup_task(cls, args, **kwargs):\r\n args.left_pad_source = options.eval_bool(args.left_pad_source)\r\n args.left_pad_target = options.eval_bool(args.left_pad_target)\r\n args.trigram_block = options.eval_bool(args.trigram_block)\r\n args.init_from_pretrained_doc_model = options.eval_bool(args.init_from_pretrained_doc_model)\r\n\r\n # find language pair automatically\r\n if args.source_lang is None or args.target_lang is None:\r\n args.source_lang, args.target_lang = data_utils.infer_language_pair(args.data)\r\n if args.source_lang is None or args.target_lang is None:\r\n raise Exception('Could not infer language pair, please provide it explicitly')\r\n\r\n # load dictionaries\r\n if args.roberta_model.startswith('roberta'):\r\n src_dict = GPT2Dictionary.load(os.path.join(args.data, 'dict.{}.txt'.format(args.source_lang)))\r\n else:\r\n src_dict = BertDictionary.load(os.path.join(args.data, 'dict.{}.txt'.format(args.source_lang)))\r\n idx = src_dict.add_special_token('<sent_mask>')\r\n print('<sent_mask> id = {}, token = {}'.format(idx, src_dict[idx]))\r\n print('<mask> id is', src_dict.index('<mask>'))\r\n print('<sent_mask> id is', src_dict.index('<sent_mask>'))\r\n\r\n tgt_dict = FlexibleDictionary.load(os.path.join(args.data, 'dict.{}.txt'.format(args.target_lang)))\r\n print('| [{}] dictionary: {} types'.format(args.source_lang, len(src_dict)))\r\n print('| [{}] dictionary: {} types'.format(args.target_lang, len(tgt_dict)))\r\n\r\n return cls(args, src_dict, tgt_dict)\r\n\r\n def create_doc_size_file(self, doc_dataset, sent_sep_idx, doc_size_file):\r\n with open(doc_size_file, 'w', encoding='utf8') as fout:\r\n print('dataset size', len(doc_dataset))\r\n for i in range(len(doc_dataset)):\r\n src_doc = doc_dataset[i]\r\n # src_doc = self.src[index]\r\n\r\n istart = 0\r\n max_sent_len = 0\r\n doc_nsent = 0\r\n for i in range(len(src_doc)):\r\n if src_doc[i] == sent_sep_idx or i == len(src_doc) - 1:\r\n sent_len = i - istart\r\n if src_doc[i] != sent_sep_idx:\r\n sent_len += 1\r\n max_sent_len = max(max_sent_len, sent_len)\r\n istart = i+1\r\n doc_nsent += 1\r\n\r\n fout.write('{}\\t{}\\n'.format(doc_nsent, max_sent_len))\r\n fout.flush()\r\n\r\n def load_doc_size_file(self, doc_size_file):\r\n doc_sizes = []\r\n for line in open(doc_size_file, encoding='utf8'):\r\n fds = line.strip().split()\r\n assert len(fds) == 2, 'size file MUST have two fileds'\r\n doc_sizes.append( (int(fds[0]), int(fds[1])) )\r\n print('load doc size done', len(doc_sizes))\r\n return doc_sizes\r\n\r\n def load_dataset(self, split, shuffle=True):\r\n \"\"\"Load a dataset split.\"\"\"\r\n\r\n def split_exists(split, src, tgt, lang, data_path):\r\n filename = os.path.join(data_path, '{}.{}-{}.{}'.format(split, src, tgt, lang))\r\n return indexed_dataset.dataset_exists(filename, impl=self.args.dataset_impl)\r\n\r\n # infer langcode\r\n src, tgt = self.args.source_lang, self.args.target_lang\r\n if split_exists(split, src, tgt, src, self.args.data):\r\n prefix = os.path.join(self.args.data, '{}.{}-{}.'.format(split, src, tgt))\r\n elif split_exists(split, tgt, src, src, self.args.data):\r\n prefix = os.path.join(self.args.data, '{}.{}-{}.'.format(split, tgt, src))\r\n else:\r\n raise FileNotFoundError('Dataset not found: {} ({})'.format(split, self.args.data))\r\n\r\n src_dataset = data_utils.load_indexed_dataset(prefix + src, self.src_dict, self.args.dataset_impl)\r\n tgt_dataset = data_utils.load_indexed_dataset(prefix + tgt, self.tgt_dict, self.args.dataset_impl)\r\n\r\n rng = np.random.RandomState(self.args.seed)\r\n\r\n # get doc size information\r\n assert isinstance(src_dataset, IndexedCachedDataset), 'currently only support IndexedInMemoryDataset'\r\n src_path = prefix + src\r\n\r\n # need to be updated with extractive summarization dataset\r\n self.datasets[split] = ExtractSumRecoveryDevDataset(\r\n src_dataset, src_dataset.sizes, self.src_dict,\r\n tgt_dataset, tgt_dataset.sizes if tgt_dataset is not None else None, self.tgt_dict,\r\n left_pad_source=self.args.left_pad_source,\r\n left_pad_target=self.args.left_pad_target,\r\n max_source_positions=self.args.max_source_positions,\r\n max_target_positions=self.args.max_target_positions,\r\n shuffle=shuffle,\r\n max_sent_len=self.args.max_sent_length,\r\n max_doc_len=self.args.max_doc_length,\r\n masked_sent_prob=self.args.masked_sent_prob,\r\n max_predictions_per_doc=self.args.max_predictions_per_doc,\r\n rng=rng,\r\n doc_sizes=None,\r\n mask_other_sents=eval(self.args.mask_other_sents),\r\n bert_model= self.args.roberta_model,\r\n )\r\n\r\n\r\n def load_pretrained_model(self, model, state_file_name):\r\n from torch.serialization import default_restore_location\r\n state = torch.load(state_file_name, map_location=lambda s, l: default_restore_location(s, 'cpu'))\r\n if state['args'].fp16 != model.args.fp16:\r\n print('change the fp16 in model to {}'.format(state['args'].fp16))\r\n model.args.fp16 = state['args'].fp16\r\n params = state['model']\r\n\r\n print('num params', len(list(params.keys())))\r\n tobe_del_param_names = [k for k in params.keys() if k.startswith('decoder.out_proj')]\r\n for nk in tobe_del_param_names:\r\n del params[nk]\r\n\r\n print('num params after removing', len(list(params.keys())) )\r\n\r\n model.load_state_dict(params, strict=False)\r\n print('*** *** load pretrained doc encoder done! *** ***')\r\n\r\n\r\n @property\r\n def source_dictionary(self):\r\n return self.src_dict\r\n\r\n @property\r\n def target_dictionary(self):\r\n return self.tgt_dict\r\n\r\n def clear_cuda(self, sample):\r\n src_size = sample['net_input']['src_tokens'].numel()\r\n tgt_size = sample['target'].numel()\r\n if src_size > self.max_src_size or tgt_size > self.max_tgt_size:\r\n torch.cuda.empty_cache()\r\n if src_size > self.max_src_size:\r\n self.max_src_size = src_size\r\n if tgt_size > self.max_tgt_size:\r\n self.max_tgt_size = tgt_size\r\n",
"\r\nimport math\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nfrom fairseq import utils\r\n\r\nfrom fairseq.modules import (\r\n LearnedPositionalEmbedding, MultiheadAttention,\r\n SinusoidalPositionalEmbedding,\r\n)\r\nfrom fairseq.modules.attn_score_bert_encoder import AttnScoreBertEncoder\r\nfrom . import (\r\n FairseqIncrementalDecoder, FairseqEncoder, FairseqModel,\r\n register_model, register_model_architecture, FairseqDecoder\r\n)\r\n\r\nfrom pytorch_transformers.modeling_bert import BertEncoder, BertLayerNorm\r\n\r\ndef get_sent_end_repr(src_emb, sent_ends):\r\n bsz, nsent = sent_ends.size()\r\n assert bsz == src_emb.size(0)\r\n seqlen = src_emb.size(1)\r\n offset = torch.linspace(0, (bsz-1)*seqlen, bsz).type(sent_ends.type())\r\n sent_ends_abs = sent_ends + offset.view(-1, 1)\r\n sent_ends_repr = src_emb.contiguous().view(bsz*seqlen, -1)[sent_ends_abs]\r\n sent_ends_repr = sent_ends_repr.view(bsz, nsent, -1)\r\n\r\n return sent_ends_repr\r\n\r\n\r\n@register_model('extract_sum_roberta_long_transformer_rank')\r\nclass ExtractSumRobertaLongTransformerModel(FairseqModel):\r\n def __init__(self, args, encoder, decoder):\r\n super().__init__(encoder, decoder)\r\n self.args = args\r\n\r\n @staticmethod\r\n def add_args(parser):\r\n \"\"\"Add model-specific arguments to the parser.\"\"\"\r\n parser.add_argument('--dropout', type=float, metavar='D',\r\n help='dropout probability')\r\n parser.add_argument('--attention-dropout', type=float, metavar='D',\r\n help='dropout probability for attention weights')\r\n parser.add_argument('--relu-dropout', type=float, metavar='D',\r\n help='dropout probability after ReLU in FFN')\r\n parser.add_argument('--encoder-embed-path', type=str, metavar='STR',\r\n help='path to pre-trained encoder embedding')\r\n parser.add_argument('--encoder-embed-dim', type=int, metavar='N',\r\n help='encoder embedding dimension')\r\n parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N',\r\n help='encoder embedding dimension for FFN')\r\n parser.add_argument('--encoder-layers', type=int, metavar='N',\r\n help='num encoder layers')\r\n parser.add_argument('--encoder-attention-heads', type=int, metavar='N',\r\n help='num encoder attention heads')\r\n parser.add_argument('--encoder-normalize-before', default=False, action='store_true',\r\n help='apply layernorm before each encoder block')\r\n parser.add_argument('--encoder-learned-pos', default=False, action='store_true',\r\n help='use learned positional embeddings in the encoder')\r\n parser.add_argument('--decoder-embed-path', type=str, metavar='STR',\r\n help='path to pre-trained decoder embedding')\r\n parser.add_argument('--decoder-embed-dim', type=int, metavar='N',\r\n help='decoder embedding dimension')\r\n parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N',\r\n help='decoder embedding dimension for FFN')\r\n parser.add_argument('--decoder-layers', type=int, metavar='N',\r\n help='num decoder layers')\r\n parser.add_argument('--decoder-attention-heads', type=int, metavar='N',\r\n help='num decoder attention heads')\r\n parser.add_argument('--decoder-learned-pos', default=False, action='store_true',\r\n help='use learned positional embeddings in the decoder')\r\n parser.add_argument('--decoder-normalize-before', default=False, action='store_true',\r\n help='apply layernorm before each decoder block')\r\n parser.add_argument('--share-decoder-input-output-embed', default=False, action='store_true',\r\n help='share decoder input and output embeddings')\r\n parser.add_argument('--share-all-embeddings', default=False, action='store_true',\r\n help='share encoder, decoder and output embeddings'\r\n ' (requires shared dictionary and embed dim)')\r\n parser.add_argument('--roberta-model', default='roberta-base', help=\"RoBERTa pre-trained model selected in the list: roberta-base, \"\r\n \"roberta-large\")\r\n parser.add_argument('--sentence-transformer-arch', default='fairseq', help=\"sentence level transformer architecture [fairseq, bert]\")\r\n parser.add_argument('--bert-no-decay', default=False, action='store_true', help=\"no decay for bias and LayerNorm.weight\")\r\n parser.add_argument('--attn-type', default='attn_score', choices=['attn_score', 'attn_prob'], help='attn_socre is before softmax and attn_prob is after softmax')\r\n parser.add_argument('--transpose_method', choices=['transpose', 'not_transpose', 'add'], default='add')\r\n parser.add_argument('--attn-layer', default='all', choices=['all', 'final']) \r\n parser.add_argument('--topk', default=3, type=int)\r\n\r\n\r\n @classmethod\r\n def build_model(cls, args, task):\r\n \"\"\"Build a new model instance.\"\"\"\r\n # make sure that all args are properly defaulted (in case there are any new ones)\r\n base_architecture(args)\r\n\r\n src_dict, tgt_dict = task.source_dictionary, task.target_dictionary\r\n\r\n def build_embedding(dictionary, embed_dim, path=None):\r\n num_embeddings = len(dictionary)\r\n padding_idx = dictionary.pad()\r\n emb = Embedding(num_embeddings, embed_dim, padding_idx)\r\n # if provided, load from preloaded dictionaries\r\n if path:\r\n embed_dict = utils.parse_embedding(path)\r\n utils.load_embedding(embed_dict, dictionary, emb)\r\n return emb\r\n\r\n if args.share_all_embeddings:\r\n if src_dict != tgt_dict:\r\n raise RuntimeError('--share-all-embeddings requires a joined dictionary')\r\n if args.encoder_embed_dim != args.decoder_embed_dim:\r\n raise RuntimeError(\r\n '--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim')\r\n if args.decoder_embed_path and (\r\n args.decoder_embed_path != args.encoder_embed_path):\r\n raise RuntimeError('--share-all-embeddings not compatible with --decoder-embed-path')\r\n encoder_embed_tokens = build_embedding(\r\n src_dict, args.encoder_embed_dim, args.encoder_embed_path\r\n )\r\n decoder_embed_tokens = encoder_embed_tokens\r\n args.share_decoder_input_output_embed = True\r\n else:\r\n encoder_embed_tokens = build_embedding(\r\n src_dict, args.encoder_embed_dim, args.encoder_embed_path\r\n )\r\n decoder_embed_tokens = build_embedding(\r\n tgt_dict, args.decoder_embed_dim, args.decoder_embed_path\r\n )\r\n\r\n encoder = TransformerEncoder(args, src_dict, encoder_embed_tokens)\r\n decoder = RankDecoder(args, tgt_dict)\r\n return ExtractSumRobertaLongTransformerModel(args, encoder, decoder)\r\n\r\n def forward(self, src_tokens, segment_ids, doc_pad_mask, doc_pos_tok, cls_pos, token_mask):\r\n encoder_out = self.encoder(src_tokens, segment_ids, doc_pad_mask, doc_pos_tok, cls_pos, token_mask)\r\n decoder_out = self.decoder(self.args.transpose_method,encoder_out)\r\n return decoder_out\r\n\r\n\r\nclass TransformerEncoder(FairseqEncoder):\r\n \"\"\"Transformer encoder.\"\"\"\r\n\r\n def __init__(self, args, dictionary, embed_tokens, left_pad=False):\r\n super().__init__(dictionary)\r\n self.dropout = args.dropout\r\n\r\n # from pytorch_transformers import RobertaModel\r\n from fairseq.modules.roberta_causal_mask import RobertaCasulMaskModel\r\n from pytorch_transformers.file_utils import PYTORCH_TRANSFORMERS_CACHE\r\n\r\n self.roberta = RobertaCasulMaskModel.from_pretrained(args.roberta_model,\r\n cache_dir=PYTORCH_TRANSFORMERS_CACHE / 'distributed_{}'.format(args.distributed_rank))\r\n self.roberta.pooler.dense.weight.requires_grad = False\r\n self.roberta.pooler.dense.bias.requires_grad = False\r\n\r\n embed_dim = embed_tokens.embedding_dim\r\n\r\n # self.embed_tokens = embed_tokens\r\n # self.embed_scale = math.sqrt(embed_dim)\r\n\r\n self.args = args\r\n\r\n if args.sentence_transformer_arch == 'fairseq':\r\n self.padding_idx = embed_tokens.padding_idx\r\n\r\n self.sent_embed_positions = PositionalEmbedding(\r\n 1024, embed_dim, self.padding_idx,\r\n left_pad=False,\r\n learned=args.encoder_learned_pos,\r\n )\r\n\r\n self.doc_layers = nn.ModuleList([])\r\n self.doc_layers.extend([\r\n TransformerEncoderLayer(args)\r\n for i in range(args.encoder_layers)\r\n ])\r\n elif args.sentence_transformer_arch == 'bert':\r\n from pytorch_transformers import RobertaConfig, RobertaTokenizer\r\n\r\n self.config = RobertaConfig.from_pretrained(args.roberta_model)\r\n self.config.output_attentions = True\r\n self.tokenizer = RobertaTokenizer.from_pretrained('roberta-base')\r\n\r\n embed_dim = self.config.hidden_size\r\n print('*** padding idx before ***', embed_tokens.padding_idx)\r\n self.padding_idx = self.tokenizer.convert_tokens_to_ids(self.tokenizer.pad_token)\r\n print('*** padding idx after ***', self.padding_idx)\r\n\r\n # let's assume each document has at most 128-self.padding_idx-1 sentences\r\n # in case of roberta, it is 126\r\n self.sent_position_embeddings = nn.Embedding(128, embed_dim)\r\n if args.encoder_layers:\r\n self.config.num_hidden_layers = args.encoder_layers\r\n if args.dropout:\r\n self.config.hidden_dropout_prob = args.dropout\r\n if args.attention_dropout:\r\n self.config.attention_probs_dropout_prob = args.attention_dropout\r\n if args.attn_type == 'attn_score':\r\n self.sent_encoder = AttnScoreBertEncoder(self.config)\r\n elif args.attn_type == 'attn_prob':\r\n self.sent_encoder = BertEncoder(self.config)\r\n else:\r\n raise Exception('--attn-type doesn\\'t support {} yet !'.format(args.attn_type))\r\n self.sent_encoder.apply(self._init_weights)\r\n\r\n print('*** sentence encoder config ***')\r\n print(self.config)\r\n else:\r\n raise Exception('--sentence-transformer-arch doesn\\'t support {} yet!'.format(args.sentence_transformer_arch))\r\n\r\n def _init_weights(self, module):\r\n \"\"\" Initialize the weights \"\"\"\r\n if isinstance(module, (nn.Linear, nn.Embedding)):\r\n # Slightly different from the TF version which uses truncated_normal for initialization\r\n # cf https://github.com/pytorch/pytorch/pull/5617\r\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\r\n elif isinstance(module, BertLayerNorm):\r\n module.bias.data.zero_()\r\n module.weight.data.fill_(1.0)\r\n if isinstance(module, nn.Linear) and module.bias is not None:\r\n module.bias.data.zero_()\r\n\r\n def forward(self, src_tokens, segment_ids, doc_pad_mask, doc_pos_tok, cls_pos, attention_mask):\r\n if self.args.sentence_transformer_arch == 'fairseq':\r\n bsz, seqlen = src_tokens.size()\r\n\r\n # compute padding mask\r\n attention_mask = src_tokens.ne(self.padding_idx)\r\n # enc_hids, _ = self.bert(src_tokens, segment_ids, attention_mask, output_all_encoded_layers=False)\r\n all_hids = self.roberta(src_tokens, segment_ids, attention_mask=None)\r\n # print('all_hids', all_hids.size())\r\n enc_hids = all_hids[0]\r\n doc_pos = self.sent_embed_positions(doc_pos_tok)\r\n\r\n sent_repr = get_sent_end_repr(enc_hids, cls_pos)\r\n\r\n sent_repr = sent_repr + doc_pos\r\n # n_sent x bsz x C\r\n sent_repr = sent_repr.transpose(0, 1)\r\n for doc_layer in self.doc_layers:\r\n sent_repr = doc_layer(sent_repr, doc_pad_mask)\r\n\r\n return {\r\n 'encoder_out': sent_repr, # n_sent x bsz x C\r\n 'encoder_padding_mask': doc_pad_mask, # bsz x n_sent\r\n }\r\n elif self.args.sentence_transformer_arch == 'bert':\r\n bsz, seqlen = src_tokens.size()\r\n\r\n doclen = cls_pos.size(1)\r\n position_ids = torch.arange(1+self.padding_idx, doclen+1+self.padding_idx, dtype=torch.long, device=cls_pos.device)\r\n position_ids = position_ids.unsqueeze(0).expand_as(cls_pos)\r\n doc_pos = self.sent_position_embeddings(position_ids)\r\n\r\n # compute padding mask\r\n if attention_mask is None:\r\n attention_mask = src_tokens.ne(self.padding_idx)\r\n all_hids = self.roberta(src_tokens, segment_ids, attention_mask)\r\n enc_hids = all_hids[0]\r\n\r\n sent_repr = get_sent_end_repr(enc_hids, cls_pos)\r\n\r\n sent_repr = sent_repr + doc_pos\r\n\r\n head_mask = [None] * self.config.num_hidden_layers\r\n\r\n extended_doc_mask = doc_pad_mask.unsqueeze(1).unsqueeze(2)\r\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\r\n # masked positions, this operation will create a tensor which is 0.0 for\r\n # positions we want to attend and -10000.0 for masked positions.\r\n # Since we are adding it to the raw scores before the softmax, this is\r\n # effectively the same as removing these entirely.\r\n extended_doc_mask = extended_doc_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\r\n extended_doc_mask = extended_doc_mask * -10000.0\r\n\r\n all_hids_doc = self.sent_encoder(sent_repr, extended_doc_mask, head_mask)\r\n sent_repr_given_doc = all_hids_doc[0]\r\n attn_weights = all_hids_doc[1]\r\n return {\r\n 'encoder_out': sent_repr_given_doc, # bsz x n_sent x C\r\n 'attn_weights': attn_weights,\r\n 'encoder_doc_mask': doc_pad_mask, # bsz x n_sent\r\n }\r\n else:\r\n raise Exception('--sentence-transformer-arch doesn\\'t support {} yet!'.format(args.sentence_transformer_arch))\r\n\r\n def reorder_encoder_out(self, encoder_out_dict, new_order):\r\n if encoder_out_dict['encoder_out'] is not None:\r\n encoder_out_dict['encoder_out'] = \\\r\n encoder_out_dict['encoder_out'].index_select(1, new_order)\r\n if encoder_out_dict['encoder_padding_mask'] is not None:\r\n encoder_out_dict['encoder_padding_mask'] = \\\r\n encoder_out_dict['encoder_padding_mask'].index_select(0, new_order)\r\n return encoder_out_dict\r\n\r\n def max_positions(self):\r\n \"\"\"Maximum input length supported by the encoder.\"\"\"\r\n # return self.embed_positions.max_positions()\r\n return 10240\r\n\r\n def upgrade_state_dict(self, state_dict):\r\n '''\r\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\r\n if 'encoder.embed_positions.weights' in state_dict:\r\n del state_dict['encoder.embed_positions.weights']\r\n if 'encoder.embed_positions._float_tensor' not in state_dict:\r\n state_dict['encoder.embed_positions._float_tensor'] = torch.FloatTensor()\r\n '''\r\n return state_dict\r\n\r\n\r\nclass RankDecoder(FairseqDecoder):\r\n \"\"\"Transformer decoder.\"\"\"\r\n\r\n def __init__(self, args, tgt_dic):\r\n super().__init__(tgt_dic)\r\n self.dropout = args.dropout\r\n self.topk = args.topk if args.topk else 3\r\n self.args = args\r\n\r\n def forward(self, transpose_method, encoder_out):\r\n x = encoder_out['encoder_out']\r\n attn_weights = encoder_out['attn_weights']\r\n \r\n attn_head_avg = [weight.mean(dim=1) for weight in attn_weights]\r\n if self.args.attn_layer == 'all':\r\n attn_weights = sum(attn_head_avg)\r\n elif self.args.attn_layer == 'final':\r\n attn_weights = attn_head_avg[-1] \r\n else:\r\n raise RuntimeError \r\n attn_weights = F.relu(attn_weights)\r\n mask = encoder_out['encoder_doc_mask']\r\n\r\n bsz, n_sent = mask.shape\r\n\r\n attn_weights = F.relu(attn_weights)\r\n\r\n if transpose_method == 'transpose':\r\n attn_weights = attn_weights.transpose(1, 2)\r\n # print('transpose')\r\n elif transpose_method == 'add':\r\n attn_weights += attn_weights.transpose(1, 2)\r\n # print('add')\r\n elif transpose_method == 'not_transpose':\r\n # print('not transpose')\r\n pass\r\n else:\r\n raise RuntimeError('error transpose_method')\r\n\r\n # weights = torch.stack([torch.triu(weight) * lam_1 + torch.tril(weight) * lam_2 for weight in attn_weights])\r\n # eye = torch.stack([torch.eye(weights.shape[1], device='cuda').byte() for _ in weights])\r\n # weights.masked_fill_(eye, 0) \r\n weights = attn_weights\r\n\r\n pr = weights.sum(dim=1)\r\n # pr = torch.stack([weight.diag() for weight in weights])\r\n\r\n out = torch.ones([bsz, n_sent], dtype=torch.int32).cuda() * self.dictionary.indices['F']\r\n pad = torch.ones_like(out).int() * self.dictionary.indices['<pad>']\r\n false = torch.ones_like(out) * self.dictionary.indices['F']\r\n\r\n topk = pr.argsort(dim=-1)[:, -self.topk:]\r\n # topk = torch.stack([torch.tensor([0, 1, 2]).type_as(t) for t in topk])\r\n\r\n for idx in range(bsz):\r\n out[idx, topk[idx]] = self.dictionary.indices['T']\r\n # out = false\r\n out = torch.where(mask==0, out, pad).int()\r\n return out, pr\r\n\r\n def max_positions(self):\r\n \"\"\"Maximum output length supported by the decoder.\"\"\"\r\n return 1024\r\n\r\n def upgrade_state_dict(self, state_dict):\r\n '''\r\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\r\n if 'decoder.embed_positions.weights' in state_dict:\r\n del state_dict['decoder.embed_positions.weights']\r\n if 'decoder.embed_positions._float_tensor' not in state_dict:\r\n state_dict['decoder.embed_positions._float_tensor'] = torch.FloatTensor()\r\n '''\r\n return state_dict\r\n\r\n\r\nclass TransformerEncoderLayer(nn.Module):\r\n \"\"\"Encoder layer block.\r\n\r\n In the original paper each operation (multi-head attention or FFN) is\r\n postprocessed with: dropout -> add residual -> layernorm.\r\n In the tensor2tensor code they suggest that learning is more robust when\r\n preprocessing each layer with layernorm and postprocessing with:\r\n dropout -> add residual.\r\n We default to the approach in the paper, but the tensor2tensor approach can\r\n be enabled by setting `normalize_before=True`.\r\n \"\"\"\r\n\r\n def __init__(self, args):\r\n super().__init__()\r\n self.embed_dim = args.encoder_embed_dim\r\n self.self_attn = MultiheadAttention(\r\n self.embed_dim, args.encoder_attention_heads,\r\n dropout=args.attention_dropout,\r\n )\r\n self.dropout = args.dropout\r\n self.relu_dropout = args.relu_dropout\r\n self.normalize_before = args.encoder_normalize_before\r\n self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim)\r\n self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim)\r\n self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim) for i in range(2)])\r\n\r\n def forward(self, x, encoder_padding_mask):\r\n residual = x\r\n x = self.maybe_layer_norm(0, x, before=True)\r\n x, _ = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask)\r\n x = F.dropout(x, p=self.dropout, training=self.training)\r\n x = residual + x\r\n x = self.maybe_layer_norm(0, x, after=True)\r\n\r\n residual = x\r\n x = self.maybe_layer_norm(1, x, before=True)\r\n x = F.relu(self.fc1(x))\r\n x = F.dropout(x, p=self.relu_dropout, training=self.training)\r\n x = self.fc2(x)\r\n x = F.dropout(x, p=self.dropout, training=self.training)\r\n x = residual + x\r\n x = self.maybe_layer_norm(1, x, after=True)\r\n return x\r\n\r\n def maybe_layer_norm(self, i, x, before=False, after=False):\r\n assert before ^ after\r\n if after ^ self.normalize_before:\r\n return self.layer_norms[i](x)\r\n else:\r\n return x\r\n\r\n\r\ndef Embedding(num_embeddings, embedding_dim, padding_idx):\r\n m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)\r\n nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)\r\n return m\r\n\r\n\r\ndef LayerNorm(embedding_dim):\r\n m = nn.LayerNorm(embedding_dim)\r\n return m\r\n\r\n\r\ndef Linear(in_features, out_features, bias=True):\r\n m = nn.Linear(in_features, out_features, bias)\r\n nn.init.xavier_uniform_(m.weight)\r\n nn.init.constant_(m.bias, 0.)\r\n return m\r\n\r\n\r\ndef PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False):\r\n if learned:\r\n m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad)\r\n nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)\r\n nn.init.constant_(m.weight[padding_idx], 0)\r\n else:\r\n m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_pad, num_embeddings)\r\n return m\r\n\r\n\r\n@register_model_architecture('extract_sum_roberta_long_transformer_rank', 'extract_sum_roberta_long_transformer_rank')\r\ndef base_architecture(args):\r\n args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)\r\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)\r\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048)\r\n args.encoder_layers = getattr(args, 'encoder_layers', 6)\r\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8)\r\n args.decoder_embed_path = getattr(args, 'decoder_embed_path', None)\r\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim)\r\n args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim)\r\n args.decoder_layers = getattr(args, 'decoder_layers', 6)\r\n args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8)\r\n args.attention_dropout = getattr(args, 'attention_dropout', 0.)\r\n args.relu_dropout = getattr(args, 'relu_dropout', 0.)\r\n args.dropout = getattr(args, 'dropout', 0.1)\r\n\r\n# Medium size transformer\r\n@register_model_architecture('extract_sum_roberta_long_transformer_rank', 'extract_sum_roberta_long_transformer_rank_medium')\r\ndef transformer_medium(args):\r\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768)\r\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 3072)\r\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 12)\r\n args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False)\r\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768)\r\n args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 3072)\r\n args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 12)\r\n args.dropout = getattr(args, 'dropout', 0.1)\r\n base_architecture(args)\r\n\r\n\r\n# Medium size transformer\r\n@register_model_architecture('extract_sum_roberta_long_transformer_rank', 'extract_sum_roberta_long_transformer_rank_large')\r\ndef transformer_medium(args):\r\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024)\r\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4086)\r\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16)\r\n args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False)\r\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024)\r\n args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4086)\r\n args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16)\r\n args.dropout = getattr(args, 'dropout', 0.1)\r\n base_architecture(args)\r\n"
] | [
[
"torch.serialization.default_restore_location",
"numpy.random.RandomState",
"torch.cuda.empty_cache"
],
[
"torch.linspace",
"torch.ones",
"torch.nn.functional.dropout",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.arange",
"torch.nn.Embedding",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.init.normal_",
"torch.where",
"torch.nn.init.xavier_uniform_",
"torch.ones_like"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
matthew-frank/training | [
"dc72f48cc5279f80e8e1736d0756c83f9e3cf116"
] | [
"single_stage_detector/ssd/model/transform.py"
] | [
"import math\nimport torch\nimport torchvision\n\nfrom torch import nn, Tensor\nfrom typing import List, Tuple, Dict, Optional\n\nfrom model.image_list import ImageList\nfrom model.roi_heads import paste_masks_in_image\n\n\[email protected]\ndef _get_shape_onnx(image: Tensor) -> Tensor:\n from torch.onnx import operators\n return operators.shape_as_tensor(image)[-2:]\n\n\[email protected]\ndef _fake_cast_onnx(v: Tensor) -> float:\n # ONNX requires a tensor but here we fake its type for JIT.\n return v\n\n\ndef _resize_image_and_masks(image: Tensor,\n target: Optional[Dict[str, Tensor]] = None,\n image_size: Optional[Tuple[int, int]] = None,\n ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:\n if torchvision._is_tracing():\n im_shape = _get_shape_onnx(image)\n else:\n im_shape = torch.tensor(image.shape[-2:])\n\n image = torch.nn.functional.interpolate(image[None], size=image_size, scale_factor=None, mode='bilinear',\n recompute_scale_factor=None, align_corners=False)[0]\n\n if target is None:\n return image, target\n\n if \"masks\" in target:\n mask = target[\"masks\"]\n mask = torch.nn.functional.interpolate(mask[:, None].float(), size=image_size, scale_factor=None,\n recompute_scale_factor=None)[:, 0].byte()\n target[\"masks\"] = mask\n return image, target\n\n\nclass GeneralizedRCNNTransform(nn.Module):\n \"\"\"\n Performs input / target transformation before feeding the data to a GeneralizedRCNN\n model.\n\n The transformations it perform are:\n - input normalization (mean subtraction and std division)\n - input / target resizing to match image_size\n\n It returns a ImageList for the inputs, and a List[Dict[Tensor]] for the targets\n \"\"\"\n\n def __init__(self, image_size: Optional[Tuple[int, int]],\n image_mean: List[float], image_std: List[float],):\n super(GeneralizedRCNNTransform, self).__init__()\n self.image_size = image_size\n self.image_mean = image_mean\n self.image_std = image_std\n\n def forward(self,\n images: List[Tensor],\n targets: Optional[List[Dict[str, Tensor]]] = None\n ) -> Tuple[ImageList, Optional[List[Dict[str, Tensor]]]]:\n images = [img for img in images]\n if targets is not None:\n # make a copy of targets to avoid modifying it in-place\n # once torchscript supports dict comprehension\n # this can be simplified as follows\n # targets = [{k: v for k,v in t.items()} for t in targets]\n targets_copy: List[Dict[str, Tensor]] = []\n for t in targets:\n data: Dict[str, Tensor] = {}\n for k, v in t.items():\n data[k] = v\n targets_copy.append(data)\n targets = targets_copy\n for i in range(len(images)):\n image = images[i]\n target_index = targets[i] if targets is not None else None\n\n if image.dim() != 3:\n raise ValueError(\"images is expected to be a list of 3d tensors \"\n \"of shape [C, H, W], got {}\".format(image.shape))\n image = self.normalize(image)\n image, target_index = self.resize(image, target_index)\n images[i] = image\n if targets is not None and target_index is not None:\n targets[i] = target_index\n\n image_sizes = [img.shape[-2:] for img in images]\n images = torch.stack(images)\n image_sizes_list: List[Tuple[int, int]] = []\n for image_size in image_sizes:\n assert len(image_size) == 2\n image_sizes_list.append((image_size[0], image_size[1]))\n\n image_list = ImageList(images, image_sizes_list)\n return image_list, targets\n\n def normalize(self, image: Tensor) -> Tensor:\n if not image.is_floating_point():\n raise TypeError(\n f\"Expected input images to be of floating type (in range [0, 1]), \"\n f\"but found type {image.dtype} instead\"\n )\n dtype, device = image.dtype, image.device\n mean = torch.as_tensor(self.image_mean, dtype=dtype, device=device)\n std = torch.as_tensor(self.image_std, dtype=dtype, device=device)\n return (image - mean[:, None, None]) / std[:, None, None]\n\n def torch_choice(self, k: List[int]) -> int:\n \"\"\"\n Implements `random.choice` via torch ops so it can be compiled with\n TorchScript. Remove if https://github.com/pytorch/pytorch/issues/25803\n is fixed.\n \"\"\"\n index = int(torch.empty(1).uniform_(0., float(len(k))).item())\n return k[index]\n\n def resize(self,\n image: Tensor,\n target: Optional[Dict[str, Tensor]] = None,\n ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:\n h, w = image.shape[-2:]\n image, target = _resize_image_and_masks(image, target, self.image_size)\n\n if target is None:\n return image, target\n\n bbox = target[\"boxes\"]\n bbox = resize_boxes(bbox, (h, w), image.shape[-2:])\n target[\"boxes\"] = bbox\n\n if \"keypoints\" in target:\n keypoints = target[\"keypoints\"]\n keypoints = resize_keypoints(keypoints, (h, w), image.shape[-2:])\n target[\"keypoints\"] = keypoints\n return image, target\n\n def postprocess(self,\n result: List[Dict[str, Tensor]],\n image_shapes: List[Tuple[int, int]],\n original_image_sizes: List[Tuple[int, int]]\n ) -> List[Dict[str, Tensor]]:\n if self.training:\n return result\n for i, (pred, im_s, o_im_s) in enumerate(zip(result, image_shapes, original_image_sizes)):\n boxes = pred[\"boxes\"]\n boxes = resize_boxes(boxes, im_s, o_im_s)\n result[i][\"boxes\"] = boxes\n if \"masks\" in pred:\n masks = pred[\"masks\"]\n masks = paste_masks_in_image(masks, boxes, o_im_s)\n result[i][\"masks\"] = masks\n if \"keypoints\" in pred:\n keypoints = pred[\"keypoints\"]\n keypoints = resize_keypoints(keypoints, im_s, o_im_s)\n result[i][\"keypoints\"] = keypoints\n return result\n\n def __repr__(self) -> str:\n format_string = self.__class__.__name__ + '('\n _indent = '\\n '\n format_string += \"{0}Normalize(mean={1}, std={2})\".format(_indent, self.image_mean, self.image_std)\n format_string += \"{0}Resize(height={1}, width={2}, mode='bilinear')\".format(_indent, self.image_size[0],\n self.image_size[1])\n format_string += '\\n)'\n return format_string\n\n\ndef resize_keypoints(keypoints: Tensor, original_size: List[int], new_size: List[int]) -> Tensor:\n ratios = [\n torch.tensor(s, dtype=torch.float32, device=keypoints.device) /\n torch.tensor(s_orig, dtype=torch.float32, device=keypoints.device)\n for s, s_orig in zip(new_size, original_size)\n ]\n ratio_h, ratio_w = ratios\n resized_data = keypoints.clone()\n if torch._C._get_tracing_state():\n resized_data_0 = resized_data[:, :, 0] * ratio_w\n resized_data_1 = resized_data[:, :, 1] * ratio_h\n resized_data = torch.stack((resized_data_0, resized_data_1, resized_data[:, :, 2]), dim=2)\n else:\n resized_data[..., 0] *= ratio_w\n resized_data[..., 1] *= ratio_h\n return resized_data\n\n\ndef resize_boxes(boxes: Tensor, original_size: List[int], new_size: List[int]) -> Tensor:\n ratios = [\n torch.tensor(s, dtype=torch.float32, device=boxes.device) /\n torch.tensor(s_orig, dtype=torch.float32, device=boxes.device)\n for s, s_orig in zip(new_size, original_size)\n ]\n ratio_height, ratio_width = ratios\n xmin, ymin, xmax, ymax = boxes.unbind(1)\n\n xmin = xmin * ratio_width\n xmax = xmax * ratio_width\n ymin = ymin * ratio_height\n ymax = ymax * ratio_height\n return torch.stack((xmin, ymin, xmax, ymax), dim=1)\n"
] | [
[
"torch._C._get_tracing_state",
"torch.empty",
"torch.onnx.operators.shape_as_tensor",
"torch.tensor",
"torch.nn.functional.interpolate",
"torch.stack",
"torch.as_tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
J-bytes/Epidemiologic-simulation | [
"1a1b4d8744a3ba2bdbe3bdc900694704bf82d61a"
] | [
"app.py"
] | [
"# -*- coding: utf-8 -*-\n\n\n\n#========================================================================================\n#Importation des modules\nimport dash\n\n\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\n\nfrom dash.dependencies import Input, Output\nimport dash_table\nfrom flask_babel import _ ,Babel\nfrom flask import session, redirect, url_for\nfrom flask import Response\n\nimport numpy as np\n\n\nfrom plague import epidemic\nimport networkx as nx\nimport plotly.graph_objects as go\nfrom modals import modals_language\n\n\n\n\n\n#==========================================================================================\n# Importation des scripts et feuille de style pour l'application\n#Initialisation du serveur\n\nexternal_stylesheets = [\n 'https://use.fontawesome.com/releases/v5.8.1/css/all.css',\n 'https://wet-boew.github.io/themes-dist/GCWeb/css/theme.min.css',\n 'https://codepen.io/chriddyp/pen/bWLwgP.css',\n 'https://wet-boew.github.io/themes-dist/GCWeb/wet-boew/css/noscript.min.css'] # Link to external CSS\n\nexternal_scripts = [\n 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.js',\n 'https://wet-boew.github.io/themes-dist/GCWeb/wet-boew/js/wet-boew.min.js',\n 'https://wet-boew.github.io/themes-dist/GCWeb/js/theme.min.js',\n 'https://cdn.plot.ly/plotly-locale-de-latest.js',\n\n]\n\n\n\n\nprefixe=\"\"\n\napp = dash.Dash(__name__,meta_tags=[{\"name\": \"viewport\", \"content\": \"width=device-width\"}],external_stylesheets=external_stylesheets,external_scripts=external_scripts,)\nserver = app.server\nserver.config['SECRET_KEY'] = '7887syfds98hfs7hr3bibr7f' # Setting up secret key to access flask session\nbabel = Babel(server) # Hook flask-babel to the app\n\n\n\n#======================================================================================\n# Controls for webapp\n\n# Dropdown options\nmodel_options = [\n\n\n {'label': _('Small-world (watts-strogatz)'), 'value': \"watts\"},\n {'label': _('Small-world (connected watts-strogatz)'), 'value': \"connected-watts\"},\n {'label': _('2D Grid'), 'value': \"grid\"},\n {'label': _('Power Law'), 'value': \"power_law\"},\n\n\n ]\n#--------------------------------------------------------\n#Advanced feature control\n#!!!! Modifying those three element will require manual changes in grid_init,which is located inside plague.py\n\nglobal walkers,liste_dead,liste_sick,liste_health\nwalkers, liste_dead, liste_sick, liste_health=[],[],[],[]\nparams_table = [\n 'infectiosity', 'movements', 'mortality','proportion of population'\n]\n\n\n\nparams_table_limits={'infectiosity' : [0,1],'movements' : [0,1],'mortality' : [0,1],'proportion of population' : ['%']}\nAge_groups=[\"0-24\",\"25-50\",\"50+\"]\ndf_diseases=pd.read_csv('disease_compare.csv')\nAge_groups_dict={}\nfor (ex,p) in enumerate(params_table) :\n Age_groups_dict.update({p : ex})\n#======================================================================================\n\n\n# Create global chart template\nmapbox_access_token = \"pk.eyJ1IjoiamFja2x1byIsImEiOiJjajNlcnh3MzEwMHZtMzNueGw3NWw5ZXF5In0.fk8k06T96Ml9CLGgKmk81w\"\n\nlayout = dict(\n autosize=True,\n automargin=True,\n margin=dict(l=30, r=30, b=20, t=40),\n hovermode=\"closest\",\n plot_bgcolor=\"#F9F9F9\",\n paper_bgcolor=\"#F9F9F9\",\n legend=dict(font=dict(size=10), orientation=\"h\"),\n title=\"Gas Concentration Overview\",\n mapbox=dict(\n accesstoken=mapbox_access_token,\n style=\"light\",\n\n zoom=2,\n ),\n transition={'duration': 500},\n)\n\n\n#===========================================================================\n# Builds the layout for the header\ndef build_header():\n \n return html.Div(\n [\n html.Div([], className=\"one column\"),\n html.Div(\n [\n html.Img(\n src=app.get_asset_url(\"logo_jonathan2.png\"),\n id=\"CSA-logo\",\n style={\n \"height\": \"140px\",\n \"width\": \"auto\",\n \"margin\": \"25px\",\n },\n alt=\"Logo\"\n )\n ],\n className=\"one column\",\n ),\n html.Div(\n [\n html.H1(\n _(\"Application to visualize epidemiologic simulations\"),\n style={\"margin-bottom\": \"10px\", \"margin-left\": \"15%\"},\n ),\n ],\n className=\"six columns\",\n id=\"title\",\n ),\n html.Div(\n [\n html.A(\n html.Button( _(\"Learn more about this app\"), className=\"dash_button\"),\n href=\"\",id='learn-more-link'\n ),\n html.A(\n html.Button('FR', id='language-button', className=\"dash_button\"),\n href='/language/fr', id='language-link'\n ),\n\n\n ],\n className=\"four columns\",\n id=\"button-div\",\n style={\"text-align\": \"center\"}\n ),\n ],\n id=\"header\",\n className=\"row flex-display\",\n style={\"margin-bottom\": \"25px\"},\n )\n\n#===========================================================================\n# Builds the layout and components for the inputs to control the simulation\n\ncote_gauche= html.Div(\n [\n html.Div(\n [\n html.Div(html.H3(_(\"Parameters of the model\"))),\n\n html.Div(\n children=[\n html.H4(\n [\n _(\"Selection of the model for generating the space\"),\n html.Img(\n id=\"show-model-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin-bottom\" : \"0 0 0px\"}\n )],\n id=\"model-div\"),\n html.Div([\n html.Label(\n dcc.Dropdown(\n id=\"model_list\",\n options= model_options,\n multi=False,\n value='connected-watts',\n className=\"dcc_control\",\n\n\n ),\n ),\n\n ],style={\"padding-bottom\": \"15px\"}),\n\n html.Div([\n html.Div( #connectivity parameter\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Connectivity of the graph\"),\n html.Img(\n id=\"show-connectivity-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0px\"}\n )],\n id=\"connectivity-div\"),\n\n dcc.Slider(\n id=\"connectivity-parameter\",\n\n value=2,\n\n min=0,\n max=10,\n marks=dict([(i,str(i)) for i in range(0,10)]),\n step=None,\n ),\n html.H5(\n \"\", style={\"margin-top\": \"0px\"},\n className=\"one-half column\"\n )]\n\n\n ),\n\n\n html.Div( #connectivity parameter\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Randomness of the graph\"),\n html.Img(\n id=\"show-connectivity_node-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0px\"}\n )],\n id=\"connectivity_node-div\"),\n\n dcc.Slider(\n id=\"max-connectivity-parameter\",\n\n value=2,\n\n min=0,\n max=10,\n marks=dict([(i,str(i)) for i in range(0,10)]),\n step=10,\n ),\n html.H5(\n \"\", style={\"margin-top\": \"0px\"},\n className=\"one-half column\"\n )]\n\n\n ),\n\n\n html.Div( #network size\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Size of the network\"),\n html.Img(\n id=\"show-size-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0 0 0px\"}\n\n )],\n id=\"size-div\"),\n\n dcc.Slider(\n id=\"network-size\",\n\n value=500,\n\n min=500,\n max=5000,\n marks=dict([(i,str(i)) for i in range(500,5500,500)]),\n step=None,\n\n ),\n ],\n # className=\"one-half column\"\n ),\n\n html.Div( #network size\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Number of walkers\"),\n html.Img(\n id=\"show-n_walker-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0 0 0px\"}\n\n ),\n ],\n id=\"n_walker-div\"),\n\n dcc.Slider(\n id=\"n_walkers\",\n\n value=1000,\n\n min=1000,\n max=51000,\n marks=dict([(i,str(i)) for i in range(1000,56000,5000)]),\n step=None,\n\n ),\n html.Span(children=_(\"Selection of the range of longitude\"),className=\"wb-inv\") ],\n # className=\"one-half column\"\n ),\n\n html.Div( #network size\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Number of repetitions\"),\n html.Img(\n id=\"show-n_repetition-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0 0 0px\"}\n )],\n id=\"n_repetition-div\"),\n\n dcc.Slider(\n id=\"repetition\",\n\n value=1,\n\n min=1,\n max=10,\n marks=dict([(i,str(i)) for i in range(1,10)]),\n step=10,\n\n ),\n html.Span(children=_(\"Selection of the range of longitude\"),className=\"wb-inv\") ],\n # className=\"one-half column\"\n ),\n\n html.H5(\n \"\", style={\"margin-top\": \"0px\"}\n ),\n ],\n id=\"map-options\",\n ), #End of map options\n ]),\n\n\n ],\n id=\"left-column-1\",\n style={\"flex-grow\": 1},\n className=\"six columns\",\n )\n\n\n\n\n\n\ncote_droit=html.Div(\n [\n html.Div( #Gas Picker\n [\n\n html.Div(html.H3(_(\"Parameters of the disease\"))),\n \n# html.Div(\n# children=[\n# html.H4(\n# [\n# _(\"Select presets based on a specific disease\"),\n# html.Img(\n# id=\"show-preset-modal\",\n# src=\"assets/question-circle-solid.svg\",\n# n_clicks=0,\n# className=\"info-icon\",\n# ),\n# ],\n# className=\"container_title\",\n# style={\"margin_bottom\" : \"0 0 0px\"}\n# )],\n# id=\"preset-div\"),\n# \n# html.Div([\n# html.Label(\n# dcc.Dropdown(\n# id=\"preset_list\",\n# options= model_options,\n# multi=False,\n# value='',\n# className=\"dcc_control\",\n#\n#\n# ),\n# ),\n#\n# ], style={\"padding-bottom\": \"15px\"}\n# ),\n\n html.Div([\n html.Div( #connectivity parameter\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Infectiosity\"),\n\n html.Img(\n id=\"show-infectiosity-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0 0 0px\"}\n )],\n id=\"infectiosity-div\"),\n\n dcc.Slider(\n id=\"infectiosity-parameter\",\n\n value=2,\n\n min=0,\n max=10,\n marks=dict([(i,str(i)) for i in range(0,10)]),\n step=10,\n ),\n html.H5(\n \"\", style={\"margin-top\": \"0px\"},\n className=\"one-half column\"\n )]\n\n\n ),\n\n\n html.Div( #connectivity parameter\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Mortality\"),\n\n html.Img(\n id=\"show-mortality-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0 0 0px\"}\n )],\n id=\"mortality-div\")\n ,\n\n dcc.Slider(\n id=\"mortality-parameter\",\n\n value=2,\n\n min=0,\n max=10,\n marks=dict([(i,str(i)) for i in range(0,10)]),\n step=10,\n ),\n html.H5(\n \"\", style={\"margin-top\": \"0px\"},\n className=\"one-half column\"\n )]\n\n\n ),\n\n html.Div(\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Number of person initially sick\"),\n\n html.Img(\n id=\"show-n_sick-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0 0 0px\"}\n )],\n id=\"n_sick-div\"),\n\n dcc.Slider(\n id=\"n_sick_initial\",\n\n value=1,\n\n min=1,\n max=100,\n marks=dict([(i,str(i)) for i in range(1,101,10)]),\n step=None,\n ),\n html.H5(\n \"\", style={\"margin-top\": \"0px\"},\n className=\"one-half column\"\n )]\n\n\n ),\n\n html.Div(\n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Duration of the infection\"),\n\n html.Img(\n id=\"show-duree-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"0 0 0px\"}\n )],\n id=\"duree-div\"),\n\n dcc.Slider(\n id=\"duree\",\n\n value=5,\n\n min=5,\n max=25,\n marks=dict([(i,str(i)) for i in range(5,30,5)]),\n step=None,\n ),\n html.H5(\n \"\", style={\"margin-top\": \"0px\"},\n className=\"one-half column\"\n )]\n\n\n ),\n\n\n\n html.H5(\n \"\", style={\"margin-top\": \"0px\"}\n ),\n ],\n\n ), #End of map options\n ]),\n\n\n ],\n id=\"right-column-1\",\n style={\"flex-grow\": 1},\n className=\"six columns\",\n )\n\nmodals=modals_language()\n\n\n\ndef build_filtering():\n \"\"\"\n \n\n Returns\n -------\n TYPE : Dash html component \n This function build the html structure of the application input section, to be later injected inside the app for more convenience.\n\n \"\"\"\n return html.Div([\n html.Div(\n [\n html.Div(\n [\n html.H3( _(\"The application is running!\")),\n\n ],\n id=\"info-container\",\n className=\"mini_container three columns\",\n style={\"text-align\": \"center\"},\n ),\n html.Div(\n [\n html.Div(\n [\n html.H6( _(\"\")),\n html.P( _(\"This application allows the user to quickly see the results of epidemiologic simulations on small-world networks and others.\")),\n html.P( _(\"This application provides users the ability to alter different parameters and visualize the impact of those on the propagation of a virus throughout a community.\"))\n ],\n id=\"description_div\",\n ),\n ],\n id=\"description-container\",\n className=\"container-display mini_container nine columns\",\n ),\n ],\n className=\"row flex-display twelve columns\"\n ),\n\n html.Div(\n [\n html.H3(\n id=\"select-data\"\n ),\n ],\n style={\"margin-top\": \"10px\", \"margin-left\": \"auto\", \"margin-right\": \"auto\", \"text-align\": \"center\"},\n className=\"twelve columns\"\n ),\n\n html.Div(\n [ modals,cote_gauche,cote_droit],\n className=\"row flex-display pretty_container twelve columns\",\n style={\"justify-content\": \"space-evenly\"}\n ),\n ])\n\n\n\n\n\ndef build_advanced_filtering():\n \"\"\"\n \n\n Returns\n -------\n TYPE : Dash html component\n This function builds the layout for the advanced features inputs by the user\n\n \"\"\"\n return html.Div([\n html.Details(\n \n html.Div([\n \n html.H3(_(\"This panel let you control advanced features. Those features are still experimental by lack of time, I cannot garantee the accuracy of these results\")),\n \n \n \n dcc.Checklist(\n options=[\n {'label': _(\" Activate advanced features\"), 'value': 'True'},\n \n ],\n id=\"advanced_feature_switch\",\n value=[]\n ),\n \n \n\n \n \n html.Div( #contingency measures\n [\n html.Div(\n children=[\n html.H5(\n [\n _(\"Vary parameter based on age\"),\n\n html.Img(\n id=\"show-age-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin-bottom\" : \"1em\" , \"margin-top\" : \"2em\"}\n )],\n id=\"age-div\"),\n \n \n dash_table.DataTable(\n id='table-editing-simple',\n columns=(\n [{'id': 'Age', 'name': 'Age'}] +\n [{'id': p, 'name': p} for p in params_table]\n ),\n data=[\n dict(Age=i, **{param: 0 for param in params_table})\n for i in Age_groups\n ],\n editable=True\n ),\n #dcc.Graph(id='table-editing-simple-output')\n \n \n ]\n\n\n ), #End of contingency measures \n \n \n html.H6(id='validation message'),\n html.Div( #contingency measures\n [\n html.Div(\n children=[\n html.H5(\n [\n _(\"Apply contingency measures\"),\n\n html.Img(\n id=\"show-contingency-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin-bottom\" : \"1em\" , \"margin-top\" : \"2em\"}\n )],\n id=\"contingency-div\"),\n \n\n dcc.Checklist(\n \n options=[\n {'label': _(\"Confine sick population\"), 'value': 'confine'},\n {'label': _(\"Restrict movement\"), 'value': 'restrict'},\n {'label': _(\"Mask mandate and other sanitary measures\"), 'value': 'masks'},\n {'label': _(\"Close gathering spots\"), 'value': 'lockdown'},\n \n ],\n id=\"advanced_feature\",\n value=[],\n inputStyle={\"margin-right\": \"30px\"}\n ),\n html.H5(\n \"\", style={\"margin-top\": \"5px\"},\n className=\"one-half column\"\n )]\n\n\n ), #End of contingency measures\n \n \n \n html.Div( #proportion of population\n \n [\n html.Div(\n children=[\n html.H4(\n [\n _(\"Population adherence to sanitary measures ( %) \"),\n html.Img(\n id=\"show-adherence-modal\",\n src=\"assets/question-circle-solid.svg\",\n n_clicks=0,\n className=\"info-icon\",\n ),\n ],\n className=\"container_title\",\n style={\"margin_bottom\" : \"5px\", \"margin-top\" : \"2em\"}\n )],\n id=\"adherence-div\"),\n\n dcc.Slider(\n id=\"adherence-parameter\",\n\n value=50,\n\n min=0,\n max=100,\n marks=dict([(i,str(i)) for i in range(0,110,10)]),\n step=None,\n )\n ]\n\n\n ), # end of adherence parameter\n \n \n \n ])\n \n )\n ],\n className=\"pretty_container\")\n\n\n\n\n\ndef build_stats():\n \"\"\"\n \n\n Returns\n -------\n TYPE : Dash html component\n This function builds the layout for the graph and conclusion\n\n \"\"\"\n return html.Div([\n html.Div([\n html.Div(\n [\n html.Div([\n dcc.Graph(\n id=\"viz_chart\")\n ]),\n\n html.Div ([\n html.P( id = \"TimeS_description\")\n ]),\n ],\n id=\"vizChartContainer\",\n className=\"pretty_container\",\n ),\n\n html.A(\n html.Button(_('Download data as csv'), className=\"dash_button\"),\n href='/dash/downloadCSV'\n ),\n html.A(\n html.Button(_('Download walkers data as csv'), className=\"dash_button\"),\n href='/dash/downloadCSV2'\n ),\n ]),\n\n\n html.Div([\n html.Div(\n [\n html.Div([\n html.P(\n id=\"Conclusion\")\n ]),\n\n\n ],\n id=\"ConclusionContainer\",\n className=\"pretty_container\",\n ),\n ]),\n\n html.Div([\n html.Div(\n [\n html.Div([\n html.P(\n \"Credits : Jonathan Beaulieu-Emond\")\n ]),\n\n ],\n\n\n ),\n ]),\n\n html.Div(id='none', children=[], style={'display': 'none'}), # Placeholder element to trigger translations upon page load\n ])\n\n# Create app layout by merging the predefined layout\napp.layout = html.Div(\n [\n #html.Div([\"\"], id='gc-header'),\n html.Div(\n [\n dcc.Store(id=\"aggregate_data\"),\n html.Div(id=\"output-clientside\"), # empty Div to trigger javascript file for graph resizing\n\n build_header(),\n build_filtering(),\n build_advanced_filtering(),\n build_stats(),\n ],\n id=\"mainContainer\",\n style={\"display\": \"flex\", \"flex-direction\": \"column\", \"margin\": \"auto\", \"width\":\"75%\"},\n ),\n #html.Div([\"\"], id='gc-footer'),\n html.Div(id='none2', children=[], style={'display': 'none'}), # Placeholder element to trigger translations upon page load\n ]\n)\n\n\n\n\n#============================================================================\n # Create show/hide callbacks for each info modal\nfor id in [\"model\", \"connectivity\", \"connectivity_node\", \"size\", \"n_walker\",\"mortality\",\"n_repetition\", \"infectiosity\", \"n_sick\",\"duree\",\"adherence\",\"contingency\",\"age\"]:\n\n @app.callback(\n [Output(f\"{id}-modal\", \"style\"), Output(f\"{id}-div\", \"style\")],\n [Input(f\"show-{id}-modal\", \"n_clicks\"), Input(f\"close-{id}-modal\", \"n_clicks\")],\n )\n def toggle_modal(n_show, n_close):\n ctx = dash.callback_context\n if ctx.triggered and ctx.triggered[0][\"prop_id\"].startswith(\"show-\"):\n return {\"display\": \"block\"}, {\"zIndex\": 1003}\n else:\n return {\"display\": \"none\"}, {\"zIndex\": 0}\n\n#=========================================================================\n\n\n\"\"\"\[email protected](\n Output('table-editing-simple-output', 'figure'),\n Input('table-editing-simple', 'data'),\n Input('table-editing-simple', 'columns'))\ndef display_output(rows, columns):\n \n df = pd.DataFrame(rows, columns=[c for c in params_table])\n colors=[\"red\",\"blue\",\"green\"]\n return {\n 'data': [{\n 'type': 'parcoords',\n 'dimensions': [{\n 'label': col,\n 'values': df[col],\n 'line' : {'name' : Age_groups[Age_groups_dict[col]],\n 'color' : colors[Age_groups_dict[col]]}\n } for col in params_table]\n }]\n }\n\"\"\"\n\n#=================================================================================\n\n\n# Selectors -> viz chart (95% CI)\[email protected](\n Output(\"viz_chart\", \"figure\"),\n Output(\"validation message\", \"children\"),\n Output(\"Conclusion\", \"children\"),\n \n [\n\n Input(\"model_list\", \"value\"),\n Input(\"connectivity-parameter\", \"value\"),\n \n Input(\"max-connectivity-parameter\", \"value\"),\n Input(\"network-size\", \"value\"),\n \n Input(\"infectiosity-parameter\", \"value\"),\n Input(\"mortality-parameter\", \"value\"),\n\n Input(\"n_sick_initial\", \"value\"),\n Input(\"n_walkers\", \"value\"),\n Input(\"repetition\", \"value\"),\n Input(\"duree\", \"value\"),\n \n Input(\"advanced_feature_switch\",\"value\"),\n Input('table-editing-simple', 'data'),\n Input('table-editing-simple', 'columns'),\n Input('advanced_feature','value'),\n Input('adherence-parameter','value')\n\n\n ]\n)\ndef make_viz_chart(model,P,C,N,P_infection,P_mortality,n_sick_original,M,repetition,duree,advanced_switch,rows,columns,advanced_feature,adherence):\n \"\"\"\n \n\n Parameters\n ----------\n model : string\n the name of the generator to use for the graph\n P : integer\n The probability (normalize between 0-10) that a given edge randomly changes one of its connection to a node\n C : integer\n An integer between 0 and 10 to control the number of edge each node should have at first\n N : integer\n The size of the network given by the number of node\n P_infection : integer\n the probability of getting infected when encountering a sick individual, from 0 to 10\n P_mortality : integer\n the probability of dying after the disease, from 0 to 10\n n_sick_original : integer\n The number of sick person at iteration 0\n M : integer\n The number of walkers in the network\n repetition : integer\n The number of time the simulation is repeated for statistical analysis (standard deviation and average)\n duree : integer\n The number of iteration a person stay sick before either dying or getting immune\n advanced_switch : array\n An array which will contain \"True\" if the checkbox is checked\n rows : Array\n An array of dictionnary containing the data for the pandas dataframe from the datatable\n columns : Array\n An array of dictionnary containing the column name for the pandas dataframe from the datatable\n advanced_feature : array\n an arry containing the keywords [\"confine\",\"restrict\",\"masks\",\"lockdown\"] depending if the checkboxes are checked\n adherence : integer\n An integer from 0 to 100 reflecting the percentage of the population that respect the measures as defined in advanced_feture\n\n Returns\n -------\n fig : Dash component\n Dash component that includes the plot\n \n message : string\n A string that will be showned under the table to explain if a parameter has an unexpected value\n \"\"\"\n\n global walkers,liste_dead,liste_sick,liste_health\n #formatting basic parameter------------------------------\n P/=10\n C=int(0.3*C/10*N)#!!!!!!\n P_infection/=10\n P_mortality/=10\n \n #formatting advanced features------------------------------\n adherence/=100\n message=_(\"The selected parameters are within their accepted values\")# default value\n if \"True\" in advanced_switch :\n df = pd.DataFrame(rows, columns=[c['name'] for c in columns])\n #df.set_index('Age')\n #df.to_csv('test.csv')\n #----------------------------------------------------------------\n #let's verify the parameter selected are within their accepted value\n for c in params_table :\n \n limites=params_table_limits[c]\n if '%' in limites :\n \n if not df[c].astype(float).sum()==100 :\n message=_(f\"The {c} parameter does not sums to 100\")\n advanced_switch=[]\n else :\n minimum,maximum=limites[0],limites[1]\n for rangee in df[c].values :\n if not minimum<=float(rangee)<=maximum :\n message=_(f\"The {c} parameter has the value {rangee} outside the permitted range {limites}\")\n advanced_switch=[]\n \n \n #----------------------------------------------------------------\n \n \n \n \n #selection of the generator-------------------------------\n if model==\"watts\" :\n G=nx.Graph(nx.watts_strogatz_graph(N,C,P))\n if \"lockdown\" in advanced_feature :\n for i in range(0,int(N*0.2)) :\n noeud=max(dict(G.degree()).items(), key = lambda x : x[1])[0]\n G.remove_node(noeud)\n N-=int(0.2*N)\n \n\n elif model==\"grid\" :\n G=nx.Graph(nx.grid_2d_graph(np.sqrt(N),np.sqrt(N)))\n if \"lockdown\" in advanced_feature :\n for i in range(0,int(N*0.2)) :\n noeud=max(dict(G.degree()).items(), key = lambda x : x[1])[0]\n G.remove_node(noeud)\n N-=int(0.2*N)\n \n\n elif model==\"power_law\" :\n G=nx.Graph(nx.powerlaw_cluster_graph(N,C,P))\n if \"lockdown\" in advanced_feature :\n for i in range(0,int(N*0.2)) :\n noeud=max(dict(G.degree()).items(), key = lambda x : x[1])[0]\n G.remove_node(noeud)\n N-=int(0.2*N)\n \n else :\n G=nx.Graph(nx.generators.random_graphs.connected_watts_strogatz_graph(N,C,P))\n if \"lockdown\" in advanced_feature :\n for i in range(0,int(N*0.2)) :\n noeud=max(dict(G.degree()).items(), key = lambda x : x[1])[0]\n G.remove_node(noeud)\n N-=int(0.2*N)\n \n\n N=int(N)\n #we need to relabel the nodes if they were deleted!\n if \"lockdown\" in advanced_feature :\n dictionnary={}\n for (ex,i) in enumerate(G.nodes) :\n dictionnary.update( { i : ex } )\n \n G=nx.relabel_nodes(G,dictionnary)\n \n \n maps=nx.to_dict_of_lists(G)\n #---------------------------------------------------------\n max_iter=1000 #!!!!!! a remplacer dans le futur si necessaire\n \n\n\n \n \n\n liste_sick,liste_health,liste_dead=np.zeros((repetition,max_iter)),np.zeros((repetition,max_iter)),np.zeros((repetition,max_iter))\n if \"True\" in advanced_switch :\n r0,walkers=epidemic(M,N,n_sick_original,max_iter,duree,maps,repetition,liste_sick,liste_health,liste_dead,P_infection,P_mortality,df,columns,advanced_feature,adherence)\n else :\n r0,walkers=epidemic(M,N,n_sick_original,max_iter,duree,maps,repetition,liste_sick,liste_health,liste_dead,P_infection,P_mortality)\n \n\n #limit the range of iteration-------------------------------------\n try :\n limite=np.where(np.logical_or(liste_sick.mean(axis=0).round(0)<1,liste_dead.mean(axis=0).round(0)>M-1))[0][0]+1\n liste_sick,liste_health,liste_dead=liste_sick[:,0:limite],liste_health[:,0:limite],liste_dead[:,0:limite]\n\n\n except :\n limite=max_iter\n liste_sick,liste_health,liste_dead=liste_sick[:,0:limite],liste_health[:,0:limite],liste_dead[:,0:limite]\n\n\n if repetition>1 :\n repetition=0.2\n else :\n repetition=0\n \n #graphic setup-------------------------------------------------\n fig = go.Figure()\n fig.update_layout(\n title=\"Status of the population at each iteration\",\n xaxis_title=\"Iterations\",\n yaxis_title=\"Number of persons\",\n\n # font=dict(\n # family=\"Courier New, monospace\",\n # size=18,\n # color=\"RebeccaPurple\"\n # )\n )\n fig.add_trace(go.Scatter(\n\n name=\"dead\",\n type=\"scatter\",\n\n y=np.mean(liste_dead,axis=0),\n\n #line_color=\"rgba(255,255,255,0)\",\n fillcolor=\"rgba(255,255,255,0)\",\n line={'color': 'purple'},\n connectgaps=True,\n showlegend=True,\n error_y= dict(\n type='data',\n array=np.std(liste_dead,axis=0)*repetition,\n color='purple',\n thickness=1.5,\n width=3,\n ),\n marker=dict(color='purple', size=8)\n))\n\n fig.add_trace(go.Scatter(\n\n name=\"healthy\",\n type=\"scatter\",\n\n y=np.mean(liste_health,axis=0),\n\n #line_color=\"rgba(255,255,255,0)\",\n fillcolor=\"rgba(255,255,255,0)\",\n line={'color': 'blue'},\n connectgaps=True,\n showlegend=True,\n error_y=dict(\n type='data',\n array=np.std(liste_health,axis=0)*repetition,\n color='blue',\n thickness=1.5,\n width=3,\n ),\n marker=dict(color='blue', size=8)\n))\n\n\n fig.add_trace(go.Scatter(\n\n name=\"sick\",\n type=\"scatter\",\n\n y=np.mean(liste_sick,axis=0),\n\n #line_color=\"rgba(255,255,255,0)\",\n fillcolor=\"rgba(255,255,255,0)\",\n line={'color': 'red'},\n connectgaps=True,\n showlegend=True,\n error_y=dict(\n type='data',\n array=np.std(liste_sick,axis=0)*repetition,\n color='red',\n thickness=1.5,\n width=3,\n ),\n marker=dict(color='red', size=8)\n))\n\n dr0 = \"\"\n if len(r0) > 1:\n dr0 += f\"+/- {np.std(r0)}\"\n r0 = np.mean(r0)\n for g in model_options :\n if g['value']==model :\n model_label=g['label']\n\n argument = np.argmin((df_diseases['R0'].values - r0) ** 2 + ((df_diseases['mortality'].values) - P_mortality) ** 2)\n\n disease_name=df_diseases['Name'].values[argument]\n disease_R0=df_diseases['R0'].values[argument]\n disease_mortality=df_diseases['mortality'].values[argument]\n\n\n\n\n conclusion=f\"Using the {model_label} to generate the network, you have infected {(1-np.mean(liste_health,axis=0)[limite-1]/M)*100}% of the population leaving {np.mean(liste_dead,axis=0)[limite-1]/M*100}% of the original \" \\\n f\" population dead. This model estimated the R0 factor to be {r0} {dr0}. Your epidemic most closely ressemble {disease_name} which has a {disease_mortality} mortality rate\" \\\n f\" and a r0 factor of {disease_R0} \\n\" \\\n f\"\\n\" \\\n f\" The R0 factor represent the number of person, in average, one sick person will then infect. This number is one of the primordial \" \\\n f\" caracteristic of a disease during an outbreak.py \\n\" \\\n f\"\\n\" \\\n f\" Interesting fact, {disease_name} is a {df_diseases['ty^pe'].values[argument]} that is spreads by {df_diseases['spread'].values[argument]} \\n\" \\\n f\"\\n\" \\\n f\"\\n\" \\\n f\"***The mortality rates for the other diseases are for healthy adults. Source : https://docs.google.com/spreadsheets/d/1kHCEWY-d9HXlWrft9jjRQ2xf6WHQlmwyrXel6wjxkW8/edit#gid=0\"\n\n return fig,message,conclusion\n\n\n\n\n\[email protected](\n [\n Output('language-button', 'children'),\n Output('language-link', 'href'),\n Output(\"learn-more-link\", 'href')\n ],\n [Input('none2', 'children')]\n)\ndef update_language_button(x):\n \"\"\"Updates the button to switch languages\n \"\"\"\n\n language = session['language']\n if language == 'fr':\n return 'EN', prefixe+'/language/en','https://github.com/J-bytes/Epidemiologic-simulation/' #! Le code est bizarre et fait l'inverse. à mettre pour update le lien\n else:\n return 'FR', prefixe+'/language/fr','https://github.com/J-bytes/Epidemiologic-simulation/'\n\n\[email protected]\ndef get_locale():\n # if the user has set up the language manually it will be stored in the session,\n # so we use the locale from the user settings\n try:\n language = session['language']\n except KeyError:\n language = None\n if language is not None:\n return language\n return 'en'\n\n\[email protected]('/language/<language>')\ndef set_language(language=None):\n \"\"\"Sets the session language, then refreshes the page\n \"\"\"\n session['language'] = language\n\n return redirect(url_for('/'))\n\n\n\[email protected]('/dash/downloadCSV')\ndef download_csv():\n global walkers, liste_dead, liste_sick, liste_health\n\n\n dff = pd.DataFrame({\"n_dead\" : liste_dead[0,:],\"n_sick\" : liste_sick[0,:],\"n_healthy\" : liste_health[0,:]})\n csv = dff.to_csv(index=False)\n\n return Response(\n csv,\n mimetype=\"text/csv\",\n headers={\n \"Content-disposition\": \"attachment; filename=rcom_data.csv\"\n }\n )\n\n\[email protected]('/dash/downloadCSV2')\ndef download_csv2():\n global walkers, liste_dead, liste_sick, liste_health\n columns = ['x', 'lifespan', 'number', 'P_infection', 'P_mortality', 'status', 'age', 'P_movements',\n 'advanced_feature']\n df2=pd.DataFrame([{fn: getattr(f, fn) for fn in columns} for f in walkers])\n\n\n csv2=df2.to_csv(index=False)\n return Response(\n csv2,\n mimetype=\"text/csv\",\n headers={\n \"Content-disposition\": \"attachment; filename=rcom_data.csv\"\n }\n )\n\n\n\nif __name__ == '__main__':\n #app.run_server(debug=True) # For development/testing\n\n app.run_server(debug=True, host='0.0.0.0', port=5555) # For the server\n"
] | [
[
"pandas.read_csv",
"numpy.sqrt",
"pandas.DataFrame",
"numpy.std",
"numpy.mean",
"numpy.argmin",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
jyqi/mx-viddet | [
"af89ed736362fecdd1ee5e6584d9b221c59ff8c4"
] | [
"rfcn/core/DataParallelExecutorGroup.py"
] | [
"# --------------------------------------------------------\n# Deep Feature Flow\n# Copyright (c) 2016 by Contributors\n# Copyright (c) 2017 Microsoft\n# Licensed under The Apache-2.0 License [see LICENSE for details]\n# Modified by Yuwen Xiong\n# --------------------------------------------------------\n\nimport logging\nimport numpy as np\n\nfrom mxnet import context as ctx\nfrom mxnet import ndarray as nd\nfrom mxnet.io import DataDesc\nfrom mxnet.executor_manager import _split_input_slice\n\n\n\ndef _load_general(data, targets, major_axis):\n \"\"\"Load a list of arrays into a list of arrays specified by slices\"\"\"\n for d_src, d_targets in zip(data, targets):\n if isinstance(d_targets, nd.NDArray):\n d_src.copyto(d_targets)\n elif isinstance(d_src, (list, tuple)):\n for src, dst in zip(d_src, d_targets):\n src.copyto(dst)\n else:\n raise NotImplementedError\n\n\n\ndef _load_data(batch, targets, major_axis):\n \"\"\"Load data into sliced arrays\"\"\"\n _load_general(batch.data, targets, major_axis)\n\n\ndef _load_label(batch, targets, major_axis):\n \"\"\"Load label into sliced arrays\"\"\"\n _load_general(batch.label, targets, major_axis)\n\n\ndef _merge_multi_context(outputs, major_axis):\n \"\"\"Merge outputs that lives on multiple context into one, so that they look\n like living on one context.\n \"\"\"\n rets = []\n for tensors, axis in zip(outputs, major_axis):\n if axis >= 0:\n rets.append(nd.concatenate(tensors, axis=axis, always_copy=False))\n else:\n # negative axis means the there is no batch_size axis, and all the\n # results should be the same on each device. We simply take the\n # first one, without checking they are actually the same\n rets.append(tensors[0])\n return rets\n\n\n\nclass DataParallelExecutorGroup(object):\n \"\"\"DataParallelExecutorGroup is a group of executors that lives on a group of devices.\n This is a helper class used to implement data parallelization. Each mini-batch will\n be split and run on the devices.\n\n Parameters\n ----------\n symbol : Symbol\n The common symbolic computation graph for all executors.\n contexts : list\n A list of contexts.\n workload : list\n If not `None`, could be a list of numbers that specify the workload to be assigned\n to different context. Larger number indicate heavier workload.\n data_shapes : list\n Should be a list of (name, shape) tuples, for the shapes of data. Note the order is\n important and should be the same as the order that the `DataIter` provide the data.\n label_shapes : list\n Should be a list of (name, shape) tuples, for the shapes of label. Note the order is\n important and should be the same as the order that the `DataIter` provide the label.\n param_names : list\n A list of strings, indicating the names of parameters (e.g. weights, filters, etc.)\n in the computation graph.\n for_training : bool\n Indicate whether the executors should be bind for training. When not doing training,\n the memory for gradients will not be allocated.\n inputs_need_grad : bool\n Indicate whether the gradients for the input data should be computed. This is currently\n not used. It will be useful for implementing composition of modules.\n shared_group : DataParallelExecutorGroup\n Default is `None`. This is used in bucketing. When not `None`, it should be a executor\n group corresponding to a different bucket. In other words, it will correspond to a different\n symbol but with the same set of parameters (e.g. unrolled RNNs with different lengths).\n In this case, many memory will be shared.\n logger : Logger\n Default is `logging`.\n fixed_param_names: list of str\n Indicate parameters to be fixed during training. Parameters in this list will not allocate\n space for gradient, nor do gradient calculation.\n grad_req : str, list of str, dict of str to str\n Requirement for gradient accumulation. Can be 'write', 'add', or 'null'\n (default to 'write').\n Can be specified globally (str) or for each argument (list, dict).\n \"\"\"\n def __init__(self, symbol, contexts, workload, data_shapes, label_shapes, param_names,\n for_training, inputs_need_grad, shared_group=None, logger=logging,\n fixed_param_names=None, grad_req='write', state_names=None):\n self.param_names = param_names\n self.arg_names = symbol.list_arguments()\n self.aux_names = symbol.list_auxiliary_states()\n\n self.symbol = symbol\n self.contexts = contexts\n self.workload = workload\n\n self.for_training = for_training\n self.inputs_need_grad = inputs_need_grad\n\n self.logger = logger\n #In the future we should have a better way to profile memory per device (haibin)\n # self._total_exec_bytes = 0\n self.fixed_param_names = fixed_param_names\n if self.fixed_param_names is None:\n self.fixed_param_names = []\n\n self.state_names = state_names\n if self.state_names is None:\n self.state_names = []\n\n if not for_training:\n grad_req = 'null'\n\n # data_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in data_shapes]\n # if label_shapes is not None:\n # label_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in label_shapes]\n\n data_names = [x.name for x in data_shapes[0]]\n\n if isinstance(grad_req, str):\n self.grad_req = {}\n for k in self.arg_names:\n if k in self.param_names:\n self.grad_req[k] = 'null' if k in self.fixed_param_names else grad_req\n elif k in data_names:\n self.grad_req[k] = grad_req if self.inputs_need_grad else 'null'\n else:\n self.grad_req[k] = 'null'\n elif isinstance(grad_req, (list, tuple)):\n assert len(grad_req) == len(self.arg_names)\n self.grad_req = dict(zip(self.arg_names, grad_req))\n elif isinstance(grad_req, dict):\n self.grad_req = {}\n for k in self.arg_names:\n if k in self.param_names:\n self.grad_req[k] = 'null' if k in self.fixed_param_names else 'write'\n elif k in data_names:\n self.grad_req[k] = 'write' if self.inputs_need_grad else 'null'\n else:\n self.grad_req[k] = 'null'\n self.grad_req.update(grad_req)\n else:\n raise ValueError(\"grad_req must be one of str, list, tuple, or dict.\")\n\n if shared_group is not None:\n self.shared_data_arrays = shared_group.shared_data_arrays\n else:\n self.shared_data_arrays = [{} for _ in contexts]\n\n # initialize some instance variables\n self.batch_size = len(data_shapes)\n self.slices = None\n self.execs = []\n self._default_execs = None\n self.data_arrays = None\n self.label_arrays = None\n self.param_arrays = None\n self.state_arrays = None\n self.grad_arrays = None\n self.aux_arrays = None\n self.input_grad_arrays = None\n\n self.data_shapes = None\n self.label_shapes = None\n self.data_layouts = None\n self.label_layouts = None\n self.output_layouts = [DataDesc.get_batch_axis(self.symbol[name].attr('__layout__'))\n for name in self.symbol.list_outputs()]\n self.bind_exec(data_shapes, label_shapes, shared_group)\n\n def decide_slices(self, data_shapes):\n \"\"\"Decide the slices for each context according to the workload.\n\n Parameters\n ----------\n data_shapes : list\n list of (name, shape) specifying the shapes for the input data or label.\n \"\"\"\n assert len(data_shapes) > 0\n major_axis = [DataDesc.get_batch_axis(x.layout) for x in data_shapes]\n\n for (name, shape), axis in zip(data_shapes, major_axis):\n if axis == -1:\n continue\n\n batch_size = shape[axis]\n if self.batch_size is not None:\n assert batch_size == self.batch_size, (\"all data must have the same batch size: \"\n + (\"batch_size = %d, but \" % self.batch_size)\n + (\"%s has shape %s\" % (name, shape)))\n else:\n self.batch_size = batch_size\n self.slices = _split_input_slice(self.batch_size, self.workload)\n\n return major_axis\n\n def _collect_arrays(self):\n \"\"\"Collect internal arrays from executors.\"\"\"\n # convenient data structures\n self.data_arrays = [[e.arg_dict[name] for name, _ in self.data_shapes[0]] for e in self.execs]\n\n self.state_arrays = [[e.arg_dict[name] for e in self.execs]\n for name in self.state_names]\n\n if self.label_shapes is not None:\n self.label_arrays = [[e.arg_dict[name] for name, _ in self.label_shapes[0]] for e in self.execs]\n else:\n self.label_arrays = None\n\n self.param_arrays = [[exec_.arg_arrays[i] for exec_ in self.execs]\n for i, name in enumerate(self.arg_names)\n if name in self.param_names]\n if self.for_training:\n self.grad_arrays = [[exec_.grad_arrays[i] for exec_ in self.execs]\n for i, name in enumerate(self.arg_names)\n if name in self.param_names]\n else:\n self.grad_arrays = None\n\n data_names = [x[0] for x in self.data_shapes]\n if self.inputs_need_grad:\n self.input_grad_arrays = [[exec_.grad_arrays[i] for exec_ in self.execs]\n for i, name in enumerate(self.arg_names)\n if name in data_names]\n else:\n self.input_grad_arrays = None\n\n self.aux_arrays = [[exec_.aux_arrays[i] for exec_ in self.execs]\n for i in range(len(self.aux_names))]\n\n def bind_exec(self, data_shapes, label_shapes, shared_group=None, reshape=False):\n \"\"\"Bind executors on their respective devices.\n\n Parameters\n ----------\n data_shapes : list\n label_shapes : list\n shared_group : DataParallelExecutorGroup\n reshape : bool\n \"\"\"\n assert reshape or not self.execs\n\n for i in range(len(self.contexts)):\n data_shapes_i = data_shapes[i]\n if label_shapes is not None:\n label_shapes_i = label_shapes[i]\n else:\n label_shapes_i = []\n\n if reshape:\n self.execs[i] = self._default_execs[i].reshape(\n allow_up_sizing=True, **dict(data_shapes_i + label_shapes_i))\n else:\n self.execs.append(self._bind_ith_exec(i, data_shapes_i, label_shapes_i,\n shared_group))\n\n self.data_shapes = data_shapes\n self.label_shapes = label_shapes\n self._collect_arrays()\n\n def reshape(self, data_shapes, label_shapes):\n \"\"\"Reshape executors.\n\n Parameters\n ----------\n data_shapes : list\n label_shapes : list\n \"\"\"\n if self._default_execs is None:\n self._default_execs = [i for i in self.execs]\n for i in range(len(self.contexts)):\n self.execs[i] = self._default_execs[i].reshape(\n allow_up_sizing=True, **dict(data_shapes[i] + (label_shapes[i] if label_shapes is not None else []))\n )\n self.data_shapes = data_shapes\n self.label_shapes = label_shapes\n self._collect_arrays()\n\n\n def set_params(self, arg_params, aux_params):\n \"\"\"Assign, i.e. copy parameters to all the executors.\n\n Parameters\n ----------\n arg_params : dict\n A dictionary of name to `NDArray` parameter mapping.\n aux_params : dict\n A dictionary of name to `NDArray` auxiliary variable mapping.\n \"\"\"\n for exec_ in self.execs:\n exec_.copy_params_from(arg_params, aux_params)\n\n def get_params(self, arg_params, aux_params):\n \"\"\" Copy data from each executor to `arg_params` and `aux_params`.\n\n Parameters\n ----------\n arg_params : list of NDArray\n target parameter arrays\n aux_params : list of NDArray\n target aux arrays\n\n Notes\n -----\n - This function will inplace update the NDArrays in arg_params and aux_params.\n \"\"\"\n for name, block in zip(self.param_names, self.param_arrays):\n weight = sum(w.copyto(ctx.cpu()) for w in block) / len(block)\n weight.astype(arg_params[name].dtype).copyto(arg_params[name])\n for name, block in zip(self.aux_names, self.aux_arrays):\n weight = sum(w.copyto(ctx.cpu()) for w in block) / len(block)\n weight.astype(aux_params[name].dtype).copyto(aux_params[name])\n\n def forward(self, data_batch, is_train=None):\n \"\"\"Split `data_batch` according to workload and run forward on each devices.\n\n Parameters\n ----------\n data_batch : DataBatch\n Or could be any object implementing similar interface.\n is_train : bool\n The hint for the backend, indicating whether we are during training phase.\n Default is `None`, then the value `self.for_training` will be used.\n Returns\n -------\n\n \"\"\"\n _load_data(data_batch, self.data_arrays, self.data_layouts)\n if is_train is None:\n is_train = self.for_training\n\n if self.label_arrays is not None:\n assert not is_train or data_batch.label\n if data_batch.label:\n _load_label(data_batch, self.label_arrays, self.label_layouts)\n\n for exec_ in self.execs:\n exec_.forward(is_train=is_train)\n\n\n def get_outputs(self, merge_multi_context=True):\n \"\"\"Get outputs of the previous forward computation.\n\n Parameters\n ----------\n merge_multi_context : bool\n Default is `True`. In the case when data-parallelism is used, the outputs\n will be collected from multiple devices. A `True` value indicate that we\n should merge the collected results so that they look like from a single\n executor.\n\n Returns\n -------\n If `merge_multi_context` is `True`, it is like `[out1, out2]`. Otherwise, it\n is like `[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]`. All the output\n elements are `NDArray`.\n \"\"\"\n outputs = [[exec_.outputs[i] for exec_ in self.execs]\n for i in range(len(self.execs[0].outputs))]\n if merge_multi_context:\n outputs = _merge_multi_context(outputs, self.output_layouts)\n return outputs\n\n def get_states(self, merge_multi_context=True):\n \"\"\"Get states from all devices\n\n Parameters\n ----------\n merge_multi_context : bool\n Default is `True`. In the case when data-parallelism is used, the states\n will be collected from multiple devices. A `True` value indicate that we\n should merge the collected results so that they look like from a single\n executor.\n\n Returns\n -------\n If `merge_multi_context` is `True`, it is like `[out1, out2]`. Otherwise, it\n is like `[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]`. All the output\n elements are `NDArray`.\n \"\"\"\n assert not merge_multi_context, \\\n \"merge_multi_context=True is not supported for get_states yet.\"\n return self.state_arrays\n\n def set_states(self, states=None, value=None):\n \"\"\"Set value for states. Only one of states & value can be specified.\n\n Parameters\n ----------\n states : list of list of NDArrays\n source states arrays formatted like [[state1_dev1, state1_dev2],\n [state2_dev1, state2_dev2]].\n value : number\n a single scalar value for all state arrays.\n \"\"\"\n if states is not None:\n assert value is None, \"Only one of states & value can be specified.\"\n _load_general(states, self.state_arrays, (0,)*len(states))\n else:\n assert value is not None, \"At least one of states & value must be specified.\"\n assert states is None, \"Only one of states & value can be specified.\"\n for d_dst in self.state_arrays:\n for dst in d_dst:\n dst[:] = value\n\n def get_input_grads(self, merge_multi_context=True):\n \"\"\"Get the gradients with respect to the inputs of the module.\n\n Parameters\n ----------\n merge_multi_context : bool\n Default is `True`. In the case when data-parallelism is used, the outputs\n will be collected from multiple devices. A `True` value indicate that we\n should merge the collected results so that they look like from a single\n executor.\n\n Returns\n -------\n If `merge_multi_context` is `True`, it is like `[grad1, grad2]`. Otherwise, it\n is like `[[grad1_dev1, grad1_dev2], [grad2_dev1, grad2_dev2]]`. All the output\n elements are `NDArray`.\n \"\"\"\n assert self.inputs_need_grad\n if merge_multi_context:\n return _merge_multi_context(self.input_grad_arrays, self.data_layouts)\n return self.input_grad_arrays\n\n def backward(self, out_grads=None):\n \"\"\"Run backward on all devices. A backward should be called after\n a call to the forward function. Backward cannot be called unless\n `self.for_training` is `True`.\n\n Parameters\n ----------\n out_grads : NDArray or list of NDArray, optional\n Gradient on the outputs to be propagated back.\n This parameter is only needed when bind is called\n on outputs that are not a loss function.\n \"\"\"\n assert self.for_training, 're-bind with for_training=True to run backward'\n if out_grads is None:\n out_grads = []\n\n for i, exec_ in enumerate(self.execs):\n out_grads_slice = []\n exec_.backward(out_grads=out_grads_slice)\n\n def update_metric(self, eval_metric, labels):\n \"\"\"Accumulate the performance according to `eval_metric` on all devices.\n\n Parameters\n ----------\n eval_metric : EvalMetric\n The metric used for evaluation.\n labels : list of NDArray\n Typically comes from `label` of a `DataBatch`.\n \"\"\"\n for texec, labels in zip(self.execs, labels):\n eval_metric.update(labels, texec.outputs)\n\n def _bind_ith_exec(self, i, data_shapes, label_shapes, shared_group):\n \"\"\"Internal utility function to bind the i-th executor.\n \"\"\"\n shared_exec = None if shared_group is None else shared_group.execs[i]\n context = self.contexts[i]\n shared_data_arrays = self.shared_data_arrays[i]\n\n input_shapes = dict(data_shapes)\n if label_shapes is not None:\n input_shapes.update(dict(label_shapes))\n\n arg_shapes, _, aux_shapes = self.symbol.infer_shape(**input_shapes)\n assert arg_shapes is not None, \"shape inference failed\"\n\n input_types = {x.name: x.dtype for x in data_shapes}\n if label_shapes is not None:\n input_types.update({x.name: x.dtype for x in label_shapes})\n arg_types, _, aux_types = self.symbol.infer_type(**input_types)\n assert arg_types is not None, \"type inference failed\"\n\n arg_arrays = []\n grad_arrays = {} if self.for_training else None\n\n def _get_or_reshape(name, shared_data_arrays, arg_shape, arg_type, context, logger):\n \"\"\"Internal helper to get a memory block or re-use by re-shaping\"\"\"\n if name in shared_data_arrays:\n arg_arr = shared_data_arrays[name]\n\n if np.prod(arg_arr.shape) >= np.prod(arg_shape):\n # nice, we can directly re-use this data blob\n assert arg_arr.dtype == arg_type\n arg_arr = arg_arr.reshape(arg_shape)\n else:\n logger.warning(('bucketing: data \"%s\" has a shape %s' % (name, arg_shape)) +\n (', which is larger than already allocated ') +\n ('shape %s' % (arg_arr.shape,)) +\n ('. Need to re-allocate. Consider putting ') +\n ('default_bucket_key to') +\n (' be the bucket taking the largest input for better ') +\n ('memory sharing.'))\n arg_arr = nd.zeros(arg_shape, context, dtype=arg_type)\n\n # replace existing shared array because the new one is bigger\n shared_data_arrays[name] = arg_arr\n else:\n arg_arr = nd.zeros(arg_shape, context, dtype=arg_type)\n shared_data_arrays[name] = arg_arr\n\n return arg_arr\n\n # create or borrow arguments and gradients\n for j in range(len(self.arg_names)):\n name = self.arg_names[j]\n if name in self.param_names: # model parameters\n if shared_exec is None:\n arg_arr = nd.zeros(arg_shapes[j], context, dtype=arg_types[j])\n if self.grad_req[name] != 'null':\n grad_arr = nd.zeros(arg_shapes[j], context, dtype=arg_types[j])\n grad_arrays[name] = grad_arr\n else:\n arg_arr = shared_exec.arg_dict[name]\n assert arg_arr.shape == arg_shapes[j]\n assert arg_arr.dtype == arg_types[j]\n if self.grad_req[name] != 'null':\n grad_arrays[name] = shared_exec.grad_dict[name]\n else: # data, label, or states\n arg_arr = _get_or_reshape(name, shared_data_arrays, arg_shapes[j], arg_types[j],\n context, self.logger)\n\n # data might also need grad if inputs_need_grad is True\n if self.grad_req[name] != 'null':\n grad_arrays[name] = _get_or_reshape('grad of ' + name, shared_data_arrays,\n arg_shapes[j], arg_types[j], context,\n self.logger)\n\n arg_arrays.append(arg_arr)\n\n # create or borrow aux variables\n if shared_exec is None:\n aux_arrays = [nd.zeros(s, context, dtype=t) for s, t in zip(aux_shapes, aux_types)]\n else:\n for j, arr in enumerate(shared_exec.aux_arrays):\n assert aux_shapes[j] == arr.shape\n assert aux_types[j] == arr.dtype\n aux_arrays = shared_exec.aux_arrays[:]\n\n executor = self.symbol.bind(ctx=context, args=arg_arrays,\n args_grad=grad_arrays, aux_states=aux_arrays,\n grad_req=self.grad_req, shared_exec=shared_exec)\n # Get the total bytes allocated for this executor\n return executor\n\n def _sliced_shape(self, shapes, i, major_axis):\n \"\"\"Get the sliced shapes for the i-th executor.\n\n Parameters\n ----------\n shapes : list of (str, tuple)\n The original (name, shape) pairs.\n i : int\n Which executor we are dealing with.\n \"\"\"\n sliced_shapes = []\n for desc, axis in zip(shapes, major_axis):\n shape = list(desc.shape)\n if axis >= 0:\n shape[axis] = self.slices[i].stop - self.slices[i].start\n sliced_shapes.append(DataDesc(desc.name, tuple(shape), desc.dtype, desc.layout))\n return sliced_shapes\n\n def install_monitor(self, mon):\n \"\"\"Install monitor on all executors\"\"\"\n for exe in self.execs:\n mon.install(exe)\n"
] | [
[
"numpy.prod"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MartimQS/Deep-MVLM | [
"b01b5f44f423f236e94741d94a7a3628240123dd"
] | [
"utils3d/utils3d.py"
] | [
"import numpy as np\nimport vtk\nimport os\n\n\nclass Utils3D:\n def __init__(self, config):\n self.config = config\n self.heatmap_maxima = None\n self.transformations_3d = None\n self.lm_start = None\n self.lm_end = None\n self.landmarks = None\n self.logger = config.get_logger('Utils3D')\n\n def read_heatmap_maxima(self, dir_name=None):\n if dir_name is None:\n dir_name = str(self.config.temp_dir)\n print('Reading from', dir_name)\n\n n_landmarks = self.config['arch']['args']['n_landmarks']\n n_views = self.config['data_loader']['args']['n_views']\n\n # [n_landmarks, n_views, x, y, value]\n self.heatmap_maxima = np.zeros((n_landmarks, n_views, 3))\n\n for idx in range(n_views):\n name_hm_maxima = dir_name + '/hm_maxima' + str(idx) + '.txt'\n with open(name_hm_maxima) as f:\n id_lm = 0\n for line in f:\n line = line.strip(\"/n\")\n x, y, val = np.double(line.split(\" \"))\n self.heatmap_maxima[id_lm, idx, :] = (x, y, val)\n id_lm = id_lm + 1\n if id_lm > n_landmarks:\n print('Too many landmarks in file ', name_hm_maxima)\n break\n\n if id_lm != n_landmarks:\n print('Too few landmarks in file ', name_hm_maxima)\n\n def read_3d_transformations(self, dir_name=None):\n if dir_name is None:\n dir_name = str(self.config.temp_dir)\n print('Reading from', dir_name)\n\n n_views = self.config['data_loader']['args']['n_views']\n\n # [n_views, rx, ry, rz, s, tx, ty]\n self.transformations_3d = np.zeros((n_views, 6))\n\n for idx in range(n_views):\n name_hm_maxima = dir_name + '/transform' + str(idx) + '.txt'\n rx, ry, rz, s, tx, ty = np.loadtxt(name_hm_maxima)\n self.transformations_3d[idx, :] = (rx, ry, rz, s, tx, ty)\n\n # Each maxima in a heatmap corresponds to a line in 3D space of the original 3D shape\n # This function transforms the maxima to (start point, end point) pairs\n def compute_lines_from_heatmap_maxima(self):\n n_landmarks = self.heatmap_maxima.shape[0]\n n_views = self.heatmap_maxima.shape[1]\n\n self.lm_start = np.zeros((n_landmarks, n_views, 3))\n self.lm_end = np.zeros((n_landmarks, n_views, 3))\n\n img_size = self.config['data_loader']['args']['image_size']\n hm_size = self.config['data_loader']['args']['heatmap_size']\n winsize = img_size\n\n # TODO these fixed values should probably be in a config file\n x_min = -150\n x_max = 150\n y_min = -150\n y_max = 150\n x_len = x_max - x_min\n y_len = y_max - y_min\n\n pd = vtk.vtkPolyData()\n for idx in range(n_views):\n rx, ry, rz, s, tx, ty = self.transformations_3d[idx, :]\n\n # Set transformation matrix in vtk\n t = vtk.vtkTransform()\n t.Identity()\n t.Update()\n\n t.Identity()\n t.RotateY(ry)\n t.RotateX(rx)\n t.RotateZ(rz)\n t.Update()\n\n for lm_no in range(n_landmarks):\n # [n_landmarks, n_views, x, y, value]\n y = self.heatmap_maxima[lm_no, idx, 0]\n x = self.heatmap_maxima[lm_no, idx, 1]\n # value = self.heatmap_maxima[lm_no, idx, 2]\n\n # Extract just one landmark and scale it according to heatmap and image sizes\n y = y / hm_size * img_size\n x = x / hm_size * img_size\n\n # Making end points of line in world coordinates\n p_wc_s = np.zeros((3, 1))\n p_wc_e = np.zeros((3, 1))\n\n p_wc_s[0] = (x / winsize) * x_len + x_min\n p_wc_s[1] = ((winsize - 1 - y) / winsize) * y_len + y_min\n p_wc_s[2] = 500\n\n p_wc_e[0] = (x / winsize) * x_len + x_min\n p_wc_e[1] = ((winsize - 1 - y) / winsize) * y_len + y_min\n p_wc_e[2] = -500\n\n # Insert line into vtk-framework to transform\n points = vtk.vtkPoints()\n lines = vtk.vtkCellArray()\n\n lines.InsertNextCell(2)\n pid = points.InsertNextPoint(p_wc_s)\n lines.InsertCellPoint(pid)\n pid = points.InsertNextPoint(p_wc_e)\n lines.InsertCellPoint(pid)\n\n pd.SetPoints(points)\n del points\n pd.SetLines(lines)\n del lines\n\n # Do inverse transform into original space\n tfilt = vtk.vtkTransformPolyDataFilter()\n tfilt.SetTransform(t.GetInverse())\n tfilt.SetInputData(pd)\n tfilt.Update()\n\n lm_out = vtk.vtkPolyData()\n lm_out.DeepCopy(tfilt.GetOutput())\n\n self.lm_start[lm_no, idx, :] = lm_out.GetPoint(0)\n self.lm_end[lm_no, idx, :] = lm_out.GetPoint(1)\n\n del tfilt\n del t\n del pd\n\n def visualise_one_landmark_lines(self, lm_no, dir_name=None):\n if dir_name is None:\n dir_name = str(self.config.temp_dir)\n print('Writing to', dir_name)\n\n lm_name = dir_name + '/lm_lines_' + str(lm_no) + '.vtk'\n\n n_views = self.heatmap_maxima.shape[1]\n pd = vtk.vtkPolyData()\n points = vtk.vtkPoints()\n lines = vtk.vtkCellArray()\n verts = vtk.vtkCellArray()\n scalars = vtk.vtkDoubleArray()\n scalars.SetNumberOfComponents(1)\n scalars.SetNumberOfValues(2 * n_views)\n\n for idx in range(n_views):\n lines.InsertNextCell(2)\n pid = points.InsertNextPoint(self.lm_start[lm_no, idx, :])\n lines.InsertCellPoint(pid)\n verts.InsertNextCell(1)\n verts.InsertCellPoint(pid)\n pid = points.InsertNextPoint(self.lm_end[lm_no, idx, :])\n lines.InsertCellPoint(pid)\n scalars.SetValue(idx * 2, self.heatmap_maxima[lm_no, idx, 2]) # Color code according to maxima value\n scalars.SetValue(idx * 2 + 1, self.heatmap_maxima[lm_no, idx, 2])\n\n pd.SetPoints(points)\n del points\n pd.SetLines(lines)\n del lines\n pd.SetVerts(verts)\n del verts\n pd.GetPointData().SetScalars(scalars)\n del scalars\n\n writer = vtk.vtkPolyDataWriter()\n writer.SetInputData(pd)\n writer.SetFileName(lm_name)\n writer.Write()\n\n del writer\n del pd\n\n # FROM: https://se.mathworks.com/matlabcentral/fileexchange/37192-intersection-point-of-lines-in-3d-space?focused\n # =5235003&tab=function\"\n \"\"\"\n Find intersection point of lines in 3D space, in the least squares sense.\n pa : Nx3-matrix containing starting point of N lines\n pa : Nx3-matrix containing end point of N lines\n p_intersect : Best intersection point of the N lines, in least squares sense.\n distances : Distances from intersection point to the input lines\n Anders Eikenes, 2012 \"\"\"\n def compute_intersection_between_lines(self, pa, pb):\n n_lines = pa.shape[0]\n si = pb - pa # N lines described as vectors\n ni = np.divide(si, np.transpose(np.sqrt(np.sum(si ** 2, 1)) * np.ones((3, n_lines)))) # Normalize vectors\n nx = ni[:, 0]\n ny = ni[:, 1]\n nz = ni[:, 2]\n sxx = np.sum(nx ** 2 - 1)\n syy = np.sum(ny ** 2 - 1)\n szz = np.sum(nz ** 2 - 1)\n sxy = np.sum(np.multiply(nx, ny))\n sxz = np.sum(np.multiply(nx, nz))\n syz = np.sum(np.multiply(ny, nz))\n s = np.array([[sxx, sxy, sxz], [sxy, syy, syz], [sxz, syz, szz]])\n cx = np.sum(np.multiply(pa[:, 0], (nx ** 2 - 1)) + np.multiply(pa[:, 1], np.multiply(nx, ny)) +\n np.multiply(pa[:, 2], np.multiply(nx, nz)))\n cy = np.sum(np.multiply(pa[:, 0], np.multiply(nx, ny)) + np.multiply(pa[:, 1], (ny ** 2 - 1)) +\n np.multiply(pa[:, 2], np.multiply(ny, nz)))\n cz = np.sum(np.multiply(pa[:, 0], np.multiply(nx, nz)) + np.multiply(pa[:, 1], np.multiply(ny, nz)) +\n np.multiply(pa[:, 2], (nz ** 2 - 1)))\n\n c = np.array([[cx], [cy], [cz]])\n p_intersect = np.matmul(np.linalg.pinv(s), c)\n return p_intersect[:, 0]\n\n def compute_intersection_between_lines_ransac(self, pa, pb):\n # TODO parameters in config\n iterations = 100\n best_error = 100000000 # TODO should find a better initialiser\n best_p = (0, 0, 0)\n dist_thres = 10 * 10 # TODO should find a better way to esimtate dist_thres\n # d = 10 #\n n_lines = len(pa)\n d = n_lines / 3\n used_lines = -1\n\n for i in range(iterations):\n # get 3 random lines\n ran_lines = np.random.choice(range(n_lines), 3, replace=False)\n # Compute first estimate of intersection\n p_est = self.compute_intersection_between_lines(pa[ran_lines, :], pb[ran_lines, :])\n # Compute distance from all lines to intersection\n top = np.cross((np.transpose(p_est) - pa), (np.transpose(p_est) - pb))\n bottom = pb - pa\n distances = (np.linalg.norm(top, axis=1) / np.linalg.norm(bottom, axis=1))**2\n # number of inliners\n n_inliners = np.sum(distances < dist_thres)\n if n_inliners > d:\n # reestimate based on inliners\n idx = distances < dist_thres\n p_est = self.compute_intersection_between_lines(pa[idx, :], pb[idx, :])\n\n # Compute distance from all inliners to intersection\n top = np.cross((np.transpose(p_est) - pa[idx, :]), (np.transpose(p_est) - pb[idx, :]))\n bottom = pb[idx, :] - pa[idx, :]\n distances = (np.linalg.norm(top, axis=1) / np.linalg.norm(bottom, axis=1))**2\n\n # sum_squared = np.sum(np.square(distances)) / n_inliners\n sum_squared = np.sum(distances) / n_inliners\n if sum_squared < best_error:\n best_error = sum_squared\n best_p = p_est\n used_lines = n_inliners\n\n if used_lines == -1:\n self.logger.warning('Ransac failed - estimating from all lines')\n best_p = self.compute_intersection_between_lines(pa, pb)\n # else:\n # print('Ransac error ', best_error, ' with ', used_lines, ' lines')\n\n return best_p, best_error\n\n # return the lines that correspond to a high valued maxima in the heatmap\n def filter_lines_based_on_heatmap_value_using_quantiles(self, lm_no, pa, pb):\n max_values = self.heatmap_maxima[lm_no, :, 2]\n q = self.config['process_3d']['heatmap_max_quantile']\n threshold = np.quantile(max_values, q)\n idx = max_values > threshold\n # print('Using ', threshold, ' as threshold in heatmap maxima')\n pa_new = pa[idx]\n pb_new = pb[idx]\n return pa_new, pb_new\n\n # return the lines that correspond to a high valued maxima in the heatmap\n def filter_lines_based_on_heatmap_value_using_absolute_value(self, lm_no, pa, pb):\n max_values = self.heatmap_maxima[lm_no, :, 2]\n threshold = self.config['process_3d']['heatmap_abs_threshold']\n idx = max_values > threshold\n pa_new = pa[idx]\n pb_new = pb[idx]\n return pa_new, pb_new\n\n # Each landmark can be computed by the intersection of the view lines going trough (or near) it\n def compute_all_landmarks_from_view_lines(self):\n n_landmarks = self.heatmap_maxima.shape[0]\n self.landmarks = np.zeros((n_landmarks, 3))\n\n sum_error = 0\n for lm_no in range(n_landmarks):\n pa = self.lm_start[lm_no, :, :]\n pb = self.lm_end[lm_no, :, :]\n if self.config['process_3d']['filter_view_lines'] == \"abs_value\":\n pa, pb = self.filter_lines_based_on_heatmap_value_using_absolute_value(lm_no, pa, pb)\n elif self.config['process_3d']['filter_view_lines'] == \"quantile\":\n pa, pb = self.filter_lines_based_on_heatmap_value_using_quantiles(lm_no, pa, pb)\n p_intersect = (0, 0, 0)\n if len(pa) < 3:\n print('Not enough valid view lines for landmark ', lm_no)\n else:\n # p_intersect = self.compute_intersection_between_lines(pa, pb)\n p_intersect, best_error = self.compute_intersection_between_lines_ransac(pa, pb)\n sum_error = sum_error + best_error\n self.landmarks[lm_no, :] = p_intersect\n print(\"Ransac average error \", sum_error/n_landmarks)\n\n @staticmethod\n def multi_read_surface(file_name):\n clean_name, file_extension = os.path.splitext(file_name)\n if file_extension == \".obj\":\n obj_in = vtk.vtkOBJReader()\n obj_in.SetFileName(file_name)\n obj_in.Update()\n pd = obj_in.GetOutput()\n return pd\n elif file_extension == \".wrl\":\n vrmlin = vtk.vtkVRMLImporter()\n vrmlin.SetFileName(file_name)\n vrmlin.Update()\n pd = vrmlin.GetRenderer().GetActors().GetLastActor().GetMapper().GetInput()\n return pd\n elif file_extension == \".vtk\":\n pd_in = vtk.vtkPolyDataReader()\n pd_in.SetFileName(file_name)\n pd_in.Update()\n pd = pd_in.GetOutput()\n return pd\n elif file_extension == \".stl\":\n pd_in = vtk.vtkSTLReader()\n pd_in.SetFileName(file_name)\n pd_in.Update()\n pd = pd_in.GetOutput()\n return pd\n elif file_extension == \".ply\":\n pd_in = vtk.vtkPLYReader()\n pd_in.SetFileName(file_name)\n pd_in.Update()\n pd = pd_in.GetOutput()\n return pd\n else:\n print(\"Can not read files with extenstion\", file_extension)\n return None\n\n @staticmethod\n def multi_read_texture(file_name, texture_file_name=None):\n if texture_file_name is None:\n img_texture = os.path.splitext(file_name)[0] + \".bmp\"\n if os.path.isfile(img_texture):\n texture_file_name = img_texture\n img_texture = os.path.splitext(file_name)[0] + \".png\"\n if os.path.isfile(img_texture):\n texture_file_name = img_texture\n img_texture = os.path.splitext(file_name)[0] + \".jpg\"\n if os.path.isfile(img_texture):\n texture_file_name = img_texture\n if file_name.find('RAW.wrl') > 0:\n img_texture = file_name.replace('RAW.wrl', 'F3D.bmp') # BU-3DFE RAW file hack\n if os.path.isfile(img_texture):\n texture_file_name = img_texture\n\n # Load texture\n if texture_file_name is not None:\n clean_name, file_extension = os.path.splitext(texture_file_name)\n if file_extension == \".bmp\":\n texture_image = vtk.vtkBMPReader()\n texture_image.SetFileName(texture_file_name)\n texture_image.Update()\n return texture_image.GetOutput()\n elif file_extension == \".png\":\n texture_image = vtk.vtkPNGReader()\n texture_image.SetFileName(texture_file_name)\n texture_image.Update()\n return texture_image.GetOutput()\n elif file_extension == \".jpg\":\n texture_image = vtk.vtkJPEGReader()\n texture_image.SetFileName(texture_file_name)\n texture_image.Update()\n return texture_image.GetOutput()\n\n return None\n\n # TODO this is also present in render3D - should probably be merged\n def apply_pre_transformation(self, pd):\n translation = [0, 0, 0]\n if self.config['pre-align']['align_center_of_mass']:\n vtk_cm = vtk.vtkCenterOfMass()\n vtk_cm.SetInputData(pd)\n vtk_cm.SetUseScalarsAsWeights(False)\n vtk_cm.Update()\n cm = vtk_cm.GetCenter()\n translation = [-cm[0], -cm[1], -cm[2]]\n\n t = vtk.vtkTransform()\n t.Identity()\n\n rx = self.config['pre-align']['rot_x']\n ry = self.config['pre-align']['rot_y']\n rz = self.config['pre-align']['rot_z']\n s = self.config['pre-align']['scale']\n\n t.Scale(s, s, s)\n t.RotateY(ry)\n t.RotateX(rx)\n t.RotateZ(rz)\n t.Translate(translation)\n t.Update()\n\n # Transform (assuming only one mesh)\n trans = vtk.vtkTransformPolyDataFilter()\n trans.SetInputData(pd)\n trans.SetTransform(t)\n trans.Update()\n\n if self.config['pre-align']['write_pre_aligned']:\n name_out = str(self.config.temp_dir / ('pre_transform_mesh.vtk'))\n writer = vtk.vtkPolyDataWriter()\n writer.SetInputData(trans.GetOutput())\n writer.SetFileName(name_out)\n writer.Write()\n\n return trans.GetOutput(), t\n\n def transform_landmarks_to_original_space(self, landmarks, t):\n points = vtk.vtkPoints()\n pd = vtk.vtkPolyData()\n # verts = vtk.vtkCellArray()\n\n for lm in landmarks:\n pid = points.InsertNextPoint(lm)\n # verts.InsertNextCell(1)\n # verts.InsertCellPoint(pid)\n pd.SetPoints(points)\n\n trans = vtk.vtkTransformPolyDataFilter()\n trans.SetInputData(pd)\n trans.SetTransform(t.GetInverse())\n trans.Update()\n pd_trans = trans.GetOutput()\n\n n_landmarks = pd_trans.GetNumberOfPoints()\n new_landmarks = np.zeros((n_landmarks, 3))\n for lm_no in range(pd_trans.GetNumberOfPoints()):\n p = pd_trans.GetPoint(lm_no)\n new_landmarks[lm_no, :] = (p[0], p[1], p[2])\n return new_landmarks\n\n # Project found landmarks to closest point on the target surface\n # return the landmarks in the original space\n def project_landmarks_to_surface(self, mesh_name):\n pd = self.multi_read_surface(mesh_name)\n\n pd, t = self.apply_pre_transformation(pd)\n\n clean = vtk.vtkCleanPolyData()\n clean.SetInputData(pd)\n # clean.SetInputConnection(pd.GetOutputPort())\n clean.Update()\n\n locator = vtk.vtkCellLocator()\n locator.SetDataSet(clean.GetOutput())\n locator.SetNumberOfCellsPerBucket(1)\n locator.BuildLocator()\n\n projected_landmarks = np.copy(self.landmarks)\n n_landmarks = self.landmarks.shape[0]\n\n for i in range(n_landmarks):\n p = self.landmarks[i, :]\n cell_id = vtk.mutable(0)\n sub_id = vtk.mutable(0)\n dist2 = vtk.reference(0)\n tcp = np.zeros(3)\n\n locator.FindClosestPoint(p, tcp, cell_id, sub_id, dist2)\n # print('Nearest point in distance ', np.sqrt(np.float(dist2)))\n projected_landmarks[i, :] = tcp\n\n # self.landmarks = projected_landmarks\n self.landmarks = self.transform_landmarks_to_original_space(projected_landmarks, t)\n\n del pd\n del clean\n del locator\n\n def write_landmarks_as_vtk_points(self, dir_name=None):\n if dir_name is None:\n dir_name = str(self.config.temp_dir)\n print('Writing to', dir_name)\n\n lm_name = dir_name + '/lms_as_points.vtk'\n n_landmarks = self.heatmap_maxima.shape[0]\n\n pd = vtk.vtkPolyData()\n points = vtk.vtkPoints()\n verts = vtk.vtkCellArray()\n\n for lm_no in range(n_landmarks):\n pid = points.InsertNextPoint(self.landmarks[lm_no, :])\n verts.InsertNextCell(1)\n verts.InsertCellPoint(pid)\n\n pd.SetPoints(points)\n del points\n pd.SetVerts(verts)\n del verts\n\n writer = vtk.vtkPolyDataWriter()\n writer.SetInputData(pd)\n writer.SetFileName(lm_name)\n writer.Write()\n\n del writer\n del pd\n\n @staticmethod\n def write_landmarks_as_vtk_points_external(landmarks, file_name):\n n_landmarks = landmarks.shape[0]\n\n pd = vtk.vtkPolyData()\n points = vtk.vtkPoints()\n verts = vtk.vtkCellArray()\n\n for lm_no in range(n_landmarks):\n pid = points.InsertNextPoint(landmarks[lm_no, :])\n verts.InsertNextCell(1)\n verts.InsertCellPoint(pid)\n\n pd.SetPoints(points)\n del points\n pd.SetVerts(verts)\n del verts\n\n writer = vtk.vtkPolyDataWriter()\n writer.SetInputData(pd)\n writer.SetFileName(file_name)\n writer.Write()\n\n del writer\n del pd\n\n @staticmethod\n def write_landmarks_as_text_external(landmarks, file_name):\n f = open(file_name, 'w')\n\n for lm in landmarks:\n px = lm[0]\n py = lm[1]\n pz = lm[2]\n out_str = str(px) + ' ' + str(py) + ' ' + str(pz) + '\\n'\n f.write(out_str)\n\n f.close()\n\n @staticmethod\n def get_mesh_files_in_dir(directory):\n names = []\n for root, dirs, files in os.walk(directory):\n for filename in files:\n if filename.lower().endswith(('.obj', '.wrl', '.vtk', '.ply', '.stl')):\n full_name = os.path.join(root, filename)\n if os.path.isfile(full_name) and os.stat(full_name).st_size > 5:\n names.append(full_name)\n return names\n"
] | [
[
"numpy.multiply",
"numpy.quantile",
"numpy.linalg.norm",
"numpy.ones",
"numpy.linalg.pinv",
"numpy.copy",
"numpy.transpose",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MayankShrivastava17/opencv-operation-on-image | [
"c5ade8fa527ad05d99b65016678d8d25db201132"
] | [
"denoiseOfColor.py"
] | [
"import numpy as np\nimport cv2 as cv \nfrom matplotlib import pyplot as plt\n\nimg = cv.imread(\"dog.jpg\")\n\ndst = cv.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 15)\n\nplt.subplot(121), plt.imshow(img)\nplt.subplot(122), plt.imshow(dst)\n\nplt.show()\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplot"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Zumo09/Feedback-Prize | [
"e7e7343a81bfec2f5b187f2266154da0bbe48fb9"
] | [
"engine.py"
] | [
"from collections import deque\nfrom datetime import datetime\nimport math\nfrom pathlib import Path\nimport sys\nfrom tqdm import tqdm\nfrom typing import Optional\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard.writer import SummaryWriter\n\nfrom models import CriterionDETR, PrepareInputs, DETR\nfrom datasets import FBPPostProcess\n\n\nclass Engine:\n def __init__(self) -> None:\n self.global_step = 0\n self.writer: Optional[SummaryWriter] = None\n self.loss_window = deque(maxlen=100)\n\n @staticmethod\n def get_outputs(tokenizer, model, samples, device):\n outputs = []\n for doc in samples:\n inputs = tokenizer([doc]).to(device)\n\n enc_attend_every = 10\n times = math.ceil(inputs.size()[1] / enc_attend_every)\n glob_enc_attn = torch.zeros(enc_attend_every, device=device)\n glob_enc_attn[0] = 1\n glob_enc_attn = glob_enc_attn.tile(times)[:inputs.size()[1]]\n\n glob_dec_attn = torch.ones(model.num_queries).to(device)\n\n # BUG Token indices sequence length is longer than the specified maximum \n # sequence length for this model (16823 > 16384). Running this sequence \n # through the model will result in indexing errors\n\n outputs.append(model(inputs, glob_enc_attn, glob_dec_attn))\n\n batch_outputs = {\n key: torch.cat([o[key] for o in outputs]) for key in outputs[0].keys()\n }\n\n return batch_outputs\n\n def train_one_epoch(\n self,\n tokenizer: PrepareInputs,\n model: DETR,\n criterion: CriterionDETR,\n postprocessor: FBPPostProcess,\n data_loader: DataLoader,\n optimizer: torch.optim.Optimizer,\n device: torch.device,\n epoch: int,\n max_norm: float = 0,\n ):\n model.train()\n criterion.train()\n\n data_bar = tqdm(data_loader, desc=f\"Train Epoch {epoch}\")\n for samples, targets, infos in data_bar:\n targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\n batch_outputs = self.get_outputs(tokenizer, model, samples, device)\n\n loss_dict = criterion(batch_outputs, targets)\n\n weight_dict = criterion.weight_dict\n losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) # type: ignore\n\n loss_dict_unscaled = {f\"{k}_unscaled\": v for k, v in loss_dict.items()}\n loss_dict_scaled = {\n k: v * weight_dict[k] for k, v in loss_dict.items() if k in weight_dict\n }\n losses_scaled = sum(loss_dict_scaled.values()) # type: ignore\n\n loss_value = losses_scaled.item() # type: ignore\n\n postprocessor.add_outputs(batch_outputs, infos)\n\n if not math.isfinite(loss_value):\n print(\"Loss is {}, stopping training\".format(loss_value))\n print(loss_dict)\n sys.exit(1)\n\n optimizer.zero_grad()\n losses.backward() # type: ignore\n if max_norm > 0:\n torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) # type: ignore\n optimizer.step()\n\n self.loss_window.append(losses.item()) # type: ignore\n data_bar.set_postfix(\n {\n \"loss\": f\"{sum(self.loss_window) / len(self.loss_window):.3f}\",\n **{k: f\"{v.item():.3f}\" for k, v in loss_dict_scaled.items()},\n \"lr\": \", \".join(f\"{g['lr']:.1e}\" for g in optimizer.param_groups),\n }\n )\n self.global_step += 1\n if self.writer:\n scalars = {\n \"lr\": optimizer.param_groups[0][\"lr\"],\n \"loss\": losses.item(), # type: ignore\n **loss_dict_scaled,\n **loss_dict_unscaled,\n }\n for key, value in scalars.items():\n self.writer.add_scalars(key, {\"Train\": value}, self.global_step)\n \n report = postprocessor.evaluate()\n if self.writer:\n self.writer.add_scalars(\"accuracy\", {\"Train\": report[\"f1\"][\"macro_avg\"]}, self.global_step)\n \n return report\n\n\n @torch.no_grad()\n def evaluate(\n self,\n tokenizer: PrepareInputs,\n model: DETR,\n criterion: CriterionDETR,\n postprocessor: FBPPostProcess,\n data_loader: DataLoader,\n epoch: int,\n device: torch.device,\n ):\n model.eval()\n criterion.eval()\n\n loss_list = []\n data_bar = tqdm(data_loader, desc=f\"Valid Epoch {epoch}\")\n for samples, targets, infos in data_bar:\n targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\n batch_outputs = self.get_outputs(tokenizer, model, samples, device)\n\n loss_dict = criterion(batch_outputs, targets)\n weight_dict = criterion.weight_dict\n\n loss_dict_scaled = {\n k: v * weight_dict[k] for k, v in loss_dict.items() if k in weight_dict\n }\n losses_scaled = sum(loss_dict_scaled.values())\n\n postprocessor.add_outputs(batch_outputs, infos)\n\n loss_value = losses_scaled.item() # type: ignore\n loss_list.append(loss_value)\n\n data_bar.set_postfix(\n {\n \"loss\": f\"{sum(loss_list) / len(loss_list):.3f}\",\n **{k: f\"{v.item():.3f}\" for k, v in loss_dict_scaled.items()},\n }\n )\n\n loss = sum(loss_list) / len(loss_list)\n report = postprocessor.evaluate()\n scalars = {\"loss\": loss, \"accuracy\": report[\"f1\"][\"macro_avg\"]}\n\n if self.writer:\n for key, value in scalars.items():\n self.writer.add_scalars(key, {\"Validation\": value}, self.global_step)\n\n return report\n\n def set_outputs(self, args_output_dir) -> Path:\n output_dir = Path(\".\")\n if args_output_dir:\n timestamp = datetime.now().strftime(\"%Y_%m_%d-%I_%M\")\n output_dir = Path(args_output_dir).joinpath(timestamp)\n self.writer = SummaryWriter(output_dir.joinpath(\"logs\"))\n print(\"Saving outputs at:\", output_dir)\n return output_dir\n"
] | [
[
"torch.no_grad",
"torch.cat",
"torch.ones",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
josancamon19/facial_keypoint_detection | [
"c0ae09a54c5f4e1ab4f3e4aa669523fbeb53a045"
] | [
"models.py"
] | [
"## TODO: define the convolutional neural network architecture\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\n# can use the below import should you choose to initialize the weights of your Net\nimport torch.nn.init as I\n\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n \n ## TODO: Define all the layers of this CNN, the only requirements are:\n ## 1. This network takes in a square (same width and height), grayscale image as input\n ## 2. It ends with a linear layer that represents the keypoints\n ## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs\n \n # As an example, you've been given a convolutional layer, which you may (but don't have to) change:\n # 1 input image channel (grayscale), 32 output channels/feature maps, 5x5 square convolution kernel\n self.conv1 = nn.Conv2d(1, 32, 4)\n self.conv2 = nn.Conv2d(32, 64, 3)\n self.conv3 = nn.Conv2d(64, 128, 2)\n self.conv4 = nn.Conv2d(128, 256, 1)\n \n self.pool = nn.MaxPool2d(2,2)\n \n self.fc1 = nn.Linear(256*13*13,1000)\n self.fc2 = nn.Linear(1000,1000)\n self.fc3 = nn.Linear(1000,136)\n ## Note that among the layers to add, consider including:\n # maxpooling layers, multiple conv layers, fully-connected layers, and other layers (such as dropout or batch normalization) to avoid overfitting\n \n\n \n def forward(self, x):\n ## TODO: Define the feedforward behavior of this model\n ## x is the input image and, as an example, here you may choose to include a pool/conv step:\n x = self.pool(F.elu(self.conv1(x)))\n x = F.dropout(x, p = 0.6)\n x = self.pool(F.elu(self.conv2(x)))\n x = F.dropout(x, p = 0.5)\n x = self.pool(F.elu(self.conv3(x)))\n x = F.dropout(x, p = 0.4)\n x = self.pool(F.elu(self.conv4(x)))\n x = F.dropout(x, p = 0.3)\n \n x = x.view(x.size(0),-1)\n \n x = F.dropout(F.elu(self.fc1(x)),p = 0.2)\n x = F.dropout(F.relu(self.fc2(x)),p = 0.1) \n x = self.fc3(x)\n # a modified x, having gone through all the layers of your model, should be returned\n return x\n"
] | [
[
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.Conv2d",
"torch.nn.functional.dropout"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jellis18/courses | [
"8fa995169e20ef89a4cf30a585ed28564616ded5"
] | [
"deeplearning1/nbs/utils.py"
] | [
"from __future__ import division,print_function\nimport math, os, json, sys, re\ntry:\n import cPickle as pickle\nexcept ModuleNotFoundError:\n import pickle\nfrom glob import glob\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom operator import itemgetter, attrgetter, methodcaller\nfrom collections import OrderedDict\nimport itertools\nfrom itertools import chain\n\nimport pandas as pd\nimport PIL\nfrom PIL import Image\nfrom numpy.random import random, permutation, randn, normal, uniform, choice\nfrom numpy import newaxis\nimport scipy\nfrom scipy import misc, ndimage\nfrom scipy.ndimage.interpolation import zoom\nfrom scipy.ndimage import imread\nfrom sklearn.metrics import confusion_matrix\nimport bcolz\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.manifold import TSNE\n\nfrom IPython.lib.display import FileLink\n\nimport theano\nfrom theano import shared, tensor as T\nfrom theano.tensor.nnet import conv2d, nnet\nfrom theano.tensor.signal import pool\n\nimport keras\nfrom keras import backend as K\nfrom keras.utils.data_utils import get_file\nfrom keras.utils import np_utils\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Embedding, Reshape, merge, LSTM, Bidirectional\nfrom keras.layers import TimeDistributed, Activation, SimpleRNN, GRU\nfrom keras.layers.core import Flatten, Dense, Dropout, Lambda\nfrom keras.regularizers import l2, l1\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import SGD, RMSprop, Adam\nfrom keras.layers import deserialize as layer_from_config\nfrom keras.metrics import categorical_crossentropy, categorical_accuracy\nfrom keras.layers.convolutional import *\nfrom keras.preprocessing import image, sequence\nfrom keras.preprocessing.text import Tokenizer\n\nfrom vgg16 import *\nfrom vgg16bn import *\nnp.set_printoptions(precision=4, linewidth=100)\n\n\nto_bw = np.array([0.299, 0.587, 0.114])\n\ndef gray(img):\n if K.image_dim_ordering() == 'tf':\n return np.rollaxis(img, 0, 1).dot(to_bw)\n else:\n return np.rollaxis(img, 0, 3).dot(to_bw)\n\ndef to_plot(img):\n if K.image_dim_ordering() == 'tf':\n return np.rollaxis(img, 0, 1).astype(np.uint8)\n else:\n return np.rollaxis(img, 0, 3).astype(np.uint8)\n\ndef plot(img):\n plt.imshow(to_plot(img))\n\n\ndef floor(x):\n return int(math.floor(x))\ndef ceil(x):\n return int(math.ceil(x))\n\ndef plots(ims, figsize=(12,6), rows=1, interp=False, titles=None):\n if type(ims[0]) is np.ndarray:\n ims = np.array(ims).astype(np.uint8)\n if (ims.shape[-1] != 3):\n ims = ims.transpose((0,2,3,1))\n f = plt.figure(figsize=figsize)\n cols = len(ims)//rows if len(ims) % 2 == 0 else len(ims)//rows + 1\n for i in range(len(ims)):\n sp = f.add_subplot(rows, cols, i+1)\n sp.axis('Off')\n if titles is not None:\n sp.set_title(titles[i], fontsize=16)\n plt.imshow(ims[i], interpolation=None if interp else 'none')\n\n\ndef do_clip(arr, mx):\n clipped = np.clip(arr, (1-mx)/1, mx)\n return clipped/clipped.sum(axis=1)[:, np.newaxis]\n\n\ndef get_batches(dirname, gen=image.ImageDataGenerator(), shuffle=True, batch_size=4, class_mode='categorical',\n target_size=(224,224)):\n return gen.flow_from_directory(dirname, target_size=target_size,\n class_mode=class_mode, shuffle=shuffle, batch_size=batch_size)\n\n\ndef onehot(x):\n return to_categorical(x)\n\n\ndef wrap_config(layer):\n return {'class_name': layer.__class__.__name__, 'config': layer.get_config()}\n\n\ndef copy_layer(layer): return layer_from_config(wrap_config(layer))\n\n\ndef copy_layers(layers): return [copy_layer(layer) for layer in layers]\n\n\ndef copy_weights(from_layers, to_layers):\n for from_layer,to_layer in zip(from_layers, to_layers):\n to_layer.set_weights(from_layer.get_weights())\n\n\ndef copy_model(m):\n res = Sequential(copy_layers(m.layers))\n copy_weights(m.layers, res.layers)\n return res\n\n\ndef insert_layer(model, new_layer, index):\n res = Sequential()\n for i,layer in enumerate(model.layers):\n if i==index: res.add(new_layer)\n copied = layer_from_config(wrap_config(layer))\n res.add(copied)\n copied.set_weights(layer.get_weights())\n return res\n\n\ndef adjust_dropout(weights, prev_p, new_p):\n scal = (1-prev_p)/(1-new_p)\n return [o*scal for o in weights]\n\n\ndef get_data(path, target_size=(224,224)):\n batches = get_batches(path, shuffle=False, batch_size=1, class_mode=None, target_size=target_size)\n return np.concatenate([batches.next() for i in range(batches.nb_sample)])\n\n\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n (This function is copied from the scikit docs.)\n \"\"\"\n plt.figure()\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(cm)\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j], horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef save_array(fname, arr):\n c=bcolz.carray(arr, rootdir=fname, mode='w')\n c.flush()\n\n\ndef load_array(fname):\n return bcolz.open(fname)[:]\n\n\ndef mk_size(img, r2c):\n r,c,_ = img.shape\n curr_r2c = r/c\n new_r, new_c = r,c\n if r2c>curr_r2c:\n new_r = floor(c*r2c)\n else:\n new_c = floor(r/r2c)\n arr = np.zeros((new_r, new_c, 3), dtype=np.float32)\n r2=(new_r-r)//2\n c2=(new_c-c)//2\n arr[floor(r2):floor(r2)+r,floor(c2):floor(c2)+c] = img\n return arr\n\n\ndef mk_square(img):\n x,y,_ = img.shape\n maxs = max(img.shape[:2])\n y2=(maxs-y)//2\n x2=(maxs-x)//2\n arr = np.zeros((maxs,maxs,3), dtype=np.float32)\n arr[floor(x2):floor(x2)+x,floor(y2):floor(y2)+y] = img\n return arr\n\n\ndef vgg_ft(out_dim):\n vgg = Vgg16()\n vgg.ft(out_dim)\n model = vgg.model\n return model\n\ndef vgg_ft_bn(out_dim):\n vgg = Vgg16BN()\n vgg.ft(out_dim)\n model = vgg.model\n return model\n\n\ndef get_classes(path):\n batches = get_batches(path+'train', shuffle=False, batch_size=1)\n val_batches = get_batches(path+'valid', shuffle=False, batch_size=1)\n test_batches = get_batches(path+'test', shuffle=False, batch_size=1)\n return (val_batches.classes, batches.classes, onehot(val_batches.classes), onehot(batches.classes),\n val_batches.filenames, batches.filenames, test_batches.filenames)\n\n\ndef split_at(model, layer_type):\n layers = model.layers\n layer_idx = [index for index,layer in enumerate(layers)\n if type(layer) is layer_type][-1]\n return layers[:layer_idx+1], layers[layer_idx+1:]\n\n\nclass MixIterator(object):\n def __init__(self, iters):\n self.iters = iters\n self.multi = type(iters) is list\n if self.multi:\n self.N = sum([it[0].N for it in self.iters])\n else:\n self.N = sum([it.N for it in self.iters])\n\n def reset(self):\n for it in self.iters: it.reset()\n\n def __iter__(self):\n return self\n\n def next(self, *args, **kwargs):\n if self.multi:\n nexts = [[next(it) for it in o] for o in self.iters]\n n0 = np.concatenate([n[0] for n in nexts])\n n1 = np.concatenate([n[1] for n in nexts])\n return (n0, n1)\n else:\n nexts = [next(it) for it in self.iters]\n n0 = np.concatenate([n[0] for n in nexts])\n n1 = np.concatenate([n[1] for n in nexts])\n return (n0, n1)\n"
] | [
[
"matplotlib.pyplot.text",
"numpy.rollaxis",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"numpy.clip",
"numpy.set_printoptions",
"numpy.concatenate",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
freedomkite/easytext | [
"ef83261a366bd8d7c259aa112da14f3fa7cdf918"
] | [
"event/event_detection_without_tirgger/tests/test_metric.py"
] | [
"#!/usr/bin/env python 3\n# -*- coding: utf-8 -*-\n\n#\n# Copyright (c) 2020 PanXu, Inc. All Rights Reserved\n#\n\"\"\"\n测试 metric\n\nAuthors: panxu([email protected])\nDate: 2020/06/17 09:35:00\n\"\"\"\nimport logging\nimport pytest\n\nimport torch\n\nfrom easytext.tests import ASSERT\nfrom easytext.data import Vocabulary\nfrom easytext.utils.json_util import json2str\nfrom easytext.utils import log_util\nfrom easytext.metrics import F1Metric\n\nfrom event.event_detection_without_tirgger.models import EventModelOutputs\nfrom event.event_detection_without_tirgger.metrics import EventF1MetricAdapter\n\nlog_util.config()\n\n\[email protected](scope=\"class\")\ndef event_type_vocabulary():\n event_types = [[\"A\", \"B\", \"C\"], [\"A\", \"B\"], [\"A\"]]\n\n vocabulary = Vocabulary(tokens=event_types, padding=\"\", unk=\"Negative\", special_first=True)\n\n ASSERT.assertEqual(4, vocabulary.size)\n ASSERT.assertEqual(0, vocabulary.index(vocabulary.unk))\n ASSERT.assertEqual(1, vocabulary.index(\"A\"))\n ASSERT.assertEqual(2, vocabulary.index(\"B\"))\n ASSERT.assertEqual(3, vocabulary.index(\"C\"))\n\n return vocabulary\n\n\ndef test_event_f1_metric(event_type_vocabulary):\n \"\"\"\n 测试 event f1 metric\n \"\"\"\n f1_metric = EventF1MetricAdapter(event_type_vocabulary=event_type_vocabulary)\n\n # label: [1, 0, 1, 1, 0, 0, 1, 1, 0]\n logits = torch.tensor([0.6, 0.2, 0.7, 0.8, 0.1, 0.2, 0.8, 0.9, 0.3], dtype=torch.float)\n\n # [1, 0, 1, 1, 0, 0, 1, 1, 0]\n golden_labels = torch.tensor([1, 0, 0, 1, 1, 0, 0, 1, 1], dtype=torch.long)\n\n event_type = torch.tensor([event_type_vocabulary.index(\"A\"),\n event_type_vocabulary.index(\"A\"),\n event_type_vocabulary.index(\"A\"),\n event_type_vocabulary.index(\"B\"),\n event_type_vocabulary.index(\"B\"),\n event_type_vocabulary.index(\"C\"),\n event_type_vocabulary.index(\"C\"),\n event_type_vocabulary.index(event_type_vocabulary.unk),\n event_type_vocabulary.index(event_type_vocabulary.unk)],\n dtype=torch.long)\n\n model_outputs = EventModelOutputs(logits=logits,\n event_type=event_type)\n\n metric, target_metric = f1_metric(model_outputs=model_outputs, golden_labels=golden_labels)\n\n expect_precision_A_1 = 1 / 2\n expect_recall_A_1 = 1 / 1\n expect_f1_A_1 = 2 * expect_precision_A_1 * expect_recall_A_1 / (expect_precision_A_1 + expect_recall_A_1)\n\n ASSERT.assertAlmostEqual(expect_precision_A_1, metric[f\"{F1Metric.PRECISION}-A\"])\n ASSERT.assertAlmostEqual(expect_recall_A_1, metric[f\"{F1Metric.RECALL}-A\"])\n ASSERT.assertAlmostEqual(expect_f1_A_1, metric[f\"{F1Metric.F1}-A\"])\n\n expect_precision_overall = 2 / 4\n expect_recall_overall = 2 / 3\n\n expect_f1_overall = 2 * expect_precision_overall * expect_recall_overall / (expect_precision_overall +\n expect_recall_overall)\n\n ASSERT.assertAlmostEqual(expect_precision_overall, metric[F1Metric.PRECISION_OVERALL])\n ASSERT.assertAlmostEqual(expect_recall_overall, metric[F1Metric.RECALL_OVERALL])\n ASSERT.assertAlmostEqual(expect_f1_overall, metric[F1Metric.F1_OVERALL])\n\n # 在增加一个数据,因为实际是多个batch的\n # label: [1, 1, 0]\n logits = torch.tensor([0.6, 0.8, 0.2], dtype=torch.float)\n golden_labels = torch.tensor([1, 1, 1], dtype=torch.long)\n\n event_type = torch.tensor([event_type_vocabulary.index(\"A\"),\n event_type_vocabulary.index(\"A\"),\n event_type_vocabulary.index(\"A\")],\n dtype=torch.long)\n\n model_outputs = EventModelOutputs(logits=logits,\n event_type=event_type)\n\n metric, target_metric = f1_metric(model_outputs=model_outputs, golden_labels=golden_labels)\n\n expect_final_precision_A_1 = (1 + 2) / (2 + 2)\n expect_final_recall_A_1 = (1 + 2) / (1 + 3)\n expect_final_f1_A_1 = 2 * expect_final_precision_A_1 * expect_final_recall_A_1 / (expect_final_precision_A_1\n + expect_final_recall_A_1)\n\n ASSERT.assertAlmostEqual(expect_final_precision_A_1, f1_metric.metric[0][f\"{F1Metric.PRECISION}-A\"])\n ASSERT.assertAlmostEqual(expect_final_recall_A_1, f1_metric.metric[0][f\"{F1Metric.RECALL}-A\"])\n ASSERT.assertAlmostEqual(expect_final_f1_A_1, f1_metric.metric[0][f\"{F1Metric.F1}-A\"])\n\n expect_final_precision_overall = (2 + 2) / (4 + 2)\n expect_final_recall_overall = (2 + 2) / (3 + 3)\n expect_final_f1_overall = 2 * expect_final_precision_overall * expect_final_recall_overall / (\n expect_final_precision_overall + expect_final_recall_overall\n )\n ASSERT.assertAlmostEqual(expect_final_precision_overall, f1_metric.metric[0][F1Metric.PRECISION_OVERALL])\n ASSERT.assertAlmostEqual(expect_final_recall_overall, f1_metric.metric[0][F1Metric.RECALL_OVERALL])\n ASSERT.assertAlmostEqual(expect_final_f1_overall, f1_metric.metric[0][F1Metric.F1_OVERALL])\n\n ASSERT.assertEqual(F1Metric.F1_OVERALL, f1_metric.metric[1].name)\n ASSERT.assertAlmostEqual(f1_metric.metric[1].value, expect_final_f1_overall)\n\n\n\n"
] | [
[
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
eejbyfeldt/spark | [
"5edbbd1711402735623fa1fc9b86ff41c28996e9"
] | [
"python/pyspark/pandas/data_type_ops/num_ops.py"
] | [
"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# 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, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport numbers\nfrom typing import cast, Any, Union\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.api.types import CategoricalDtype\n\nfrom pyspark.pandas._typing import Dtype, IndexOpsLike, SeriesOrIndex\nfrom pyspark.pandas.base import column_op, IndexOpsMixin, numpy_column_op\nfrom pyspark.pandas.data_type_ops.base import (\n DataTypeOps,\n is_valid_operand_for_numeric_arithmetic,\n transform_boolean_operand_to_numeric,\n _as_bool_type,\n _as_categorical_type,\n _as_other_type,\n _as_string_type,\n)\nfrom pyspark.pandas.spark import functions as SF\nfrom pyspark.pandas.typedef.typehints import extension_dtypes, pandas_on_spark_type\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.column import Column\nfrom pyspark.sql.types import (\n BooleanType,\n StringType,\n)\n\n\nclass NumericOps(DataTypeOps):\n \"\"\"The class for binary operations of numeric pandas-on-Spark objects.\"\"\"\n\n @property\n def pretty_name(self) -> str:\n return \"numerics\"\n\n def add(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Addition can not be applied to given types.\")\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return column_op(Column.__add__)(left, right)\n\n def sub(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Subtraction can not be applied to given types.\")\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return column_op(Column.__sub__)(left, right)\n\n def mod(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Modulo can not be applied to given types.\")\n\n def mod(left: Column, right: Any) -> Column:\n return ((left % right) + right) % right\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return column_op(mod)(left, right)\n\n def pow(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Exponentiation can not be applied to given types.\")\n\n def pow_func(left: Column, right: Any) -> Column:\n return F.when(left == 1, left).otherwise(Column.__pow__(left, right))\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return column_op(pow_func)(left, right)\n\n def radd(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"Addition can not be applied to given types.\")\n right = transform_boolean_operand_to_numeric(right)\n return column_op(Column.__radd__)(left, right)\n\n def rsub(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"Subtraction can not be applied to given types.\")\n right = transform_boolean_operand_to_numeric(right)\n return column_op(Column.__rsub__)(left, right)\n\n def rmul(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"Multiplication can not be applied to given types.\")\n right = transform_boolean_operand_to_numeric(right)\n return column_op(Column.__rmul__)(left, right)\n\n def rpow(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"Exponentiation can not be applied to given types.\")\n\n def rpow_func(left: Column, right: Any) -> Column:\n return F.when(SF.lit(right == 1), right).otherwise(Column.__rpow__(left, right))\n\n right = transform_boolean_operand_to_numeric(right)\n return column_op(rpow_func)(left, right)\n\n def rmod(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"Modulo can not be applied to given types.\")\n\n def rmod(left: Column, right: Any) -> Column:\n return ((right % left) + left) % left\n\n right = transform_boolean_operand_to_numeric(right)\n return column_op(rmod)(left, right)\n\n def invert(self, operand: IndexOpsLike) -> IndexOpsLike:\n return cast(IndexOpsLike, column_op(F.bitwise_not)(operand))\n\n def neg(self, operand: IndexOpsLike) -> IndexOpsLike:\n return cast(IndexOpsLike, column_op(Column.__neg__)(operand))\n\n def abs(self, operand: IndexOpsLike) -> IndexOpsLike:\n return cast(IndexOpsLike, column_op(F.abs)(operand))\n\n def lt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n return column_op(Column.__lt__)(left, right)\n\n def le(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n return column_op(Column.__le__)(left, right)\n\n def ge(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n return column_op(Column.__ge__)(left, right)\n\n def gt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n return column_op(Column.__gt__)(left, right)\n\n\nclass IntegralOps(NumericOps):\n \"\"\"\n The class for binary operations of pandas-on-Spark objects with spark types:\n LongType, IntegerType, ByteType and ShortType.\n \"\"\"\n\n @property\n def pretty_name(self) -> str:\n return \"integrals\"\n\n def mul(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if isinstance(right, IndexOpsMixin) and isinstance(right.spark.data_type, StringType):\n return column_op(SF.repeat)(right, left)\n\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Multiplication can not be applied to given types.\")\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return column_op(Column.__mul__)(left, right)\n\n def truediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"True division can not be applied to given types.\")\n\n def truediv(left: Column, right: Any) -> Column:\n return F.when(\n SF.lit(right != 0) | SF.lit(right).isNull(), left.__div__(right)\n ).otherwise(SF.lit(np.inf).__div__(left))\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(truediv)(left, right)\n\n def floordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Floor division can not be applied to given types.\")\n\n def floordiv(left: Column, right: Any) -> Column:\n return F.when(SF.lit(right is np.nan), np.nan).otherwise(\n F.when(\n SF.lit(right != 0) | SF.lit(right).isNull(), F.floor(left.__div__(right))\n ).otherwise(SF.lit(np.inf).__div__(left))\n )\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(floordiv)(left, right)\n\n def rtruediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"True division can not be applied to given types.\")\n\n def rtruediv(left: Column, right: Any) -> Column:\n return F.when(left == 0, SF.lit(np.inf).__div__(right)).otherwise(\n SF.lit(right).__truediv__(left)\n )\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(rtruediv)(left, right)\n\n def rfloordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"Floor division can not be applied to given types.\")\n\n def rfloordiv(left: Column, right: Any) -> Column:\n return F.when(SF.lit(left == 0), SF.lit(np.inf).__div__(right)).otherwise(\n F.floor(SF.lit(right).__div__(left))\n )\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(rfloordiv)(left, right)\n\n def astype(self, index_ops: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike:\n dtype, spark_type = pandas_on_spark_type(dtype)\n\n if isinstance(dtype, CategoricalDtype):\n return _as_categorical_type(index_ops, dtype, spark_type)\n elif isinstance(spark_type, BooleanType):\n return _as_bool_type(index_ops, dtype)\n elif isinstance(spark_type, StringType):\n return _as_string_type(index_ops, dtype, null_str=str(np.nan))\n else:\n return _as_other_type(index_ops, dtype, spark_type)\n\n\nclass FractionalOps(NumericOps):\n \"\"\"\n The class for binary operations of pandas-on-Spark objects with spark types:\n FloatType, DoubleType.\n \"\"\"\n\n @property\n def pretty_name(self) -> str:\n return \"fractions\"\n\n def mul(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Multiplication can not be applied to given types.\")\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return column_op(Column.__mul__)(left, right)\n\n def truediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"True division can not be applied to given types.\")\n\n def truediv(left: Column, right: Any) -> Column:\n return F.when(\n SF.lit(right != 0) | SF.lit(right).isNull(), left.__div__(right)\n ).otherwise(\n F.when(SF.lit(left == np.inf) | SF.lit(left == -np.inf), left).otherwise(\n SF.lit(np.inf).__div__(left)\n )\n )\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(truediv)(left, right)\n\n def floordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not is_valid_operand_for_numeric_arithmetic(right):\n raise TypeError(\"Floor division can not be applied to given types.\")\n\n def floordiv(left: Column, right: Any) -> Column:\n return F.when(SF.lit(right is np.nan), np.nan).otherwise(\n F.when(\n SF.lit(right != 0) | SF.lit(right).isNull(), F.floor(left.__div__(right))\n ).otherwise(\n F.when(SF.lit(left == np.inf) | SF.lit(left == -np.inf), left).otherwise(\n SF.lit(np.inf).__div__(left)\n )\n )\n )\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(floordiv)(left, right)\n\n def rtruediv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"True division can not be applied to given types.\")\n\n def rtruediv(left: Column, right: Any) -> Column:\n return F.when(left == 0, SF.lit(np.inf).__div__(right)).otherwise(\n SF.lit(right).__truediv__(left)\n )\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(rtruediv)(left, right)\n\n def rfloordiv(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n if not isinstance(right, numbers.Number):\n raise TypeError(\"Floor division can not be applied to given types.\")\n\n def rfloordiv(left: Column, right: Any) -> Column:\n return F.when(SF.lit(left == 0), SF.lit(np.inf).__div__(right)).otherwise(\n F.when(SF.lit(left) == np.nan, np.nan).otherwise(\n F.floor(SF.lit(right).__div__(left))\n )\n )\n\n right = transform_boolean_operand_to_numeric(right, spark_type=left.spark.data_type)\n return numpy_column_op(rfloordiv)(left, right)\n\n def invert(self, operand: IndexOpsLike) -> IndexOpsLike:\n raise TypeError(\"Unary ~ can not be applied to %s.\" % self.pretty_name)\n\n def isnull(self, index_ops: IndexOpsLike) -> IndexOpsLike:\n return index_ops._with_new_scol(\n index_ops.spark.column.isNull() | F.isnan(index_ops.spark.column),\n field=index_ops._internal.data_fields[0].copy(\n dtype=np.dtype(\"bool\"), spark_type=BooleanType(), nullable=False\n ),\n )\n\n def astype(self, index_ops: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike:\n dtype, spark_type = pandas_on_spark_type(dtype)\n\n if isinstance(dtype, CategoricalDtype):\n return _as_categorical_type(index_ops, dtype, spark_type)\n elif isinstance(spark_type, BooleanType):\n if isinstance(dtype, extension_dtypes):\n scol = index_ops.spark.column.cast(spark_type)\n else:\n scol = F.when(\n index_ops.spark.column.isNull() | F.isnan(index_ops.spark.column),\n SF.lit(True),\n ).otherwise(index_ops.spark.column.cast(spark_type))\n return index_ops._with_new_scol(\n scol.alias(index_ops._internal.data_spark_column_names[0]),\n field=index_ops._internal.data_fields[0].copy(dtype=dtype, spark_type=spark_type),\n )\n elif isinstance(spark_type, StringType):\n return _as_string_type(index_ops, dtype, null_str=str(np.nan))\n else:\n return _as_other_type(index_ops, dtype, spark_type)\n\n\nclass DecimalOps(FractionalOps):\n \"\"\"\n The class for decimal operations of pandas-on-Spark objects with spark type:\n DecimalType.\n \"\"\"\n\n @property\n def pretty_name(self) -> str:\n return \"decimal\"\n\n def invert(self, operand: IndexOpsLike) -> IndexOpsLike:\n raise TypeError(\"Unary ~ can not be applied to %s.\" % self.pretty_name)\n\n def lt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n raise TypeError(\"< can not be applied to %s.\" % self.pretty_name)\n\n def le(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n raise TypeError(\"<= can not be applied to %s.\" % self.pretty_name)\n\n def ge(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n raise TypeError(\"> can not be applied to %s.\" % self.pretty_name)\n\n def gt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex:\n raise TypeError(\">= can not be applied to %s.\" % self.pretty_name)\n\n def isnull(self, index_ops: IndexOpsLike) -> IndexOpsLike:\n return index_ops._with_new_scol(\n index_ops.spark.column.isNull(),\n field=index_ops._internal.data_fields[0].copy(\n dtype=np.dtype(\"bool\"), spark_type=BooleanType(), nullable=False\n ),\n )\n\n def astype(self, index_ops: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike:\n dtype, spark_type = pandas_on_spark_type(dtype)\n\n if isinstance(dtype, CategoricalDtype):\n return _as_categorical_type(index_ops, dtype, spark_type)\n elif isinstance(spark_type, BooleanType):\n return _as_bool_type(index_ops, dtype)\n elif isinstance(spark_type, StringType):\n return _as_string_type(index_ops, dtype, null_str=str(np.nan))\n else:\n return _as_other_type(index_ops, dtype, spark_type)\n\n\nclass IntegralExtensionOps(IntegralOps):\n \"\"\"\n The class for binary operations of pandas-on-Spark objects with one of the\n - spark types:\n LongType, IntegerType, ByteType and ShortType\n - dtypes:\n Int8Dtype, Int16Dtype, Int32Dtype, Int64Dtype\n \"\"\"\n\n def restore(self, col: pd.Series) -> pd.Series:\n \"\"\"Restore column when to_pandas.\"\"\"\n return col.astype(self.dtype)\n\n\nclass FractionalExtensionOps(FractionalOps):\n \"\"\"\n The class for binary operations of pandas-on-Spark objects with one of the\n - spark types:\n FloatType, DoubleType and DecimalType\n - dtypes:\n Float32Dtype, Float64Dtype\n \"\"\"\n\n def restore(self, col: pd.Series) -> pd.Series:\n \"\"\"Restore column when to_pandas.\"\"\"\n return col.astype(self.dtype)\n"
] | [
[
"numpy.dtype"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RickyDoge/WFGN | [
"88c70ad623f370fa76eb0b75a452c8f2c527ca6e"
] | [
"autoencoder/decoder.py"
] | [
"import torch\nfrom torch import nn\n\n\nclass AEDecoder(nn.Module):\n def __init__(self, encoder):\n super(AEDecoder, self).__init__()\n self.decoder = nn.ModuleList()\n for module in reversed(encoder.encoder):\n if isinstance(module, nn.Conv2d):\n self.decoder.append(nn.ConvTranspose2d(\n in_channels=module.out_channels,\n out_channels=module.in_channels,\n kernel_size=module.kernel_size,\n stride=module.stride,\n padding=module.padding,\n ))\n self.decoder.append(nn.BatchNorm2d(module.in_channels))\n self.decoder.append(nn.ReLU(inplace=True))\n elif isinstance(module, nn.MaxPool2d):\n self.decoder.append(nn.MaxUnpool2d(\n kernel_size=module.kernel_size,\n stride=module.stride,\n padding=module.padding,\n ))\n\n def forward(self, x, pool_indices):\n pool_indices, ptr = list(reversed(pool_indices)), 0\n for module in self.decoder:\n if isinstance(module, nn.MaxUnpool2d):\n x = module(x, indices=pool_indices[ptr])\n ptr += 1\n else:\n x = module(x)\n return x\n"
] | [
[
"torch.nn.ConvTranspose2d",
"torch.nn.MaxUnpool2d",
"torch.nn.ModuleList",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AJueling/melt | [
"3b55d7b021f67f56d5c7503ccc5a1670acc45591"
] | [
"src/advect.py"
] | [
"import numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom tqdm.autonotebook import tqdm\n\n\nzgl = r'$z_{gl}(x,y)'\n\ndef advect_grl(ds, eps, T, verbose=True, plots=True):\n \"\"\" function to advect grounding line depth as described in Pelle at al (2019) \n using centered finite different in space and RK4 in time with backward derivatives\n (https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods)\n \n input:\n ds .. [xr.DataSet] containing\n x/y .. grid coordinates of size nx/ny [m]\n grl2 .. binary mask identifying grounding line including islands\n draft .. includes grl depth at grl mask [m]\n u/v .. x/y velocities [m/yr]\n T .. [int] number of years to run\n eps .. [float] diffusion constant epsilon scaled with dx**2,\n decent values around 1/25\n \n output:\n evo .. [xr.DataArray] (ny,nx,nt) evolution of grounding line depths $z_{gl}$ in [m]\n \"\"\"\n dx = (ds.x[1]-ds.x[0]).values\n dy = (ds.y[1]-ds.y[0]).values\n if dx<0:\n if verbose: print('inverting x-coordinates')\n ds = ds.reindex(x=list(reversed(ds.x)))\n dx = -dx\n if dy<0:\n if verbose: print('inverting y-coordinates')\n ds = ds.reindex(y=list(reversed(ds.y)))\n dy = -dy\n eps *= dx**2\n maxvel = max([-ds.u.min().values, ds.u.max().values,\n -ds.v.min().values, ds.v.max().values])\n draftmin = ds.draft.min().values\n draftmax = ds.draft.max().values\n if maxvel==0: dt = .1 # for test cases with diffusion only\n else: dt = dx/maxvel/2 # time step in [years]\n Nt = int(T/dt)+1\n if verbose:\n print(f'dx = {dx} m; dy = {dy} m; maxvel = {maxvel} m/yr')\n print(f'min(draft) = {draftmin:.2f} m; max(draft) = {draftmax:.2f} m')\n print(f'dt = {dt} yr; Nt = {Nt}; T = {T} yr')\n \n ds = ds.pad(x=1, mode='edge')\n ds = ds.pad(y=1, mode='edge')\n evo = xr.DataArray(data=np.zeros((len(ds.y), len(ds.x), Nt)),\n dims=['y','x','time'],\n coords={'y':ds.y, 'x':ds.x, 'time':np.arange(0,dt*Nt-1e-10,dt)}\n )\n # domain mask of points inside ice shelf, but outside of grl\n mask_ = ds.mask.where(ds.grl2==0)\n ds['u'] = xr.where(ds.mask, ds.u, 0)\n ds['v'] = xr.where(ds.mask, ds.v, 0)\n \n # initial conditions\n # in ice shelf set depth to minimum draft depth\n evo[:,:,0] = xr.where(ds.mask==3, draftmin, 0)\n # at grl set depth to draft\n evo[:,:,0] = xr.where(ds.grl2==1, ds.draft, evo[:,:,0]) \n \n def reset_pads(z):\n \"\"\" resets padding values\n so that 1st&2nd order derivatives = 0 on boundary\n input:\n z .. 2D xr.DataArray\n \"\"\"\n z[ 0, :] = z.isel(y= 1)\n z[-1, :] = z.isel(y=-2)\n z[ :, 0] = z.isel(x= 1)\n z[ :,-1] = z.isel(x=-2)\n return z\n\n def rhs(z, eps):\n \"\"\" evaluates right hand side function\n with space centered, 2nd order accurate method\n \"\"\"\n ip1 = z.roll(x=-1, roll_coords=False)\n im1 = z.roll(x= 1, roll_coords=False)\n jp1 = z.roll(y=-1, roll_coords=False)\n jm1 = z.roll(y= 1, roll_coords=False)\n adv = ds.u*(ip1-im1)/2/dx + ds.v*(jp1-jm1)/2/dy\n dif = (ip1-2*z+im1)/dx**2 + (jp1-2*z+jm1)/dy**2\n return -adv+eps*dif\n\n for t in tqdm(range(1,Nt)): # explicit time evolution\n evo_ = evo.isel(time=t-1).copy()\n k1 = rhs(evo_ , eps)\n k2 = rhs(evo_+dt*k1/2, eps)\n k3 = rhs(evo_+dt*k2/2, eps)\n k4 = rhs(evo_+dt*k3 , eps)\n evo[:,:,t] = evo_ + dt*(k1+2*(k2+k3)+k4)/6 \n \n # update boundary conditions\n evo[:,:,t] = xr.where(ds.draft<evo[:,:,t], ds.draft, evo[:,:,t]) # if draft deeper, replace evo with draft\n evo[:,:,t] = xr.where(ds.grl2==1 , ds.draft, evo[:,:,t]) # grl depth constant\n evo[:,:,t] = reset_pads(evo[:,:,t])\n evo[:,:,t] = xr.where(evo[:,:,t]<draftmin, draftmin, evo[:,:,t]) #\n evo[:,:,t] = xr.where(evo[:,:,t]>draftmax, draftmax, evo[:,:,t]) #\n evo = evo.where(ds.mask==3) # mask out everything outside ice shelf\n \n if plots:\n # convergence plot\n plt.figure(figsize=(6.4,4), constrained_layout=True)\n (np.sqrt((evo-evo.shift(time=-1))**2)/ds.mask.sum().values)\\\n .sum(dim=['x','y']).plot()\n plt.axhline(0, c='k', lw=.5)\n #plt.yscale('log')\n plt.ylabel(r'$\\frac{1}{N}\\Sigma\\sqrt{(z_t-z_{t-1})^2}$ [m]')\n plt.xlabel('time [yr]')\n plt.show()\n\n # final z_{gl} plot\n plt.figure(figsize=(6.4,4), constrained_layout=True)\n evo.isel(time=-1).plot(label=zgl)\n plt.title(f'final {zgl} at time={evo.time[-1].values} years')\n plt.show()\n return evo"
] | [
[
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aouyang1/covid-jhu | [
"6c03cc5813e2e8fe9aacf123e0e0fd321b0a0e55"
] | [
"study.py"
] | [
"import pandas as pd\nimport requests\nimport io\nimport os\n\nfrom sqlalchemy import create_engine\n\ndef init_sql_conn():\n user = \"root\"\n host = os.getenv('MYSQL_HOST')\n db = \"covid\"\n engine = create_engine(f'mysql://{user}@{host}/{db}')\n conn = engine.connect()\n return conn\n\nif __name__ == \"__main__\":\n start_date = \"3/1/20\"\n\n url = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series\"\n\n datasets = {\n \"deaths\": \"time_series_covid19_deaths_global.csv\",\n \"cases\": \"time_series_covid19_confirmed_global.csv\",\n }\n\n columns = [\"day\", \"region\"]\n df_all = pd.DataFrame(columns=columns)\n\n for dtype, fname in datasets.items():\n raw = requests.get(url+\"/\"+fname).content\n df = pd.read_csv(io.StringIO(raw.decode('utf-8')))\n df = df.drop([\"Province/State\",\"Lat\",\"Long\"], axis=1)\n df = df.groupby([\"Country/Region\"]).sum().T\n df.index = pd.to_datetime(df.index)\n df['day'] = df.index\n df.reset_index()\n df = df.loc[df.index >= start_date]\n df = pd.melt(df,\n id_vars='day',\n value_vars=df.columns.tolist()[:-1],\n var_name='region',\n value_name=dtype,\n )\n df.sort_values(by=[\"region\",\"day\"], inplace=True)\n df_grouped = df.groupby([\"region\"])\n df[\"daily_\"+dtype] = df_grouped[dtype].diff()\n df_all = pd.merge(df_all, df, how='outer', on=['day','region'])\n\n try:\n conn = init_sql_conn()\n df_all.to_sql(con=conn, name='covid_region', if_exists='replace', index=False)\n except ValueError as err:\n print(f'{err} for {dtype}')\n except Exception as err:\n print(f'Unknown exception {err} for {dtype}')\n"
] | [
[
"pandas.merge",
"pandas.to_datetime",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
matham/glitter2 | [
"ebede5a18edb1b2e34f1824e4262d01a148cf2f3"
] | [
"examples/add_data_to_data_file.py"
] | [
"\"\"\"Demo example file that shows how to add or duplicate data channels in a\nNixIO Glitter2 h5 file.\n\"\"\"\n\nimport nixio\nfrom glitter2.storage.data_file import DataFile\nfrom os.path import join, dirname\nimport shutil\nfrom kivy_garden.painter import PaintCircle\nimport numpy as np\nimport math\n\n# first copy the file before editing\nsrc_data_file = join(dirname(__file__), 'video_data.h5')\ndata_file = join(dirname(__file__), 'video.h5')\nshutil.copy(src_data_file, data_file)\n\n# open the nix data file for editing\nnix_file = nixio.File.open(data_file, nixio.FileMode.ReadWrite)\n# create our data controller\ndata_file = DataFile(nix_file=nix_file)\n# load the data from the file\ndata_file.open_file()\n\n# check whether we have seen all frame. If we haven't then the timestamps and\n# channel data may be discontinuous, otherwise we can just read the data from\n# the single timestamps array. For this demo file it should be True\nassert data_file.saw_all_timestamps\n\n\n# get video metadata\nvideo_metadata = data_file.video_metadata_dict\nwidth, height = video_metadata['src_vid_size']\n\n# get the timestamps\ntimestamps = np.array(data_file.timestamps)\n\n\n# Duplicate the event channel. There should only be one event channel\n# in the demo file so get that one\nevent = list(data_file.event_channels.values())[0]\nnew_event = data_file.duplicate_channel(event)\n# fix the name of the duplicated channel because all the channels should have\n# unique names\nmetadata = event.channel_config_dict\nmetadata['name'] += ' copy'\nevent.channel_config_dict = metadata\n\n\n# create the channels\nevent = data_file.create_channel('event')\npos = data_file.create_channel('pos')\nzone = data_file.create_channel('zone')\n\n# set channel metadata\nevent.channel_config_dict = {'name': 'A new event'}\npos.channel_config_dict = {'name': 'A new spiral'}\n\ncenter_x = width / 2. + 10\ncenter_y = height / 2. + 10\ncircle = PaintCircle.create_shape(\n [center_x, center_y], 5 / 12 * min(width, height))\nzone.channel_config_dict = {\n 'name': 'A new circle', 'shape_config': circle.get_state()}\n\n\n# add the new channels' data\n# set the channel data and timestamps as we \"read\" the timestamps\nangle = 20 * math.pi / len(timestamps)\nextent = 1 / 3 * min(width, height)\nfor i, t in enumerate(timestamps):\n event.set_timestamp_value(t, bool((i // 10) % 2))\n\n current_angle = i * angle\n pos.set_timestamp_value(t, (\n center_x + i / len(timestamps) * extent * math.cos(current_angle),\n center_y + i / len(timestamps) * extent * math.sin(current_angle)\n ))\n\n# finally close the nix file\nnix_file.close()\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AmineKheldouni/Object-Recognition | [
"047367e9506a9f46dae0daaf74404e660176997f"
] | [
"A3 - Bird Classification Challenge/model.py"
] | [
"import numpy as np\nfrom torch import nn\nfrom torchvision import models\n\n\nclass FineTuneModel(nn.Module):\n \"\"\"Model used to test a ResNet50 with finetuning FC layers\"\"\"\n def __init__(self, num_classes):\n super(FineTuneModel, self).__init__()\n # Everything except the last linear layer\n original_model = models.resnet50(pretrained=True)\n self.features = nn.Sequential(*list(original_model.children())[:-1])\n self.classifier = nn.Sequential(\n nn.Linear(2048, 128),\n nn.ReLU(),\n nn.Linear(128, 128),\n nn.ReLU(),\n nn.Linear(128, num_classes),\n )\n\n def forward(self, x):\n f = self.features(x)\n f = f.view(f.size(0), -1)\n y = self.classifier(f)\n return y\n"
] | [
[
"torch.nn.Linear",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
USF-GT-Molecular-Modeling/hoomd-blue | [
"2ba2f9e60b0320746d21aa8219bfc9df119c053f"
] | [
"hoomd/pytest/test_syncedlist.py"
] | [
"# Copyright (c) 2009-2022 The Regents of the University of Michigan.\n# Part of HOOMD-blue, released under the BSD 3-Clause License.\n\nimport numpy as np\nimport pytest\nfrom hoomd.conftest import BaseListTest, pickling_check\nfrom hoomd.pytest.dummy import DummyOperation, DummySimulation\nfrom hoomd.data.syncedlist import SyncedList, _PartialIsInstance\n\n\nclass OpInt(int):\n \"\"\"Used to test SyncedList where item equality checks are needed.\"\"\"\n\n def _attach(self):\n self._cpp_obj = None\n\n @property\n def _attached(self):\n return hasattr(self, '_cpp_obj')\n\n def _detach(self):\n del self._cpp_obj\n\n def _add(self, simulation):\n self._simulation = simulation\n\n def _remove(self):\n del self._simulation\n\n @property\n def _added(self):\n return hasattr(self, '_simulation')\n\n\nclass TestSyncedList(BaseListTest):\n _rng = np.random.default_rng(12564)\n\n @property\n def rng(self):\n return self._rng\n\n @pytest.fixture(autouse=True, params=(DummyOperation, OpInt))\n def item_cls(self, request):\n return request.param\n\n @pytest.fixture(autouse=True, params=(True, False))\n def attached(self, request):\n return request.param\n\n @pytest.fixture(autouse=True, params=(True, False))\n def attach_items(self, request):\n return request.param\n\n @pytest.fixture\n def generate_plain_collection(self, item_cls):\n if item_cls == DummyOperation:\n\n def generate(n):\n return [DummyOperation() for _ in range(n)]\n\n return generate\n else:\n\n def generate(n):\n return [OpInt(self.rng.integers(100_000_000)) for _ in range(n)]\n\n return generate\n\n @pytest.fixture\n def empty_collection(self, item_cls, attached, attach_items):\n list_ = SyncedList(validation=_PartialIsInstance(item_cls),\n attach_members=attach_items)\n if attached:\n self._synced_list = []\n list_._sync(DummySimulation(), self._synced_list)\n return list_\n\n def is_equal(self, a, b):\n if isinstance(a, DummyOperation):\n return a is b\n return a == b\n\n def final_check(self, test_list):\n if test_list._synced:\n if test_list._attach_members:\n assert all(item._attached for item in test_list)\n else:\n assert not any(\n getattr(item, \"_attached\", False) for item in test_list)\n for item, synced_item in zip(test_list, self._synced_list):\n assert self.is_equal(item, synced_item)\n assert self._synced_list is test_list._synced_list\n if test_list._attach_members:\n assert all(item._added for item in test_list)\n else:\n assert not any(getattr(item, \"_added\", False) for item in test_list)\n\n def test_init(self, generate_plain_collection, item_cls):\n\n validate = _PartialIsInstance(item_cls)\n\n # Test automatic to_synced_list function generation\n synced_list = SyncedList(validation=validate)\n assert synced_list._validate == validate\n op = item_cls()\n assert synced_list._to_synced_list_conversion(op) is op\n\n # Test specified to_synced_list\n def cpp_identity(x):\n return x._cpp_obj\n\n # Test full initialziation\n plain_list = generate_plain_collection(5)\n synced_list = SyncedList(validation=validate,\n to_synced_list=cpp_identity,\n iterable=plain_list)\n assert synced_list._to_synced_list_conversion == cpp_identity\n op._cpp_obj = 2\n assert synced_list._to_synced_list_conversion(op) == 2\n assert all(op._added for op in synced_list)\n self.check_equivalent(plain_list, synced_list)\n\n def test_synced(self):\n test_list = SyncedList(lambda x: x)\n assert not test_list._synced\n test_list._sync(None, [])\n assert test_list._synced\n test_list._unsync()\n assert not test_list._synced\n\n def test_attach_value(self, empty_collection, item_cls):\n op = item_cls()\n empty_collection._attach_value(op)\n assert op._attached == (empty_collection._synced\n and empty_collection._attach_members)\n assert op._added or not empty_collection._attach_members\n\n def test_validate_or_error(self, empty_collection, item_cls):\n with pytest.raises(ValueError):\n empty_collection._validate_or_error(3)\n with pytest.raises(ValueError):\n empty_collection._validate_or_error(None)\n with pytest.raises(ValueError):\n empty_collection._validate_or_error(\"hello\")\n empty_collection._validate_or_error(item_cls())\n\n def test_syncing(self, populated_collection):\n test_list, plain_list = populated_collection\n self.final_check(test_list)\n\n def test_unsync(self, populated_collection):\n test_list, plain_list = populated_collection\n test_list._unsync()\n assert not hasattr(test_list, \"_synced_list\")\n self.final_check(test_list)\n\n def test_synced_iter(self, empty_collection):\n empty_collection._sync(None, [3, 2, 1])\n empty_collection._synced_list = [1, 2, 3]\n assert all([\n i == j for i, j in zip(range(1, 4), empty_collection._synced_iter())\n ])\n\n def test_pickling(self, populated_collection):\n test_list, _ = populated_collection\n pickling_check(test_list)\n"
] | [
[
"numpy.random.default_rng"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
daikon899/PRNU | [
"6ea64c54169f087d66d5e9b17039945145e03ee5"
] | [
"prnu/VDNet/utils.py"
] | [
"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Power by Zongsheng Yue 2019-01-22 22:07:08\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Function as autoF\nfrom scipy.special import gammaln\nfrom skimage.measure import compare_psnr, compare_ssim\nfrom skimage import img_as_ubyte\nimport numpy as np\nimport sys\nfrom math import floor\n\ndef ssim_index(im1, im2):\n '''\n Input:\n im1, im2: np.uint8 format\n '''\n if im1.ndim == 2:\n out = compare_ssim(im1, im2, data_range=255, gaussian_weights=True,\n use_sample_covariance=False, multichannel=False)\n elif im1.ndim == 3:\n out = compare_ssim(im1, im2, data_range=255, gaussian_weights=True,\n use_sample_covariance=False, multichannel=True)\n else:\n sys.exit('Please input the corrected images')\n return out\n\ndef im2patch(im, pch_size, stride=1):\n '''\n Transform image to patches.\n Input:\n im: 3 x H x W or 1 X H x W image, numpy format\n pch_size: (int, int) tuple or integer\n stride: (int, int) tuple or integer\n '''\n if isinstance(pch_size, tuple):\n pch_H, pch_W = pch_size\n elif isinstance(pch_size, int):\n pch_H = pch_W = pch_size\n else:\n sys.exit('The input of pch_size must be a integer or a int tuple!')\n\n if isinstance(stride, tuple):\n stride_H, stride_W = stride\n elif isinstance(stride, int):\n stride_H = stride_W = stride\n else:\n sys.exit('The input of stride must be a integer or a int tuple!')\n\n C, H, W = im.shape\n num_H = len(range(0, H-pch_H+1, stride_H))\n num_W = len(range(0, W-pch_W+1, stride_W))\n num_pch = num_H * num_W\n pch = np.zeros((C, pch_H*pch_W, num_pch), dtype=im.dtype)\n kk = 0\n for ii in range(pch_H):\n for jj in range(pch_W):\n temp = im[:, ii:H-pch_H+ii+1:stride_H, jj:W-pch_W+jj+1:stride_W]\n pch[:, kk, :] = temp.reshape((C, num_pch))\n kk += 1\n\n return pch.reshape((C, pch_H, pch_W, num_pch))\n\ndef batch_PSNR(img, imclean):\n Img = img.data.cpu().numpy()\n Iclean = imclean.data.cpu().numpy()\n Img = img_as_ubyte(Img)\n Iclean = img_as_ubyte(Iclean)\n PSNR = 0\n for i in range(Img.shape[0]):\n PSNR += compare_psnr(Iclean[i,:,:,:], Img[i,:,:,:], data_range=255)\n return (PSNR/Img.shape[0])\n\ndef batch_SSIM(img, imclean):\n Img = img.data.cpu().numpy()\n Iclean = imclean.data.cpu().numpy()\n Img = img_as_ubyte(Img)\n Iclean = img_as_ubyte(Iclean)\n SSIM = 0\n for i in range(Img.shape[0]):\n SSIM += ssim_index(Iclean[i,:,:,:].transpose((1,2,0)), Img[i,:,:,:].transpose((1,2,0)))\n return (SSIM/Img.shape[0])\n\ndef peaks(n):\n '''\n Implementation the peak function of matlab.\n '''\n X = np.linspace(-3, 3, n)\n Y = np.linspace(-3, 3, n)\n [XX, YY] = np.meshgrid(X, Y)\n ZZ = 3 * (1-XX)**2 * np.exp(-XX**2 - (YY+1)**2) \\\n - 10 * (XX/5.0 - XX**3 -YY**5) * np.exp(-XX**2-YY**2) - 1/3.0 * np.exp(-(XX+1)**2 - YY**2)\n return ZZ\n\ndef generate_gauss_kernel_mix(H, W):\n '''\n Generate a H x W mixture Gaussian kernel with mean (center) and std (scale).\n Input:\n H, W: interger\n center: mean value of x axis and y axis\n scale: float value\n '''\n pch_size = 32\n K_H = floor(H / pch_size)\n K_W = floor(W / pch_size)\n K = K_H * K_W\n # prob = np.random.dirichlet(np.ones((K,)), size=1).reshape((1,1,K))\n centerW = np.random.uniform(low=0, high=pch_size, size=(K_H, K_W))\n ind_W = np.arange(K_W) * pch_size\n centerW += ind_W.reshape((1, -1))\n centerW = centerW.reshape((1,1,K)).astype(np.float32)\n centerH = np.random.uniform(low=0, high=pch_size, size=(K_H, K_W))\n ind_H = np.arange(K_H) * pch_size\n centerH += ind_H.reshape((-1, 1))\n centerH = centerH.reshape((1,1,K)).astype(np.float32)\n scale = np.random.uniform(low=pch_size/2, high=pch_size, size=(1,1,K))\n scale = scale.astype(np.float32)\n XX, YY = np.meshgrid(np.arange(0, W), np.arange(0,H))\n XX = XX[:, :, np.newaxis].astype(np.float32)\n YY = YY[:, :, np.newaxis].astype(np.float32)\n ZZ = 1./(2*np.pi*scale**2) * np.exp( (-(XX-centerW)**2-(YY-centerH)**2)/(2*scale**2) )\n out = ZZ.sum(axis=2, keepdims=False) / K\n\n return out\n\ndef sincos_kernel():\n # Nips Version\n [xx, yy] = np.meshgrid(np.linspace(1, 10, 256), np.linspace(1, 20, 256))\n # [xx, yy] = np.meshgrid(np.linspace(1, 10, 256), np.linspace(-10, 15, 256))\n zz = np.sin(xx) + np.cos(yy)\n return zz\n\ndef capacity_cal(net):\n out = 0\n for param in net.parameters():\n out += param.numel()*4/1024/1024\n # print('Networks Parameters: {:.2f}M'.format(out))\n return out\n\nclass LogGamma(autoF):\n '''\n Implement of the logarithm of gamma Function.\n '''\n @staticmethod\n def forward(ctx, input):\n ctx.save_for_backward(input)\n if input.is_cuda:\n input_np = input.detach().cpu().numpy()\n else:\n input_np = input.detach().numpy()\n out = gammaln(input_np)\n out = torch.from_numpy(out).to(device=input.device).type(dtype=input.dtype)\n\n return out\n\n @staticmethod\n def backward(ctx, grad_output):\n input, = ctx.saved_tensors\n grad_input = torch.digamma(input) * grad_output\n\n return grad_input\n\ndef load_state_dict_cpu(net, state_dict0):\n state_dict1 = net.state_dict()\n for name, value in state_dict1.items():\n assert 'module.'+name in state_dict0\n state_dict1[name] = state_dict0['module.'+name]\n net.load_state_dict(state_dict1)\n"
] | [
[
"numpy.linspace",
"numpy.arange",
"torch.digamma",
"numpy.cos",
"torch.from_numpy",
"numpy.sin",
"scipy.special.gammaln",
"numpy.exp",
"numpy.random.uniform",
"numpy.meshgrid",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.18",
"0.19"
],
"tensorflow": []
}
] |
femtotrader/alpha_vantage | [
"aea5da8271a983cd12b655b72f8ebfee9fb75233"
] | [
"alpha_vantage/alphavantage.py"
] | [
"try:\n # Python 3 import\n from urllib.request import urlopen\nexcept ImportError:\n # Python 2.* import\n from urllib2 import urlopen\n\nfrom simplejson import loads\nfrom functools import wraps\nimport inspect\nimport pandas\nimport re\n\n\nclass AlphaVantage:\n \"\"\" Base class where the decorators and base function for the other\n classes of this python wrapper will inherit from.\n \"\"\"\n _ALPHA_VANTAGE_API_URL = \"http://www.alphavantage.co/query?\"\n _ALPHA_VANTAGE_MATH_MAP = ['SMA', 'EMA', 'WMA', 'DEMA', 'TEMA', 'TRIMA', 'T3',\n 'KAMA', 'MAMA']\n _EXCHANGE_SUPPORTED = { 'ASX': 'Australian Securities Exchange',\n 'BOM': 'Bombay Stock Exchange',\n 'BIT': 'Borsa Italiana Milan Stock Exchange',\n 'TSE': 'Canadian/Toronto Securities Exchange',\n 'FRA': 'Deutsche Boerse Frankfurt Stock Exchange',\n 'ETR': 'Deutsche Boerse Frankfurt Stock Exchange',\n 'AMS': 'Euronext Amsterdam',\n 'EBR': 'Euronext Brussels',\n 'ELI': 'Euronext Lisbon',\n 'EPA': 'Euronext Paris',\n 'LON': 'London Stock Exchange',\n 'MCX': 'Moscow Exchange',\n 'NASDAQ': 'NASDAQ Exchange',\n 'CPH': 'NASDAQ OMX Copenhagen',\n 'HEL': 'NASDAQ OMX Helsinki',\n 'ICE': 'NASDAQ OMX Iceland',\n 'STO': 'NASDAQ OMX Stockholm',\n 'NSE': 'National Stock Exchange of India',\n 'NYSE': 'New York Stock Exchange',\n 'SGX': 'Singapore Exchange',\n 'SHA': 'Shanghai Stock Exchange',\n 'SHE': 'Shenzhen Stock Exchange',\n 'TPE': 'Taiwan Stock Exchange',\n 'TYO': 'Tokyo Stock Exchange'}\n\n def __init__(self, key=None, retries=5, output_format='json', treat_info_as_error=True):\n \"\"\" Initialize the class\n\n Keyword Arguments:\n key: Alpha Vantage api key\n retries: Maximum amount of retries in case of faulty connection or\n server not able to answer the call.\n output_format: Either 'json' or 'pandas'\n \"\"\"\n if key is None:\n raise ValueError('Get a free key from the alphavantage website: https://www.alphavantage.co/support/#api-key')\n self.key = key\n self.retries = retries\n self.output_format = output_format\n self.treat_info_as_error = treat_info_as_error\n\n def _retry(func):\n \"\"\" Decorator for retrying api calls (in case of errors from the api\n side in bringing the data)\n\n Keyword Arguments:\n func: The function to be retried\n \"\"\"\n @wraps(func)\n def _retry_wrapper(self, *args, **kwargs):\n error_message = \"\"\n for retry in range(self.retries + 1):\n try:\n return func(self, *args, **kwargs)\n except ValueError as err:\n error_message = str(err)\n raise ValueError(str(error_message))\n return _retry_wrapper\n\n @classmethod\n def _call_api_on_func(cls, func):\n \"\"\" Decorator for forming the api call with the arguments of the\n function, it works by taking the arguments given to the function\n and building the url to call the api on it\n\n Keyword Arguments:\n func: The function to be decorated\n \"\"\"\n\n # Argument Handling\n argspec = inspect.getargspec(func)\n try:\n # Asumme most of the cases have a mixed between args and named\n # args\n positional_count = len(argspec.args) - len(argspec.defaults)\n defaults = dict(zip(argspec.args[positional_count:], argspec.defaults))\n except TypeError:\n if argspec.args:\n # No defaults\n positional_count = len(argspec.args)\n defaults = {}\n elif argspec.defaults:\n # Only defaults\n positional_count = 0\n defaults = argspec.defaults\n # Actual decorating\n\n @wraps(func)\n def _call_wrapper(self, *args, **kwargs):\n used_kwargs = kwargs.copy()\n # Get the used positional arguments given to the function\n used_kwargs.update(zip(argspec.args[positional_count:],\n args[positional_count:]))\n # Update the dictionary to include the default parameters from the\n # function\n used_kwargs.update({k: used_kwargs.get(k, d)\n for k, d in defaults.items()})\n # Form the base url, the original function called must return\n # the function name defined in the alpha vantage api and the data\n # key for it and for its meta data.\n function_name, data_key, meta_data_key = func(self, *args, **kwargs)\n url = \"{}function={}\".format(AlphaVantage._ALPHA_VANTAGE_API_URL,\n function_name)\n for idx, arg_name in enumerate(argspec.args[1:]):\n try:\n arg_value = args[idx]\n except IndexError:\n arg_value = used_kwargs[arg_name]\n if 'matype' in arg_name and arg_value:\n # If the argument name has matype, we gotta map the string\n # or the integer\n arg_value = self.map_to_matype(arg_value)\n if arg_value:\n # Discard argument in the url formation if it was set to\n # None (in other words, this will call the api with its\n # internal defined parameter)\n url = '{}&{}={}'.format(url, arg_name, arg_value)\n url = '{}&apikey={}'.format(url, self.key)\n return self._handle_api_call(url), data_key, meta_data_key\n return _call_wrapper\n\n @classmethod\n def _output_format(cls, func, override=None):\n \"\"\" Decorator in charge of giving the output its right format, either\n json or pandas\n\n Keyword Arguments:\n func: The function to be decorated\n override: Override the internal format of the call, default None\n \"\"\"\n @wraps(func)\n def _format_wrapper(self, *args, **kwargs):\n json_response, data_key, meta_data_key = func(self, *args, **kwargs)\n data = json_response[data_key]\n if meta_data_key is not None:\n meta_data = json_response[meta_data_key]\n else:\n meta_data = None\n # Allow to override the output parameter in the call\n if override is None:\n output_format = self.output_format.lower()\n elif 'json' or 'pandas' in override.lower():\n output_format = override.lower()\n # Choose output format\n if output_format == 'json':\n return data, meta_data\n elif output_format == 'pandas':\n data_pandas = pandas.DataFrame.from_dict(data,\n orient='index', dtype=float)\n # Rename columns to have a nicer name\n col_names = [re.sub(r'\\d+.', '', name).strip(' ')\n for name in list(data_pandas)]\n data_pandas.columns = col_names\n return data_pandas, meta_data\n else:\n raise ValueError('Format: {} is not supported'.format(\n self.output_format))\n return _format_wrapper\n\n def map_to_matype(self, matype):\n \"\"\" Convert to the alpha vantage math type integer. It returns an\n integer correspondant to the type of math to apply to a function. It\n raises ValueError if an integer greater than the supported math types\n is given.\n\n Keyword Arguments:\n matype: The math type of the alpha vantage api. It accepts integers\n or a string representing the math type.\n\n * 0 = Simple Moving Average (SMA),\n * 1 = Exponential Moving Average (EMA),\n * 2 = Weighted Moving Average (WMA),\n * 3 = Double Exponential Moving Average (DEMA),\n * 4 = Triple Exponential Moving Average (TEMA),\n * 5 = Triangular Moving Average (TRIMA),\n * 6 = T3 Moving Average,\n * 7 = Kaufman Adaptive Moving Average (KAMA),\n * 8 = MESA Adaptive Moving Average (MAMA)\n \"\"\"\n # Check if it is an integer or a string\n try:\n value = int(matype)\n if abs(value) > len(AlphaVantage._ALPHA_VANTAGE_MATH_MAP):\n raise ValueError(\"The value {} is not supported\".format(value))\n except ValueError:\n value = AlphaVantage._ALPHA_VANTAGE_MATH_MAP.index(matype)\n return value\n\n @_retry\n def _handle_api_call(self, url):\n \"\"\" Handle the return call from the api and return a data and meta_data\n object. It raises a ValueError on problems\n\n Keyword Arguments:\n url: The url of the service\n data_key: The key for getting the data from the jso object\n meta_data_key: The key for getting the meta data information out of\n the json object\n \"\"\"\n response = urlopen(url)\n url_response = response.read()\n json_response = loads(url_response)\n \n if not json_response:\n raise ValueError('Error getting data from the api, no return was given.')\n elif \"Error Message\" in json_response:\n raise ValueError(json_response[\"Error Message\"])\n elif \"Information\" in json_response and self.treat_info_as_error:\n raise ValueError(json_response[\"Information\"])\n \n return json_response\n\n def is_exchange_supported(self, exchange_name):\n \"\"\"\n Get if a specific global exchange type is supported by this library\n\n Keyword Arguments:\n exchange_name: The exchange type to check for\n Returns:\n The description of the given key or None\n \"\"\"\n try:\n return AlphaVantage._EXCHANGE_SUPPORTED[exchange_name]\n except KeyError:\n return None\n"
] | [
[
"pandas.DataFrame.from_dict"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
NAnand-TUD/open-moc | [
"1d4808b96366d77e4b8b7b56c3fe0940390b1e18"
] | [
"Tools/MoCTool/srcMOC/CLASSES.py"
] | [
"####################FILE NAME: CLASSES.py#######################\r\n#================================================================\r\n# author: Nitish Anand\t& Jozef Stuijt\t\t\t\t\t\t\t|\r\n# \t:Master Student, \t\t\t\t\t\t\t\t\t\t\t|\r\n#\t:Process and Energy Departmemt,\t\t\t\t\t\t\t\t|\r\n#\t:TU Delft,\t\t\t\t\t\t\t\t\t\t\t\t\t|\r\n#\t:The Netherlands\t\t\t\t\t\t\t\t\t\t\t|\r\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t|\r\n# email : [email protected]\t\t\t\t\t\t\t\t\t|\r\n# \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t|\r\n# Description: Defines the class variable for the MAIN code. \t|\r\n#\t: All the property variable defined in the MOC is a \t\t|\r\n#\t: object of the CLASS mentioned in this module.\t\t\t\t|\r\n# CLASS Function:\t\t\t\t\t\t\t\t\t\t\t\t|\r\n#\t:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t|\r\n#================================================================\r\n\r\n# Imports\r\nimport time\r\nimport sys\r\nimport os \r\nimport math as calc\r\nfrom sympy import Symbol, nsolve, log, ln\r\nfrom sympy.solvers import solve\r\nimport pdb\r\nimport numpy as np\r\nfrom srcMOC.IO import *\r\nimport subprocess\r\nimport CoolProp.CoolProp as cp\r\n\r\n#\r\n# CLASS to store only points\r\n#\r\n\r\nclass Points_mini:\r\n\t# Dummy Class for Data Passing Only\r\n\tdef __init__(self,x=0,y=0,u=0,v=0):\r\n\t\t#if Input == None:\r\n\t\tself.x=x\r\n\t\tself.y=y\r\n\t\tself.u=u\r\n\t\tself.v=v\r\n#\r\n# CLASS-> MAIN CLASS, contains \r\n#\t\t\t\t 1.ThermoProp()\r\n#\t\t\t 2. Sauer_Line(real,perfect)\r\n#\t\t\t 3. Reflex_Zone()\r\n#\t\t\t 4. OtherSupportingFunction\r\n\t\t\r\nclass Points(Points_mini):\r\n\t# Function:\r\n\t#\ta. SauerRealGas()\r\n\t#\tb. SauerMain() -> ThermoProp Not Needed\r\n\t#\tc. ThermoProp() -> PRFT , EoS , EoS_TAB, RefProp, CoolProp\r\n\t#\td. ReflexLine()\r\n\t#\te. PointInPoly()\r\n\t# Self Initialized Variables\r\n\r\n\t# Argument Enabled Initialization <1st argument name will be considered as the InputFile>\r\n\tDIR = os.getcwd()+'/'\r\n\ttry:INFile = DIR+sys.argv[1]\r\n\texcept:INFile = DIR+'MOC_Config.in'\r\n\tIN = ReadUserInput(INFile)\r\n\tTo = float(IN['To'])\r\n\tPo = float(IN['Po'])\r\n\tgamma = float(IN['gamma'])\r\n\tR = float(IN['R'])/float(IN['M'])\r\n\ty_t = float(IN['y_t'])\r\n\tn = float(IN['n'])\r\n\trho_t = float(IN['rho_t'])\r\n\tdelta = 0\r\n\tTc = float(IN['Tc'])\r\n\tPc = float(IN['Pc'])\r\n\tVc = float(IN['Vc'])/float(IN['M'])\r\n\tGasEqu = IN['GAS_EQU']\r\n\tHo = float(IN['Ho'])\r\n\tao = calc.sqrt(gamma*R*To)\r\n\tOmega = 0\r\n\tIT_rho = 0\r\n\tIT_P = 0\r\n\tIT_c = 0\r\n\tIT_v = 0\r\n\tIT_h = 0\r\n\tIT_T = 0\r\n\r\n\t# Added by Jozef to check throat file\r\n\tTHROAT = IN['THROAT_PROP']\r\n\tif THROAT=='ITER': pass\r\n\telse:\r\n\t\ttry: THROAT_FILE = np.loadtxt(THROAT)\r\n\t\texcept: \r\n\t\t\traise IOError('Invalid Input: THROAT_PROP')\r\n\t\t\tsys.exit()\r\n\t\r\n\t#Initlaizating Fluid for RefProp or CoolProp ONLY\r\n\tif (GasEqu=='RefProp' or GasEqu=='RefProp_TAB'):\r\n\t\tFLD = IN['FLDNAME']\r\n\t\ts = fp.fluidprop_py(FLD,'PT',float(IN['Po'])/1e5,float(IN['To'])-273,'entropy')\r\n\t\tHo = fp.fluidprop_py(FLD,'PT',float(IN['Po'])/1e5,float(IN['To'])-273,'enthalpy')\r\n\telif (GasEqu == 'CoolProp'):\r\n\t\tFLD = IN['FLDNAME']\r\n\t\ts = cp.PropsSI('S','P',float(IN['Po']),'T',float(IN['To']),FLD)/1000\r\n\t\tHo = cp.PropsSI('H','P',float(IN['Po']),'T',float(IN['To']),FLD)/1000\r\n\telif (GasEqu == 'CoolProp-PR'):\r\n\t\tpdb.set_trace()\r\n\t\tFLD = IN['FLDNAME']\r\n\t\ts = cp.PropsSI('S','P',float(IN['Po']),'T',float(IN['To']),\"PR::\"+FLD)/1000\r\n\t\tHo = cp.PropsSI('H','P',float(IN['Po']),'T',float(IN['To']),\"PR::\"+FLD)/1000\r\n\t#else:\r\n\t#\traise IOError('Invalid Input: GasEqu')\r\n\t#\tsys.exit()\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Printing the entire Class Variable using str(ObjectName)\r\n\tdef __str__(self):\r\n\t\tprint(\"x = {} \\ny = {} \\nu = {} \\nv = {} \\nM = {} \\na = {} \\nP = {} \\nT = {} \\nrho = {} \\nV = {} \\nh = {} \\n\".format(self.x,self.y,self.u,self.v,self.M,self.a,self.Press,self.Temp,self.rho,self.V,self.h))\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Initializing the variable (Optional)[Default=0]\r\n\tdef __init__(self,x=0,y=0,u=0,v=0):\r\n\t\tPoints_mini.__init__(self,x,y,u,v)\r\n\t\tself.M = 0\r\n\t\tself.a = 0\r\n\t\tself.V = 0\r\n\t\tself.Press = 0\r\n\t\tself.Temp = 0\r\n\t\tself.rho = 0\r\n\t\tself.h = 0\r\n\t\tself.r = 0\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\r\n\t# Sauer Analysis with RefProp (Ref: Under Inspection)\r\n\tdef Sauer_RefTab(self):\r\n\t\tV_flag =95\r\n\t\tf=1\r\n\t\twhile abs(self.M-1)>1e-5:\r\n\t\t\tself.u = V_flag\r\n\t\t\tself.ThermoProp(self.IN)\r\n\t\t\tf=self.a**2/2000 + self.h - self.Ho\r\n\t\t\tprint(f)\r\n\t\t\tprint('M',self.M)\r\n\t\t\tV_flag = self.a - (0.1*f*(abs(f)/1000)**0.5/abs(f))\r\n\t\t\tprint('V_flag',V_flag)\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Sauer Analysis with RefProp (Ref: Alberto Code, Contact Matteo Pini for more Info.)[Special CASE for TOL]\r\n\t# Gustavo: Do not Review this function (similar function is at the end of the code)\r\n\t# Jozef: Added this code to the Sauer function\r\n\t'''def Sauer_RealGas1(self):\r\n\t\tif (self.GasEqu=='RefProp' or self.GasEqu=='RefProp_TAB'):\r\n\t\t\tIT_rho=fp.fluidprop_py(self.FLD,'hs',self.Ho,self.s,'density')\r\n\t\t\tIT_T=fp.fluidprop_py(self.FLD,'vs',1/IT_rho,self.s,'temperature')\r\n\t\t\tfor i in range(0,10000):\r\n\t\t\t\tIT_T=fp.fluidprop_py(self.FLD,'vs',1/IT_rho,self.s,'temperature')\r\n\t\t\t\tIT_c=fp.fluidprop_py(self.FLD,'Tv',IT_T,1/IT_rho,'soundspeed')\t\t\t\r\n\t\t\t\tIT_G=fp.fluidprop_py(self.FLD,'Tv',IT_T,1/IT_rho,'gamma')\r\n\t\t\t\tIT_h=fp.fluidprop_py(self.FLD,'Tv',IT_T,1/IT_rho,'enthalpy')\r\n\t\t\t\tIT_P=fp.fluidprop_py(self.FLD,'Tv',IT_T,1/IT_rho,'pressure')\r\n\t\t\t\tf=IT_c**2/2000 +IT_h-self.Ho\r\n\t\t\t\tdf=-IT_G*(IT_c**2*IT_rho)\r\n\t\t\t\tIT_v=1/IT_rho - f/df\r\n\t\t\t\tIT_rho=1/IT_v\r\n\t\t\t\tprint(f)\r\n\t\t\t\tif 1:#(abs(f)<1e-3):\r\n\t\t\t\t\tThroat=np.loadtxt('ThroatProp.out')\r\n\t\t\t\t\tself.a=Throat[0]#140.455#IT_c\r\n\t\t\t\t\tself.Press=Throat[1]#13.9751#IT_P\r\n\t\t\t\t\tself.Temp=Throat[2]#288.327#IT_T\r\n\t\t\t\t\tself.rho=Throat[3]#59.773443394897484#IT_rho\r\n\t\t\t\t\tself.gamma=Throat[4]#0.829105#IT_G\r\n\t\t\t\t\tself.h=Throat[5]#538.028#IT_h\r\n\t\t\t\t\t#print(IT_c,IT_P,IT_T,IT_rho,IT_G,IT_h)\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\tbreak\r\n\t\t\talpha = calc.sqrt((1+self.delta)/(2*(self.gamma*self.rho_t*self.y_t)))\r\n\t\t\tepsilon = -alpha*self.y_t*self.gamma/(3+self.delta)\r\n\t\t\tself.x = -self.gamma*alpha*self.y**2/(3+self.delta)\r\n\t\t\tself.u = self.a*(1+(alpha*self.x+self.gamma*(alpha*self.y)**2/(1+self.delta)))\r\n\t\t\tself.v=self.a*((2*self.gamma*alpha**2*self.x*self.y/(1+self.delta))+(2*self.gamma**2*(alpha*self.y)**3)/((1+self.delta)*(3+self.delta)))\r\n\t\t\tself.x=self.x-epsilon\r\n\t\telif (self.GasEqu == 'CoolProp'):\r\n\t\t\t#print('Sauer_RealGas1 with CoolProp')\r\n\t\t\tIT_rho = cp.PropsSI('D','H',self.Ho*1000,'S',self.s*1000,self.FLD)\r\n\t\t\tIT_T = cp.PropsSI('T','H',self.Ho*1000,'S',self.s*1000,self.FLD)-273\r\n\t\t\tfor i in range(0,10000):\r\n\t\t\t\tIT_T = cp.PropsSI('T','D',IT_rho,'S',self.s*1000,self.FLD)-273\r\n\t\t\t\tIT_c = cp.PropsSI('A','D',IT_rho,'T',IT_T-273,self.FLD)\r\n\t\t\t\tIT_G = (cp.PropsSI('CPMASS','D',IT_rho,'T',IT_T-273,self.FLD)/cp.PropsSI('CVMASS','D',IT_rho,'T',IT_T-273,self.FLD))\r\n\t\t\t\tIT_h = cp.PropsSI('H','D',IT_rho,'T',IT_T-273,self.FLD)/1000\r\n\t\t\t\tIT_P = cp.PropsSI('P','D',IT_rho,'T',IT_T-273,self.FLD)/1e5\r\n\t\t\t\tf=IT_c**2/2000 +IT_h-self.Ho\r\n\t\t\t\tdf=-IT_G*(IT_c**2*IT_rho)\r\n\t\t\t\tIT_v=1/IT_rho - f/df\r\n\t\t\t\tIT_rho=1/IT_v\r\n\t\t\t\tprint(f)\r\n\t\t\t\tif 1:#(abs(f)<1e-3):\r\n\t\t\t\t\tThroat=np.loadtxt('ThroatProp.out')\r\n\t\t\t\t\tself.a=Throat[0]#140.455#IT_c\r\n\t\t\t\t\tself.Press=Throat[1]#13.9751#IT_P\r\n\t\t\t\t\tself.Temp=Throat[2]#288.327#IT_T\r\n\t\t\t\t\tself.rho=Throat[3]#59.773443394897484#IT_rho\r\n\t\t\t\t\tself.gamma=Throat[4]#0.829105#IT_G\r\n\t\t\t\t\tself.h=Throat[5]#538.028#IT_h\r\n\t\t\t\t\t#print(IT_c,IT_P,IT_T,IT_rho,IT_G,IT_h)\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\t\tbreak\r\n\t\t\talpha = calc.sqrt((1+self.delta)/(2*(self.gamma*self.rho_t*self.y_t)))\r\n\t\t\tepsilon = -alpha*self.y_t*self.gamma/(3+self.delta)\r\n\t\t\tself.x = -self.gamma*alpha*self.y**2/(3+self.delta)\r\n\t\t\tself.u = self.a*(1+(alpha*self.x+self.gamma*(alpha*self.y)**2/(1+self.delta)))\r\n\t\t\tself.v=self.a*((2*self.gamma*alpha**2*self.x*self.y/(1+self.delta))+(2*self.gamma**2*(alpha*self.y)**3)/((1+self.delta)*(3+self.delta)))\r\n\t\t\tself.x=self.x-epsilon\r\n\t\telse:\r\n\t\t\tprint(\"Invalid Input: GasEqu\")'''\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Main Function for Sauer Analysis\r\n\tdef SauerMain(self):\r\n\t\t#if (self.GasEqu=='RefProp'or self.GasEqu=='RefProp_TAB'):\r\n\t\t#\tself.Sauer_RealGas()\r\n\t\t\t#self.Sauer_RefTab()\r\n\t\t\t#print('GAMMA',self.gamma)\r\n\t\t\t#pdb.set_trace()\r\n\t\tif 1:\r\n\t\t\tao = calc.sqrt(self.gamma*self.R*self.To)\r\n\t\t\tepsilon = -1*(self.y_t/(2*(3+self.delta)))*(((self.gamma+1)*(1+self.delta)/(self.rho_t/self.y_t))**0.5);\r\n\t\t\ta_star = ((2*self.gamma*self.R*self.To)/(self.gamma+1))**0.5;\r\n\t\t\talpha = ((1+self.delta)/((self.gamma+1)*self.rho_t*self.y_t))**0.5\r\n\t\t\tflag = 0\t\t\r\n\t\t\tx_ = (-(self.gamma+1)*alpha*self.y**2/(2*(flag+1+self.delta)));\r\n\t\t\tflag = 2\r\n\t\t\tself.x = (-(self.gamma+1)*alpha*self.y**2/(2*(flag+1+self.delta)))\r\n\t\t\tu_dash = (alpha*self.x)+((((self.gamma+1)*alpha**2*self.y**2))/(2*(self.delta+1)))\r\n\t\t\tv_dash = ((((self.gamma+1)*alpha**2*self.y*self.x))/((self.delta+1)))+(((self.gamma+1)**2*alpha**3*self.y**3)/(2*(1+self.delta)*(3+self.delta)))\r\n\t\t\tself.u = a_star*(1+u_dash)\r\n\t\t\tv_tilde = a_star*v_dash\t\r\n\t\t\tif (self.GasEqu!='RefProp' and self.GasEqu!='RefProp_TAB'):\r\n\t\t\t\tself.a = calc.sqrt(ao**2 - ((self.gamma-1)*self.u**2/(2)))\r\n\t\t\t\tself.M = self.u / self.a\r\n\t\t\t\tself.Press = self.Po/(1+((self.gamma-1)*self.M**2/(2)))**((self.gamma)/(self.gamma-1))\r\n\t\t\t\tself.Temp = self.To/(1+((self.gamma-1)*self.M**2/(2)))\r\n\t\t\t\tself.rho = self.Press/(self.R*self.Temp)\r\n\t\t\t\tself.x=self.x-epsilon\r\n\t\tself.M = calc.sqrt(self.u**2+self.v**2) / self.a\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Thermodynamics Properties Calculator (PRFT, EoS, EoS_TAB,RefProp)\r\n\tdef ThermoProp(self,IN):\r\n\t\tself.V = calc.sqrt((self.u**2 + self.v**2))\r\n\t\t#PRFT: Solve using PERFECT gas equations [gamma necessary]\r\n\t\tif self.GasEqu == 'PRFT':\r\n\t\t\tCp = self.R*self.gamma/(self.gamma-1)\r\n\t\t\tself.Temp = self.To - (self.V**2/(2*Cp))\r\n\t\t\tself.Press = self.Po*(self.Temp/self.To)**(self.gamma/(self.gamma-1))\r\n\t\t\tself.rho = self.Press / (self.R*self.Temp)\r\n\t\t\tself.a = calc.sqrt((self.ao**2)-((self.gamma-1)*self.V**2/2))\r\n\t\t\tself.M = self.V/self.a\r\n\t\t#EoS: Solve by directly solving Van der Waals EoS\r\n\t\telif self.GasEqu == 'EoS':\r\n\t\t\teqP = Symbol('eqP')\r\n\t\t\teqT = Symbol('eqT')\r\n\t\t\tVrho = Symbol('Vrho')\r\n\t\t\tb1 = self.R*self.Tc/(8*self.Pc)\r\n\t\t\ta1 = 27*(self.R*self.Tc)**2/(64*self.Pc) \r\n\t\t\tCp = self.gamma*self.R/(self.gamma-1)\r\n\t\t\thig = self.Ho - (Cp)*(self.To-eqT)\r\n\t\t\th = self.Ho - (0.5*self.V**2)\r\n\t\t\tVDW_h = - (2*a1/Vrho) + (b1*self.R*eqT/(Vrho-b1)) + hig - h\r\n\t\t\tVDW = (eqP*Vrho**3) -(eqP*b1+self.R*eqT)*Vrho**2 + a1*Vrho - a1*b1\r\n\t\t\tVDW_s = (self.gamma*log(eqT/self.To))/(self.gamma-1) - log(eqP/self.Po) + log(Vrho-b1) - log(Vrho) + log(eqP*Vrho/self.R/eqT) \r\n\t\t\ttry:[Vrho,T,P] = nsolve((VDW,VDW_h,VDW_s),(Vrho,eqT,eqP),(float(IN['VrhoGuess']),float(IN['TGuess']),float(IN['PGuess'])))\r\n\t\t\texcept:pdb.set_trace()\r\n\t\t\ttry:Vrho = float(Vrho.real)\r\n\t\t\texcept:pdb.set_trace()\r\n\t\t\ttry:self.Temp = float(T)\r\n\t\t\texcept:self.Temp = float(T.real)\r\n\t\t\ttry:self.Press = float(P)\r\n\t\t\texcept:self.Press = float(P.real)\r\n\t\t\tself.rho = 1/float(Vrho)\r\n\t\t\tD1 = (2-self.gamma)*(Vrho-b1)/(self.gamma-1)\r\n\t\t\tD2 = self.R*self.Temp/self.Press\r\n\t\t\tN1 = self.R*T*((1/(Vrho-b1))+(1/Vrho))\r\n\t\t\tN2 = (P-(a1/Vrho**2) + (2*a1*b1/Vrho**3))*((2-self.gamma)/(self.gamma-1))\r\n\t\t\ttry:a = calc.sqrt(Vrho**2*(N1.real+N2.real)/(D1.real+D2.real))\r\n\t\t\texcept: pdb.set_trace()\r\n\t\t\tself.a = a\r\n\t\t\tself.M = self.V/self.a\r\n\t\t\tIN['VrhoGuess'] = float(Vrho.real)\r\n\t\t\tIN['TGuess'] = float(T.real)\r\n\t\t\tIN['PGuess'] = float(P.real)\r\n\t\t# EoS_TAB = Make and solve using van der Waals EoS table\r\n\t\telif self.GasEqu == 'EoS_TAB':\r\n\t\t\teqP = Symbol('eqP')\r\n\t\t\teqT = Symbol('eqT')\r\n\t\t\teqVrho = Symbol('eqVrho')\r\n\t\t\tb1 = self.R*self.Tc/(8*self.Pc)\r\n\t\t\ta1 = 27*(self.R*self.Tc)**2/(64*self.Pc)\r\n\t\t\tCp = self.gamma*self.R/(self.gamma-1)\r\n\t\t\thig = self.Ho - (Cp)*(self.To-eqT)\r\n\t\t\t# CREATE TABLE\r\n\t\t\tif IN['Table_Oper'] == 'Create':\r\n\t\t\t\ttry:os.remove(os.getcwd()+'/Table.TAB')\r\n\t\t\t\texcept: print (\"Continue: No File to Delete <Table> \\n Location:\",os.getcwd())\r\n\t\t\t\tminV = int(IN['LLim'])\r\n\t\t\t\tmaxV = int(IN['ULim'])\r\n\t\t\t\tdV = float(IN['dV'])\r\n\t\t\t\tV1= np.arange(minV,maxV,dV)\r\n\t\t\t\tfor V in V1:\r\n\t\t\t\t\tself.V = V\r\n\t\t\t\t\th = self.Ho - (0.5*self.V**2)\r\n\t\t\t\t\tVDW_h = - (2*a1/eqVrho) + (b1*self.R*eqT/(eqVrho-b1)) + hig - h\r\n\t\t\t\t\tVDW = (eqP*eqVrho**3) -(eqP*b1+self.R*eqT)*eqVrho**2 + a1*eqVrho - a1*b1\r\n\t\t\t\t\tVDW_s = (self.gamma*log(eqT/self.To))/(self.gamma-1) - log(eqP/self.Po) + log(eqVrho-b1) - log(eqVrho) + log(eqP*eqVrho/self.R/eqT) \r\n\t\t\t\t\ttry:[Vrho,T,P] = nsolve((VDW,VDW_h,VDW_s),(eqVrho,eqT,eqP),(float(IN['VrhoGuess']),float(IN['TGuess']),float(IN['PGuess'])))\r\n\t\t\t\t\texcept:pdb.set_trace()\r\n\t\t\t\t\ttry:Vrho = float(Vrho.real)\r\n\t\t\t\t\texcept:pdb.set_trace()\r\n\t\t\t\t\ttry:self.Temp = float(T)\r\n\t\t\t\t\texcept:self.Temp = float(T.real)\r\n\t\t\t\t\ttry:self.Press = float(P) \r\n\t\t\t\t\texcept:self.Press = float(P.real)\r\n\t\t\t\t\tself.rho = 1/float(Vrho)\r\n \t\t\t\t###Refer Thesis for derivation###\r\n\t\t\t\t\tD1 = (2-self.gamma)*(Vrho-b1)/(self.gamma-1)\r\n\t\t\t\t\tD2 = self.R*self.Temp/self.Press\r\n\t\t\t\t\tN1 = self.R*T*((1/(Vrho-b1))+(1/Vrho)) \r\n\t\t\t\t\tN2 = (self.Press-(a1/Vrho**2) + (2*a1*b1/Vrho**3))*((2-self.gamma)/(self.gamma-1)) \r\n\t\t\t\t\ta = calc.sqrt(Vrho**2*(N1.real+N2.real)/(D1.real+D2.real))\r\n\t\t\t\t\tself.a = a\r\n\t\t\t\t\tself.M = self.V/self.a\r\n\t\t\t\t\tIN['VrhoGuess'] = float(Vrho.real)\r\n\t\t\t\t\tIN['TGuess'] = float(T.real)\r\n\t\t\t\t\tIN['PGuess'] = float(P.real)\r\n\t\t\t\t\tWriteDataFile('a',self,'Table.TAB','TAB')\r\n\t\t\t\tprint('***Table Create***')\r\n\t\t\t\tsys.exit(-1)\r\n\t\t\t# CALCULATE FROM TABLE\r\n\t\t\tif IN['Table_Oper'] == 'Calc':\r\n\t\t\t\tTABProp = np.loadtxt('Table.TAB')\r\n\t\t\t\tfor i in range(len(TABProp)):\r\n\t\t\t\t\tif TABProp[i][0]>self.V:\r\n\t\t\t\t\t\tself.M = self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][1],TABProp[i-1][1])\r\n\t\t\t\t\t\tself.rho= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][2],TABProp[i-1][2])\r\n\t\t\t\t\t\tself.a= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][3],TABProp[i-1][3])\r\n\t\t\t\t\t\tself.Temp= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][4],TABProp[i-1][4])\r\n\t\t\t\t\t\tself.Press= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][5],TABProp[i-1][5])\r\n\t\t\t\t\t\tbreak\r\n\t\t# RefProp_TAB = Table generated from RefProp\r\n\t\telif self.GasEqu == 'RefProp_TAB':\r\n\t\t\tif IN['Table_Oper']=='Create':\r\n\t\t\t\ttry:os.remove(os.getcwd()+'/Table.TAB')\r\n\t\t\t\texcept: print (\"Continue: No File to Delete <Table> \\n Location:\",os.getcwd())\r\n\t\t\t\tminV = int(IN['LLim'])\r\n\t\t\t\tmaxV = int(IN['ULim'])\r\n\t\t\t\tdV = float(IN['dV'])\r\n\t\t\t\tV1= np.arange(minV,maxV,dV)\r\n\t\t\t\tprint('***Creating File***')\r\n\t\t\t\tfor V in V1:\r\n\t\t\t\t\tself.V = V\r\n\t\t\t\t\tself.h = self.Ho - (0.5*self.V**2/1000)\r\n\t\t\t\t\tself.Press=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'pressure')\r\n\t\t\t\t\tself.Temp=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'temperature')\r\n\t\t\t\t\tself.rho=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'density')\r\n\t\t\t\t\tself.a=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'soundspeed')\r\n\t\t\t\t\tself.M=self.V/self.a\r\n\t\t\t\t\tself.gamma =fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'gamma')\r\n\t\t\t\t\tWriteDataFile('a',self,'Table.TAB','TAB')\r\n\t\t\t\t\t#pdb.set_trace()\r\n\t\t\t\tprint('***Table Create***')\r\n\t\t\t\tsys.exit(-1)\r\n\t\t\tif IN['Table_Oper']=='Calc':\r\n\t\t\t\tself.h = self.Ho - (0.5*self.V**2/1000)\r\n\t\t\t\tTABProp = np.loadtxt('Table.TAB') #[HARDCODED]\r\n\t\t\t\tfor i in range(len(TABProp)):\r\n\t\t\t\t\tif TABProp[i][0]>self.V:\r\n\t\t\t\t\t\t#print(TABProp[i][0],self.V)\r\n\t\t\t\t\t\tself.M = self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][1],TABProp[i-1][1])\r\n\t\t\t\t\t\tself.rho= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][2],TABProp[i-1][2])\r\n\t\t\t\t\t\tself.a= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][3],TABProp[i-1][3])\r\n\t\t\t\t\t\tself.Temp= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][4],TABProp[i-1][4])\r\n\t\t\t\t\t\tself.Press= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][5],TABProp[i-1][5])\r\n\t\t\t\t\t\tself.gamma= self.Inter(TABProp[i][0],TABProp[i-1][0],TABProp[i][6],TABProp[i-1][6])\r\n\t\t\t\t\t\t#print(self.Temp,self.rho,self.a,self.gamma,self.M)\r\n\t\t\t\t\t\tbreak\r\n\t\t# RefProp = RefProp interpretor via python [Module fluidprop.py]\r\n\t\telif self.GasEqu == 'RefProp':\r\n\t\t\tself.h = self.Ho - (0.5*self.V**2/1000)\r\n\t\t\tself.Press=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'pressure')\r\n\t\t\tself.Temp=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'temperature')\r\n\t\t\tself.rho=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'density')\r\n\t\t\tself.a=fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'soundspeed')\r\n\t\t\tself.M=self.V/self.a\r\n\t\t\t#print(self.M)\r\n\t\t\tself.gamma =fp.fluidprop_py(self.FLD,'hs',self.h,self.s,'gamma')\r\n\t\t# CoolProp = Import fluid Properties using CoolProp\r\n\t\telif self.GasEqu=='CoolProp':\r\n\t\t\tself.h = self.Ho - (0.5*self.V**2/1000)\r\n\t\t\tself.Press = cp.PropsSI('P','H',self.h*1000,'S',self.s*1000,self.FLD)/1e5\r\n\t\t\tself.Temp = cp.PropsSI('T','H',self.h*1000,'S',self.s*1000,self.FLD)-273\r\n\t\t\tself.rho = cp.PropsSI('D','H',self.h*1000,'S',self.s*1000,self.FLD)\r\n\t\t\tself.a = cp.PropsSI('A','H',self.h*1000,'S',self.s*1000,self.FLD)\r\n\t\t\tself.M = self.V/self.a\r\n\t\t\tself.gamma = (cp.PropsSI('CPMASS','H',self.h*1000,'S',self.s*1000,self.FLD)/cp.PropsSI('CVMASS','H',self.h*1000,'S',self.s*1000,self.FLD))\r\n\r\n\t\telif self.GasEqu=='CoolProp-PR':\r\n\t\t\tself.h = self.Ho - (0.5*self.V**2/1000)\r\n\t\t\tself.Press = cp.PropsSI('P','H',self.h*1000,'S',self.s*1000,\"PR::\"+self.FLD)/1e5\r\n\t\t\tself.Temp = cp.PropsSI('T','H',self.h*1000,'S',self.s*1000,\"PR::\"+self.FLD)-273\r\n\t\t\tself.rho = cp.PropsSI('D','H',self.h*1000,'S',self.s*1000,\"PR::\"+self.FLD)\r\n\t\t\tself.a = cp.PropsSI('A','H',self.h*1000,'S',self.s*1000,\"PR::\"+self.FLD)\r\n\t\t\tself.M = self.V/self.a\r\n\t\t\tself.gamma = (cp.PropsSI('CPMASS','H',self.h*1000,'S',self.s*1000,\"PR::\"+self.FLD)/cp.PropsSI('CVMASS','H',self.h*1000,'S',self.s*1000,\"PR::\"+self.FLD))\r\n\r\n\t\t# ERROR Message\r\n\t\telse:\r\n\t\t\tprint(\"\\n\\n\\n\\t*********INVALID INPUT DATA**********\\n\\t *GAS_EQU : PRFT -> Isentropic case \\n\\t *GAS_EQU : EoS -> Equations of State \\n\\t *GAS_EQU : EoS_TAB -> Equations of State using table \\n\\t *GAS_EQU : CoolProp -> Calcuate properties using CoolProp \\n\\t***************************************\\n\\n\\n\")\r\n\t\t\tsys.exit(1)\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Reflex Line position calculator (ReflexZone)\r\n\tdef ReflexLine(self,n,l):\r\n\t\tRetObj = Points()\r\n\t\tRetObj.x = self.x + 1*n*l*calc.cos(((1*calc.asin(1/self.M))+(calc.atan(self.v/self.u))))\r\n\t\tRetObj.y = self.y + 1*n*l*calc.sin(((1*calc.asin(1/self.M))+(calc.atan(self.v/self.u))))\r\n\t\tRetObj.u = self.u\r\n\t\tRetObj.v = 0\r\n\t\treturn(RetObj)\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Check if the characteristic point is inside the nozzle [Exclusive for Reflex Zone]\r\n\tdef PointInPoly(self,poly):\r\n\t\tn = len(poly)\r\n\t\tinside = False\r\n\t\tp1x = poly[0].x\r\n\t\tp1y = poly[0].y\r\n\t\tfor i in range(n+1):\r\n\t\t\tp2x = poly[i % n].x\r\n\t\t\tp2y = poly[i % n].y\r\n\t\t\tif self.y > min(p1y,p2y):\r\n\t\t\t\tif self.y <= max(p1y,p2y):\r\n\t\t\t\t\tif self.x <= max(p1x,p2x):\r\n\t\t\t\t\t\tif p1y != p2y:\r\n\t\t\t\t\t\t\txints = (self.y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x\r\n\t\t\t\t\t\tif p1x == p2x or self.x <= xints:\r\n\t\t\t\t\t\t\tinside = not inside\r\n\t\t\tp1x,p1y = p2x,p2y\r\n\t\treturn inside\r\n\r\n#---------------------------------------------------------------------------------------------#\r\n\t# Liner Interpolation function for Table\r\n\tdef Inter(self,x1,x2,y1,y2):\r\n\t\tif self.GasEqu == 'EoS_TAB':X = self.V\r\n\t\telse: X = self.h\r\n\t\tk=y1+(X-x1)*((y2-y1)/(x2-x1));\r\n\t\treturn(k);\r\n#---------------------------------------------------------------------------------------------#\r\n# Sauer Analysis with RefProp (Ref: Alberto Code) [General Case]\r\n# Guardone 2012, supersonic nozzle design code [point of contact: Matteo Pini]\r\ndef Sauer_RealGas(P):\r\n\tif (P.THROAT=='ITER'):\r\n\t\tif (P.GasEqu=='RefProp' or P.GasEqu=='RefProp_TAB'):\r\n\t\t\tIT_rho = fp.fluidprop_py(P.FLD,'hs',P.Ho,P.s,'density')\r\n\t\t\tIT_T = fp.fluidprop_py(P.FLD,'vs',1/IT_rho,P.s,'temperature')\r\n\t\t\tfor i in range(0,10000):\r\n\t\t\t\tIT_T = fp.fluidprop_py(P.FLD,'vs',1/IT_rho,P.s,'temperature')\r\n\t\t\t\tIT_c = fp.fluidprop_py(P.FLD,'Tv',IT_T,1/IT_rho,'soundspeed')\t\t\t\r\n\t\t\t\tIT_G = fp.fluidprop_py(P.FLD,'Tv',IT_T,1/IT_rho,'gamma')\r\n\t\t\t\tIT_h = fp.fluidprop_py(P.FLD,'Tv',IT_T,1/IT_rho,'enthalpy')\r\n\t\t\t\tIT_P = fp.fluidprop_py(P.FLD,'Tv',IT_T,1/IT_rho,'pressure')\r\n\t\t\t\tf = IT_c**2/2000 +IT_h-P.Ho\r\n\t\t\t\tif i==0: f_tot=f\r\n\t\t\t\tdf = -IT_G*(IT_c**2*IT_rho)\r\n\t\t\t\tIT_v = 1/IT_rho - f/df\r\n\t\t\t\tIT_rho = 1/IT_v\r\n\t\t\t\tprintProgress(f_tot-f,f_tot,'REAL GAS: Sauer Iteration')\r\n\t\t\t\tif (abs(f)<1e-3):\r\n\t\t\t\t\tP.a = IT_c\r\n\t\t\t\t\tP.Press = IT_P\r\n\t\t\t\t\tP.Temp = IT_T\r\n\t\t\t\t\tP.rho = IT_rho\r\n\t\t\t\t\tP.gamma = IT_G\r\n\t\t\t\t\tP.h = IT_h\r\n\t\t\t\t\tprint(\"\\n\\n*****Iteration Summary****\\nsos\\t:%f\\nPress\\t:%f\\nTemp\\t:%f\\nRho\\t:%f\\ngamma\\t:%f\\nh\\t:%f\\n*****Summary End*****\\n\"%(IT_c,IT_P,IT_T,IT_rho,IT_G,IT_h))\r\n\t\t\t\t\tprint(\"Writing Throat Prop. File\\n\\n\")\r\n\t\t\t\t\tf = open('ThroatProp.out','w')\r\n\t\t\t\t\tf.write(\"%.10f\\t%.10f\\t%.10f\\t%.10f\\t%.10f\\t%.10f\\t\"%(IT_c,IT_P,IT_T,IT_rho,IT_G,IT_h,mu))\r\n\t\t\t\t\tf.close()\r\n\t\t\t\t\tbreak\r\n\t\telif (P.GasEqu == 'CoolProp'):\r\n\t\t\t#print('DOING THIS WITH COOLPROP')\r\n\t\t\tIT_rho = cp.PropsSI('D','H',P.Ho*1000,'S',P.s*1000,P.FLD)\r\n\t\t\tIT_T = cp.PropsSI('T','H',P.Ho*1000,'S',P.s*1000,P.FLD)-273\r\n\t\t\t#for i in range(0,10000):\r\n\t\t\tf = 1\r\n\t\t\ti = 0\r\n\t\t\twhile (abs(f)>1e-3):\r\n\t\t\t\tIT_T = cp.PropsSI('T','D',IT_rho,'S',P.s*1000,P.FLD)-273\r\n\t\t\t\tIT_c = cp.PropsSI('A','D',IT_rho,'T',IT_T+273,P.FLD)\r\n\t\t\t\tIT_G = (cp.PropsSI('CPMASS','D',IT_rho,'T',IT_T+273,P.FLD)/cp.PropsSI('CVMASS','D',IT_rho,'T',IT_T+273,P.FLD))\r\n\t\t\t\tIT_h = cp.PropsSI('H','D',IT_rho,'T',IT_T+273,P.FLD)/1000\r\n\t\t\t\tIT_P = cp.PropsSI('P','D',IT_rho,'T',IT_T+273,P.FLD)/1e5\r\n\t\t\t\tf = IT_c**2/2000 +IT_h-P.Ho\r\n\t\t\t\tif i==0: f_tot=f\r\n\t\t\t\tdf = -IT_G*(IT_c**2*IT_rho)\r\n\t\t\t\tIT_v = 1/IT_rho - f/df\r\n\t\t\t\tIT_rho = 1/IT_v\r\n\t\t\t\ti = i+1\r\n\t\t\t\tprintProgress(f_tot-f,f_tot,'REAL GAS: Sauer Iteration')\r\n\t\telif (P.GasEqu == 'CoolProp-PR'):\r\n\t\t\t# print('DOING THIS WITH COOLPROP')\r\n\t\t\tIT_rho = cp.PropsSI('D', 'H', P.Ho * 1000, 'S', P.s * 1000, \"PR::\"+P.FLD)\r\n\t\t\tIT_T = cp.PropsSI('T', 'H', P.Ho * 1000, 'S', P.s * 1000, \"PR::\"+P.FLD) - 273\r\n\t\t\t# for i in range(0,10000):\r\n\t\t\tf = 1\r\n\t\t\ti = 0\r\n\t\t\twhile (abs(f) > 1e-3):\r\n\t\t\t\tIT_T = cp.PropsSI('T', 'D', IT_rho, 'S', P.s * 1000, \"PR::\"+P.FLD) - 273\r\n\t\t\t\tIT_c = cp.PropsSI('A', 'D', IT_rho, 'T', IT_T + 273, \"PR::\"+P.FLD)\r\n\t\t\t\tIT_G = (cp.PropsSI('CPMASS', 'D', IT_rho, 'T', IT_T + 273, \"PR::\"+P.FLD) / cp.PropsSI('CVMASS', 'D', IT_rho,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'T', IT_T + 273, \"PR::\"+P.FLD))\r\n\t\t\t\tIT_h = cp.PropsSI('H', 'D', IT_rho, 'T', IT_T + 273, \"PR::\"+P.FLD) / 1000\r\n\t\t\t\tIT_P = cp.PropsSI('P', 'D', IT_rho, 'T', IT_T + 273, \"PR::\"+P.FLD) / 1e5\r\n\t\t\t\tf = IT_c ** 2 / 2000 + IT_h - P.Ho\r\n\t\t\t\tif i == 0: f_tot = f\r\n\t\t\t\tdf = -IT_G * (IT_c ** 2 * IT_rho)\r\n\t\t\t\tIT_v = 1 / IT_rho - f / df\r\n\t\t\t\tIT_rho = 1 / IT_v\r\n\t\t\t\ti = i + 1\r\n\t\t\t\tprintProgress(f_tot - f, f_tot, 'REAL GAS: Sauer Iteration')\r\n\r\n\t\t\t#print('Sauer finished after '+str(i)+' iterations')\r\n\t\t\t\r\n\t\t\tP.a = IT_c\r\n\t\t\tP.Press = IT_P\r\n\t\t\tP.Temp = IT_T\r\n\t\t\tP.rho = IT_rho\r\n\t\t\tP.gamma = IT_G\r\n\t\t\tP.h = IT_h\r\n\t\t\tmu = cp.PropsSI('V','D',IT_rho,'T',IT_T+273,P.FLD)\r\n\t\t\tprint(\"\\n\\n*****Iteration Summary****\\nsos\\t:%f\\nPress\\t:%f\\nTemp\\t:%f\\nRho\\t:%f\\ngamma\\t:%f\\nh\\t:%f\\n*****Summary End*****\\n\"%(IT_c,IT_P,IT_T,IT_rho,IT_G,IT_h))\r\n\t\t\tprint(\"Writing Throat Prop. File\\n\\n\")\r\n\t\t\tf=open('ThroatProp.out','w')\r\n\t\t\tf.write('Title = MoC Throat Propery File\\nProperties =\\nc\\tP\\tT\\trho\\tG\\th\\tmu\\n')\r\n\t\t\tf.write(\"%.10f\\t%.10f\\t%.10f\\t%.10f\\t%.10f\\t%.10f\\t%.10f\\t\"%(IT_c,IT_P,IT_T,IT_rho,IT_G,IT_h,mu))\r\n\t\t\tf.close()\t\r\n\telse:\r\n\t\tthroat_props = np.loadtxt(P.THROAT)\r\n\t\tP.a = throat_props[0]\r\n\t\tP.Press = throat_props[1]\r\n\t\tP.Temp = throat_props[2]\r\n\t\tP.rho = throat_props[3]\r\n\t\tP.gamma = throat_props[4]\r\n\t\tP.h = throat_props[5]\r\n\r\n\talpha = calc.sqrt((1+P.delta)/(2*(P.gamma*P.rho_t*P.y_t)))\r\n\tepsilon = -alpha*P.y_t*P.gamma/(3+P.delta)\r\n\tP.x = -P.gamma*alpha*P.y**2/(3+P.delta)\r\n\tP.u = P.a*(1+(alpha*P.x+P.gamma*(alpha*P.y)**2/(1+P.delta)))\r\n\tP.v = P.a*((2*P.gamma*alpha**2*P.x*P.y/(1+P.delta))+(2*P.gamma**2*(alpha*P.y)**3)/((1+P.delta)*(3+P.delta)))\r\n\tP.x = P.x-epsilon\r\n\t#print('Epsilon = '+str(epsilon)+' & P.x = '+str(P.x))\r\n\treturn P\r\n\r\n##\r\n## END\r\n##\r\n\r\n"
] | [
[
"numpy.arange",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kentnagumo/LoadSeqFile | [
"5d0efbfb9230442ed4813637c0dbb3b366bfa4e3"
] | [
"util/raw.py"
] | [
"import numpy as np\nimport math\n\ndef raw2temp(raw, meta, out_temp, out_rh, distance):\n \"\"\"\n Convert raw pixel values to temperature, if calibration coefficients are known. The\n equations for atmospheric and window transmission are found in Minkina and Dudzik, as \n well as some of FLIR's documentation.\n\n Roughly ported from ThermImage: https://github.com/gtatters/Thermimage/blob/master/R/raw2temp.R\n\n \"\"\"\n\n ATA1 = float(meta[\"Atmospheric Trans Alpha 1\"])\n ATA2 = float(meta[\"Atmospheric Trans Alpha 2\"])\n ATB1 = float(meta[\"Atmospheric Trans Beta 1\"])\n ATB2 = float(meta[\"Atmospheric Trans Beta 2\"])\n ATX = float(meta[\"Atmospheric Trans X\"])\n PR1 = float(meta[\"Planck R1\"])\n PR2 = float(meta[\"Planck R2\"])\n PO = float(meta[\"Planck O\"])\n PB = float(meta[\"Planck B\"])\n PF = float(meta[\"Planck F\"])\n E = float(meta[\"Emissivity\"])\n IRT = float(meta[\"IR Window Transmission\"])\n IRWTemp = float(meta[\"IR Window Temperature\"].split('C')[0])\n OD = float(meta[\"Object Distance\"].split('m')[0])\n ATemp = float(meta[\"Atmospheric Temperature\"].split('C')[0])\n RTemp = float(meta[\"Reflected Apparent Temperature\"].split('C')[0])\n humidity = float(meta[\"Relative Humidity\"].split('%')[0])\n\n if out_temp != None:\n IRWTemp = out_temp\n ATemp = out_temp\n RTemp = out_temp\n\n if out_rh != None:\n humidity = humidity\n \n if distance != None:\n OD = distance\n\n E = 0.98\n\n # Equations to convert to temperature\n # See http://130.15.24.88/exiftool/forum/index.php/topic,4898.60.html\n # Standard equation: temperature<-PB/log(PR1/(PR2*(raw+PO))+PF)-273.15\n # Other source of information: Minkina and Dudzik's Infrared Thermography: Errors and Uncertainties\n\n window_emissivity = 1 - IRT\n window_reflectivity = 0\n\n # Converts relative humidity into water vapour pressure (mmHg)\n water = (humidity/100.0)*math.exp(1.5587+0.06939*(ATemp)-0.00027816*(ATemp)**2+0.00000068455*(ATemp)**3)\n\n #tau1 = ATX*np.exp(-np.sqrt(OD/2))\n tau1 = ATX*np.exp(-np.sqrt(OD/2)*(ATA1+ATB1*np.sqrt(water)))+(1-ATX)*np.exp(-np.sqrt(OD/2)*(ATA2+ATB2*np.sqrt(water)))\n tau2 = ATX*np.exp(-np.sqrt(OD/2)*(ATA1+ATB1*np.sqrt(water)))+(1-ATX)*np.exp(-np.sqrt(OD/2)*(ATA2+ATB2*np.sqrt(water)))\n\n # transmission through atmosphere - equations from Minkina and Dudzik's Infrared Thermography Book\n # Note: for this script, we assume the thermal window is at the mid-point (OD/2) between the source\n # and the camera sensor\n\n raw_refl = PR1/(PR2*(np.exp(PB/(RTemp+273.15))-PF))-PO # radiance reflecting off the object before the window\n raw_refl_attn = (1-E)/E*raw_refl # attn = the attenuated radiance (in raw units) \n\n raw_atm1 = PR1/(PR2*(np.exp(PB/(ATemp+273.15))-PF))-PO # radiance from the atmosphere (before the window)\n raw_atm1_attn = (1-tau1)/E/tau1*raw_atm1 # attn = the attenuated radiance (in raw units) \n\n raw_window = PR1/(PR2*(math.exp(PB/(IRWTemp+273.15))-PF))-PO\n raw_window_attn = window_emissivity/E/tau1/IRT*raw_window\n\n raw_refl2 = PR1/(PR2*(np.exp(PB/(RTemp+273.15))-PF))-PO \n raw_refl2_attn = window_reflectivity/E/tau1/IRT*raw_refl2\n\n raw_atm2 = PR1/(PR2*(np.exp(PB/(ATemp+273.15))-PF))-PO\n raw_atm2_attn = (1-tau2)/E/tau1/IRT/tau2*raw_atm2\n\n raw_object = raw/E/tau1/IRT/tau2-raw_atm1_attn-raw_atm2_attn-raw_window_attn-raw_refl_attn-raw_refl2_attn\n\n temp = PB/np.log(PR1/(PR2*(raw_object+PO))+PF)-273.15\n\n return temp"
] | [
[
"numpy.log",
"numpy.exp",
"numpy.sqrt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Ahmad1s/FastSpeech2 | [
"d31802ffcd74bb2c2ca57b53e481917989ded6b9"
] | [
"utils/model.py"
] | [
"import os\nimport json\n\nimport torch\nimport numpy as np\n\nimport hifigan\nfrom model import FastSpeech2, ScheduledOptim\nimport gdown\n\n\n\ndef get_model(args, configs, device, train=False):\n (preprocess_config, model_config, train_config) = configs\n\n model = FastSpeech2(preprocess_config, model_config).to(device)\n if args.restore_step:\n ckpt_path = os.path.join(\n train_config[\"path\"][\"ckpt_path\"],\n \"{}.pth.tar\".format(args.restore_step),\n )\n ckpt = torch.load(ckpt_path)\n model.load_state_dict(ckpt[\"model\"])\n\n if train:\n scheduled_optim = ScheduledOptim(\n model, train_config, model_config, args.restore_step\n )\n if args.restore_step:\n scheduled_optim.load_state_dict(ckpt[\"optimizer\"])\n model.train()\n return model, scheduled_optim\n\n model.eval()\n model.requires_grad_ = False\n return model\n\ndef get_model_inference(configs, device, train=False):\n (preprocess_config, model_config, train_config) = configs\n\n model = FastSpeech2(preprocess_config, model_config).to(device)\n url = 'https://drive.google.com/uc?id=1J7ZP_q-6mryXUhZ-8j9-RIItz2nJGOIX'\n ckpt_path = 'model.pth.tar'\n if not os.path.exists(ckpt_path):\n gdown.download(url, ckpt_path, quiet=False) \n ckpt = torch.load(ckpt_path)\n model.load_state_dict(ckpt[\"model\"])\n\n model.eval()\n model.requires_grad_ = False\n return model\n\n\ndef get_param_num(model):\n num_param = sum(param.numel() for param in model.parameters())\n return num_param\n\n\ndef get_vocoder(config, device):\n name = config[\"vocoder\"][\"model\"]\n speaker = config[\"vocoder\"][\"speaker\"]\n\n if name == \"MelGAN\":\n if speaker == \"LJSpeech\":\n vocoder = torch.hub.load(\n \"descriptinc/melgan-neurips\", \"load_melgan\", \"linda_johnson\"\n )\n elif speaker == \"universal\":\n vocoder = torch.hub.load(\n \"descriptinc/melgan-neurips\", \"load_melgan\", \"multi_speaker\"\n )\n vocoder.mel2wav.eval()\n vocoder.mel2wav.to(device)\n elif name == \"HiFi-GAN\":\n with open(\"hifigan/config.json\", \"r\") as f:\n config = json.load(f)\n config = hifigan.AttrDict(config)\n vocoder = hifigan.Generator(config)\n if speaker == \"LJSpeech\":\n ckpt = torch.load(\"hifigan/generator_LJSpeech.pth.tar\")\n elif speaker == \"universal\":\n ckpt = torch.load(\"hifigan/generator_universal.pth.tar\")\n vocoder.load_state_dict(ckpt[\"generator\"])\n vocoder.eval()\n vocoder.remove_weight_norm()\n vocoder.to(device)\n\n return vocoder\n\n\ndef vocoder_infer(mels, vocoder, model_config, preprocess_config, lengths=None):\n name = model_config[\"vocoder\"][\"model\"]\n with torch.no_grad():\n if name == \"MelGAN\":\n wavs = vocoder.inverse(mels / np.log(10))\n elif name == \"HiFi-GAN\":\n wavs = vocoder(mels).squeeze(1)\n\n wavs = (\n wavs.cpu().numpy()\n * preprocess_config[\"preprocessing\"][\"audio\"][\"max_wav_value\"]\n ).astype(\"int16\")\n wavs = [wav for wav in wavs]\n\n for i in range(len(mels)):\n if lengths is not None:\n wavs[i] = wavs[i][: lengths[i]]\n\n return wavs\n"
] | [
[
"numpy.log",
"torch.hub.load",
"torch.no_grad",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
leondz/datasets | [
"4110fb6034f79c5fb470cf1043ff52180e9c63b7"
] | [
"metrics/matthews_correlation/matthews_correlation.py"
] | [
"# Copyright 2021 The HuggingFace Datasets Authors and the current dataset script contributor.\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\"\"\"Matthews Correlation metric.\"\"\"\n\nfrom sklearn.metrics import matthews_corrcoef\n\nimport datasets\n\n\n_DESCRIPTION = \"\"\"\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n\"\"\"\n\n_KWARGS_DESCRIPTION = \"\"\"\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results['matthews_correlation'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results['matthews_correlation'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results['matthews_correlation'], 2))\n -0.25\n\"\"\"\n\n_CITATION = \"\"\"\\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n\"\"\"\n\n\[email protected]_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)\nclass MatthewsCorrelation(datasets.Metric):\n def _info(self):\n return datasets.MetricInfo(\n description=_DESCRIPTION,\n citation=_CITATION,\n inputs_description=_KWARGS_DESCRIPTION,\n features=datasets.Features(\n {\n \"predictions\": datasets.Value(\"int32\"),\n \"references\": datasets.Value(\"int32\"),\n }\n ),\n reference_urls=[\n \"https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html\"\n ],\n )\n\n def _compute(self, predictions, references, sample_weight=None):\n return {\n \"matthews_correlation\": float(matthews_corrcoef(references, predictions, sample_weight=sample_weight)),\n }\n"
] | [
[
"sklearn.metrics.matthews_corrcoef"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
losvedir/gtfs_kit | [
"814ae754a8b048455c6c9c8d33b3e3384e79ce9e"
] | [
"tests/test_validators.py"
] | [
"import pandas as pd\n\nfrom .context import gtfs_kit, sample\nfrom gtfs_kit import *\n\n\ndef test_valid_str():\n assert valid_str(\"hello3\")\n assert not valid_str(np.nan)\n assert not valid_str(\" \")\n\n\ndef test_valid_time():\n assert valid_time(\"2:43:00\")\n assert valid_time(\"22:43:00\")\n assert valid_time(\"42:43:00\")\n assert not valid_time(\"142:43:00\")\n\n\ndef test_valid_date():\n assert valid_date(\"20140310\")\n assert not valid_date(\"2014031\")\n\n\ndef test_valid_timezone():\n assert valid_timezone(\"Africa/Abidjan\")\n assert not valid_timezone(\"zoom\")\n\n\ndef test_valid_lang():\n assert valid_lang(\"aa\")\n assert not valid_lang(\"aaa\")\n\n\ndef test_valid_currency():\n assert valid_currency(\"AED\")\n assert not valid_currency(\"aed\")\n\n\ndef test_valid_url():\n assert valid_url(\"http://www.example.com\")\n assert not valid_url(\"www.example.com\")\n\n\ndef test_valid_email():\n assert valid_email(\"[email protected]\")\n assert not valid_email(\"a@[email protected]\")\n\n\ndef test_valid_color():\n assert valid_color(\"00FFFF\")\n assert not valid_color(\"0FF\")\n assert not valid_color(\"GGFFFF\")\n\n\ndef test_check_for_required_columns():\n assert not check_for_required_columns([], \"routes\", sample.routes)\n\n feed = sample.copy()\n del feed.routes[\"route_type\"]\n assert check_for_required_columns([], \"routes\", feed.routes)\n\n\ndef test_check_for_invalid_columns():\n assert not check_for_invalid_columns([], \"routes\", sample.routes)\n\n feed = sample.copy()\n feed.routes[\"bingo\"] = \"snoop\"\n assert check_for_invalid_columns([], \"routes\", feed.routes)\n\n\ndef test_check_table():\n feed = sample.copy()\n cond = feed.routes[\"route_id\"].isnull()\n assert not check_table([], \"routes\", feed.routes, cond, \"Bingo\")\n assert check_table([], \"routes\", feed.routes, ~cond, \"Bongo\")\n\n\ndef test_check_column():\n feed = sample.copy()\n assert not check_column([], \"agency\", feed.agency, \"agency_url\", valid_url)\n feed.agency[\"agency_url\"].iat[0] = \"example.com\"\n assert check_column([], \"agency\", feed.agency, \"agency_url\", valid_url)\n\n\ndef test_check_column_id():\n feed = sample.copy()\n assert not check_column_id([], \"routes\", feed.routes, \"route_id\")\n feed.routes[\"route_id\"].iat[0] = np.nan\n assert check_column_id([], \"routes\", feed.routes, \"route_id\")\n\n\ndef test_check_column_linked_id():\n feed = sample.copy()\n assert not check_column_linked_id(\n [], \"trips\", feed.trips, \"route_id\", feed.routes\n )\n feed.trips[\"route_id\"].iat[0] = \"Hummus!\"\n assert check_column_linked_id(\n [], \"trips\", feed.trips, \"route_id\", feed.routes\n )\n\n\ndef test_format_problems():\n problems = [(\"ba\", \"da\", \"boom\", \"boom\")]\n assert problems == format_problems(problems, as_df=False)\n\n e = format_problems(problems, as_df=True)\n assert isinstance(e, pd.DataFrame)\n assert e.columns.tolist() == [\"type\", \"message\", \"table\", \"rows\"]\n\n\ndef test_check_agency():\n assert not check_agency(sample)\n\n feed = sample.copy()\n feed.agency = None\n assert check_agency(feed)\n\n feed = sample.copy()\n del feed.agency[\"agency_name\"]\n assert check_agency(feed)\n\n feed = sample.copy()\n feed.agency[\"b\"] = 3\n assert check_agency(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.agency = feed.agency.append(feed.agency.iloc[0])\n assert check_agency(feed)\n\n feed = sample.copy()\n feed.agency[\"agency_name\"] = \"\"\n assert check_agency(feed)\n\n for col in [\n \"agency_timezone\",\n \"agency_url\",\n \"agency_fare_url\",\n \"agency_lang\",\n \"agency_phone\",\n \"agency_email\",\n ]:\n feed = sample.copy()\n feed.agency[col] = \"\"\n assert check_agency(feed)\n\n\ndef test_check_calendar():\n assert not check_calendar(sample)\n assert check_calendar(sample, include_warnings=True) # feed has expired\n\n feed = sample.copy()\n feed.calendar = None\n assert not check_calendar(feed)\n\n feed = sample.copy()\n del feed.calendar[\"service_id\"]\n assert check_calendar(feed)\n\n feed = sample.copy()\n feed.calendar[\"yo\"] = 3\n assert not check_calendar(feed)\n assert check_calendar(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.calendar[\"service_id\"].iat[0] = feed.calendar[\"service_id\"].iat[1]\n assert check_calendar(feed)\n\n for col in [\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n \"sunday\",\n \"start_date\",\n \"end_date\",\n ]:\n feed = sample.copy()\n feed.calendar[col].iat[0] = \"5\"\n assert check_calendar(feed)\n\n\ndef test_check_calendar_dates():\n assert not check_calendar_dates(sample)\n\n feed = sample.copy()\n feed.calendar_dates = None\n assert not check_calendar_dates(feed)\n\n feed = sample.copy()\n del feed.calendar_dates[\"service_id\"]\n assert check_calendar_dates(feed)\n\n feed = sample.copy()\n feed.calendar_dates[\"yo\"] = 3\n assert not check_calendar_dates(feed)\n assert check_calendar_dates(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.calendar_dates = feed.calendar_dates.append(\n feed.calendar_dates.iloc[0]\n )\n assert check_calendar_dates(feed)\n\n for col in [\"date\", \"exception_type\"]:\n feed = sample.copy()\n feed.calendar_dates[col].iat[0] = \"5\"\n assert check_calendar_dates(feed)\n\n\ndef test_check_fare_attributes():\n assert not check_fare_attributes(sample)\n\n feed = sample.copy()\n feed.fare_attributes = None\n assert not check_fare_attributes(feed)\n\n feed = sample.copy()\n del feed.fare_attributes[\"fare_id\"]\n assert check_fare_attributes(feed)\n\n feed = sample.copy()\n feed.fare_attributes[\"yo\"] = 3\n assert not check_fare_attributes(feed)\n assert check_fare_attributes(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.fare_attributes = feed.fare_attributes.append(\n feed.fare_attributes.iloc[0]\n )\n assert check_fare_attributes(feed)\n\n feed = sample.copy()\n feed.fare_attributes[\"currency_type\"] = \"jubjub\"\n assert check_fare_attributes(feed)\n\n for col in [\"payment_method\", \"transfers\", \"transfer_duration\"]:\n feed = sample.copy()\n feed.fare_attributes[col] = -7\n assert check_fare_attributes(feed)\n\n\ndef test_check_fare_rules():\n assert not check_fare_rules(sample)\n\n feed = sample.copy()\n feed.fare_rules = None\n assert not check_fare_rules(feed)\n\n feed = sample.copy()\n del feed.fare_rules[\"fare_id\"]\n assert check_fare_rules(feed)\n\n feed = sample.copy()\n feed.fare_rules[\"yo\"] = 3\n assert not check_fare_rules(feed)\n assert check_fare_rules(feed, include_warnings=True)\n\n for col in [\n \"fare_id\",\n \"route_id\",\n \"origin_id\",\n \"destination_id\",\n \"contains_id\",\n ]:\n feed = sample.copy()\n feed.fare_rules[col] = \"tuberosity\"\n print(col)\n print(feed.fare_rules)\n assert check_fare_rules(feed)\n\n\ndef test_check_feed_info():\n # Create feed_info table\n feed = sample.copy()\n columns = [\n \"feed_publisher_name\",\n \"feed_publisher_url\",\n \"feed_lang\",\n \"feed_start_date\",\n \"feed_end_date\",\n \"feed_version\",\n ]\n rows = [[\"slurp\", \"http://slurp.burp\", \"aa\", \"21110101\", \"21110102\", \"69\"]]\n feed.feed_info = pd.DataFrame(rows, columns=columns)\n assert not check_feed_info(feed)\n\n feed1 = feed.copy()\n feed1.feed_info = None\n assert not check_feed_info(feed1)\n\n feed1 = feed.copy()\n del feed1.feed_info[\"feed_lang\"]\n assert check_feed_info(feed1)\n\n feed1 = feed.copy()\n feed1.feed_info[\"yo\"] = 3\n assert not check_feed_info(feed1)\n assert check_feed_info(feed1, include_warnings=True)\n\n for col in columns:\n feed1 = feed.copy()\n feed1.feed_info[col] = \"\"\n assert check_feed_info(feed1)\n\n\ndef test_check_frequencies():\n assert not check_frequencies(sample)\n\n feed = sample.copy()\n feed.frequencies = None\n assert not check_frequencies(feed)\n\n feed = sample.copy()\n del feed.frequencies[\"trip_id\"]\n assert check_frequencies(feed)\n\n feed = sample.copy()\n feed.frequencies[\"yo\"] = 3\n assert not check_frequencies(feed)\n assert check_frequencies(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.frequencies[\"trip_id\"].iat[0] = \"ratatat\"\n assert check_frequencies(feed)\n\n for col in [\"start_time\", \"end_time\"]:\n feed = sample.copy()\n feed.frequencies[col] = \"07:00:00\"\n assert check_frequencies(feed)\n\n feed = sample.copy()\n feed.frequencies = feed.frequencies.append(feed.frequencies.iloc[0])\n assert check_frequencies(feed)\n\n for col in [\"headway_secs\", \"exact_times\"]:\n feed = sample.copy()\n feed.frequencies[col] = -7\n assert check_frequencies(feed)\n\n\ndef test_check_routes():\n assert not check_routes(sample)\n\n feed = sample.copy()\n feed.routes = None\n assert check_routes(feed)\n\n feed = sample.copy()\n del feed.routes[\"route_id\"]\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"bingo\"] = 3\n assert check_routes(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.routes[\"route_id\"].iat[0] = feed.routes[\"route_id\"].iat[1]\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"agency_id\"] = \"Hubba hubba\"\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"route_short_name\"].iat[0] = \"\"\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"route_short_name\"].iat[0] = \"\"\n feed.routes[\"route_long_name\"].iat[0] = \"\"\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"route_type\"].iat[0] = 8\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"route_color\"].iat[0] = \"FFF\"\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"route_text_color\"].iat[0] = \"FFF\"\n assert check_routes(feed)\n\n feed = sample.copy()\n feed.routes[\"route_short_name\"].iat[1] = feed.routes[\n \"route_short_name\"\n ].iat[0]\n feed.routes[\"route_long_name\"].iat[1] = feed.routes[\"route_long_name\"].iat[\n 0\n ]\n assert not check_routes(feed)\n assert check_routes(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.routes[\"route_id\"].iat[0] = \"Shwing\"\n assert not check_routes(feed)\n assert check_routes(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.agency = None\n assert check_routes(feed)\n\n\ndef test_check_shapes():\n assert not check_shapes(sample)\n\n # Make a nonempty shapes table to check\n feed = sample.copy()\n rows = [\n [\"1100015\", -16.743_632, 145.668_255, 10001, 1.2],\n [\"1100015\", -16.743_522, 145.668_394, 10002, 1.3],\n ]\n columns = [\n \"shape_id\",\n \"shape_pt_lat\",\n \"shape_pt_lon\",\n \"shape_pt_sequence\",\n \"shape_dist_traveled\",\n ]\n feed.shapes = pd.DataFrame(rows, columns=columns)\n assert not check_shapes(feed)\n\n feed1 = feed.copy()\n del feed1.shapes[\"shape_id\"]\n assert check_shapes(feed1)\n\n feed1 = feed.copy()\n feed1.shapes[\"yo\"] = 3\n assert not check_shapes(feed1)\n assert check_shapes(feed1, include_warnings=True)\n\n feed1 = feed.copy()\n feed1.shapes[\"shape_id\"].iat[0] = \"\"\n assert check_shapes(feed1)\n\n for column in [\"shape_pt_lon\", \"shape_pt_lat\"]:\n feed1 = feed.copy()\n feed1.shapes[column] = 185\n assert check_shapes(feed1)\n\n feed1 = feed.copy()\n feed1.shapes[\"shape_pt_sequence\"].iat[1] = feed1.shapes[\n \"shape_pt_sequence\"\n ].iat[0]\n assert check_shapes(feed1)\n\n feed1 = feed.copy()\n feed1.shapes[\"shape_dist_traveled\"].iat[1] = 0\n assert check_shapes(feed1)\n\n feed1 = feed.copy()\n t1 = feed1.shapes.iloc[0].copy()\n t2 = feed1.shapes.iloc[1].copy()\n feed1.shapes.iloc[0] = t2\n feed1.shapes.iloc[1] = t1\n assert not check_shapes(feed1)\n\n\ndef test_check_stops():\n assert not check_stops(sample)\n\n feed = sample.copy()\n feed.stops = None\n assert check_stops(feed)\n\n feed = sample.copy()\n del feed.stops[\"stop_id\"]\n assert check_stops(feed)\n\n feed = sample.copy()\n feed.stops[\"b\"] = 3\n assert check_stops(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.stops[\"stop_id\"].iat[0] = feed.stops[\"stop_id\"].iat[1]\n assert check_stops(feed)\n\n for column in [\"stop_code\", \"stop_desc\", \"zone_id\", \"parent_station\"]:\n feed = sample.copy()\n feed.stops[column] = \"\"\n assert check_stops(feed)\n\n for column in [\"stop_url\", \"stop_timezone\"]:\n feed = sample.copy()\n feed.stops[column] = \"Wa wa\"\n assert check_stops(feed)\n\n for column in [\n \"stop_lon\",\n \"stop_lat\",\n \"location_type\",\n \"wheelchair_boarding\",\n ]:\n feed = sample.copy()\n feed.stops[column] = 185\n assert check_stops(feed)\n\n feed = sample.copy()\n feed.stops[\"parent_station\"] = \"bingo\"\n assert check_stops(feed)\n\n feed = sample.copy()\n feed.stops[\"location_type\"] = 1\n feed.stops[\"parent_station\"] = \"bingo\"\n assert check_stops(feed)\n\n feed = sample.copy()\n feed.stops[\"location_type\"] = 0\n feed.stops[\"parent_station\"] = feed.stops[\"stop_id\"].iat[1]\n assert check_stops(feed)\n\n feed = sample.copy()\n # valid location type\n feed.stops[\"location_type\"] = 2\n assert not check_stops(feed)\n # requires a location\n feed.stops[\"stop_lat\"] = np.NaN\n assert check_stops(feed)\n # valid location_type, does not require location\n feed.stops[\"location_type\"] = 3\n assert not check_stops(feed)\n # valid location_type, does not require location\n feed.stops[\"location_type\"] = 4\n assert not check_stops(feed)\n # location type 4 requires a parent station\n feed.stops[\"parent_station\"] = np.NaN\n assert check_stops(feed)\n # valid parent station for location type 4\n feed.stops[\"stop_lat\"] = 0.0\n feed.stops[\"parent_station\"] = feed.stops[\"stop_id\"].iat[1]\n feed.stops[\"parent_station\"].iat[1] = np.NaN\n feed.stops[\"location_type\"].iat[1] = 1\n assert not check_stops(feed)\n\n feed = sample.copy()\n feed.stops[\"stop_id\"].iat[0] = \"Flippity flew\"\n assert not check_stops(feed)\n assert check_stops(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.stop_times = None\n assert not check_stops(feed)\n assert check_stops(feed, include_warnings=True)\n\n\ndef test_check_stop_times():\n assert not check_stop_times(sample)\n\n feed = sample.copy()\n feed.stop_times = None\n assert check_stop_times(feed)\n\n feed = sample.copy()\n del feed.stop_times[\"stop_id\"]\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"b\"] = 3\n assert check_stop_times(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.stop_times[\"trip_id\"].iat[0] = \"bingo\"\n assert check_stop_times(feed)\n\n for col in [\"arrival_time\", \"departure_time\"]:\n feed = sample.copy()\n feed.stop_times[col].iat[0] = \"1:0:00\"\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"arrival_time\"].iat[-1] = np.nan\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"stop_id\"].iat[0] = \"bingo\"\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"stop_headsign\"].iat[0] = \"\"\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"stop_sequence\"].iat[1] = feed.stop_times[\n \"stop_sequence\"\n ].iat[0]\n assert check_stop_times(feed)\n\n for col in [\"pickup_type\", \"drop_off_type\"]:\n feed = sample.copy()\n feed.stop_times[col] = \"bongo\"\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"shape_dist_traveled\"] = 1\n feed.stop_times[\"shape_dist_traveled\"].iat[1] = 0.9\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"timepoint\"] = 3\n assert check_stop_times(feed)\n\n feed = sample.copy()\n feed.stop_times[\"departure_time\"].iat[1] = feed.stop_times[\n \"departure_time\"\n ].iat[0]\n assert not check_stop_times(feed)\n assert check_stop_times(feed, include_warnings=True)\n\n # Return the correct index of the missing time\n feed = sample.copy()\n # Index 2 is the first stop of the second trip\n # Index 2 is the last stop of the second trip\n feed.stop_times[\"arrival_time\"].iat[6] = np.nan\n t1, t2 = feed.stop_times.iloc[2].copy(), feed.stop_times.iloc[6].copy()\n feed.stop_times.iloc[2], feed.stop_times.iloc[6] = t2, t1\n assert check_stop_times(feed)[0][3][0] == 2\n\n # Check for last stop of last trip\n # Trips are ordered by trip_id so the STBA trip_id from the sample feed\n # is last and its last stop (index 1) is the last row\n feed = sample.copy()\n feed.stop_times[\"arrival_time\"].iat[1] = np.nan\n assert check_stop_times(feed)\n\n\ndef test_check_transfers():\n assert not check_transfers(sample)\n\n # Create transfers table\n feed = sample.copy()\n columns = [\n \"from_stop_id\",\n \"to_stop_id\",\n \"transfer_type\",\n \"min_transfer_time\",\n ]\n rows = [\n [feed.stops[\"stop_id\"].iat[0], feed.stops[\"stop_id\"].iat[1], 2, 3600]\n ]\n feed.transfers = pd.DataFrame(rows, columns=columns)\n assert not check_transfers(feed)\n\n feed1 = feed.copy()\n del feed1.transfers[\"from_stop_id\"]\n assert check_transfers(feed1)\n\n feed1 = feed.copy()\n feed1.transfers[\"yo\"] = 3\n assert not check_transfers(feed1)\n assert check_transfers(feed1, include_warnings=True)\n\n for col in set(columns) - set([\"transfer_type\", \"min_transfer_time\"]):\n feed1 = feed.copy()\n feed1.transfers[col].iat[0] = \"\"\n assert check_transfers(feed1)\n\n for col in [\"transfer_type\", \"min_transfer_time\"]:\n feed1 = feed.copy()\n feed1.transfers[col] = -7\n assert check_transfers(feed1)\n\n\ndef test_check_trips():\n assert not check_trips(sample)\n\n feed = sample.copy()\n feed.trips = None\n assert check_trips(feed)\n\n feed = sample.copy()\n del feed.trips[\"trip_id\"]\n assert check_trips(feed)\n\n feed = sample.copy()\n feed.trips[\"b\"] = 3\n assert check_trips(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.trips[\"trip_id\"].iat[0] = feed.trips[\"trip_id\"].iat[1]\n assert check_trips(feed)\n\n feed = sample.copy()\n feed.trips[\"route_id\"] = \"Hubba hubba\"\n assert check_trips(feed)\n\n feed = sample.copy()\n feed.trips[\"service_id\"] = \"Boom boom\"\n assert check_trips(feed)\n\n feed = sample.copy()\n feed.trips[\"direction_id\"].iat[0] = 7\n assert check_trips(feed)\n\n feed = sample.copy()\n feed.trips[\"block_id\"].iat[0] = \"\"\n assert check_trips(feed)\n\n feed = sample.copy()\n feed.trips[\"shape_id\"].iat[0] = \"Hello\"\n assert check_trips(feed)\n\n feed = sample.copy()\n feed.trips[\"wheelchair_accessible\"] = \"\"\n assert check_trips(feed)\n\n feed = sample.copy()\n tid = feed.trips[\"trip_id\"].iat[0]\n feed.stop_times = feed.stop_times[feed.stop_times[\"trip_id\"] != tid].copy()\n assert not check_trips(feed)\n assert check_trips(feed, include_warnings=True)\n\n feed = sample.copy()\n feed.stop_times = None\n assert not check_trips(feed)\n assert check_trips(feed, include_warnings=True)\n\n\ndef test_validate():\n assert not validate(sample, as_df=False, include_warnings=False)\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
JimStearns206/kivy | [
"f6958b4f9871dd2942d4299276fcab45ef73943b"
] | [
"kivy/core/camera/camera_picamera.py"
] | [
"'''\nPiCamera Camera: Implement CameraBase with PiCamera\n'''\n\n#\n# TODO: make usage of thread or multiprocess\n#\n\n__all__ = ('CameraPiCamera', )\n\nfrom math import ceil\n\nfrom kivy.logger import Logger\nfrom kivy.clock import Clock\nfrom kivy.graphics.texture import Texture\nfrom kivy.core.camera import CameraBase\n\nfrom picamera import PiCamera\nimport numpy\n\n\nclass CameraPiCamera(CameraBase):\n '''Implementation of CameraBase using PiCamera\n '''\n _update_ev = None\n\n def __init__(self, **kwargs):\n self._camera = None\n self._format = 'bgr'\n self._framerate = kwargs.get('framerate', 30)\n super(CameraPiCamera, self).__init__(**kwargs)\n\n def init_camera(self):\n if self._camera is not None:\n self._camera.close()\n\n self._camera = PiCamera()\n self._camera.resolution = self.resolution\n self._camera.framerate = self._framerate\n self._camera.iso = 800\n\n self.fps = 1. / self._framerate\n\n if not self.stopped:\n self.start()\n\n def raw_buffer_size(self):\n '''Round buffer size up to 32x16 blocks.\n\n See https://picamera.readthedocs.io/en/release-1.13/recipes2.html#capturing-to-a-numpy-array\n '''\n return (ceil(self.resolution[0] / 32.) * 32, ceil(self.resolution[1] / 16.) * 16)\n\n def _update(self, dt):\n if self.stopped:\n return\n\n if self._texture is None:\n # Create the texture\n self._texture = Texture.create(self._resolution)\n self._texture.flip_vertical()\n self.dispatch('on_load')\n\n try:\n bufsize = self.raw_buffer_size()\n output = numpy.empty((bufsize[0] * bufsize[1] * 3,), dtype=numpy.uint8)\n self._camera.capture(output, self._format, use_video_port=True)\n\n # Trim the buffer to fit the actual requested resolution.\n # TODO: Is there a simpler way to do all this reshuffling?\n output = output.reshape((bufsize[0], bufsize[1], 3))\n output = output[:self.resolution[0], :self.resolution[1], :]\n self._buffer = output.reshape((self.resolution[0] * self.resolution[1] * 3,))\n\n self._copy_to_gpu()\n except KeyboardInterrupt:\n raise\n except:\n Logger.exception('PiCamera: Couldn\\'t get image from Camera')\n\n def start(self):\n super(CameraPiCamera, self).start()\n if self._update_ev is not None:\n self._update_ev.cancel()\n self._update_ev = Clock.schedule_interval(self._update, self.fps)\n\n def stop(self):\n super(CameraPiCamera, self).stop()\n if self._update_ev is not None:\n self._update_ev.cancel()\n self._update_ev = None\n"
] | [
[
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ageron/addons | [
"c2faddd818280815bd5e47b81742efdfc90e7aaf"
] | [
"tensorflow_addons/seq2seq/beam_search_decoder.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# ==============================================================================\n\"\"\"A decoder that performs beam search.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport numpy as np\n\nimport tensorflow as tf\n\nfrom tensorflow_addons.seq2seq import attention_wrapper\nfrom tensorflow_addons.seq2seq import decoder\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.keras import layers\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import rnn_cell_impl\nfrom tensorflow.python.platform import tf_logging\n\nfrom tensorflow.python.framework import load_library\nfrom tensorflow_addons.utils.resource_loader import get_path_to_datafile\n\n_beam_search_ops_so = load_library.load_op_library(\n get_path_to_datafile(\"custom_ops/seq2seq/_beam_search_ops.so\"))\ngather_tree = _beam_search_ops_so.gather_tree\n\n\nclass BeamSearchDecoderState(\n collections.namedtuple(\"BeamSearchDecoderState\",\n (\"cell_state\", \"log_probs\", \"finished\",\n \"lengths\", \"accumulated_attention_probs\"))):\n pass\n\n\nclass BeamSearchDecoderOutput(\n collections.namedtuple(\"BeamSearchDecoderOutput\",\n (\"scores\", \"predicted_ids\", \"parent_ids\"))):\n pass\n\n\nclass FinalBeamSearchDecoderOutput(\n collections.namedtuple(\n \"FinalBeamDecoderOutput\",\n [\"predicted_ids\", \"beam_search_decoder_output\"])):\n \"\"\"Final outputs returned by the beam search after all decoding is\n finished.\n\n Args:\n predicted_ids: The final prediction. A tensor of shape\n `[batch_size, T, beam_width]` (or `[T, batch_size, beam_width]` if\n `output_time_major` is True). Beams are ordered from best to worst.\n beam_search_decoder_output: An instance of `BeamSearchDecoderOutput` that\n describes the state of the beam search.\n \"\"\"\n pass\n\n\ndef _tile_batch(t, multiplier):\n \"\"\"Core single-tensor implementation of tile_batch.\"\"\"\n t = tf.convert_to_tensor(t, name=\"t\")\n shape_t = tf.shape(t)\n if t.shape.ndims is None or t.shape.ndims < 1:\n raise ValueError(\"t must have statically known rank\")\n tiling = [1] * (t.shape.ndims + 1)\n tiling[1] = multiplier\n tiled_static_batch_size = (t.shape.dims[0].value * multiplier\n if t.shape.dims[0].value is not None else None)\n tiled = tf.tile(tf.expand_dims(t, 1), tiling)\n tiled = tf.reshape(tiled,\n tf.concat(([shape_t[0] * multiplier], shape_t[1:]), 0))\n tiled.set_shape(\n tf.TensorShape([tiled_static_batch_size]).concatenate(t.shape[1:]))\n return tiled\n\n\ndef tile_batch(t, multiplier, name=None):\n \"\"\"Tile the batch dimension of a (possibly nested structure of) tensor(s)\n t.\n\n For each tensor t in a (possibly nested structure) of tensors,\n this function takes a tensor t shaped `[batch_size, s0, s1, ...]` composed\n of minibatch entries `t[0], ..., t[batch_size - 1]` and tiles it to have a\n shape `[batch_size * multiplier, s0, s1, ...]` composed of minibatch\n entries `t[0], t[0], ..., t[1], t[1], ...` where each minibatch entry is\n repeated `multiplier` times.\n\n Args:\n t: `Tensor` shaped `[batch_size, ...]`.\n multiplier: Python int.\n name: Name scope for any created operations.\n\n Returns:\n A (possibly nested structure of) `Tensor` shaped\n `[batch_size * multiplier, ...]`.\n\n Raises:\n ValueError: if tensor(s) `t` do not have a statically known rank or\n the rank is < 1.\n \"\"\"\n flat_t = tf.nest.flatten(t)\n with tf.name_scope(name or \"tile_batch\"):\n return tf.nest.map_structure(lambda t_: _tile_batch(t_, multiplier), t)\n\n\ndef gather_tree_from_array(t, parent_ids, sequence_length):\n \"\"\"Calculates the full beams for `TensorArray`s.\n\n Args:\n t: A stacked `TensorArray` of size `max_time` that contains `Tensor`s of\n shape `[batch_size, beam_width, s]` or `[batch_size * beam_width, s]`\n where `s` is the depth shape.\n parent_ids: The parent ids of shape `[max_time, batch_size, beam_width]`.\n sequence_length: The sequence length of shape `[batch_size, beam_width]`.\n\n Returns:\n A `Tensor` which is a stacked `TensorArray` of the same size and type as\n `t` and where beams are sorted in each `Tensor` according to\n `parent_ids`.\n \"\"\"\n max_time = parent_ids.shape.dims[0].value or tf.shape(parent_ids)[0]\n batch_size = parent_ids.shape.dims[1].value or tf.shape(parent_ids)[1]\n beam_width = parent_ids.shape.dims[2].value or tf.shape(parent_ids)[2]\n\n # Generate beam ids that will be reordered by gather_tree.\n beam_ids = tf.expand_dims(tf.expand_dims(tf.range(beam_width), 0), 0)\n beam_ids = tf.tile(beam_ids, [max_time, batch_size, 1])\n\n max_sequence_lengths = tf.cast(\n tf.reduce_max(sequence_length, axis=1), tf.int32)\n sorted_beam_ids = gather_tree(\n step_ids=beam_ids,\n parent_ids=parent_ids,\n max_sequence_lengths=max_sequence_lengths,\n end_token=beam_width + 1)\n\n # For out of range steps, simply copy the same beam.\n in_bound_steps = tf.transpose(\n tf.sequence_mask(sequence_length, maxlen=max_time), perm=[2, 0, 1])\n sorted_beam_ids = tf.where(in_bound_steps, x=sorted_beam_ids, y=beam_ids)\n\n # Generate indices for gather_nd.\n time_ind = tf.tile(\n tf.reshape(tf.range(max_time), [-1, 1, 1]),\n [1, batch_size, beam_width])\n batch_ind = tf.tile(\n tf.reshape(tf.range(batch_size), [-1, 1, 1]),\n [1, max_time, beam_width])\n batch_ind = tf.transpose(batch_ind, perm=[1, 0, 2])\n indices = tf.stack([time_ind, batch_ind, sorted_beam_ids], -1)\n\n # Gather from a tensor with collapsed additional dimensions.\n gather_from = t\n final_shape = tf.shape(gather_from)\n gather_from = tf.reshape(gather_from,\n [max_time, batch_size, beam_width, -1])\n ordered = tf.gather_nd(gather_from, indices)\n ordered = tf.reshape(ordered, final_shape)\n\n return ordered\n\n\ndef _check_ndims(t):\n if t.shape.ndims is None:\n raise ValueError(\n \"Expected tensor (%s) to have known rank, but ndims == None.\" % t)\n\n\ndef _check_static_batch_beam_maybe(shape, batch_size, beam_width):\n \"\"\"Raises an exception if dimensions are known statically and can not be\n reshaped to [batch_size, beam_size, -1].\"\"\"\n reshaped_shape = tf.TensorShape([batch_size, beam_width, None])\n if (batch_size is not None and shape.dims[0].value is not None\n and (shape[0] != batch_size * beam_width or\n (shape.ndims >= 2 and shape.dims[1].value is not None and\n (shape[0] != batch_size or shape[1] != beam_width)))):\n tf_logging.warn(\n \"TensorArray reordering expects elements to be \"\n \"reshapable to %s which is incompatible with the \"\n \"current shape %s. Consider setting \"\n \"reorder_tensor_arrays to False to disable TensorArray \"\n \"reordering during the beam search.\" % (reshaped_shape, shape))\n return False\n return True\n\n\ndef _check_batch_beam(t, batch_size, beam_width):\n \"\"\"Returns an Assert operation checking that the elements of the stacked\n TensorArray can be reshaped to [batch_size, beam_size, -1].\n\n At this point, the TensorArray elements have a known rank of at\n least 1.\n \"\"\"\n error_message = (\n \"TensorArray reordering expects elements to be \"\n \"reshapable to [batch_size, beam_size, -1] which is \"\n \"incompatible with the dynamic shape of %s elements. \"\n \"Consider setting reorder_tensor_arrays to False to disable \"\n \"TensorArray reordering during the beam search.\" %\n (t if context.executing_eagerly() else t.name))\n rank = t.shape.ndims\n shape = tf.shape(t)\n if rank == 2:\n condition = tf.equal(shape[1], batch_size * beam_width)\n else:\n condition = tf.logical_or(\n tf.equal(shape[1], batch_size * beam_width),\n tf.logical_and(\n tf.equal(shape[1], batch_size), tf.equal(shape[2],\n beam_width)))\n return tf.Assert(condition, [error_message])\n\n\nclass BeamSearchDecoderMixin(object):\n \"\"\"BeamSearchDecoderMixin contains the common methods for\n BeamSearchDecoder.\n\n It is expected to be used a base class for concrete\n BeamSearchDecoder. Since this is a mixin class, it is expected to be\n used together with other class as base.\n \"\"\"\n\n def __init__(self,\n cell,\n beam_width,\n output_layer=None,\n length_penalty_weight=0.0,\n coverage_penalty_weight=0.0,\n reorder_tensor_arrays=True,\n **kwargs):\n \"\"\"Initialize the BeamSearchDecoderMixin.\n\n Args:\n cell: An `RNNCell` instance.\n beam_width: Python integer, the number of beams.\n output_layer: (Optional) An instance of `tf.keras.layers.Layer`,\n i.e., `tf.keras.layers.Dense`. Optional layer to apply to the RNN\n output prior to storing the result or sampling.\n length_penalty_weight: Float weight to penalize length. Disabled with\n 0.0.\n coverage_penalty_weight: Float weight to penalize the coverage of\n source sentence. Disabled with 0.0.\n reorder_tensor_arrays: If `True`, `TensorArray`s' elements within the\n cell state will be reordered according to the beam search path. If\n the `TensorArray` can be reordered, the stacked form will be\n returned. Otherwise, the `TensorArray` will be returned as is. Set\n this flag to `False` if the cell state contains `TensorArray`s that\n are not amenable to reordering.\n **kwargs: Dict, other keyword arguments for parent class.\n\n Raises:\n TypeError: if `cell` is not an instance of `RNNCell`,\n or `output_layer` is not an instance of `tf.keras.layers.Layer`.\n \"\"\"\n rnn_cell_impl.assert_like_rnncell(\"cell\", cell) # pylint: disable=protected-access\n if (output_layer is not None\n and not isinstance(output_layer, layers.Layer)):\n raise TypeError(\"output_layer must be a Layer, received: %s\" %\n type(output_layer))\n self._cell = cell\n self._output_layer = output_layer\n self._reorder_tensor_arrays = reorder_tensor_arrays\n\n self._start_tokens = None\n self._end_token = None\n self._batch_size = None\n self._beam_width = beam_width\n self._length_penalty_weight = length_penalty_weight\n self._coverage_penalty_weight = coverage_penalty_weight\n super(BeamSearchDecoderMixin, self).__init__(**kwargs)\n\n @property\n def batch_size(self):\n return self._batch_size\n\n def _rnn_output_size(self):\n \"\"\"Get the output shape from the RNN layer.\"\"\"\n size = self._cell.output_size\n if self._output_layer is None:\n return size\n else:\n # To use layer's compute_output_shape, we need to convert the\n # RNNCell's output_size entries into shapes with an unknown\n # batch size. We then pass this through the layer's\n # compute_output_shape and read off all but the first (batch)\n # dimensions to get the output size of the rnn with the layer\n # applied to the top.\n output_shape_with_unknown_batch = tf.nest.map_structure(\n lambda s: tf.TensorShape([None]).concatenate(s), size)\n layer_output_shape = self._output_layer.compute_output_shape(\n output_shape_with_unknown_batch)\n return tf.nest.map_structure(lambda s: s[1:], layer_output_shape)\n\n @property\n def tracks_own_finished(self):\n \"\"\"The BeamSearchDecoder shuffles its beams and their finished state.\n\n For this reason, it conflicts with the `dynamic_decode` function's\n tracking of finished states. Setting this property to true avoids\n early stopping of decoding due to mismanagement of the finished state\n in `dynamic_decode`.\n\n Returns:\n `True`.\n \"\"\"\n return True\n\n @property\n def output_size(self):\n # Return the cell output and the id\n return BeamSearchDecoderOutput(\n scores=tf.TensorShape([self._beam_width]),\n predicted_ids=tf.TensorShape([self._beam_width]),\n parent_ids=tf.TensorShape([self._beam_width]))\n\n def finalize(self, outputs, final_state, sequence_lengths):\n \"\"\"Finalize and return the predicted_ids.\n\n Args:\n outputs: An instance of BeamSearchDecoderOutput.\n final_state: An instance of BeamSearchDecoderState. Passed through to\n the output.\n sequence_lengths: An `int64` tensor shaped\n `[batch_size, beam_width]`. The sequence lengths determined for\n each beam during decode. **NOTE** These are ignored; the updated\n sequence lengths are stored in `final_state.lengths`.\n\n Returns:\n outputs: An instance of `FinalBeamSearchDecoderOutput` where the\n predicted_ids are the result of calling _gather_tree.\n final_state: The same input instance of `BeamSearchDecoderState`.\n \"\"\"\n del sequence_lengths\n # Get max_sequence_length across all beams for each batch.\n max_sequence_lengths = tf.cast(\n tf.reduce_max(final_state.lengths, axis=1), tf.int32)\n predicted_ids = gather_tree(\n outputs.predicted_ids,\n outputs.parent_ids,\n max_sequence_lengths=max_sequence_lengths,\n end_token=self._end_token)\n if self._reorder_tensor_arrays:\n final_state = final_state._replace(\n cell_state=tf.nest.map_structure(\n lambda t: self._maybe_sort_array_beams(\n t, outputs.parent_ids, final_state.lengths),\n final_state.cell_state))\n outputs = FinalBeamSearchDecoderOutput(\n beam_search_decoder_output=outputs, predicted_ids=predicted_ids)\n return outputs, final_state\n\n def _merge_batch_beams(self, t, s=None):\n \"\"\"Merges the tensor from a batch of beams into a batch by beams.\n\n More exactly, t is a tensor of dimension [batch_size, beam_width, s].\n We reshape this into [batch_size*beam_width, s]\n\n Args:\n t: Tensor of dimension [batch_size, beam_width, s]\n s: (Possibly known) depth shape.\n\n Returns:\n A reshaped version of t with dimension [batch_size * beam_width, s].\n \"\"\"\n if isinstance(s, tf.Tensor):\n s = tensor_shape.as_shape(tensor_util.constant_value(s))\n else:\n s = tf.TensorShape(s)\n t_shape = tf.shape(t)\n static_batch_size = tensor_util.constant_value(self._batch_size)\n batch_size_beam_width = (None if static_batch_size is None else\n static_batch_size * self._beam_width)\n reshaped_t = tf.reshape(\n t,\n tf.concat(([self._batch_size * self._beam_width], t_shape[2:]), 0))\n reshaped_t.set_shape(\n (tf.TensorShape([batch_size_beam_width]).concatenate(s)))\n return reshaped_t\n\n def _split_batch_beams(self, t, s=None):\n \"\"\"Splits the tensor from a batch by beams into a batch of beams.\n\n More exactly, t is a tensor of dimension [batch_size*beam_width, s]. We\n reshape this into [batch_size, beam_width, s]\n\n Args:\n t: Tensor of dimension [batch_size*beam_width, s].\n s: (Possibly known) depth shape.\n\n Returns:\n A reshaped version of t with dimension [batch_size, beam_width, s].\n\n Raises:\n ValueError: If, after reshaping, the new tensor is not shaped\n `[batch_size, beam_width, s]` (assuming batch_size and beam_width\n are known statically).\n \"\"\"\n if isinstance(s, tf.Tensor):\n s = tf.TensorShape(tensor_util.constant_value(s))\n else:\n s = tf.TensorShape(s)\n t_shape = tf.shape(t)\n reshaped_t = tf.reshape(\n t, tf.concat(([self._batch_size, self._beam_width], t_shape[1:]),\n 0))\n static_batch_size = tensor_util.constant_value(self._batch_size)\n expected_reshaped_shape = tf.TensorShape(\n [static_batch_size, self._beam_width]).concatenate(s)\n if not reshaped_t.shape.is_compatible_with(expected_reshaped_shape):\n raise ValueError(\n \"Unexpected behavior when reshaping between beam width \"\n \"and batch size. The reshaped tensor has shape: %s. \"\n \"We expected it to have shape \"\n \"(batch_size, beam_width, depth) == %s. Perhaps you \"\n \"forgot to call get_initial_state with \"\n \"batch_size=encoder_batch_size * beam_width?\" %\n (reshaped_t.shape, expected_reshaped_shape))\n reshaped_t.set_shape(expected_reshaped_shape)\n return reshaped_t\n\n def _maybe_split_batch_beams(self, t, s):\n \"\"\"Maybe splits the tensor from a batch by beams into a batch of beams.\n\n We do this so that we can use nest and not run into problems with\n shapes.\n\n Args:\n t: `Tensor`, either scalar or shaped `[batch_size * beam_width] + s`.\n s: `Tensor`, Python int, or `TensorShape`.\n\n Returns:\n If `t` is a matrix or higher order tensor, then the return value is\n `t` reshaped to `[batch_size, beam_width] + s`. Otherwise `t` is\n returned unchanged.\n\n Raises:\n ValueError: If the rank of `t` is not statically known.\n \"\"\"\n if isinstance(t, tf.TensorArray):\n return t\n _check_ndims(t)\n if t.shape.ndims >= 1:\n return self._split_batch_beams(t, s)\n else:\n return t\n\n def _maybe_merge_batch_beams(self, t, s):\n \"\"\"Splits the tensor from a batch by beams into a batch of beams.\n\n More exactly, `t` is a tensor of dimension\n `[batch_size * beam_width] + s`, then we reshape it to\n `[batch_size, beam_width] + s`.\n\n Args:\n t: `Tensor` of dimension `[batch_size * beam_width] + s`.\n s: `Tensor`, Python int, or `TensorShape`.\n\n Returns:\n A reshaped version of t with shape `[batch_size, beam_width] + s`.\n\n Raises:\n ValueError: If the rank of `t` is not statically known.\n \"\"\"\n if isinstance(t, tf.TensorArray):\n return t\n _check_ndims(t)\n if t.shape.ndims >= 2:\n return self._merge_batch_beams(t, s)\n else:\n return t\n\n def _maybe_sort_array_beams(self, t, parent_ids, sequence_length):\n \"\"\"Maybe sorts beams within a `TensorArray`.\n\n Args:\n t: A `TensorArray` of size `max_time` that contains `Tensor`s of\n shape `[batch_size, beam_width, s]` or\n `[batch_size * beam_width, s]` where `s` is the depth shape.\n parent_ids: The parent ids of shape\n `[max_time, batch_size, beam_width]`.\n sequence_length: The sequence length of shape\n `[batch_size, beam_width]`.\n\n Returns:\n A `TensorArray` where beams are sorted in each `Tensor` or `t` itself\n if it is not a `TensorArray` or does not meet shape requirements.\n \"\"\"\n if not isinstance(t, tf.TensorArray):\n return t\n # pylint: disable=protected-access\n # This is a bad hack due to the implementation detail of eager/graph TA.\n # TODO(b/124374427): Update this to use public property of TensorArray.\n if context.executing_eagerly():\n element_shape = t._element_shape\n else:\n element_shape = t._element_shape[0]\n if (not t._infer_shape or not t._element_shape\n or element_shape.ndims is None or element_shape.ndims < 1):\n shape = (element_shape if t._infer_shape and t._element_shape else\n tf.TensorShape(None))\n tf_logging.warn(\n \"The TensorArray %s in the cell state is not amenable to \"\n \"sorting based on the beam search result. For a \"\n \"TensorArray to be sorted, its elements shape must be \"\n \"defined and have at least a rank of 1, but saw shape: %s\" %\n (t.handle.name, shape))\n return t\n # pylint: enable=protected-access\n if not _check_static_batch_beam_maybe(\n element_shape, tensor_util.constant_value(self._batch_size),\n self._beam_width):\n return t\n t = t.stack()\n with tf.control_dependencies(\n [_check_batch_beam(t, self._batch_size, self._beam_width)]):\n return gather_tree_from_array(t, parent_ids, sequence_length)\n\n def step(self, time, inputs, state, name=None):\n \"\"\"Perform a decoding step.\n\n Args:\n time: scalar `int32` tensor.\n inputs: A (structure of) input tensors.\n state: A (structure of) state tensors and TensorArrays.\n name: Name scope for any created operations.\n\n Returns:\n `(outputs, next_state, next_inputs, finished)`.\n \"\"\"\n batch_size = self._batch_size\n beam_width = self._beam_width\n end_token = self._end_token\n length_penalty_weight = self._length_penalty_weight\n coverage_penalty_weight = self._coverage_penalty_weight\n\n with tf.name_scope(name or \"BeamSearchDecoderStep\"):\n cell_state = state.cell_state\n inputs = tf.nest.map_structure(\n lambda inp: self._merge_batch_beams(inp, s=inp.shape[2:]),\n inputs)\n cell_state = tf.nest.map_structure(self._maybe_merge_batch_beams,\n cell_state,\n self._cell.state_size)\n cell_outputs, next_cell_state = self._cell(inputs, cell_state)\n cell_outputs = tf.nest.map_structure(\n lambda out: self._split_batch_beams(out, out.shape[1:]),\n cell_outputs)\n next_cell_state = tf.nest.map_structure(\n self._maybe_split_batch_beams, next_cell_state,\n self._cell.state_size)\n\n if self._output_layer is not None:\n cell_outputs = self._output_layer(cell_outputs)\n\n beam_search_output, beam_search_state = _beam_search_step(\n time=time,\n logits=cell_outputs,\n next_cell_state=next_cell_state,\n beam_state=state,\n batch_size=batch_size,\n beam_width=beam_width,\n end_token=end_token,\n length_penalty_weight=length_penalty_weight,\n coverage_penalty_weight=coverage_penalty_weight)\n\n finished = beam_search_state.finished\n sample_ids = beam_search_output.predicted_ids\n next_inputs = tf.cond(\n tf.reduce_all(finished), lambda: self._start_inputs, lambda:\n self._embedding_fn(sample_ids))\n\n return (beam_search_output, beam_search_state, next_inputs, finished)\n\n\nclass BeamSearchDecoder(BeamSearchDecoderMixin, decoder.BaseDecoder):\n # Note that the inheritance hierarchy is important here. The Mixin has to be\n # the first parent class since we will use super().__init__(), and Mixin\n # which is a object will properly invoke the __init__ method of other parent\n # class.\n \"\"\"BeamSearch sampling decoder.\n\n **NOTE** If you are using the `BeamSearchDecoder` with a cell wrapped in\n `AttentionWrapper`, then you must ensure that:\n\n - The encoder output has been tiled to `beam_width` via\n `tf.contrib.seq2seq.tile_batch` (NOT `tf.tile`).\n - The `batch_size` argument passed to the `get_initial_state` method of\n this wrapper is equal to `true_batch_size * beam_width`.\n - The initial state created with `get_initial_state` above contains a\n `cell_state` value containing properly tiled final state from the\n encoder.\n\n An example:\n\n ```\n tiled_encoder_outputs = tf.contrib.seq2seq.tile_batch(\n encoder_outputs, multiplier=beam_width)\n tiled_encoder_final_state = tf.contrib.seq2seq.tile_batch(\n encoder_final_state, multiplier=beam_width)\n tiled_sequence_length = tf.contrib.seq2seq.tile_batch(\n sequence_length, multiplier=beam_width)\n attention_mechanism = MyFavoriteAttentionMechanism(\n num_units=attention_depth,\n memory=tiled_inputs,\n memory_sequence_length=tiled_sequence_length)\n attention_cell = AttentionWrapper(cell, attention_mechanism, ...)\n decoder_initial_state = attention_cell.get_initial_state(\n batch_size=true_batch_size * beam_width, dtype=dtype)\n decoder_initial_state = decoder_initial_state.clone(\n cell_state=tiled_encoder_final_state)\n ```\n\n Meanwhile, with `AttentionWrapper`, coverage penalty is suggested to use\n when computing scores (https://arxiv.org/pdf/1609.08144.pdf). It encourages\n the decoding to cover all inputs.\n \"\"\"\n\n def __init__(self,\n cell,\n beam_width,\n embedding_fn=None,\n output_layer=None,\n length_penalty_weight=0.0,\n coverage_penalty_weight=0.0,\n reorder_tensor_arrays=True,\n **kwargs):\n \"\"\"Initialize the BeamSearchDecoder.\n\n Args:\n cell: An `RNNCell` instance.\n beam_width: Python integer, the number of beams.\n embedding_fn: A callable that takes a vector tensor of `ids`\n (argmax ids).\n output_layer: (Optional) An instance of `tf.keras.layers.Layer`,\n i.e., `tf.keras.layers.Dense`. Optional layer to apply to the RNN\n output prior to storing the result or sampling.\n length_penalty_weight: Float weight to penalize length. Disabled with\n 0.0.\n coverage_penalty_weight: Float weight to penalize the coverage of\n source sentence. Disabled with 0.0.\n reorder_tensor_arrays: If `True`, `TensorArray`s' elements within the\n cell state will be reordered according to the beam search path. If\n the `TensorArray` can be reordered, the stacked form will be\n returned. Otherwise, the `TensorArray` will be returned as is. Set\n this flag to `False` if the cell state contains `TensorArray`s that\n are not amenable to reordering.\n **kwargs: Dict, other keyword arguments for initialization.\n\n Raises:\n TypeError: if `cell` is not an instance of `RNNCell`,\n or `output_layer` is not an instance of `tf.keras.layers.Layer`.\n \"\"\"\n super(BeamSearchDecoder, self).__init__(\n cell,\n beam_width,\n output_layer=output_layer,\n length_penalty_weight=length_penalty_weight,\n coverage_penalty_weight=coverage_penalty_weight,\n reorder_tensor_arrays=reorder_tensor_arrays,\n **kwargs)\n\n if embedding_fn is None or callable(embedding_fn):\n self._embedding_fn = embedding_fn\n else:\n raise ValueError(\n \"embedding_fn is expected to be a callable, got %s\" %\n type(embedding_fn))\n\n def initialize(self, embedding, start_tokens, end_token, initial_state):\n \"\"\"Initialize the decoder.\n\n Args:\n embedding: A tensor from the embedding layer output, which is the\n `params` argument for `embedding_lookup`.\n start_tokens: `int32` vector shaped `[batch_size]`, the start tokens.\n end_token: `int32` scalar, the token that marks end of decoding.\n initial_state: A (possibly nested tuple of...) tensors and\n TensorArrays.\n Returns:\n `(finished, start_inputs, initial_state)`.\n Raises:\n ValueError: If `start_tokens` is not a vector or `end_token` is not a\n scalar.\n \"\"\"\n if embedding is not None and self._embedding_fn is not None:\n raise ValueError(\n \"embedding and embedding_fn cannot be provided at same time\")\n elif embedding is not None:\n self._embedding_fn = (\n lambda ids: embedding_ops.embedding_lookup(embedding, ids))\n\n self._start_tokens = tf.convert_to_tensor(\n start_tokens, dtype=tf.int32, name=\"start_tokens\")\n if self._start_tokens.get_shape().ndims != 1:\n raise ValueError(\"start_tokens must be a vector\")\n self._end_token = tf.convert_to_tensor(\n end_token, dtype=tf.int32, name=\"end_token\")\n if self._end_token.get_shape().ndims != 0:\n raise ValueError(\"end_token must be a scalar\")\n\n self._batch_size = tf.size(start_tokens)\n self._initial_cell_state = tf.nest.map_structure(\n self._maybe_split_batch_beams, initial_state,\n self._cell.state_size)\n self._start_tokens = tf.tile(\n tf.expand_dims(self._start_tokens, 1), [1, self._beam_width])\n self._start_inputs = self._embedding_fn(self._start_tokens)\n\n self._finished = tf.one_hot(\n tf.zeros([self._batch_size], dtype=tf.int32),\n depth=self._beam_width,\n on_value=False,\n off_value=True,\n dtype=tf.bool)\n\n finished, start_inputs = self._finished, self._start_inputs\n\n dtype = tf.nest.flatten(self._initial_cell_state)[0].dtype\n log_probs = tf.one_hot( # shape(batch_sz, beam_sz)\n tf.zeros([self._batch_size], dtype=tf.int32),\n depth=self._beam_width,\n on_value=tf.convert_to_tensor(0.0, dtype=dtype),\n off_value=tf.convert_to_tensor(-np.Inf, dtype=dtype),\n dtype=dtype)\n init_attention_probs = get_attention_probs(\n self._initial_cell_state, self._coverage_penalty_weight)\n if init_attention_probs is None:\n init_attention_probs = ()\n\n initial_state = BeamSearchDecoderState(\n cell_state=self._initial_cell_state,\n log_probs=log_probs,\n finished=finished,\n lengths=tf.zeros([self._batch_size, self._beam_width],\n dtype=tf.int64),\n accumulated_attention_probs=init_attention_probs)\n\n return (finished, start_inputs, initial_state)\n\n @property\n def output_dtype(self):\n # Assume the dtype of the cell is the output_size structure\n # containing the input_state's first component's dtype.\n # Return that structure and int32 (the id)\n dtype = tf.nest.flatten(self._initial_cell_state)[0].dtype\n return BeamSearchDecoderOutput(\n scores=tf.nest.map_structure(lambda _: dtype,\n self._rnn_output_size()),\n predicted_ids=tf.int32,\n parent_ids=tf.int32)\n\n def call(self, embeddning, start_tokens, end_token, initial_state,\n **kwargs):\n init_kwargs = kwargs\n init_kwargs[\"start_tokens\"] = start_tokens\n init_kwargs[\"end_token\"] = end_token\n init_kwargs[\"initial_state\"] = initial_state\n return decoder.dynamic_decode(\n self,\n output_time_major=self.output_time_major,\n impute_finished=self.impute_finished,\n maximum_iterations=self.maximum_iterations,\n parallel_iterations=self.parallel_iterations,\n swap_memory=self.swap_memory,\n decoder_init_input=embeddning,\n decoder_init_kwargs=init_kwargs)\n\n\ndef _beam_search_step(time, logits, next_cell_state, beam_state, batch_size,\n beam_width, end_token, length_penalty_weight,\n coverage_penalty_weight):\n \"\"\"Performs a single step of Beam Search Decoding.\n\n Args:\n time: Beam search time step, should start at 0. At time 0 we assume\n that all beams are equal and consider only the first beam for\n continuations.\n logits: Logits at the current time step. A tensor of shape\n `[batch_size, beam_width, vocab_size]`\n next_cell_state: The next state from the cell, e.g. an instance of\n AttentionWrapperState if the cell is attentional.\n beam_state: Current state of the beam search.\n An instance of `BeamSearchDecoderState`.\n batch_size: The batch size for this input.\n beam_width: Python int. The size of the beams.\n end_token: The int32 end token.\n length_penalty_weight: Float weight to penalize length. Disabled with\n 0.0.\n coverage_penalty_weight: Float weight to penalize the coverage of source\n sentence. Disabled with 0.0.\n\n Returns:\n A new beam state.\n \"\"\"\n static_batch_size = tensor_util.constant_value(batch_size)\n\n # Calculate the current lengths of the predictions\n prediction_lengths = beam_state.lengths\n previously_finished = beam_state.finished\n not_finished = tf.logical_not(previously_finished)\n\n # Calculate the total log probs for the new hypotheses\n # Final Shape: [batch_size, beam_width, vocab_size]\n step_log_probs = tf.nn.log_softmax(logits)\n step_log_probs = _mask_probs(step_log_probs, end_token,\n previously_finished)\n total_probs = tf.expand_dims(beam_state.log_probs, 2) + step_log_probs\n\n # Calculate the continuation lengths by adding to all continuing beams.\n vocab_size = logits.shape.dims[-1].value or tf.shape(logits)[-1]\n lengths_to_add = tf.one_hot(\n indices=tf.fill([batch_size, beam_width], end_token),\n depth=vocab_size,\n on_value=np.int64(0),\n off_value=np.int64(1),\n dtype=tf.int64)\n add_mask = tf.cast(not_finished, tf.int64)\n lengths_to_add *= tf.expand_dims(add_mask, 2)\n new_prediction_lengths = (\n lengths_to_add + tf.expand_dims(prediction_lengths, 2))\n\n # Calculate the accumulated attention probabilities if coverage penalty is\n # enabled.\n accumulated_attention_probs = None\n attention_probs = get_attention_probs(next_cell_state,\n coverage_penalty_weight)\n if attention_probs is not None:\n attention_probs *= tf.expand_dims(tf.cast(not_finished, tf.float32), 2)\n accumulated_attention_probs = (\n beam_state.accumulated_attention_probs + attention_probs)\n\n # Calculate the scores for each beam\n scores = _get_scores(\n log_probs=total_probs,\n sequence_lengths=new_prediction_lengths,\n length_penalty_weight=length_penalty_weight,\n coverage_penalty_weight=coverage_penalty_weight,\n finished=previously_finished,\n accumulated_attention_probs=accumulated_attention_probs)\n\n time = tf.convert_to_tensor(time, name=\"time\")\n # During the first time step we only consider the initial beam\n scores_flat = tf.reshape(scores, [batch_size, -1])\n\n # Pick the next beams according to the specified successors function\n next_beam_size = tf.convert_to_tensor(\n beam_width, dtype=tf.int32, name=\"beam_width\")\n next_beam_scores, word_indices = tf.math.top_k(\n scores_flat, k=next_beam_size)\n\n next_beam_scores.set_shape([static_batch_size, beam_width])\n word_indices.set_shape([static_batch_size, beam_width])\n\n # Pick out the probs, beam_ids, and states according to the chosen\n # predictions\n next_beam_probs = _tensor_gather_helper(\n gather_indices=word_indices,\n gather_from=total_probs,\n batch_size=batch_size,\n range_size=beam_width * vocab_size,\n gather_shape=[-1],\n name=\"next_beam_probs\")\n # Note: just doing the following\n # tf.to_int32(word_indices % vocab_size,\n # name=\"next_beam_word_ids\")\n # would be a lot cleaner but for reasons unclear, that hides the results of\n # the op which prevents capturing it with tfdbg debug ops.\n raw_next_word_ids = tf.mod(\n word_indices, vocab_size, name=\"next_beam_word_ids\")\n next_word_ids = tf.cast(raw_next_word_ids, tf.int32)\n next_beam_ids = tf.cast(\n word_indices / vocab_size, tf.int32, name=\"next_beam_parent_ids\")\n\n # Append new ids to current predictions\n previously_finished = _tensor_gather_helper(\n gather_indices=next_beam_ids,\n gather_from=previously_finished,\n batch_size=batch_size,\n range_size=beam_width,\n gather_shape=[-1])\n next_finished = tf.logical_or(\n previously_finished,\n tf.equal(next_word_ids, end_token),\n name=\"next_beam_finished\")\n\n # Calculate the length of the next predictions.\n # 1. Finished beams remain unchanged.\n # 2. Beams that are now finished (EOS predicted) have their length\n # increased by 1.\n # 3. Beams that are not yet finished have their length increased by 1.\n lengths_to_add = tf.cast(tf.logical_not(previously_finished), tf.int64)\n next_prediction_len = _tensor_gather_helper(\n gather_indices=next_beam_ids,\n gather_from=beam_state.lengths,\n batch_size=batch_size,\n range_size=beam_width,\n gather_shape=[-1])\n next_prediction_len += lengths_to_add\n next_accumulated_attention_probs = ()\n if accumulated_attention_probs is not None:\n next_accumulated_attention_probs = _tensor_gather_helper(\n gather_indices=next_beam_ids,\n gather_from=accumulated_attention_probs,\n batch_size=batch_size,\n range_size=beam_width,\n gather_shape=[batch_size * beam_width, -1],\n name=\"next_accumulated_attention_probs\")\n\n # Pick out the cell_states according to the next_beam_ids. We use a\n # different gather_shape here because the cell_state tensors, i.e.\n # the tensors that would be gathered from, all have dimension\n # greater than two and we need to preserve those dimensions.\n next_cell_state = tf.nest.map_structure(\n lambda gather_from: _maybe_tensor_gather_helper(\n gather_indices=next_beam_ids,\n gather_from=gather_from,\n batch_size=batch_size,\n range_size=beam_width,\n gather_shape=[batch_size * beam_width, -1]), next_cell_state)\n\n next_state = BeamSearchDecoderState(\n cell_state=next_cell_state,\n log_probs=next_beam_probs,\n lengths=next_prediction_len,\n finished=next_finished,\n accumulated_attention_probs=next_accumulated_attention_probs)\n\n output = BeamSearchDecoderOutput(\n scores=next_beam_scores,\n predicted_ids=next_word_ids,\n parent_ids=next_beam_ids)\n\n return output, next_state\n\n\ndef get_attention_probs(next_cell_state, coverage_penalty_weight):\n \"\"\"Get attention probabilities from the cell state.\n\n Args:\n next_cell_state: The next state from the cell, e.g. an instance of\n AttentionWrapperState if the cell is attentional.\n coverage_penalty_weight: Float weight to penalize the coverage of source\n sentence. Disabled with 0.0.\n\n Returns:\n The attention probabilities with shape\n `[batch_size, beam_width, max_time]` if coverage penalty is enabled.\n Otherwise, returns None.\n\n Raises:\n ValueError: If no cell is attentional but coverage penalty is enabled.\n \"\"\"\n if coverage_penalty_weight == 0.0:\n return None\n\n # Attention probabilities of each attention layer. Each with shape\n # `[batch_size, beam_width, max_time]`.\n probs_per_attn_layer = []\n if isinstance(next_cell_state, attention_wrapper.AttentionWrapperState):\n probs_per_attn_layer = [\n attention_probs_from_attn_state(next_cell_state)\n ]\n elif isinstance(next_cell_state, tuple):\n for state in next_cell_state:\n if isinstance(state, attention_wrapper.AttentionWrapperState):\n probs_per_attn_layer.append(\n attention_probs_from_attn_state(state))\n\n if not probs_per_attn_layer:\n raise ValueError(\n \"coverage_penalty_weight must be 0.0 if no cell is attentional.\")\n\n if len(probs_per_attn_layer) == 1:\n attention_probs = probs_per_attn_layer[0]\n else:\n # Calculate the average attention probabilities from all attention\n # layers.\n attention_probs = [\n tf.expand_dims(prob, -1) for prob in probs_per_attn_layer\n ]\n attention_probs = tf.concat(attention_probs, -1)\n attention_probs = tf.reduce_mean(attention_probs, -1)\n\n return attention_probs\n\n\ndef _get_scores(log_probs, sequence_lengths, length_penalty_weight,\n coverage_penalty_weight, finished,\n accumulated_attention_probs):\n \"\"\"Calculates scores for beam search hypotheses.\n\n Args:\n log_probs: The log probabilities with shape\n `[batch_size, beam_width, vocab_size]`.\n sequence_lengths: The array of sequence lengths.\n length_penalty_weight: Float weight to penalize length. Disabled with\n 0.0.\n coverage_penalty_weight: Float weight to penalize the coverage of source\n sentence. Disabled with 0.0.\n finished: A boolean tensor of shape `[batch_size, beam_width]` that\n specifies which elements in the beam are finished already.\n accumulated_attention_probs: Accumulated attention probabilities up to\n the current time step, with shape `[batch_size, beam_width, max_time]`\n if coverage_penalty_weight is not 0.0.\n\n Returns:\n The scores normalized by the length_penalty and coverage_penalty.\n\n Raises:\n ValueError: accumulated_attention_probs is None when coverage penalty is\n enabled.\n \"\"\"\n length_penalty_ = _length_penalty(\n sequence_lengths=sequence_lengths,\n penalty_factor=length_penalty_weight)\n length_penalty_ = tf.cast(length_penalty_, dtype=log_probs.dtype)\n scores = log_probs / length_penalty_\n\n coverage_penalty_weight = tf.convert_to_tensor(\n coverage_penalty_weight, name=\"coverage_penalty_weight\")\n if coverage_penalty_weight.shape.ndims != 0:\n raise ValueError(\"coverage_penalty_weight should be a scalar, \"\n \"but saw shape: %s\" % coverage_penalty_weight.shape)\n\n if tensor_util.constant_value(coverage_penalty_weight) == 0.0:\n return scores\n\n if accumulated_attention_probs is None:\n raise ValueError(\n \"accumulated_attention_probs can be None only if coverage penalty \"\n \"is disabled.\")\n\n # Add source sequence length mask before computing coverage penalty.\n accumulated_attention_probs = tf.where(\n tf.equal(accumulated_attention_probs, 0.0),\n tf.ones_like(accumulated_attention_probs), accumulated_attention_probs)\n\n # coverage penalty =\n # sum over `max_time` {log(min(accumulated_attention_probs, 1.0))}\n coverage_penalty = tf.reduce_sum(\n tf.math.log(tf.minimum(accumulated_attention_probs, 1.0)), 2)\n # Apply coverage penalty to finished predictions.\n coverage_penalty *= tf.cast(finished, tf.float32)\n weighted_coverage_penalty = coverage_penalty * coverage_penalty_weight\n # Reshape from [batch_size, beam_width] to [batch_size, beam_width, 1]\n weighted_coverage_penalty = tf.expand_dims(weighted_coverage_penalty, 2)\n return scores + weighted_coverage_penalty\n\n\ndef attention_probs_from_attn_state(attention_state):\n \"\"\"Calculates the average attention probabilities.\n\n Args:\n attention_state: An instance of `AttentionWrapperState`.\n\n Returns:\n The attention probabilities in the given AttentionWrapperState.\n If there're multiple attention mechanisms, return the average value from\n all attention mechanisms.\n \"\"\"\n # Attention probabilities over time steps, with shape\n # `[batch_size, beam_width, max_time]`.\n attention_probs = attention_state.alignments\n if isinstance(attention_probs, tuple):\n attention_probs = [\n tf.expand_dims(prob, -1) for prob in attention_probs\n ]\n attention_probs = tf.concat(attention_probs, -1)\n attention_probs = tf.reduce_mean(attention_probs, -1)\n return attention_probs\n\n\ndef _length_penalty(sequence_lengths, penalty_factor):\n \"\"\"Calculates the length penalty. See https://arxiv.org/abs/1609.08144.\n\n Returns the length penalty tensor:\n ```\n [(5+sequence_lengths)/6]**penalty_factor\n ```\n where all operations are performed element-wise.\n\n Args:\n sequence_lengths: `Tensor`, the sequence lengths of each hypotheses.\n penalty_factor: A scalar that weights the length penalty.\n\n Returns:\n If the penalty is `0`, returns the scalar `1.0`. Otherwise returns\n the length penalty factor, a tensor with the same shape as\n `sequence_lengths`.\n \"\"\"\n penalty_factor = tf.convert_to_tensor(\n penalty_factor, name=\"penalty_factor\")\n penalty_factor.set_shape(()) # penalty should be a scalar.\n static_penalty = tensor_util.constant_value(penalty_factor)\n if static_penalty is not None and static_penalty == 0:\n return 1.0\n return tf.math.divide(\n (5. + tf.cast(sequence_lengths, tf.float32))**penalty_factor,\n (5. + 1.)**penalty_factor)\n\n\ndef _mask_probs(probs, eos_token, finished):\n \"\"\"Masks log probabilities.\n\n The result is that finished beams allocate all probability mass to eos and\n unfinished beams remain unchanged.\n\n Args:\n probs: Log probabilities of shape `[batch_size, beam_width, vocab_size]`\n eos_token: An int32 id corresponding to the EOS token to allocate\n probability to.\n finished: A boolean tensor of shape `[batch_size, beam_width]` that\n specifies which elements in the beam are finished already.\n\n Returns:\n A tensor of shape `[batch_size, beam_width, vocab_size]`, where\n unfinished beams stay unchanged and finished beams are replaced with a\n tensor with all probability on the EOS token.\n \"\"\"\n vocab_size = tf.shape(probs)[2]\n # All finished examples are replaced with a vector that has all\n # probability on EOS\n finished_row = tf.one_hot(\n eos_token,\n vocab_size,\n dtype=probs.dtype,\n on_value=tf.convert_to_tensor(0., dtype=probs.dtype),\n off_value=probs.dtype.min)\n finished_probs = tf.tile(\n tf.reshape(finished_row, [1, 1, -1]),\n tf.concat([tf.shape(finished), [1]], 0))\n finished_mask = tf.tile(tf.expand_dims(finished, 2), [1, 1, vocab_size])\n\n return tf.where(finished_mask, finished_probs, probs)\n\n\ndef _maybe_tensor_gather_helper(gather_indices, gather_from, batch_size,\n range_size, gather_shape):\n \"\"\"Maybe applies _tensor_gather_helper.\n\n This applies _tensor_gather_helper when the gather_from dims is at least as\n big as the length of gather_shape. This is used in conjunction with nest so\n that we don't apply _tensor_gather_helper to inapplicable values like\n scalars.\n\n Args:\n gather_indices: The tensor indices that we use to gather.\n gather_from: The tensor that we are gathering from.\n batch_size: The batch size.\n range_size: The number of values in each range. Likely equal to\n beam_width.\n gather_shape: What we should reshape gather_from to in order to preserve\n the correct values. An example is when gather_from is the attention\n from an AttentionWrapperState with shape\n [batch_size, beam_width, attention_size]. There, we want to preserve\n the attention_size elements, so gather_shape is\n [batch_size * beam_width, -1]. Then, upon reshape, we still have the\n attention_size as desired.\n\n Returns:\n output: Gathered tensor of shape\n tf.shape(gather_from)[:1+len(gather_shape)] or the original tensor if\n its dimensions are too small.\n \"\"\"\n if isinstance(gather_from, tf.TensorArray):\n return gather_from\n _check_ndims(gather_from)\n if gather_from.shape.ndims >= len(gather_shape):\n return _tensor_gather_helper(\n gather_indices=gather_indices,\n gather_from=gather_from,\n batch_size=batch_size,\n range_size=range_size,\n gather_shape=gather_shape)\n else:\n return gather_from\n\n\ndef _tensor_gather_helper(gather_indices,\n gather_from,\n batch_size,\n range_size,\n gather_shape,\n name=None):\n \"\"\"Helper for gathering the right indices from the tensor.\n\n This works by reshaping gather_from to gather_shape (e.g. [-1]) and then\n gathering from that according to the gather_indices, which are offset by\n the right amounts in order to preserve the batch order.\n\n Args:\n gather_indices: The tensor indices that we use to gather.\n gather_from: The tensor that we are gathering from.\n batch_size: The input batch size.\n range_size: The number of values in each range. Likely equal to\n beam_width.\n gather_shape: What we should reshape gather_from to in order to preserve\n the correct values. An example is when gather_from is the attention\n from an AttentionWrapperState with shape\n [batch_size, beam_width, attention_size]. There, we want to preserve\n the attention_size elements, so gather_shape is\n [batch_size * beam_width, -1]. Then, upon reshape, we still have the\n attention_size as desired.\n name: The tensor name for set of operations. By default this is\n 'tensor_gather_helper'. The final output is named 'output'.\n\n Returns:\n output: Gathered tensor of shape\n tf.shape(gather_from)[:1+len(gather_shape)]\n \"\"\"\n with tf.name_scope(name or \"tensor_gather_helper\"):\n range_ = tf.expand_dims(tf.range(batch_size) * range_size, 1)\n gather_indices = tf.reshape(gather_indices + range_, [-1])\n output = tf.gather(\n tf.reshape(gather_from, gather_shape), gather_indices)\n final_shape = tf.shape(gather_from)[:1 + len(gather_shape)]\n static_batch_size = tensor_util.constant_value(batch_size)\n final_static_shape = (tf.TensorShape([static_batch_size]).concatenate(\n gather_from.shape[1:1 + len(gather_shape)]))\n output = tf.reshape(output, final_shape, name=\"output\")\n output.set_shape(final_static_shape)\n return output\n"
] | [
[
"tensorflow.convert_to_tensor",
"tensorflow.concat",
"tensorflow.nn.log_softmax",
"tensorflow.Assert",
"tensorflow.zeros",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.equal",
"tensorflow.minimum",
"tensorflow.python.ops.rnn_cell_impl.assert_like_rnncell",
"tensorflow.where",
"tensorflow.nest.flatten",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.name_scope",
"tensorflow.python.ops.embedding_ops.embedding_lookup",
"tensorflow.logical_not",
"tensorflow.tile",
"tensorflow.TensorShape",
"tensorflow.fill",
"tensorflow.gather_nd",
"tensorflow.shape",
"numpy.int64",
"tensorflow.sequence_mask",
"tensorflow.size",
"tensorflow.reduce_max",
"tensorflow.transpose",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.reduce_mean",
"tensorflow.range",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.expand_dims",
"tensorflow.mod",
"tensorflow.math.top_k",
"tensorflow.reduce_all",
"tensorflow.nest.map_structure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
surajpaib/vissl | [
"2aea1d73d51e2a5e3fcbfa6b5d025d17c7aaa748"
] | [
"vissl/utils/misc.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates.\n\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport collections\nimport importlib\nimport logging\nimport os\nimport random\nimport sys\nimport tempfile\nimport time\nfrom functools import partial, wraps\nfrom pathlib import Path\nfrom typing import Tuple\n\nimport numpy as np\nimport pkg_resources\nimport torch\nimport torch.multiprocessing as mp\nfrom iopath.common.file_io import g_pathmgr\nfrom scipy.sparse import csr_matrix\nfrom vissl.utils.extract_features_utils import ExtractedFeaturesLoader\n\n\ndef is_fairscale_sharded_available():\n \"\"\"\n Check if the fairscale version has the ShardedGradScaler()\n to use with ZeRO + PyTorchAMP\n \"\"\"\n try:\n from fairscale.optim.grad_scaler import ShardedGradScaler # NOQA\n\n fairscale_sharded_available = True\n except ImportError:\n fairscale_sharded_available = False\n return fairscale_sharded_available\n\n\ndef is_faiss_available():\n \"\"\"\n Check if faiss is available with simple python imports.\n\n To install faiss, simply do:\n If using PIP env: `pip install faiss-gpu`\n If using conda env: `conda install faiss-gpu -c pytorch`\n \"\"\"\n try:\n import faiss # NOQA\n\n faiss_available = True\n except ImportError:\n faiss_available = False\n return faiss_available\n\n\ndef is_opencv_available():\n \"\"\"\n Check if opencv is available with simple python imports.\n\n To install opencv, simply do: `pip install opencv-python`\n regardless of whether using conda or pip environment.\n \"\"\"\n try:\n import cv2 # NOQA\n\n opencv_available = True\n except ImportError:\n opencv_available = False\n return opencv_available\n\n\ndef is_apex_available():\n \"\"\"\n Check if apex is available with simple python imports.\n \"\"\"\n try:\n import apex # NOQA\n\n apex_available = True\n except ImportError:\n apex_available = False\n return apex_available\n\n\ndef is_augly_available():\n \"\"\"\n Check if apex is available with simple python imports.\n \"\"\"\n try:\n assert sys.version_info >= (\n 3,\n 7,\n 0,\n ), \"Please upgrade your python version to 3.7 or higher to use Augly.\"\n\n import augly.image # NOQA\n\n augly_available = True\n except (AssertionError, ImportError):\n augly_available = False\n return augly_available\n\n\ndef is_monai_available():\n \"\"\"\n Check if apex is available with simple python imports.\n \"\"\"\n try:\n import monai.transforms # NOQA\n\n monai_available = True\n except (AssertionError, ImportError):\n monai_available = False\n return monai_available\n\n\ndef find_free_tcp_port():\n \"\"\"\n Find the free port that can be used for Rendezvous on the local machine.\n We use this for 1 machine training where the port is automatically detected.\n \"\"\"\n import socket\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # Binding to port 0 will cause the OS to find an available port for us\n sock.bind((\"\", 0))\n port = sock.getsockname()[1]\n sock.close()\n # NOTE: there is still a chance the port could be taken by other processes.\n return port\n\n\ndef get_dist_run_id(cfg, num_nodes):\n \"\"\"\n For multi-gpu training with PyTorch, we have to specify\n how the gpus are going to rendezvous. This requires specifying\n the communication method: file, tcp and the unique rendezvous run_id that\n is specific to 1 run.\n\n We recommend:\n 1) for 1-node: use init_method=tcp and run_id=auto\n 2) for multi-node, use init_method=tcp and specify run_id={master_node}:{port}\n \"\"\"\n init_method = cfg.DISTRIBUTED.INIT_METHOD\n run_id = cfg.DISTRIBUTED.RUN_ID\n if init_method == \"tcp\" and cfg.DISTRIBUTED.RUN_ID == \"auto\":\n assert (\n num_nodes == 1\n ), \"cfg.DISTRIBUTED.RUN_ID=auto is allowed for 1 machine only.\"\n port = find_free_tcp_port()\n run_id = f\"localhost:{port}\"\n elif init_method == \"file\":\n if num_nodes > 1:\n logging.warning(\n \"file is not recommended to use for distributed training on > 1 node\"\n )\n # Find a unique tempfile if needed.\n if not run_id or run_id == \"auto\":\n unused_fno, run_id = tempfile.mkstemp()\n elif init_method == \"tcp\" and cfg.DISTRIBUTED.NUM_NODES > 1:\n assert cfg.DISTRIBUTED.RUN_ID, \"please specify RUN_ID for tcp\"\n elif init_method == \"env\":\n assert num_nodes == 1, \"can not use 'env' init method for multi-node. Use tcp\"\n return run_id\n\n\ndef setup_multiprocessing_method(method_name: str):\n \"\"\"\n PyTorch supports several multiprocessing options: forkserver | spawn | fork\n\n We recommend and use forkserver as the default method in VISSL.\n \"\"\"\n try:\n mp.set_start_method(method_name, force=True)\n logging.info(\"Set start method of multiprocessing to {}\".format(method_name))\n except RuntimeError:\n pass\n\n\ndef set_seeds(cfg, dist_rank):\n \"\"\"\n Set the python random, numpy and torch seed for each gpu. Also set the CUDA\n seeds if the CUDA is available. This ensures deterministic nature of the training.\n \"\"\"\n # Since in the pytorch sampler, we increment the seed by 1 for every epoch.\n seed_value = (cfg.SEED_VALUE + dist_rank) * cfg.OPTIMIZER.num_epochs\n logging.info(f\"MACHINE SEED: {seed_value}\")\n random.seed(seed_value)\n np.random.seed(seed_value)\n torch.manual_seed(seed_value)\n if cfg[\"MACHINE\"][\"DEVICE\"] == \"gpu\" and torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed_value)\n\n\ndef set_dataloader_seeds(_worker_id: int):\n \"\"\"\n See: https://tanelp.github.io/posts/a-bug-that-plagues-thousands-of-open-source-ml-projects/\n When using \"Fork\" process spawning, the dataloader workers inherit the seeds of the\n parent process for numpy. While torch seeds are handled correctly across dataloaders and\n across epochs, numpy seeds are not. Therefore in order to ensure each worker has a\n different and deterministic seed, we must explicitly set the numpy seed to the torch seed.\n Also see https://pytorch.org/docs/stable/data.html#randomness-in-multi-process-data-loading\n \"\"\"\n # numpy and random seed must be between 0 and 2 ** 32 - 1.\n torch_seed = torch.utils.data.get_worker_info().seed % (2 ** 32)\n random.seed(torch_seed)\n np.random.seed(torch_seed)\n\n\ndef get_indices_sparse(data):\n \"\"\"\n Is faster than np.argwhere. Used in loss functions like swav loss, etc\n \"\"\"\n cols = np.arange(data.size)\n M = csr_matrix((cols, (data.ravel(), cols)), shape=(data.max() + 1, data.size))\n return [np.unravel_index(row.data, data.shape) for row in M]\n\n\ndef merge_features(input_dir: str, split: str, layer: str):\n return ExtractedFeaturesLoader.load_features(input_dir, split, layer)\n\n\ndef get_json_catalog_path(default_dataset_catalog_path: str) -> str:\n \"\"\"\n Gets dataset catalog json file absolute path.\n Optionally set environment variable VISSL_DATASET_CATALOG_PATH for dataset catalog path.\n Useful for local development and/or remote server configuration.\n \"\"\"\n dataset_catalog_path = os.environ.get(\n \"VISSL_DATASET_CATALOG_PATH\", default_dataset_catalog_path\n )\n\n # If catalog path is the default and we cannot find it, we want to continue without failing.\n if os.environ.get(\"VISSL_DATASET_CATALOG_PATH\", False):\n assert g_pathmgr.exists(\n dataset_catalog_path\n ), f\"Dataset catalog path: { dataset_catalog_path } not found.\"\n\n return dataset_catalog_path\n\n\ndef get_json_data_catalog_file():\n \"\"\"\n Searches for the dataset_catalog.json file that contains information about\n the dataset paths if set by user.\n \"\"\"\n default_path = pkg_resources.resource_filename(\n \"configs\", \"config/dataset_catalog.json\"\n )\n json_catalog_path = get_json_catalog_path(default_path)\n\n return json_catalog_path\n\n\[email protected]_grad()\ndef concat_all_gather(tensor):\n \"\"\"\n Performs all_gather operation on the provided tensors.\n *** Warning ***: torch.distributed.all_gather has no gradient.\n \"\"\"\n tensors_gather = [\n torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())\n ]\n torch.distributed.all_gather(tensors_gather, tensor, async_op=False)\n\n output = torch.cat(tensors_gather, dim=0)\n return output\n\n\ndef get_rng_state():\n state = {\"torch_rng_state\": torch.get_rng_state()}\n if torch.cuda.is_available():\n state[\"cuda_rng_state\"] = torch.cuda.get_rng_state()\n return state\n\n\ndef set_rng_state(state):\n torch.set_rng_state(state[\"torch_rng_state\"])\n if torch.cuda.is_available():\n torch.cuda.set_rng_state(state[\"cuda_rng_state\"])\n\n\nclass set_torch_seed(object):\n def __init__(self, seed):\n assert isinstance(seed, int)\n self.rng_state = get_rng_state()\n\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(seed)\n\n def __enter__(self):\n return self\n\n def __exit__(self, *exc):\n set_rng_state(self.rng_state)\n\n\n# Credit: https://stackoverflow.com/questions/42521549/retry-function-in-python\ndef retry(func=None, exception=Exception, n_tries=5, delay=5, backoff=1, logger=False):\n \"\"\"Retry decorator with exponential backoff.\n\n Parameters\n ----------\n func : typing.Callable, optional\n Callable on which the decorator is applied, by default None\n exception : Exception or tuple of Exceptions, optional\n Exception(s) that invoke retry, by default Exception\n n_tries : int, optional\n Number of tries before giving up, by default 5\n delay : int, optional\n Initial delay between retries in seconds, by default 5\n backoff : int, optional\n Backoff multiplier e.g. value of 2 will double the delay, by default 1\n logger : bool, optional\n Option to log or print, by default False\n\n Returns\n -------\n typing.Callable\n Decorated callable that calls itself when exception(s) occur.\n\n Examples\n --------\n >>> import random\n >>> @retry(exception=Exception, n_tries=4)\n ... def test_random(text):\n ... x = random.random()\n ... if x < 0.5:\n ... raise Exception(\"Fail\")\n ... else:\n ... print(\"Success: \", text)\n >>> test_random(\"It works!\")\n \"\"\"\n\n if func is None:\n return partial(\n retry,\n exception=exception,\n n_tries=n_tries,\n delay=delay,\n backoff=backoff,\n logger=logger,\n )\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n ntries, ndelay = n_tries, delay\n\n while ntries > 1:\n try:\n return func(*args, **kwargs)\n except exception as e:\n msg = f\"{str(e)}, Retrying in {ndelay} seconds...\"\n if logger:\n logging.warning(msg)\n else:\n print(msg)\n time.sleep(ndelay)\n ntries -= 1\n ndelay *= backoff\n\n return func(*args, **kwargs)\n\n return wrapper\n\n\n# Credit: https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys # NOQA\ndef flatten_dict(d: dict, parent_key=\"\", sep=\"_\"):\n \"\"\"\n Flattens a dict, delimited with a '_'. For example the input:\n {\n 'top_1': {\n 'res_5': 100\n }\n }\n\n will return:\n\n {\n 'top_1_res_5': 100\n }\n \"\"\"\n items = []\n for k, v in d.items():\n new_key = parent_key + sep + k if parent_key else k\n if isinstance(v, collections.MutableMapping):\n items.extend(flatten_dict(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\n\n# Credit: https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries\ndef recursive_dict_merge(dict1, dict2):\n \"\"\"\n Recursively merges dict2 into dict1\n \"\"\"\n if not isinstance(dict1, dict) or not isinstance(dict2, dict):\n return dict2\n for k in dict2:\n if k in dict1:\n dict1[k] = recursive_dict_merge(dict1[k], dict2[k])\n else:\n dict1[k] = dict2[k]\n return dict1\n\n\ndef torch_version() -> Tuple[int, ...]:\n numbering = torch.__version__.split(\"+\")[0].split(\".\")[:3]\n\n # Catch torch version if run against internal pre-releases, like `1.8.0a0fb`,\n if not numbering[2].isnumeric():\n # Two options here:\n # - either skip this version (minor number check is not relevant)\n # - or check that our codebase is not broken by this ongoing development.\n\n # Assuming that we're interested in the second usecase more than the first,\n # return the pre-release or dev numbering\n numbering[2] = \"0\"\n\n return tuple(int(n) for n in numbering)\n\n\ndef add_cwd_modules(folder):\n \"\"\"\n Adds modules from the current working dir. This is useful for \n custom project imports with cluttering the vissl package\n \"\"\"\n import_dir = Path(os.getcwd()) / folder / \"__init__.py\"\n\n spec = importlib.util.spec_from_file_location(folder, str(import_dir))\n project_module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(project_module)\n sys.modules[folder] = project_module\n\n logging.info(f\"Add custom module from {import_dir}\")\n"
] | [
[
"torch.set_rng_state",
"torch.__version__.split",
"torch.cat",
"torch.no_grad",
"torch.cuda.is_available",
"torch.cuda.manual_seed_all",
"torch.multiprocessing.set_start_method",
"numpy.arange",
"torch.utils.data.get_worker_info",
"numpy.unravel_index",
"torch.cuda.set_rng_state",
"torch.ones_like",
"torch.get_rng_state",
"torch.distributed.get_world_size",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.distributed.all_gather",
"torch.cuda.get_rng_state"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amcdawes/maxwellbloch | [
"48b5301ccfa24704a4240125d377b1448d5591d9",
"48b5301ccfa24704a4240125d377b1448d5591d9"
] | [
"maxwellbloch/tests/test_hyperfine.py",
"maxwellbloch/tests/test_t_funcs.py"
] | [
"\"\"\" \nUnit tests for the hyperfine module. \n\nThomas Ogden <[email protected]>\n\"\"\"\n\nimport unittest\n\nimport numpy as np\n\nfrom maxwellbloch import hyperfine\n\n \nclass TestAtom1eAddFLevel(unittest.TestCase):\n \"\"\" Unit tests of the Atom1e.add_F_level method. \"\"\"\n\n def test_Rb87_5s12_5p12(self):\n \"\"\" TODO: put a levels diagram here. \"\"\"\n\n Rb87_5s12_5p12 = hyperfine.Atom1e(element='Rb', isotope='87')\n # Create F levels and add to atom\n Rb87_5s12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5s12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n Rb87_5p12_F1 = hyperfine.LevelF(I=1.5, J=1.5, F=1)\n Rb87_5p12_F2 = hyperfine.LevelF(I=1.5, J=1.5, F=2)\n Rb87_5s12_5p12.add_F_level(Rb87_5s12_F1)\n Rb87_5s12_5p12.add_F_level(Rb87_5s12_F2)\n Rb87_5s12_5p12.add_F_level(Rb87_5p12_F1)\n Rb87_5s12_5p12.add_F_level(Rb87_5p12_F2)\n\n self.assertEqual(Rb87_5s12_5p12.get_num_mF_levels(), 16)\n\n map = [0]*3 + [1]*5 + [2]*3 + [3]*5\n self.assertEqual(Rb87_5s12_5p12.get_F_level_idx_map(), map)\n\n self.assertEqual(len(Rb87_5s12_5p12.get_coupled_levels([0], [2])), 3*3)\n self.assertEqual(len(Rb87_5s12_5p12.get_coupled_levels([0], [3])), 3*5)\n\n self.assertEqual(len(Rb87_5s12_5p12.get_coupled_levels([0], [2, 3])), \n 3*8)\n self.assertEqual(len(Rb87_5s12_5p12.get_coupled_levels([0, 1], [2])), \n 8*3)\n\nclass TestAtom1eGetClebschHFFactors(unittest.TestCase):\n\n def setup_method(self, method):\n\n Rb87_5s12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5s12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n Rb87_5p12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5p12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n\n self.Rb87_5s12_5p12 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F2)\n\n Rb87_5p32_F0 = hyperfine.LevelF(I=1.5, J=1.5, F=0)\n Rb87_5p32_F1 = hyperfine.LevelF(I=1.5, J=1.5, F=1)\n Rb87_5p32_F2 = hyperfine.LevelF(I=1.5, J=1.5, F=2) \n Rb87_5p32_F3 = hyperfine.LevelF(I=1.5, J=1.5, F=3)\n\n self.Rb87_5s12_5p32 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F0)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F3)\n\n def test_Rb87_5s12_5p12(self):\n \"\"\"\n References:\n [0]: https://steck.us/alkalidata/rubidium87numbers.pdf\n \"\"\"\n # self.assertEqual(self.Rb87_5s12_5p12.get_num_mF_levels(), 16)\n\n Rb87_5s12_F_level_idxs = (0, 1)\n Rb87_5p12_F_level_idxs = (2, 3)\n\n cl = self.Rb87_5s12_5p12.get_coupled_levels(Rb87_5s12_F_level_idxs, \n Rb87_5p12_F_level_idxs)\n\n facts_qm1 = self.Rb87_5s12_5p12.get_clebsch_hf_factors(\n Rb87_5s12_F_level_idxs, Rb87_5p12_F_level_idxs, q=-1)\n facts_q0 = self.Rb87_5s12_5p12.get_clebsch_hf_factors(\n Rb87_5s12_F_level_idxs, Rb87_5p12_F_level_idxs, q=0)\n facts_qp1 = self.Rb87_5s12_5p12.get_clebsch_hf_factors(\n Rb87_5s12_F_level_idxs, Rb87_5p12_F_level_idxs, q=1)\n\n # For each upper mF level, get the sum of all couplings mF' \n # Eqn (40) in Ref [0]. These should sum to (2J + 1)/(2J' + 1) = 1\n # \"The interpretation of this symmetry is simply that all the excited \n # state sublevels decay at the same rate \\Gamma, and the decaying \n # population “branches” into various ground state sublevels.\"\n for upper_mF_level in range(8, 16):\n coupled = [upper_mF_level in i for i in cl]\n\n factor_sq_sum = (np.sum(facts_qm1[coupled]**2) + \n np.sum(facts_q0[coupled]**2) + np.sum(facts_qp1[coupled]**2))\n\n self.assertAlmostEqual(factor_sq_sum, 1.0) # (2J+1)/(2J'+1) = 1\n\nclass TestAtom1eGetStrengthFactor(unittest.TestCase):\n\n def setup_method(self, method):\n\n Rb87_5s12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5s12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n Rb87_5p12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5p12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n\n self.Rb87_5s12_5p12 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F2)\n\n Rb87_5p32_F0 = hyperfine.LevelF(I=1.5, J=1.5, F=0)\n Rb87_5p32_F1 = hyperfine.LevelF(I=1.5, J=1.5, F=1)\n Rb87_5p32_F2 = hyperfine.LevelF(I=1.5, J=1.5, F=2) \n Rb87_5p32_F3 = hyperfine.LevelF(I=1.5, J=1.5, F=3)\n\n self.Rb87_5s12_5p32 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F0)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F3)\n\n def test_Rb87_5s12_5p12_strength_factors(self):\n \"\"\" Test strength factors against known values from Steck [0] Table 8.\n \n Refs:\n [0]: https://steck.us/alkalidata/rubidium87numbers.pdf\n \"\"\"\n\n # The loops are to check each lower state, should be the same for each\n for i in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p12.get_strength_factor(0, 2, i), 1.0/6) # F1 -> F1\n for i in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p12.get_strength_factor(0, 3, i), 5.0/6) # F1 -> F2\n for i in range(4):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p12.get_strength_factor(1, 2, i), 1.0/2) # F2 -> F1\n for i in range(4):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p12.get_strength_factor(1, 3, i), 1.0/2) # F2 -> F2\n\n # The sum of S_{FF'} over upper F levels should be 1.\n for j in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p12.get_strength_factor(j, 2) + \n self.Rb87_5s12_5p12.get_strength_factor(j, 3), 1.0)\n\n def test_Rb87_5s12_5p32_strength_factors(self):\n \"\"\" Test strength factors against known values from Steck [0] Table 8.\n \n Refs:\n [0]: https://steck.us/alkalidata/rubidium87numbers.pdf\n \"\"\"\n\n # The loops are to check each lower state, should be the same for each\n for i in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(0, 2, i), 1./6) # F1 -> F0\n for i in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(0, 3, i), 5./12) # F1 -> F1\n for i in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(0, 4, i), 5./12) # F1 -> F2\n for i in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(0, 5, i), 0.0) # F1 -> F3\n\n for i in range(4):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(1, 2, i), 0.0) # F1 -> F0\n for i in range(4):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(1, 3, i), 1./20) # F1 -> F1\n for i in range(4):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(1, 4, i), 1./4) # F1 -> F2\n for i in range(4):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p32.get_strength_factor(1, 5, i), 7./10) # F1 -> F3\n\n # The sum of S_{FF'} over upper F levels should be 1.\n for j in range(2):\n self.assertAlmostEqual(\n self.Rb87_5s12_5p12.get_strength_factor(j, 2) + \n self.Rb87_5s12_5p12.get_strength_factor(j, 3) +\n self.Rb87_5s12_5p12.get_strength_factor(j, 4) +\n self.Rb87_5s12_5p12.get_strength_factor(j, 5), 1.0)\n\n def test_Rb87_5s12_5p32(self):\n\n Rb87_5s12_F_level_idxs = (0, 1)\n Rb87_5p32_F_level_idxs = (2, 3, 4, 5)\n cl = self.Rb87_5s12_5p32.get_coupled_levels(Rb87_5s12_F_level_idxs, \n Rb87_5p32_F_level_idxs)\n\n facts_qm1 = self.Rb87_5s12_5p32.get_clebsch_hf_factors(\n Rb87_5s12_F_level_idxs, Rb87_5p32_F_level_idxs, q=-1)\n facts_q0 = self.Rb87_5s12_5p32.get_clebsch_hf_factors(\n Rb87_5s12_F_level_idxs, Rb87_5p32_F_level_idxs, q=0)\n facts_qp1 = self.Rb87_5s12_5p32.get_clebsch_hf_factors(\n Rb87_5s12_F_level_idxs, Rb87_5p32_F_level_idxs, q=1)\n\n # For each upper mF level, get the sum of all couplings mF' \n # Eqn (40) in Ref [0]. These should sum to (2J + 1)/(2J' + 1) = 0.5\n # \"The interpretation of this symmetry is simply that all the excited \n # state sublevels decay at the same rate \\Gamma, and the decaying \n # population “branches” into various ground state sublevels.\"\n for upper_mF_level in range(8, 24):\n coupled = [upper_mF_level in i for i in cl]\n\n factor_sq_sum = (np.sum(facts_qm1[coupled]**2) + \n np.sum(facts_q0[coupled]**2) + np.sum(facts_qp1[coupled]**2))\n\n self.assertAlmostEqual(factor_sq_sum, 0.5) # (2J+1)/(2J'+1) = 0.5\n\nclass TestAtom1eGetDecayFactors(unittest.TestCase):\n\n def setup_method(self, method):\n\n Rb87_5s12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5s12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n Rb87_5p12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5p12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n \n self.Rb87_5s12_5p12 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F2)\n\n Rb87_5p32_F0 = hyperfine.LevelF(I=1.5, J=1.5, F=0)\n Rb87_5p32_F1 = hyperfine.LevelF(I=1.5, J=1.5, F=1)\n Rb87_5p32_F2 = hyperfine.LevelF(I=1.5, J=1.5, F=2) \n Rb87_5p32_F3 = hyperfine.LevelF(I=1.5, J=1.5, F=3)\n\n self.Rb87_5s12_5p32 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F0)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F3)\n\n def test_Rb87_5s12_5p12(self):\n\n Rb87_5s12_F_level_idxs = (0, 1)\n Rb87_5p12_F_level_idxs = (2, 3)\n cl = self.Rb87_5s12_5p12.get_coupled_levels(Rb87_5s12_F_level_idxs, \n Rb87_5p12_F_level_idxs)\n df = self.Rb87_5s12_5p12.get_decay_factors(Rb87_5s12_F_level_idxs, \n Rb87_5p12_F_level_idxs)\n\n # For each upper mF level, get the sum of all couplings mF' \n # Eqn (40) in Ref [0]. These should sum to (2J + 1)/(2J' + 1) = 1\n # \"The interpretation of this symmetry is simply that all the excited \n # state sublevels decay at the same rate \\Gamma, and the decaying \n # population “branches” into various ground state sublevels.\"\n for upper_mF_level in range(8, 16):\n coupled = [upper_mF_level in i for i in cl]\n factor_sq_sum = np.sum(df[coupled]**2)\n self.assertAlmostEqual(factor_sq_sum, 1.0) # (2J+1)/(2J'+1) = 1\n\n def test_Rb87_5s12_5p32(self):\n\n Rb87_5s12_F_level_idxs = (0, 1)\n Rb87_5p32_F_level_idxs = (2, 3, 4, 5)\n cl = self.Rb87_5s12_5p32.get_coupled_levels(Rb87_5s12_F_level_idxs, \n Rb87_5p32_F_level_idxs)\n df = self.Rb87_5s12_5p32.get_decay_factors(Rb87_5s12_F_level_idxs, \n Rb87_5p32_F_level_idxs)\n\n for upper_mF_level in range(8, 24):\n coupled = [upper_mF_level in i for i in cl]\n factor_sq_sum = np.sum(df[coupled]**2)\n self.assertAlmostEqual(factor_sq_sum, 0.5) # (2J+1)/(2J'+1) = 1/2\n\nclass GetClebschHFFactorsIso(unittest.TestCase):\n\n def setup_method(self, method):\n\n Rb87_5s12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5s12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n Rb87_5p12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1)\n Rb87_5p12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2)\n \n self.Rb87_5s12_5p12 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F1)\n self.Rb87_5s12_5p12.add_F_level(Rb87_5p12_F2)\n\n Rb87_5p32_F0 = hyperfine.LevelF(I=1.5, J=1.5, F=0)\n Rb87_5p32_F1 = hyperfine.LevelF(I=1.5, J=1.5, F=1)\n Rb87_5p32_F2 = hyperfine.LevelF(I=1.5, J=1.5, F=2) \n Rb87_5p32_F3 = hyperfine.LevelF(I=1.5, J=1.5, F=3)\n\n self.Rb87_5s12_5p32 = hyperfine.Atom1e(element='Rb', isotope='87')\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5s12_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F0)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F1)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F2)\n self.Rb87_5s12_5p32.add_F_level(Rb87_5p32_F3)\n\n def test_Rb87_5s12_5p12(self):\n\n Rb87_5s12_F_level_idxs = (0, 1)\n Rb87_5p12_F_level_idxs = (2, 3)\n\n cl = self.Rb87_5s12_5p12.get_coupled_levels(\n Rb87_5s12_F_level_idxs, Rb87_5p12_F_level_idxs)\n cf = self.Rb87_5s12_5p12.get_clebsch_hf_factors_iso(\n Rb87_5s12_F_level_idxs, Rb87_5p12_F_level_idxs)\n\n for upper_mF_level in range(8, 16):\n coupled = [upper_mF_level in i for i in cl]\n factor_sq_sum = np.sum(cf[coupled]**2)\n self.assertAlmostEqual(factor_sq_sum, 1.0/3)\n\n def test_Rb87_5s12_5p32(self):\n\n Rb87_5s12_F_level_idxs = (0, 1)\n Rb87_5p32_F_level_idxs = (2, 3, 4, 5)\n\n cl = self.Rb87_5s12_5p32.get_coupled_levels(\n Rb87_5s12_F_level_idxs, Rb87_5p32_F_level_idxs)\n cf = self.Rb87_5s12_5p32.get_clebsch_hf_factors_iso(\n Rb87_5s12_F_level_idxs, Rb87_5p32_F_level_idxs)\n\n for upper_mF_level in range(8, 24):\n coupled = [upper_mF_level in i for i in cl]\n factor_sq_sum = np.sum(cf[coupled]**2)\n self.assertAlmostEqual(factor_sq_sum, 0.5/3) # (2J+1)/(2J'+1) = 1/2\n\n# class TestLevelNLInit(unittest.TestCase):\n# \"\"\" Unit tests of the LevelNL.__init__ method. \"\"\"\n\n# def test_Rb_87_5s(self):\n# \"\"\" Test the structure built for the Rubidium 87 5s level. \"\"\"\n\n# Rb_87_5s = hyperfine.LevelNL(n=5, I=1.5, L=1, S=0.5)\n# self.assertEqual(len(Rb_87_5s.J_levels), 2)\n\n# # Fine structure\n# self.assertEqual(len(Rb_87_5s.J_levels[0].F_levels), 2)\n# self.assertEqual(len(Rb_87_5s.J_levels[1].F_levels), 4)\n\n# # Hyperfine structure\n# self.assertEqual(len(Rb_87_5s.J_levels[0].F_levels[0].mF_levels), 3)\n# self.assertEqual(len(Rb_87_5s.J_levels[0].F_levels[1].mF_levels), 5)\n\n# self.assertEqual(len(Rb_87_5s.J_levels[1].F_levels[0].mF_levels), 1)\n# self.assertEqual(len(Rb_87_5s.J_levels[1].F_levels[1].mF_levels), 3)\n# self.assertEqual(len(Rb_87_5s.J_levels[1].F_levels[2].mF_levels), 5)\n# self.assertEqual(len(Rb_87_5s.J_levels[1].F_levels[3].mF_levels), 7)\n\n# class TestLevelJInit(unittest.TestCase):\n# \"\"\" Unit tests of the LevelJ.__init__ method. \"\"\"\n\n# def test_not_half_ints(self):\n# \"\"\" Test that a ValueError is raised if I and J are not both half \n# integer. \"\"\"\n\n# with self.assertRaises(ValueError):\n# hyperfine.LevelJ(I=1.6, J=0.5, energy=0.0)\n# with self.assertRaises(ValueError):\n# hyperfine.LevelJ(I=1.5, J=0.6, energy=0.0)\n \n# def test_no_F_energies(self):\n# \"\"\" Test with no setting of F_energies or mF_energies (so should all be \n# zero) \"\"\"\n\n# I = 1.5 # Rb87 nuclear spin\n# J = 0.5 # 5p_{1/2}\n# Rb_87_5p12 = hyperfine.LevelJ(I=I, J=J, energy=0.0, \n# F_energies=None, mF_energies=None)\n# self.assertEqual(len(Rb_87_5p12.F_levels), 2)\n# self.assertEqual(len(Rb_87_5p12.F_levels[0].mF_levels), 2*1+1)\n# self.assertEqual(len(Rb_87_5p12.F_levels[1].mF_levels), 2*2+1)\n\n# def test_Rb_87_5p12(self):\n# \"\"\" Test building the 5p_{1/2} level of Rubidium 87. \"\"\"\n\n# I = 1.5 # Rb87 nuclear spin\n# J = 0.5 # 5p_{1/2}\n# Rb_87_5p12 = hyperfine.LevelJ(I=I, J=J, energy=0.0, \n# F_energies=[10.0, 20.0])\n\n# # F numbers are in the range |J - I| <= F <= J + I, so in this case\n# # F=1 and F=2\n# self.assertEqual(len(Rb_87_5p12.F_levels), 2)\n\n# # Each F level should have 2*F+1 sublevels.\n# self.assertEqual(len(Rb_87_5p12.F_levels[0].mF_levels), 2*1+1)\n# self.assertEqual(len(Rb_87_5p12.F_levels[1].mF_levels), 2*2+1)\n\nclass TestLevelFInit(unittest.TestCase):\n \"\"\" Unit tests of the LevelF.__init__ method. \"\"\"\n\n def test_f_2(self):\n \"\"\" Tests that without specified energies, the mF sublevel energies\n are set to zero. \"\"\"\n \n F = 2\n lf = hyperfine.LevelF(I=1.5, J=0.5, F=F, energy=0.0)\n self.assertEqual(len(lf.mF_levels), 2*F+1)\n for i in lf.mF_levels:\n self.assertEqual(i.energy, 0.0)\n\n def test_f_2_energies(self):\n \"\"\" Tests that the mF sublevel energies are set. \"\"\"\n\n F = 2\n mF_energies = [10.0, 20.0, 30.0, 40.0, 50.0]\n lf = hyperfine.LevelF(I=1.5, J=0.5, F=F, energy=0.0, \n mF_energies=mF_energies)\n\n self.assertEqual(len(lf.mF_levels), 2*F+1)\n for i, e in enumerate(mF_energies):\n self.assertEqual(e, lf.mF_levels[i].energy)\n",
"\"\"\" Unit tests for the spectral analysis module.\"\"\"\n\nimport os\nimport unittest\n\nimport numpy as np\n\nfrom maxwellbloch import t_funcs, utility\n\nclass TestGaussian(unittest.TestCase):\n\n def test_areas_pi(self):\n \"\"\"Test Gaussian areas as multiples of pi.\n \"\"\"\n FWHM = 0.1\n tlist = np.linspace(0., 1., 201)\n t_func = t_funcs.gaussian(1)\n for n in np.linspace(1.0, 10.0, 10):\n ampl = n*np.sqrt(4.*np.pi*np.log(2)/FWHM**2)/(2*np.pi) # nπ area\n t_args = {'ampl_1': ampl, 'fwhm_1': FWHM, 'centre_1': 0.5}\n area = np.trapz(t_func(tlist, t_args), tlist)*2*np.pi\n fwhm_test = utility.full_width_at_half_max(tlist, \n t_func(tlist, t_args))\n self.assertAlmostEqual(area, n*np.pi, places=3)\n self.assertAlmostEqual(fwhm_test, FWHM)\n\n def test_areas_pi_n_pi(self):\n \"\"\"Test Gaussian areas as multiples of pi given n_pi arg.\n \"\"\"\n FWHM = 0.1\n tlist = np.linspace(0., 1., 201)\n t_func = t_funcs.gaussian(1)\n for n_pi in np.linspace(1.0, 10.0, 10):\n t_args = {'n_pi_1': n_pi, 'fwhm_1': FWHM, 'centre_1': 0.5}\n area = np.trapz(t_func(tlist, t_args), tlist)*2*np.pi\n fwhm_test = utility.full_width_at_half_max(tlist, \n t_func(tlist, t_args))\n self.assertAlmostEqual(area, n_pi*np.pi, places=3)\n self.assertAlmostEqual(fwhm_test, FWHM)\n\n def test_ampl_and_n_pi(self):\n \"\"\"Test that KeyError is raised if both ampl and n_pi args set.\n \"\"\"\n tlist = np.linspace(0., 1., 201)\n t_args = {'n_pi_1': 2.0, 'ampl_1': 1.0, 'fwhm_1': 0.1, 'centre_1': 0.5}\n t_func = t_funcs.gaussian(1)\n with self.assertRaises(KeyError):\n t_func(tlist, t_args)\n\n def test_no_ampl_nor_n_pi(self):\n tlist = np.linspace(0., 1., 201)\n t_args = {'fwhm_1': 0.1, 'centre_1': 0.5}\n t_func = t_funcs.gaussian(1)\n with self.assertRaises(KeyError):\n t_func(tlist, t_args)\n\nclass TestSech(unittest.TestCase):\n \n def test_areas_pi(self):\n \"\"\"Test sech areas as multiples of pi.\n \"\"\"\n SECH_FWHM_CONV = 1./2.6339157938\n FWHM = 0.1\n width = FWHM*SECH_FWHM_CONV # [τ]\n tlist = np.linspace(0., 1., 201)\n t_func = t_funcs.sech(1)\n for n in np.linspace(1.0, 10.0, 10):\n ampl = n/width/(2*np.pi) # nπ area\n t_args = {'ampl_1': ampl, 'width_1': width, 'centre_1': 0.5}\n area = np.trapz(t_func(tlist, t_args), tlist)*2*np.pi\n fwhm_test = utility.full_width_at_half_max(tlist, \n t_func(tlist, t_args))\n self.assertAlmostEqual(area, n*np.pi, places=3)\n self.assertAlmostEqual(fwhm_test, FWHM)\n\n def test_areas_pi_n_pi(self):\n \"\"\"Test sech areas as multiples of pi given n_pi arg.\n \"\"\"\n SECH_FWHM_CONV = 1./2.6339157938\n FWHM = 0.1\n width = FWHM*SECH_FWHM_CONV # [τ]\n tlist = np.linspace(0., 1., 201)\n t_func = t_funcs.sech(1)\n for n in np.linspace(1.0, 10.0, 10):\n t_args = {'n_pi_1': n, 'width_1': width, 'centre_1': 0.5}\n area = np.trapz(t_func(tlist, t_args), tlist)*2*np.pi\n fwhm_test = utility.full_width_at_half_max(tlist, \n t_func(tlist, t_args))\n self.assertAlmostEqual(area, n*np.pi, places=3)\n self.assertAlmostEqual(fwhm_test, FWHM)\n\n def test_areas_pi_n_pi_fwhm(self):\n \"\"\"Test sech areas as multiples of pi given n_pi and fwhm args.\n \"\"\"\n tlist = np.linspace(0., 1., 201)\n t_func = t_funcs.sech(1)\n FWHM = 0.1\n for n in np.linspace(1.0, 10.0, 10):\n t_args = {'n_pi_1': n, 'fwhm_1': FWHM, 'centre_1': 0.5}\n area = np.trapz(t_func(tlist, t_args), tlist)*2*np.pi\n fwhm_test = utility.full_width_at_half_max(tlist, \n t_func(tlist, t_args))\n self.assertAlmostEqual(area, n*np.pi, places=3)\n self.assertAlmostEqual(fwhm_test, FWHM)\n # TODO: Test the FWHM is correct\n\n def test_ampl_and_n_pi(self):\n \"\"\"Test that KeyError is raised if both ampl and n_pi args set.\n \"\"\"\n tlist = np.linspace(0., 1., 201)\n t_args = {'n_pi_1': 2.0, 'ampl_1': 1.0, 'width_1': 0.1, 'centre_1': 0.5}\n t_func = t_funcs.sech(1)\n with self.assertRaises(KeyError):\n t_func(tlist, t_args)\n\n def test_no_ampl_nor_n_pi(self):\n tlist = np.linspace(0., 1., 201)\n t_args = {'width_1': 0.1, 'centre_1': 0.5}\n t_func = t_funcs.sech(1)\n with self.assertRaises(KeyError):\n t_func(tlist, t_args)\n"
] | [
[
"numpy.sum"
],
[
"numpy.log",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shyam-patel-kira/LA-CO-SS | [
"76ace6159b5fcf60063e52809b7dac76ccf4952d"
] | [
"api2/Preprocessing.py"
] | [
"from collections import OrderedDict\nimport helpers as hp\nimport configparser as cp\nimport os\nimport scipy.sparse\nimport numpy as np\nfrom scipy.linalg import pinv\nfrom scipy.sparse import csr_matrix\n\n\nconfig = cp.ConfigParser();\nconfig.read(os.getcwd()+'/config.ini')\n# degree of freedom\nk = int(config['PREPROCESSING']['k'])\nrun_task_2 = bool(int(config['PREPROCESSING']['run_task_2']))\n\n# imageId to Index\nIdsIdxMap = {}\n\n# Index to Image Id\nIdxIdsMap = {}\n\nImageWordTfIdfMap = {}\n\ndef readFromCSVTD(fileName):\n with open(fileName, \"r\", encoding=\"utf8\") as ins:\n i = 0\n w = 1\n for line in ins:\n row = line.split(' ')\n wordTfIdfMap = {};\n for j in range(len(row)):\n if(j==0):\n IdsIdxMap[row[j]]=i\n IdxIdsMap[i]=row[j]\n ImageWordTfIdfMap[row[j]]=wordTfIdfMap\n continue\n if(row[j].find('\"')!= -1):\n key = row[j].replace('\"', '')\n wordTfIdfMap[key] = float(row[j+3])\n i = i +1\n return ImageWordTfIdfMap\n\nimage_file = config['PREPROCESSING']['raw_image_path']\nreadFromCSVTD(image_file);\n\nhp.save(IdsIdxMap, \"IdsIdxMap.txt\")\nIdsIdxMap = {};\nhp.save(IdxIdsMap, \"IdxIdsMap.txt\")\nIdxIdsMap = {};\n\ncosineBoolean = {}\n\n\ndef findCosineSimilarity(key1, map1, key2, map2):\n\n if len(map1) > len(map2):\n tempKey = key1\n key1 = key2\n key2 = tempKey\n tempMap = map1\n map1 = map2\n map2 = tempMap\n try:\n return cosineBoolean[key1+key2]\n except KeyError:\n dot_prod = 0;\n for key, value in map1.items():\n prod = 0;\n try:\n value1 = map2[key]\n except KeyError:\n continue\n prod = value1 * value\n dot_prod = dot_prod + prod\n cosineBoolean[key1 + key2] = dot_prod / (len(map1) + len(map2))\n return cosineBoolean[key1 + key2]\n\nImageImageSimilarityMatrix = {}\n\nif not run_task_2:\n i = 0;\n for key, value in ImageWordTfIdfMap.items():\n if i % 20 == 0:\n print(i)\n try:\n q = ImageImageSimilarityMatrix[key]\n except KeyError:\n q = OrderedDict();\n ImageImageSimilarityMatrix[key] = q;\n for key1, value1 in ImageWordTfIdfMap.items():\n try:\n q1 = ImageImageSimilarityMatrix[key1]\n except KeyError:\n q1 = OrderedDict();\n ImageImageSimilarityMatrix[key1] = q1\n csValue = findCosineSimilarity(key, value, key1, value1);\n\n if (key1 in q):\n pass\n else:\n q[key1] = csValue;\n\n if (key in q1):\n pass\n else:\n q1[key] = csValue;\n\n q = OrderedDict(sorted(q.items(), key=lambda kv: kv[1], reverse=True))\n q1 = OrderedDict(sorted(q1.items(), key=lambda kv: kv[1], reverse=True))\n if(len(q) > k ):\n for x in list(reversed(list(q))):\n q.pop(x)\n break\n if (len(q1) > k):\n for x in list(reversed(list(q1))):\n q1.pop(x)\n break\n ImageImageSimilarityMatrix[key] = q\n ImageImageSimilarityMatrix[key1] = q1\n i = i + 1\n cosineBoolean = {}\n\n hp.save(ImageImageSimilarityMatrix, \"ImageImageSimilarityMatrix\"+ str(k) +\".txt\")\n\ndef pre_process_task2():\n\n # imageId to Index\n IdsIdxMap = hp.load(\"IdsIdxMap.txt\")\n\n # Index to Image Id\n IdxIdsMap = hp.load(\"IdxIdsMap.txt\")\n b = hp.load(\"ImageImageSimilarityMatrix\"+ str(k) +\".txt\")\n\n #adjecenty matrix\n adj_matrix = np.zeros((len(IdxIdsMap), len(IdxIdsMap)))\n weighted_adj_matrix = np.zeros((len(IdxIdsMap), len(IdxIdsMap)))\n\n for i in range(0, len(adj_matrix)):\n q = b[IdxIdsMap[i]]\n for value in q:\n adj_matrix[i][IdsIdxMap[value]] = 1.0;\n weighted_adj_matrix[i][IdsIdxMap[value]] = q[value]\n\n A = np.array(adj_matrix)\n W = np.array(weighted_adj_matrix)\n\n D_out = np.eye(A.shape[0]) * np.sum(A, axis=1, keepdims=True)\n D_out = np.sqrt(pinv(D_out))\n D_out = scipy.sparse.csr_matrix(D_out)\n\n D_in = np.eye(A.shape[0]) * np.sum(A, axis=0, keepdims=True)\n D_in = np.sqrt(pinv(D_in))\n D_in = scipy.sparse.csr_matrix(D_in)\n\n B = csr_matrix.dot(csr_matrix.dot(csr_matrix.dot(csr_matrix.dot(D_out,A),D_in),A.T),D_out)\n\n C = csr_matrix.dot(csr_matrix.dot(csr_matrix.dot(csr_matrix.dot(D_in,A.T),D_out),A),D_in)\n\n sparse_A_matrix = scipy.sparse.csr_matrix(A)\n scipy.sparse.save_npz(os.getcwd()+'/data/A_'+str(k)+'.npz', sparse_A_matrix)\n\n sparse_W_matrix = scipy.sparse.csr_matrix(W)\n scipy.sparse.save_npz(os.getcwd()+'/data/W_'+str(k)+'.npz', sparse_W_matrix)\n\n sparse_B_matrix = scipy.sparse.csr_matrix(B)\n scipy.sparse.save_npz(os.getcwd()+'/data/B_'+str(k)+'.npz', sparse_B_matrix)\n\n sparse_C_matrix = scipy.sparse.csr_matrix(C)\n scipy.sparse.save_npz(os.getcwd()+'/data/C_'+str(k)+'.npz', sparse_C_matrix)\n\nif run_task_2:\n pre_process_task2()\n"
] | [
[
"scipy.linalg.pinv",
"numpy.eye",
"scipy.sparse.csr_matrix.dot",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.12",
"0.14",
"0.15"
],
"tensorflow": []
}
] |
meet-minimalist/FCOS-Pytorch-Implementation | [
"e8ac1c6230174902732dbe8bcff3a87034f99517"
] | [
"TrainingHelper.py"
] | [
"\nimport os\nimport cv2\nimport time\nimport torch\nimport numpy as np\nfrom tqdm import tqdm\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchinfo import summary\n\nfrom LRHelper import LRHelper\nfrom DatasetHelper import get_train_loader, get_test_loader\n\nfrom models.FCOS import FCOS\nfrom models.FCOSLoss import FCOSLoss\n\nfrom utils.Logger import Logger\nfrom utils.SummaryHelper import SummaryHelper\nfrom utils.transforms.normalize import Normalize\nfrom utils.CheckpointHandler import CheckpointHandler\nfrom utils.misc import init_training, np_cpu, LossAverager\n\ncuda = torch.device('cuda:0')\ncpu = torch.device(\"cpu:0\")\n\n\nclass TrainingHelper:\n def __init__(self, config):\n self.config = config\n self.log, self.exp_path = init_training(config.exp_path)\n self.lr_helper = LRHelper(config)\n\n ckpt_folder = self.exp_path + \"/ckpt/\"\n os.makedirs(ckpt_folder, exist_ok=True)\n \n ckpt_path = ckpt_folder + \"fcos_resnet50.pth\"\n self.ckpt_handler = CheckpointHandler(ckpt_path, max_to_keep=3)\n\n\n def compute_loss_and_map(self, predictions, batch_bboxes, model, fcos_loss_fn):\n # cls_probs_pred, cnt_logits_pred, reg_values_pred = prediction\n # cls_probs_pred : [[B x 81 x H x W], [B x 81 x H x W], ...]\n # cnt_logits_pred : [[B x 1 x H x W], [B x 1 x H x W], ...]\n # reg_values_pred : [[B x 4 x H x W], [B x 4 x H x W], ...]\n \n # batch_bbox : [B x M x 5] --> [x1, y1, x2, y2, cls_id]\n \n loss_reg = torch.tensor(0, dtype=torch.float32, device=cuda, requires_grad=False)\n for layer in model.modules():\n if isinstance(layer,torch.nn.Conv2d):\n for p in layer.named_parameters():\n if 'weight' in p[0]:\n loss_reg += torch.sum((torch.square(p[1]) / 2)) \n\n loss_reg *= self.config.l2_weight_decay\n\n loss_loc, loss_cls, loss_cnt = fcos_loss_fn(predictions, batch_bboxes) \n\n loss_total = loss_loc + loss_cls + loss_cnt + loss_reg\n\n # sm_outputs = F.softmax(logits.detach(), dim=-1)\n # accuracy = (torch.argmax(sm_outputs, dim=1) == labels).sum() * 100 / labels.size(0)\n\n return loss_total, loss_loc, loss_cls, loss_cnt, loss_reg\n\n\n def get_model(self):\n model = FCOS(backbone_model=self.config.backbone, freeze_backend=self.config.freeze_backend, \\\n fpn_features=self.config.fpn_features, num_classes=self.config.num_classes, \\\n use_det_head_group_norm=self.config.use_det_head_group_norm, \\\n centerness_on_regression=self.config.centerness_on_regression, \\\n use_gradient_checkpointing=self.config.use_gradient_checkpointing, \\\n weight_init_method=self.config.weight_init_method).to(cuda, non_blocking=True)\n \n return model\n\n\n def define_loss(self):\n fcos_loss = FCOSLoss(limit_range=self.config.limit_range, central_sampling=self.config.central_sampling, \\\n central_sampling_radius=self.config.central_sampling_radius, strides=self.config.strides, \\\n regression_loss_type=self.config.regression_loss_type, num_classes=self.config.num_classes)\n \n return fcos_loss\n \n\n def train(self, resume=False, resume_ckpt=None, pretrained_ckpt=None):\n model = self.get_model()\n \n model_stats = summary(model, (1, 3, self.config.input_size[0], self.config.input_size[1]))\n \n for line in str(model_stats).split('\\n'):\n self.log(line)\n \n fcos_loss_fn = self.define_loss()\n \n opt = torch.optim.Adam(model.parameters(), lr=0.0, weight_decay=0.0)\n # Setting lr equal to 0.0 here so that it wont work as per this line.\n # But we will explicitly set lr for each weights dynamically, at every step.\n # Same is case for weight_decay, We will calculate L2_regularization_loss on our own separately.\n # L2 loss will only be calculated for conv-weights only.\n \n if self.config.use_amp:\n scaler = torch.cuda.amp.GradScaler(enabled=True)\n \n if resume:\n checkpoint = torch.load(resume_ckpt)\n model.load_state_dict(checkpoint['model'])\n opt.load_state_dict(checkpoint['optimizer'])\n if self.config.use_amp:\n scaler.load_state_dict(checkpoint['scalar'])\n resume_g_step = checkpoint['global_step']\n resume_eps = checkpoint['epoch']\n self.log(\"Resuming training from {} epochs.\".format(resume_eps))\n elif pretrained_ckpt is not None and self.config.backbone == 'resnet18':\n self.log(\"Using pre-trained checkpoint from :\".format(pretrained_ckpt))\n checkpoint = torch.load(pretrained_ckpt)\n \n filtered_checkpoint = {}\n self.log(\"\\nFollowing variables will be restored:\")\n for var_name, var_value in checkpoint.items():\n if var_name == 'fc.weight' or var_name == 'fc.bias': \n # As these layers change arent there in pretrained model definition\n continue\n if 'resnet' in self.config.backbone:\n new_var_name = 'resnet_feat.' + var_name \n # why this prefix? This comes as the model that we created contains a variable resnet_feat \n # which is sequential group of layers containing resnet layers. So all the layers and parameters \n # within it are prefixed with resnet_feat and for restoring resnet pretrained weights \n # we need to update the statedict according to the model architectural definition.\n self.log(f\"{new_var_name} : {list(var_value.size())}\")\n filtered_checkpoint[new_var_name] = var_value\n else:\n raise NotImplementedError('Pretrained model restoration is not implemented for ', self.config.backbone)\n\n self.log(\"\\n\\nFollowing variables will be initialized:\")\n remaining_vars = model.load_state_dict(filtered_checkpoint, strict=False)\n for var_name in remaining_vars.missing_keys:\n self.log(var_name)\n \n resume_g_step = 0\n resume_eps = 0\n else:\n resume_g_step = 0\n resume_eps = 0\n\n train_writer = SummaryHelper(self.exp_path + \"/train/\")\n test_writer = SummaryHelper(self.exp_path + \"/test/\")\n\n input_x = torch.randn((1,3, self.config.input_size[0], self.config.input_size[1])).to(cuda, non_blocking=True)\n train_writer.add_graph(model, input_x)\n\n # Dataloader for train and test dataset\n train_loader = get_train_loader(self.config)\n test_loader = get_test_loader(self.config)\n\n\n g_step = max(0, resume_g_step)\n for eps in range(resume_eps, self.config.epochs):\n # I hope you noticed one particular statement in the code, to which I assigned a comment “What is this?!?” — model.train().\n # In PyTorch, models have a train() method which, somewhat disappointingly, does NOT perform a training step. \n # Its only purpose is to set the model to training mode. Why is this important? Some models may use mechanisms like Dropout, \n # for instance, which have distinct behaviors in training and evaluation phases.\n # Ref: https://towardsdatascience.com/understanding-pytorch-with-an-example-a-step-by-step-tutorial-81fc5f8c4e8e\n model.train()\n\n train_iter = iter(train_loader) # This is creating issues sometimes. Check required.\n \n self.log(\"Epoch: {} Started\".format(eps+1))\n \n for batch_num in tqdm(range(self.config.train_steps)):\n # start = time.time()\n batch = next(train_iter)\n\n opt.zero_grad() # Zeroing out gradients before backprop\n # We cab avoid to zero out if we want accumulate gradients for \n # Multiple forward pass and single backward pass.\n with torch.cuda.amp.autocast(enabled=self.config.use_amp):\n predictions = model(batch['image'].to(cuda, non_blocking=True))\n # cls_probs, cnt_logits, reg_values = predictions\n # cls_probs : [[B x 81 x H x W], [B x 81 x H x W], ....]\n # cnt_logits: [[B x 1 x H x W], [B x 1 x H x W], ....]\n # reg_values: [[B x 4 x H x W], [B x 4 x H x W], ....]\n\n loss_total, loss_clsf, loss_cntness, loss_regression, loss_regularizer = \\\n self.compute_loss_and_map(predictions, batch['bbox'].to(cuda, non_blocking=True), model, fcos_loss_fn)\n \n if self.config.use_amp:\n scaler.scale(loss_total).backward()\t\t# Used when AMP is applied.\n scaler.step(opt)\n scaler.update()\n else:\n loss_total.backward()\n\n lr = self.lr_helper.step(g_step, opt)\n opt.step()\n # delta = (time.time() - start) * 1000 # in milliseconds\n # print(\"\\nTime: {:.2f} ms\".format(delta))\n\n if (batch_num+1) % self.config.loss_logging_frequency == 0:\n self.log(f\"Epoch: {eps+1}/{self.config.epochs}, Batch No.: {batch_num+1}/{self.config.train_steps}, \" + \\\n f\"Total Loss: {np_cpu(loss_total):.4f}, Loss Cls: {np_cpu(loss_clsf):.4f}, \" + \\\n f\"Loss Cntness: {np_cpu(loss_cntness):.4f}, Loss Regression: {np_cpu(loss_regression):.4f}, \" + \\\n f\"Loss Reg: {np_cpu(loss_regularizer):.4f}, Accuracy: {0}\")\n \n train_writer.add_summary({'total_loss' : np_cpu(loss_total),\n 'loss_cls' : np_cpu(loss_clsf),\n 'loss_cntness' : np_cpu(loss_cntness),\n 'loss_regression' : np_cpu(loss_regression),\n 'loss_reg' : np_cpu(loss_regularizer), \n # 'accuracy' : np_cpu(accuracy),\n 'lr' : lr}, g_step)\n \n g_step += 1\n \n \n model.eval() # Putting model in eval mode so that batch normalization and dropout will work in inference mode.\n\n test_iter = iter(test_loader)\n test_losses = LossAverager(num_elements=6)\n\n with torch.no_grad(): # Disabling the gradient calculations will reduce the calculation overhead.\n\n for batch_num in tqdm(range(self.config.test_steps)):\n batch = next(test_iter)\n predictions = model(batch['image'].to(cuda, non_blocking=True))\n \n loss_total, loss_clsf, loss_cntness, loss_regression, loss_regularizer = \\\n self.compute_loss_and_map(predictions, batch['bbox'].to(cuda, non_blocking=True), model, fcos_loss_fn)\n test_losses([np_cpu(loss_total), np_cpu(loss_clsf), np_cpu(loss_cntness), \\\n np_cpu(loss_regression), np_cpu(loss_regularizer), 0])\n \n self.log(f\"Epoch: {eps+1}/{self.config.epochs} Completed, Test Total Loss: {test_losses.avg[0]:.4f}, \" + \\\n f\"Loss Cls: {test_losses.avg[1]:.4f}, Loss Cntness: {test_losses.avg[2]:.4f}, \" + \\\n f\"Loss Regression: {test_losses.avg[3]:.4f}, Loss Reg: {test_losses.avg[4]:.4f}, \" + \\\n f\"Accuracy: {test_losses.avg[5]:.2f}\")\n \n test_writer.add_summary({'total_loss' : test_losses.avg[0], \n 'loss_cls' : test_losses.avg[1], \n 'loss_cntness' : test_losses.avg[2], \n 'loss_regression' : test_losses.avg[3], \n 'loss_reg' : test_losses.avg[4], \n # 'accuracy' : test_losses.avg[3],\n }, g_step)\n\n checkpoint = {\n 'epoch': eps + 1,\n 'global_step': g_step,\n 'test_loss': test_losses.avg[0],\n 'model': model.state_dict(),\n 'optimizer': opt.state_dict(),\n }\n if self.config.use_amp:\n checkpoint['scalar'] = scaler.state_dict()\n\n # Above code taken from : https://towardsdatascience.com/how-to-save-and-load-a-model-in-pytorch-with-a-complete-example-c2920e617dee\n self.ckpt_handler.save(checkpoint)\n self.log(\"Epoch {} completed. Checkpoint saved.\".format(eps+1))\n\n print(\"Training Completed.\")\n train_writer.close()\n test_writer.close()\n\n\n def overfit_train(self, pretrained_ckpt=None):\n model = self.get_model()\n \n model_stats = summary(model, (1, 3, self.config.input_size[0], self.config.input_size[1]))\n \n for line in str(model_stats).split('\\n'):\n self.log(line)\n \n fcos_loss_fn = self.define_loss()\n \n opt = torch.optim.Adam(model.parameters(), lr=0.0, weight_decay=0.0)\n # Setting lr equal to 0.0 here so that it wont work as per this line.\n # But we will explicitly set lr for each weights dynamically, at every step.\n # Same is case for weight_decay, We will calculate L2_regularization_loss on our own separately.\n # L2 loss will only be calculated for conv-weights only.\n \n if self.config.use_amp:\n scaler = torch.cuda.amp.GradScaler(enabled=True)\n \n if pretrained_ckpt is not None and self.config.backbone == 'resnet18':\n self.log(\"Using pre-trained checkpoint from :\".format(pretrained_ckpt))\n checkpoint = torch.load(pretrained_ckpt)\n \n filtered_checkpoint = {}\n self.log(\"\\nFollowing variables will be restored:\")\n for var_name, var_value in checkpoint.items():\n if var_name == 'fc.weight' or var_name == 'fc.bias': \n # As these layers change arent there in pretrained model definition\n continue\n if 'resnet' in self.config.backbone:\n new_var_name = 'resnet_feat.' + var_name \n # why this prefix? This comes as the model that we created contains a variable resnet_feat \n # which is sequential group of layers containing resnet layers. So all the layers and parameters \n # within it are prefixed with resnet_feat and for restoring resnet pretrained weights \n # we need to update the statedict according to the model architectural definition.\n self.log(f\"{new_var_name} : {list(var_value.size())}\")\n filtered_checkpoint[new_var_name] = var_value\n else:\n raise NotImplementedError('Pretrained model restoration is not implemented for ', self.config.backbone)\n\n self.log(\"\\n\\nFollowing variables will be initialized:\")\n remaining_vars = model.load_state_dict(filtered_checkpoint, strict=False)\n for var_name in remaining_vars.missing_keys:\n self.log(var_name)\n \n train_writer = SummaryHelper(self.exp_path + \"/train/\")\n\n # Dataloader for train and test dataset\n train_loader = get_train_loader(self.config)\n train_iter = iter(train_loader)\n batch = next(train_iter)\n \n img_tensor = batch['image'][0:1].to(cuda, non_blocking=True)\n \n # Save the image used for overfit training for inference purpose.\n orig_img = Normalize(self.config.normalization_type).denorm(img_tensor).cpu().detach().numpy()\n orig_img = np.transpose(orig_img[0], [1, 2, 0])\n orig_img = np.uint8(orig_img)\n orig_img = cv2.cvtColor(orig_img, cv2.COLOR_RGB2BGR)\n cv2.imwrite(\"./sample_imgs/overfit_img.jpg\", orig_img)\n\n single_bb_label = batch['bbox'].to(cuda, non_blocking=True)\n single_bb_label = single_bb_label[0:1, :, :]\n \n for bb in single_bb_label.detach()[0]:\n x1, y1, x2, y2, cls_id = [int(c) for c in bb]\n cv2.rectangle(orig_img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n cv2.imwrite(\"./sample_imgs/overfit_img_plotted.jpg\", orig_img)\n \n for step in range(self.config.overfit_epochs):\n model.train()\n\n opt.zero_grad() # Zeroing out gradients before backprop\n # We cab avoid to zero out if we want accumulate gradients for \n # Multiple forward pass and single backward pass.\n with torch.cuda.amp.autocast(enabled=self.config.use_amp):\n predictions = model(img_tensor)\n # cls_probs, cnt_logits, reg_values = predictions\n # cls_probs : [[B x 81 x H x W], [B x 81 x H x W], ....]\n # cnt_logits: [[B x 1 x H x W], [B x 1 x H x W], ....]\n # reg_values: [[B x 4 x H x W], [B x 4 x H x W], ....]\n\n loss_total, loss_clsf, loss_cntness, loss_regression, loss_regularizer = \\\n self.compute_loss_and_map(predictions, single_bb_label, model, fcos_loss_fn)\n \n if self.config.use_amp:\n scaler.scale(loss_total).backward()\t\t# Used when AMP is applied.\n scaler.step(opt)\n scaler.update()\n else:\n loss_total.backward()\n\n lr = self.lr_helper.step(step, opt)\n opt.step()\n\n self.log(f\"Epoch: {step+1}/{self.config.overfit_epochs}, \" + \\\n f\"Total Loss: {np_cpu(loss_total):.4f}, Loss Cls: {np_cpu(loss_clsf):.4f}, \" + \\\n f\"Loss Cntness: {np_cpu(loss_cntness):.4f}, Loss Regression: {np_cpu(loss_regression):.4f}, \" + \\\n f\"Loss Reg: {np_cpu(loss_regularizer):.4f}, Accuracy: {0}\")\n \n train_writer.add_summary({'total_loss' : np_cpu(loss_total),\n 'loss_cls' : np_cpu(loss_clsf),\n 'loss_cntness' : np_cpu(loss_cntness),\n 'loss_regression' : np_cpu(loss_regression),\n 'loss_reg' : np_cpu(loss_regularizer), \n # 'accuracy' : np_cpu(accuracy),\n 'lr' : lr}, step)\n\n checkpoint = {\n 'epoch': step + 1,\n 'global_step': step,\n 'model': model.state_dict(),\n 'optimizer': opt.state_dict(),\n 'train_loss' : np_cpu(loss_total),\n }\n if self.config.use_amp:\n checkpoint['scalar'] = scaler.state_dict()\n\n if (step+1) % 10 == 0:\n # Above code taken from : https://towardsdatascience.com/how-to-save-and-load-a-model-in-pytorch-with-a-complete-example-c2920e617dee\n self.ckpt_handler.save(checkpoint)\n self.log(\"Epoch {} completed. Checkpoint saved.\".format(step+1))\n self.log(\"Epoch {} completed.\".format(step+1))\n\n print(\"Training Completed.\")\n train_writer.close()\n"
] | [
[
"torch.load",
"numpy.uint8",
"torch.randn",
"torch.tensor",
"torch.cuda.amp.autocast",
"torch.cuda.amp.GradScaler",
"torch.no_grad",
"torch.square",
"numpy.transpose",
"torch.device"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
romellfudi/dataset_currency | [
"19a950e88fa724171cf93c47369b6fc61a57477f"
] | [
"export_inference_graph.py"
] | [
"import tensorflow as tf\nfrom google.protobuf import text_format\nimport sys\nsys.path.append(\"models/research/\")\nsys.path.append(\"models/research/slim/\")\nfrom object_detection import exporter\nfrom object_detection.protos import pipeline_pb2\n\nslim = tf.contrib.slim\nflags = tf.app.flags\n\nflags.DEFINE_string('input_type', 'image_tensor', 'Type of input node. Can be '\n 'one of [`image_tensor`, `encoded_image_string_tensor`, '\n '`tf_example`]')\nflags.DEFINE_string('input_shape', None,\n 'If input_type is `image_tensor`, this can explicitly set '\n 'the shape of this input tensor to a fixed size. The '\n 'dimensions are to be provided as a comma-separated list '\n 'of integers. A value of -1 can be used for unknown '\n 'dimensions. If not specified, for an `image_tensor, the '\n 'default shape will be partially specified as '\n '`[None, None, None, 3]`.')\nflags.DEFINE_string('pipeline_config_path', None,\n 'Path to a pipeline_pb2.TrainEvalPipelineConfig config '\n 'file.')\nflags.DEFINE_string('trained_checkpoint_prefix', None,\n 'Path to trained checkpoint, typically of the form '\n 'path/to/model.ckpt')\nflags.DEFINE_string('output_directory', None, 'Path to write outputs.')\nflags.DEFINE_string('config_override', '',\n 'pipeline_pb2.TrainEvalPipelineConfig '\n 'text proto to override pipeline_config_path.')\nflags.DEFINE_boolean('write_inference_graph', False,\n 'If true, writes inference graph to disk.')\ntf.app.flags.mark_flag_as_required('pipeline_config_path')\ntf.app.flags.mark_flag_as_required('trained_checkpoint_prefix')\ntf.app.flags.mark_flag_as_required('output_directory')\nFLAGS = flags.FLAGS\n\n\ndef main(_):\n pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()\n with tf.gfile.GFile(FLAGS.pipeline_config_path, 'r') as f:\n text_format.Merge(f.read(), pipeline_config)\n text_format.Merge(FLAGS.config_override, pipeline_config)\n if FLAGS.input_shape:\n input_shape = [\n int(dim) if dim != '-1' else None\n for dim in FLAGS.input_shape.split(',')\n ]\n else:\n input_shape = None\n exporter.export_inference_graph(\n FLAGS.input_type, pipeline_config, FLAGS.trained_checkpoint_prefix,\n FLAGS.output_directory, input_shape=input_shape,\n write_inference_graph=FLAGS.write_inference_graph)\n\n\nif __name__ == '__main__':\n tf.app.run()"
] | [
[
"tensorflow.gfile.GFile",
"tensorflow.app.flags.mark_flag_as_required",
"tensorflow.app.run"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
okviman/SEM | [
"609fdd94874e02b02101649033390335e34c43cb"
] | [
"unit_testing/test_sem.py"
] | [
"from sem import sem\nimport unittest\nimport numpy.random as npr\nimport computations as cmp\nfrom data_utils import simulate_seq, get_char_data\nfrom substitution_models import JukesCantor\nfrom tree_utils import create_tree\nfrom plot_utils import plot_loglikelihood\n\n\nclass SEMTestCase(unittest.TestCase):\n def test_sem_load_data(self):\n npr.seed(3)\n jc = JukesCantor(0.1)\n data, n_leaves, n_sites = get_char_data('../data/alignment.phylip')\n T_l, ll_vec = sem(data, jc)\n plot_loglikelihood(ll_vec)\n self.assertEqual(True, True)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] | [
[
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PeterPirog/PRT_calculations | [
"7e1e72173700fbfd624a67c7b6984256de878f42"
] | [
"GTCext.py"
] | [
"import GTC\nimport numpy as np\n\n\ndef inv(a): #this function is added cause of error in original linear algebra file\n b = np.identity(a.shape[0], a.dtype)\n return GTC.LU.invab(a, b)\n\ndef python_list_transposition(list_2D):\n np_list=np.array(list_2D)\n return np.transpose(np_list).tolist()\n\ndef convert_value_to_2Dlist(value):\n if isinstance(value, int) or isinstance(value, float): # check if list is single value\n value = [[value]]\n else:\n # find size of value_list\n try:\n len(value[0])\n except: # if list is 1D convert to 2D\n value = [value]\n return value\n\ndef urealext(value_list, unc_list=0.0, k=2, array_label='X', df=GTC.inf):\n # INPUT variables:\n # for value_list are:\n # <class 'list'>\n # <class 'numpy.ndarray'>\n # <class 'int'>\n # <class 'float'>\n # for unc_list are:\n # <class 'list'>\n # <class 'numpy.ndarray'>\n # <class 'int'>\n # <class 'float'>\n # for k are:\n # <class 'int'>\n # <class 'float'>\n # for value_name are:\n # <class 'string'>\n value_list=convert_value_to_2Dlist(value_list)\n unc_list2D =convert_value_to_2Dlist(unc_list)\n\n n_rows = len(value_list)\n n_cols = len(value_list[0])\n\n\n if df == 'N':\n df = n_rows * n_cols - 1\n\n realnumber_list = [[0 for x in range(n_cols)] for x in range(n_rows)]\n\n for i in range(n_rows):\n for j in range(n_cols):\n label = array_label + str(i) + '_' + str(j)\n if isinstance(unc_list, int) or isinstance(unc_list, float):\n unc_std = unc_list / k\n else:\n unc_std = unc_list2D[i][j] / k\n realnumber_list[i][j] = GTC.ureal(x=value_list[i][j], u=unc_std, label=label, df=df)\n unc_array = GTC.la.uarray(realnumber_list)\n\n return unc_array\n\n\ndef isGTC(value):\n typeGTC = type(GTC.ureal(0, 0))\n if type(value) == typeGTC:\n return True\n else:\n return False\n\n\n# converting float type to GTC uncertainty type\ndef float2GTC(value):\n if isGTC(value):\n return value\n else:\n return GTC.ureal(value, 0)\n\ndef calculate_func_from_UncertainArray(function_name, uncertain_array):\n \"\"\"\n :param function_name: name of function to calculate form ureal type argument\n :param uncertain_array: array built from UrealArray type\n :return: values of function calculated for each UrealArray element\n \"\"\"\n\n n_rows = len(uncertain_array)\n n_cols = len(uncertain_array[0])\n output_array = [[0 for x in range(n_cols)] for x in range(n_rows)]\n for i in range(n_rows):\n for j in range(n_cols):\n output_array[i][j] = function_name(uncertain_array[i][j])\n return output_array\n\ndef pinv(GTC_array):\n # A+=(AtxA)^1 x At\n A=GTC_array\n At = GTC.la.transpose(A)\n AtA = GTC.la.matmul(At, A)\n invAtA = inv(AtA) #corrected version of GTC inv\n pinvA = GTC.la.matmul(invAtA, At)\n return pinvA\n\ndef psolve(A,B):\n pinvA=pinv(A)\n result=GTC.la.matmul(pinvA,B)\n return result"
] | [
[
"numpy.array",
"numpy.identity",
"numpy.transpose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JadeKim/2021QuantumHackatonKorea | [
"dec44087af4e843b33483e8d53c4725916e4b24b"
] | [
"jade_plot.py"
] | [
"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\ncnn = pd.read_pickle('cnn_10.pkl')\nnl_cnn = pd.read_pickle('nl-cnn_10.pkl')\nqnn = pd.read_pickle('qnn_100_1280_5.pkl')\n\nprint(cnn['train_loss'])\nprint(nl_cnn['train_loss'])\nprint(qnn['train_loss'])\n\nplt.figure(1, figsize=(8, 4.5))\nplt.plot(cnn['train_acc'], label='CNN')\nplt.plot(nl_cnn['train_acc'], label='NL-CNN')\nplt.plot(qnn['train_acc'], label='QNN-9')\nplt.legend()\nplt.xlim(0, 9)\nplt.xticks(np.arange(0, 10, 1), np.arange(1, 11, 1))\nplt.xlabel('Epoch')\nplt.ylabel('Training accuracy')\nplt.ylim(0, 0.5)\n\n\nplt.figure(2, figsize=(8, 4.5))\nplt.plot(cnn['train_loss'], label='CNN')\nplt.plot(nl_cnn['train_loss'], label='NL-CNN')\nplt.plot(qnn['train_loss'], label='QNN-9')\nplt.legend()\nplt.xlim(0, 9)\nplt.xticks(np.arange(0, 10, 1), np.arange(1, 11, 1))\nplt.xlabel('Epoch')\nplt.ylabel('Training loss')\n# plt.ylim(0, 1)\n\nplt.show()"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylim",
"numpy.arange",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"pandas.read_pickle",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Cadene/bootstrap.pytorch | [
"43b0be90e39fdb96018411cb5bfad6bc9d29f023"
] | [
"bootstrap/datasets/transforms.py"
] | [
"import collections\nimport torch\nfrom torch.autograd import Variable\n\n\nclass Compose(object):\n \"\"\"Composes several collate together.\n\n Args:\n transforms (list of ``Collate`` objects): list of transforms to compose.\n \"\"\"\n\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, batch):\n for transform in self.transforms:\n batch = transform(batch)\n return batch\n\n\nclass ListDictsToDictLists(object):\n\n def __init__(self):\n pass\n\n def __call__(self, batch):\n batch = self.ld_to_dl(batch)\n return batch\n\n def ld_to_dl(self, batch):\n if isinstance(batch[0], collections.Mapping):\n return {key: self.ld_to_dl([d[key] for d in batch]) for key in batch[0]}\n else:\n return batch\n\n\nclass PadTensors(object):\n\n def __init__(self, value=0, use_keys=None, avoid_keys=None):\n self.value = value\n self.use_keys = use_keys or []\n self.avoid_keys = avoid_keys or []\n\n def __call__(self, batch):\n batch = self.pad_tensors(batch)\n return batch\n\n def pad_tensors(self, batch):\n if isinstance(batch, collections.Mapping):\n out = {}\n for key, value in batch.items():\n if (key in self.use_keys) or \\\n (len(self.use_keys) == 0 and key not in self.avoid_keys):\n out[key] = self.pad_tensors(value)\n else:\n out[key] = value\n return out\n elif isinstance(batch, collections.Sequence) and torch.is_tensor(batch[0]):\n max_size = [max(item.size(i) for item in batch) for i in range(batch[0].dim())]\n max_size = torch.Size(max_size)\n n_batch = []\n for item in batch:\n if item.size() != max_size:\n n_item = item.new(max_size).fill_(self.value)\n # TODO: Improve this\n if item.dim() == 1:\n n_item[:item.size(0)] = item\n elif item.dim() == 2:\n n_item[:item.size(0), :item.size(1)] = item\n elif item.dim() == 3:\n n_item[:item.size(0), :item.size(1), :item.size(2)] = item\n else:\n raise ValueError\n n_batch.append(n_item)\n else:\n n_batch.append(item)\n return n_batch\n else:\n return batch\n\n\nclass StackTensors(object):\n\n def __init__(self, use_shared_memory=False, avoid_keys=None):\n self.use_shared_memory = use_shared_memory\n self.avoid_keys = avoid_keys or []\n\n def __call__(self, batch):\n batch = self.stack_tensors(batch)\n return batch\n\n # key argument is useful for debuging\n def stack_tensors(self, batch, key=None):\n if isinstance(batch, collections.Mapping):\n out = {}\n for key, value in batch.items():\n if key not in self.avoid_keys:\n out[key] = self.stack_tensors(value, key=key)\n else:\n out[key] = value\n return out\n elif isinstance(batch, collections.Sequence) and torch.is_tensor(batch[0]):\n out = None\n if self.use_shared_memory:\n # If we're in a background process, concatenate directly into a\n # shared memory tensor to avoid an extra copy\n numel = sum(x.numel() for x in batch)\n storage = batch[0].storage()._new_shared(numel)\n out = batch[0].new(storage)\n return torch.stack(batch, 0, out=out)\n else:\n return batch\n\n\nclass CatTensors(object):\n\n def __init__(self, use_shared_memory=False, use_keys=None, avoid_keys=None):\n self.use_shared_memory = use_shared_memory\n self.use_keys = use_keys or []\n self.avoid_keys = avoid_keys or []\n\n def __call__(self, batch):\n batch = self.cat_tensors(batch)\n return batch\n\n def cat_tensors(self, batch):\n if isinstance(batch, collections.Mapping):\n out = {}\n for key, value in batch.items():\n if (key in self.use_keys) or \\\n (len(self.use_keys) == 0 and key not in self.avoid_keys):\n out[key] = self.cat_tensors(value)\n if ('batch_id' not in out) and torch.is_tensor(value[0]):\n out['batch_id'] = torch.cat(\n [i * torch.ones(x.size(0)) for i, x in enumerate(value)], 0)\n else:\n out[key] = value\n return out\n elif isinstance(batch, collections.Sequence) and torch.is_tensor(batch[0]):\n out = None\n if self.use_shared_memory:\n # If we're in a background process, concatenate directly into a\n # shared memory tensor to avoid an extra copy\n numel = sum(x.numel() for x in batch)\n storage = batch[0].storage()._new_shared(numel)\n out = batch[0].new(storage)\n return torch.cat(batch, 0, out=out)\n else:\n return batch\n\n\nclass ToCuda(object):\n\n def __init__(self, *args, **kwargs):\n pass\n\n def __call__(self, batch):\n batch = self.to_cuda(batch)\n return batch\n\n def to_cuda(self, batch):\n if isinstance(batch, collections.Mapping):\n return {key: self.to_cuda(value) for key, value in batch.items()}\n elif torch.is_tensor(batch):\n # TODO: verify async usage\n return batch.cuda(non_blocking=True)\n elif type(batch).__name__ == 'Variable':\n # TODO: Really hacky\n return Variable(batch.data.cuda(non_blocking=True))\n elif isinstance(batch, collections.Sequence) and torch.is_tensor(batch[0]):\n return [self.to_cuda(value) for value in batch]\n else:\n return batch\n\n\nclass ToCpu(object):\n\n def __init__(self, *args, **kwargs):\n pass\n\n def __call__(self, batch):\n batch = self.to_cpu(batch)\n return batch\n\n def to_cpu(self, batch):\n if isinstance(batch, collections.Mapping):\n return {key: self.to_cpu(value) for key, value in batch.items()}\n elif torch.is_tensor(batch):\n return batch.cpu()\n elif type(batch).__name__ == 'Variable':\n # TODO: Really hacky\n return Variable(batch.data.cpu())\n elif isinstance(batch, collections.Sequence) and torch.is_tensor(batch[0]):\n return [self.to_cpu(value) for value in batch]\n else:\n return batch\n\n\nclass ToVariable(object):\n\n def __init__(self, volatile=False):\n self.volatile = volatile\n\n def __call__(self, batch):\n batch = self.to_variable(batch)\n return batch\n\n def to_variable(self, batch):\n if torch.is_tensor(batch):\n if self.volatile:\n return Variable(batch, volatile=True)\n else:\n return Variable(batch)\n elif isinstance(batch, collections.Mapping):\n return {key: self.to_variable(value) for key, value in batch.items()}\n elif isinstance(batch, collections.Sequence) and torch.is_tensor(batch[0]):\n return [self.to_variable(value) for value in batch]\n else:\n return batch\n\n\nclass ToDetach(object):\n\n def __init__(self):\n pass\n\n def __call__(self, batch):\n batch = self.to_detach(batch)\n return batch\n\n def to_detach(self, batch):\n if torch.is_tensor(batch):\n return batch.detach_()\n elif isinstance(batch, collections.Mapping):\n return {key: self.to_detach(value) for key, value in batch.items()}\n elif isinstance(batch, collections.Sequence) and torch.is_tensor(batch[0]):\n return [self.to_detach(value) for value in batch]\n else:\n return batch\n\n\nclass SortByKey(object):\n\n def __init__(self, key='lengths', reverse=True):\n self.key = key\n self.reverse = True\n self.i = 0\n\n def __call__(self, batch):\n self.set_sort_keys(batch[self.key]) # must be a list\n batch = self.sort_by_key(batch)\n return batch\n\n def set_sort_keys(self, sort_keys):\n self.i = 0\n self.sort_keys = sort_keys\n\n # ugly hack to be able to sort without lambda function\n def get_key(self, _):\n key = self.sort_keys[self.i]\n self.i += 1\n if self.i >= len(self.sort_keys):\n self.i = 0\n return key\n\n def sort_by_key(self, batch):\n if isinstance(batch, collections.Mapping):\n return {key: self.sort_by_key(value) for key, value in batch.items()}\n elif type(batch) is list: # isinstance(batch, collections.Sequence):\n return sorted(batch, key=self.get_key, reverse=self.reverse)\n else:\n return batch\n"
] | [
[
"torch.Size",
"torch.cat",
"torch.is_tensor",
"torch.stack",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
GiacobboNicola/PeTar | [
"ed40946abbe346e2b0e72ae836add7e38bf851c1"
] | [
"tools/analysis/base.py"
] | [
"# base class and functions\nimport numpy as np\n\nclass DictNpArrayMix:\n \"\"\" The basic class of data structure\n The member functions are initialized by provided keys in initial function\n Member functions can be accessed by using the stype of either Dictonary or numpy.ndarray\n \"\"\"\n def __init__(self, keys, _dat=None, _offset=int(0), _append=False, **kwargs):\n \"\"\"\n Parameters\n ----------\n keys: list of class member name and the corresponding types or numpy.ndarray shape\n Class members list description. Defined by inherited types\n For exmaple: keys=[['mass',numpy.float64],['pos',(numpy.float64,3)],['sub1',typename],['sub2',(typename,kwargs)]], will provide class members: mass (1D numpy.ndarray), pos ( 2D numpy.ndarray with a shape of (*,3)), sub1 (a class instance with the type of typename) and sub2 (a type based on DictNpArrayMix with additional keyword arguments, kwargs)\n _dat: numpy.ndarray | type(self) | None\n If it is 2D numpy.ndarray type data, read data as readArray function\n If it is the same class type, copy the data \n If it is None, initial class with empty data\n _offset: int (0)\n Reading column offset of _dat if it is 2D np.ndarray\n _append: bool (False)\n If true, append keys and ncols to the current class instead of create new class members\n kwargs: dict ()\n keyword arguments, defined by inherited types\n \"\"\"\n self.initargs = kwargs.copy()\n\n if (_append): self.keys = self.keys + keys\n else: self.keys = keys.copy()\n if (issubclass(type(_dat), DictNpArrayMix)):\n icol = int(0)\n for key, parameter in keys:\n if (type(parameter) == type):\n if (issubclass(parameter, DictNpArrayMix)):\n self.__dict__[key] = parameter(_dat.__dict__[key], **kwargs)\n icol += self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat.__dict__[key].copy()\n icol += 1\n #raise ValueError('Initial fail, unknown key type, should be inherience of DictNpArrayMix, given ',parameter)\n elif (type(parameter)==tuple):\n if (type(parameter[0]) == type) & (type(parameter[1]) == int):\n self.__dict__[key] = _dat.__dict__[key].copy()\n icol += parameter[1]\n elif (type(parameter[0]) == type) & (type(parameter[1])==dict):\n if(issubclass(parameter[0], DictNpArrayMix)):\n self.__dict__[key] = parameter[0](_dat.__dict__[key], **{**kwargs, **parameter[1]})\n icol += self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat.__dict__[key].copy()\n icol += 1\n else:\n raise ValueError('Initial fail, unknown key type ',parameter[0],' and column count ', parameter[1] )\n else:\n raise ValueError('Initial fail, unknown key parameter, should be DictNpArrayMix type name or value of int, given ',parameter)\n if (_append): self.ncols += int(icol)\n else: self.ncols = int(icol)\n self.size = _dat.size\n elif (type(_dat)==np.ndarray):\n icol = _offset\n self.size = int(0)\n for key, parameter in keys:\n if (type(parameter) == type):\n if (issubclass(parameter, DictNpArrayMix)):\n self.__dict__[key] = parameter(_dat, icol, False, **kwargs)\n icol += self.__dict__[key].ncols\n self.size += self.__dict__[key].size*self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat[:,icol].astype(parameter)\n icol += 1\n self.size += self.__dict__[key].size\n #raise ValueError('Initial fail, unknown key type, should be inherience of DictNpArrayMix, given ',parameter)\n elif (type(parameter)==tuple):\n if (type(parameter[0]) == type) & (type(parameter[1]) == int):\n self.__dict__[key] = _dat[:,icol:icol+parameter[1]].astype(parameter[0])\n icol += parameter[1]\n self.size += self.__dict__[key].size\n elif (type(parameter[0]) == type) & (type(parameter[1])==dict):\n if(issubclass(parameter[0], DictNpArrayMix)):\n self.__dict__[key] = parameter[0](_dat, icol, False, **{**kwargs, **parameter[1]})\n icol += self.__dict__[key].ncols\n self.size += self.__dict__[key].size*self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat[:,icol].astype(parameter[0])\n icol += 1\n self.size += self.__dict__[key].size\n else:\n raise ValueError('Initial fail, unknown key type ',parameter[0],' and column count ', parameter[1] )\n else:\n raise ValueError('Initial fail, unknown key parameter, should be DictNpArrayMix type name or value of int, given ',parameter)\n icol -= _offset\n if (_append): self.ncols += int(icol)\n else: self.ncols = int(icol)\n self.size = int(self.size/icol)\n if (self.size != _dat.shape[0]):\n raise ValueError('Reading error, final counted size ',self.size,' is not consistent with reading ndarray shape',_dat.shape[0])\n elif (_dat==None):\n icol = int(0)\n for key, parameter in keys:\n if (type(parameter) == type):\n if (issubclass(parameter, DictNpArrayMix)):\n self.__dict__[key] = parameter(**kwargs)\n icol += self.__dict__[key].ncols\n else:\n self.__dict__[key] = np.empty(0).astype(parameter)\n icol += 1\n #raise ValueError('Initial fail, unknown key type, should be inherience of DictNpArrayMix, given b',parameter)\n elif (type(parameter)==tuple):\n if (type(parameter[0]) == type) & (type(parameter[1]) == int):\n self.__dict__[key] = np.empty([0,parameter[1]]).astype(parameter[0])\n icol += parameter[1]\n elif (type(parameter[0]) == type) & (type(parameter[1])==dict):\n if(issubclass(parameter[0], DictNpArrayMix)):\n self.__dict__[key] = parameter[0](**{**kwargs, **parameter[1]})\n icol += self.__dict__[key].ncols\n else:\n self.__dict__[key] = np.empty(0).astype(parameter[0])\n icol += 1\n else:\n raise ValueError('Initial fail, unknown key type ',parameter[0],' and column count ', parameter[1] )\n else:\n raise ValueError('Initial fail, unknown key parameter, should be DictNpArrayMix type name or value of int, given ',parameter)\n if (_append): self.ncols += int(icol)\n else: self.ncols = int(icol)\n self.size = int(0)\n else:\n raise ValueError('Initial fail, date type should be ',type(self),' or np.ndarray, given ',type(_dat))\n\n def readArray(self, _dat, _offset=int(0),**kwargs):\n \"\"\" Read class member data from a 2D numpy.ndarray\n Parameters\n ----------\n _dat: numpy.ndarray \n Read 2D array, rows are the event, columns are members. The class members are filled in the order of items in keys provided in the initial function.\n For exmaple: if keys are [['mass',1],['pos',3]], the member mass = _dat[:,_offset] and pos = _dat[:,_offset+1:_offset+3]\n _offset: int (0)\n Reading column offset of _dat if it is 2D np.ndarray\n kwaygs: dict ()\n keyword arguments\n \"\"\"\n icol = _offset\n self.size = int(0)\n for key, parameter in self.keys:\n if (type(parameter) == type):\n if (issubclass(parameter, DictNpArrayMix)):\n self.__dict__[key].readArray(_dat, icol, **kwargs)\n icol += self.__dict__[key].ncols\n self.size += self.__dict__[key].size*self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat[:,icol].astype(parameter)\n icol += 1\n self.size += self.__dict__[key].size\n #raise ValueError('Initial fail, unknown key type, should be inherience of DictNpArrayMix, given ',parameter)\n elif (type(parameter)==tuple):\n if (type(parameter[0]) == type) & (type(parameter[1]) == int):\n self.__dict__[key] = _dat[:,icol:icol+parameter[1]].astype(parameter[0])\n icol += parameter[1]\n self.size += self.__dict__[key].size\n elif (type(parameter[0]) == type) & (type(parameter[1])==dict):\n if(issubclass(parameter[0], DictNpArrayMix)):\n self.__dict__[key].readArray(_dat, icol, **kwargs,**parameter[1])\n icol += self.__dict__[key].ncols\n self.size += self.__dict__[key].size*self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat[:,icol].astype(parameter[0])\n icol += 1\n self.size += self.__dict__[key].size\n else:\n raise ValueError('Initial fail, unknown key type ',parameter[0],' and column count ', parameter[1] )\n else:\n raise ValueError('Initial fail, unknown key parameter, should be DictNpArrayMix type name or value of int, given ',parameter)\n icol -= _offset\n self.size = int(self.size/icol)\n if (self.size != _dat.shape[0]):\n raise ValueError('Reading error, final counted size ',self.size,' is not consistent with reading ndarray shape',_dat.shape[0])\n if (self.ncols != icol):\n raise ValueError('Column number inconsistence, self ncols ',self.ncols,' key ncols ', icol)\n\n def __getitem__(self, k):\n \"\"\" Map getitem to all members generated from the keys in the initial function, and return a new data filtered by k\n If the member is an inherited type of DictNpArrayMix, also map all sub-members if it.\n\n Parameters\n ----------\n k: filter\n The same type of arguments for numpy.ndarray.__getitem__\n \"\"\"\n if (type(k)==str):\n return self.__dict__[k]\n else:\n cls_type = type(self)\n new_dat = cls_type(**self.initargs)\n new_dat.ncols = self.ncols\n new_dat.size = int(0)\n new_dat.keys = self.keys.copy()\n icol = int(0)\n for key_type in new_dat.keys:\n key = key_type[0]\n item = self.__dict__[key]\n if (type(item) == np.ndarray):\n if item.shape[0]!=self.size:\n raise ValueError('Member ',key,' size/dimension',item.shape, ' is not consistent with the data size',self.size)\n new_dat.__dict__[key] = item[k]\n new_dat.size += new_dat.__dict__[key].size\n if (len(item.shape)>1): icol += item.shape[1]\n else: icol += 1\n elif (issubclass(type(item), DictNpArrayMix)):\n new_item = item[k]\n new_dat.__dict__[key] = new_item\n new_dat.size += new_item.size*new_item.ncols\n icol += new_item.ncols\n new_dat.size = int(new_dat.size/new_dat.ncols)\n if (icol != new_dat.ncols):\n raise ValueError('Column number inconsistent, counted:',icol,' saved ncols:',new_dat.ncols,'keys:',new_dat.keys,'fileter: ',k,' original size:',self.size,' original ncols:',self.ncols)\n return new_dat\n\n def __setitem__(self, k, data):\n \"\"\" Map setitem to all members generated from the keys in the initial function\n If the member is an inherited type of DictNpArrayMix, also map all sub-members if it.\n\n Parameters\n ----------\n k: filter\n The same type of arguments for numpy.ndarray.__getitem__\n data: numpy.ndarray | DictNpArrayNix\n The new data to set\n \"\"\"\n if (type(k)==str):\n self.__dict__[k] = data\n else:\n for key_type in self.keys:\n key = key_type[0]\n self.__dict__[key][k] = data[key]\n\n# def keys(self):\n# return self.__dict__.keys()\n\n def addNewMember(self, key, member):\n \"\"\" Add a new class member\n The ncols is updated also.\n Be careful if the target for adding members is a sub member, the ncols of its parent is not updated.\n This can cause issue for the parent when the size of data is needed to calculate.\n Thus after calling of this function, please also increase the ncols of parents for consistence.\n\n Parameters\n ----------\n key: string\n new member name\n member: numpy.ndarray | DictNpArrayNix\n data binding to the member, should be the same size as existing members in the class\n \"\"\"\n new_key_flag=False\n if (key in self.__dict__.keys()):\n member_old = self.__dict__[key]\n dimension = int(1)\n if (type(member_old)==np.ndarray):\n if len(member_old.shape)>1:\n dimension = member_old.shape[1]\n elif (issubclass(type(member_old), DictNpArrayMix)):\n dimension = member_old.ncols\n self.ncols -= dimension\n member_old = member\n else:\n self.__dict__[key] = member\n new_key_flag=True\n dimension = int(1)\n if (type(member)==np.ndarray):\n if len(member.shape)>1:\n dimension = member.shape[1]\n if(new_key_flag): self.keys.append([key,(type(member[:,0]),dimension)])\n else:\n if(new_key_flag): self.keys.append([key,type(member)])\n elif (issubclass(type(member), DictNpArrayMix)):\n dimension = member.ncols\n if(new_key_flag): self.keys.append([key,type(member)])\n else:\n raise ValueError('New member type should be np.ndarray or DictNpArrayMix, but given ',type(member))\n self.ncols += dimension\n if (self.size != int(member.size/dimension)):\n raise ValueError('New member has different size: ',member.size/dimension, ' host size: ',self.size)\n \n def getherDataToArray(self):\n \"\"\" gether all data to a 2D numpy.ndarray and return it\n An inverse function to readArray\n \"\"\"\n dat_out=np.zeros([self.size,self.ncols])\n icol = int(0)\n for key_type in self.keys:\n key = key_type[0]\n member = self.__dict__[key]\n if (type(member)==np.ndarray):\n if len(member.shape)>1:\n dimension= member.shape[1]\n if (dat_out.shape[0]!=member.shape[0]):\n raise ValueError('Member ',key,' size,dimension ',member.shape,' is not consistent with data output size',dat_out.shape[0])\n for k in range(dimension):\n dat_out[:,icol] = member[:,k]\n icol += 1\n else:\n dat_out[:,icol] = member\n icol += 1\n elif (issubclass(type(member), DictNpArrayMix)):\n ncols = member.ncols\n dat_out[:,icol:icol+ncols] = member.getherDataToArray()\n icol += ncols\n return dat_out\n\n def append(self, *_dat):\n \"\"\" Map the numpy.append function to each member\n Append the numpy.ndarray of each member in a group of input data to the corresponding member in self\n\n Parameters\n *_dat: inherited DictNpArrayMix\n The data should contain all members existing in the self \n \"\"\"\n #for idat in _dat:\n # if (type(idat) != type(self)):\n # raise ValueError('Initial fail, date type not consistent, type [0] is ',type(self),' given ',type(idat))\n data_with_self = [self]+list(_dat)\n for key, item in self.__dict__.items():\n if (type(item) == np.ndarray):\n if (len(item.shape)!=len(_dat[0][key].shape)):\n raise ValueError('Appending data member ',key,' has shape',_dat[0][key].shape,' but self data has shape',item.shape)\n self.__dict__[key] = np.concatenate(tuple(map(lambda x:x.__dict__[key], data_with_self)))\n elif(issubclass(type(item), DictNpArrayMix)):\n self.__dict__[key].append(*tuple(map(lambda x:x.__dict__[key], _dat)))\n self.size += np.sum(tuple(map(lambda x:x.size, _dat)))\n \n def savetxt(self, fname, **kwargs):\n \"\"\" Save class member data to a file\n Use the getherDataToArray and then numpy.savetxt\n\n Parameters\n ----------\n fname: string\n name of the output file\n kwargs: dict\n keyword arguments for numpy.savetxt\n \"\"\"\n dat_out= self.getherDataToArray()\n np.savetxt(fname, dat_out, **kwargs)\n\n def loadtxt(self, fname, **kwargs):\n \"\"\" Load class member data from a file\n Use numpy.loadtxt to read data and then use readArray\n\n Parameters\n ----------\n fname: string\n name of the input file\n kwargs: dict\n keyword arguments for numpy.loadtxt\n \"\"\"\n dat_int = np.loadtxt(fname, ndmin=2, **kwargs)\n self.readArray(dat_int, **kwargs)\n\n def collectDtype(self):\n \"\"\" Collect dtype from keys iteratively for reading BINARY format\n For member with type of DictNpArrayMix, use column name with the prefix of member name + '.'\n \"\"\"\n dt=[]\n for key, parameter in self.keys:\n if (type(parameter) == type):\n if (issubclass(parameter, DictNpArrayMix)):\n dt_sub = self.__dict__[key].collectDtype()\n for item in dt_sub:\n dt.append((key+'.'+item[0], item[1]))\n else:\n dt.append((key, parameter))\n elif (type(parameter) == tuple):\n if (type(parameter[0]) == type) & (type(parameter[1]) == int):\n dt.append((key, parameter))\n elif (type(parameter[0]) == type) & (type(parameter[1])==dict):\n if(issubclass(parameter[0], DictNpArrayMix)):\n dt_sub = self.__dict__[key].collectDtype()\n for item in dt_sub:\n dt.append((key+'.'+item[0], item[1]))\n else:\n dt.append((key, parameter[0]))\n else:\n raise ValueError('Initial fail, unknown key type ',parameter[0],' and column count ', parameter[1] )\n else:\n raise ValueError('Initial fail, unknown key parameter, should be DictNpArrayMix type name or value of int, given ',parameter)\n return dt\n\n def readArrayWithName(self, _dat, _prefix='', **kwargs):\n \"\"\" Read class member data from a numpy.ndarray with names\n Parameters\n ----------\n _dat: numpy.ndarray \n Read array with names of columns (key/member name of class)\n _prefix: string ('')\n The prefix add in front of the name of columns to read. This is used when the current class instance is a sub member (member name is consistent with prefix)\n kwaygs: dict ()\n keyword arguments\n \"\"\"\n icol = int(0)\n self.size = int(0)\n for key, parameter in self.keys:\n if (type(parameter) == type):\n if (issubclass(parameter, DictNpArrayMix)):\n self.__dict__[key].readArrayWithName(_dat, _prefix+key+'.', **kwargs)\n icol += self.__dict__[key].ncols\n self.size += self.__dict__[key].size*self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat[_prefix+key]\n icol += 1\n self.size += self.__dict__[key].size\n elif (type(parameter) == tuple):\n if (type(parameter[0]) == type) & (type(parameter[1]) == int):\n self.__dict__[key] = _dat[_prefix+key]\n icol += parameter[1]\n self.size += self.__dict__[key].size\n elif (type(parameter[0]) == type) & (type(parameter[1])==dict):\n if(issubclass(parameter[0], DictNpArrayMix)):\n self.__dict__[key].readArrayWithName(_dat, _prefix+key+'.', **kwargs,**parameter[1])\n icol += self.__dict__[key].ncols\n self.size += self.__dict__[key].size*self.__dict__[key].ncols\n else:\n self.__dict__[key] = _dat[_prefix+key]\n icol += 1\n self.size += self.__dict__[key].size\n else:\n raise ValueError('Initial fail, unknown key type ',parameter[0],' and column count ', parameter[1] )\n else:\n raise ValueError('Initial fail, unknown key parameter, should be DictNpArrayMix type name or value of int, given ',parameter)\n self.size = int(self.size/icol)\n if (self.size != _dat.size):\n raise ValueError('Reading error, final counted size ',self.size,' is not consistent with reading ndarray shape',_dat.size)\n if (self.ncols != icol):\n raise ValueError('Column number inconsistence, self ncols ',self.ncols,' key ncols ', icol)\n\n def fromfile(self, fname, **kwargs):\n \"\"\" Load clas member data from a file using BINARY format\n Use numpy.fromfile to read data, the dtype is defined by keys (members)\n Notice if the first line is header, offset counts in byte should be used\n\n Parameters\n ----------\n fname: string\n name of the input file\n kwargs: dict\n keyword arguments for numpy.fromfile, notice dtype is already defined, do not provide that\n \"\"\"\n dt = self.collectDtype()\n dat_int = np.fromfile(fname, dtype=dt, **kwargs)\n self.readArrayWithName(dat_int, '', **kwargs)\n\n def printSize(self):\n \"\"\" print size of each member\n Print the shape of each members, used for testing whether the members have consistent size\n \"\"\"\n for key_type in self.keys:\n key = key_type[0]\n member = self.__dict__[key]\n if (type(member)==np.ndarray):\n print(key,member.shape)\n elif (issubclass(type(member), DictNpArrayMix)):\n member.printSize()\n \n \n \ndef join(*_dat):\n \"\"\" Join multiple data to one\n For a list of data with the same type of inherited DictNpArrayNix, this function join all data to one \n \n Parameters\n ----------\n *_dat: inherited DictNpArrayNix\n a group of data to join\n\n return: new joined data\n \"\"\"\n type0 = type(_dat[0])\n for idat in _dat:\n if (type(idat) != type0):\n raise ValueError('Initial fail, date type not consistent, type [0] is ',type0,' given ',type(idat))\n new_dat = type0(**_dat[0].initargs)\n for key, item in _dat[0].__dict__.items():\n if (type(item) == np.ndarray):\n new_dat.__dict__[key] = np.concatenate(tuple(map(lambda x:x.__dict__[key], _dat)))\n elif(issubclass(type(item), DictNpArrayMix)):\n new_dat.__dict__[key] = join(*tuple(map(lambda x:x.__dict__[key], _dat)))\n else:\n new_dat.__dict__[key] = _dat[0].__dict__[key]\n new_dat.size = np.sum(tuple(map(lambda x:x.size, _dat)))\n return new_dat\n\n# vector dot of x, y \nvecDot = lambda x,y: np.sum(x*y,axis=1)\n\ndef cantorPairing(id1, id2):\n \"\"\" Use CantorPairing to map two components id to one binary id\n\n Parameters\n ----------\n id1: 1D numpy.ndarray or int\n ID for component 1\n id2: 1D numpy.ndarray or int\n ID for component 2\n \n return: binary id\n \"\"\" \n i1=np.minimum(id1,id2).astype('int64')\n i2=np.maximum(id1,id2).astype('int64')\n return ((i1+i2+1)*(i1+i2)/2+i2).astype('int64')\n\ndef calcTrh(N, rh, m, G, gamma=0.02): \n \"\"\" Calculate Spitzer one-component half-mass relaxation time\n Trh = 0.138 N^0.5 Rh^1.5 /( G^0.5 m^0.5 ln(gamma N))\n\n Parameters\n ----------\n N: 1D numpy.ndarray or int\n Total number of particles\n rh: 1D numpy.ndarray or float\n Half-mass radius\n m: 1D numpy.ndarray or float\n mass of one particle\n G: float\n Gravitational constant\n gamma: float (0.02 # Giersz M., Heggie D. C., 1996, MNRAS, 279, 1037)\n The coefficient for Coulomb logarithm\n\n return: half-mass relaxation time\n \"\"\"\n return 0.138*N**0.5*rh**1.5/(m**0.5*np.log(gamma*N)*G**0.5)\n\ndef calcTcr(M, rh, G): \n \"\"\" Calculate half-mass crossing time\n Tcr = Rh^1.5/sqrt(G M)\n\n Parameters\n ----------\n M: 1D numpy.ndarray or float\n total mass of the system\n rh: 1D numpy.ndarray or float\n Half-mass radius\n G: float\n Gravitational constant\n\n return: half-mass crossing time\n \"\"\"\n return rh**1.5/np.sqrt(G*M)\n"
] | [
[
"numpy.log",
"numpy.fromfile",
"numpy.minimum",
"numpy.sqrt",
"numpy.maximum",
"numpy.empty",
"numpy.savetxt",
"numpy.zeros",
"numpy.sum",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tdcosim/SolarPV-DER-simulation-utility | [
"03fb1cfd4d255117faced84cf61cd5b7ae59f69f"
] | [
"pvder/DER_components_single_phase_constant_Vdc.py"
] | [
"\"\"\"Single phase constant Vdc PV-DER code.\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport math\nimport cmath\nimport scipy\nimport six\nimport pdb\nimport warnings\n\nfrom pvder.DER_components import SolarPVDER,PVModule\nfrom pvder.grid_components import BaseValues\n\nfrom pvder import utility_functions\nfrom pvder import defaults,templates\nfrom pvder.logutil import LogUtil\n\n\nclass SolarPVDERSinglePhaseConstantVdc(PVModule,SolarPVDER):\t\n\t\"\"\"\n\tClass for describing a Solar Photo-voltaic Distributed Energy Resource consisting of panel, converters, and\n\tcontrol systems.\n\t\n\tAttributes:\n\t\tcount (int): Number of instances of `SolarPVDERSinglePhaseConstantVdc`.\n\t\tn_ODE (int): Number of ODE's.\n\t\n\t\"\"\"\n\tcount = 0\n\n\tdef __init__(self,events,configFile=None,**kwargs): \n\t\t\"\"\"Creates an instance of `SolarPV_DER_SinglePhase`.\n\t\tArgs:\n\t\tevents (SimulationEvents): An instance of `SimulationEvents`.\n\t\tgridModel (Grid): An instance of `Grid`(only need to be suppled for stand alone simulation).\n\t\tpowerRating (float): A scalar specifying the rated power (VA) of the DER.\n\t\tVrmsRating (float): A scalar specifying the rated RMS L-G voltage (V) of the DER.\n\t\tia0,xa0,ua0 (complex): Initial value of inverter states in p.u. of the DER instance.\n\t\txP0,xQ0,xPLL0,wte0 (float): Initial value of inverter states in the DER instance.\n\t\tgridVoltatePhaseA: Initial voltage phasor (V) at PCC - LV side from external program (only need to be suppled if model is not stand alone).\n\t\tstandAlone (bool): Specify if the DER instance is a stand alone simulation or part of a larger simulation.\n\t\tsteadyStateInitialization (bool): Specify whether states in the DER instance will be initialized to steady state values.\n\t\tallowUnbalancedM (bool): Allow duty cycles to take on unbalanced values during initialization (default: False).\n\t\tderConfig (dict): Configuration parameters that may be supplied from an external program.\n\t\tidentifier (str): An identifier that can be used to name the instance (default: None).\n\t\t\n\t\tRaises:\n\t\tValueError: If parameters corresponding to `Sinverter_rated` are not available.\n\t\tValueError: If rated DC link voltage is not sufficient.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tSolarPVDERSinglePhaseConstantVdc.count = SolarPVDERSinglePhaseConstantVdc.count+1 #Increment count to keep track of number of PV-DER model instances\n\t\t\t\t\t\n\t\t\tDER_arguments = self.setup_DER(events,configFile,**kwargs)\n\t\t\t\t\t\t\t\t \n\t\t\tif six.PY3:\n\t\t\t\tsuper().__init__(self.DER_config['basic_options']['Sinsol'])#Initialize PV module class (base class)\n\t\t\telif six.PY2:\n\t\t\t\tsuper(SolarPVDERSinglePhaseConstantVdc,self).__init__(self.DER_config['basic_options']['Sinsol'])\n\t\t\n\t\t\tself.initialize_DER(DER_arguments)\n\t\t\tself.creation_message()\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\t@property#Decorator used for auto updating\n\tdef y0(self):\n\t\t\"\"\"List of initial states\"\"\"\n\t\ttry:\n\t\t\treturn[self.ia.real, self.ia.imag, self.xa.real, self.xa.imag, self.ua.real,self.ua.imag,\n\t\t\t\t\t self.xP,self.xQ,self.xPLL,self.wte]\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\t#Apparent power output at inverter terminal\n\tdef S_calc(self):\n\t\t\"\"\"Inverter apparent power output\"\"\"\n\t\ttry:\n\t\t\treturn (1/2)*(self.vta*self.ia.conjugate())*1.0\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\t#Apparent power output at PCC - LV side\n\tdef S_PCC_calc(self):\n\t\t\"\"\"Power output at PCC LV side\"\"\"\n\t\ttry:\n\t\t\treturn (1/2)*(self.va*self.ia.conjugate())\n\t\t\t#return utility_functions.S_calc(self.va,self.vb,self.vc,self.ia,self.ib,self.ic)\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef S_load1_calc(self):\n\t\t\"\"\"Power absorbed by load at PCC LV side.\"\"\"\n\t\t\n\t\treturn (1/2)*(self.va*(-(self.va/self.Zload1)).conjugate())\n\t\n\tdef S_G_calc(self):\n\t\t\"\"\"Power absorbed/produced by grid voltage source.\"\"\"\n\t\ttry:\n\t\t\treturn (1/2)*(-(self.ia-(self.va/self.Zload1))/self.a).conjugate()*self.grid_model.vag\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\t#@property\n\tdef Vtrms_calc(self):\n\t\t\"\"\"Inverter terminal voltage -RMS\"\"\"\n\t\ttry:\n\t\t\treturn utility_functions.Urms_calc(self.vta,self.vta,self.vta)\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef Vrms_calc(self):\n\t\t\"\"\"PCC LV side voltage - RMS\"\"\"\n\t\ttry:\n\t\t\treturn utility_functions.Urms_calc(self.va,self.va,self.va)\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef Irms_calc(self):\n\t\t\"\"\"Inverter current - RMS\"\"\"\n\t\t\n\t\treturn utility_functions.Urms_calc(self.ia,self.ia,self.ia)\n\t\n\tdef Vabrms_calc(self):\n\t\t\"\"\"PCC LV side voltage - line to lineRMS\"\"\"\n\t\ttry:\n\t\t\treturn abs(self.va-self.vb)/math.sqrt(2)\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef update_inverter_states(self,ia,xa,ua,xP,xQ,xPLL,wte):\n\t\t\"\"\"Update inverter states\n\t\tArgs:\n\t\t\t ia (complex): Inverter phase a current.\n\t\t\t xa (complex): Inverter controller state.\n\t\t\t ua (complex): Inverter controller state.\n\t\t\t Vdc (float): DC link voltage.\t\t\t \n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.ia = ia\n\t\t\tself.xa = xa\n\t\t\tself.ua = ua\n\t\t\n\t\t\tself.xP = xP\n\t\t\tself.xQ = xQ\n\t\t\n\t\t\tself.xPLL = xPLL\n\t\t\tself.wte = wte\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef update_voltages(self):\n\t\t\"\"\"Update voltages.\"\"\"\t\t\n\t\ttry:\n\t\t\tself.vta = self.vta_calc() #Update inverter terminal voltage\n\t\t\tself.va = self.va_calc() #Update PCC LV side voltage\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef update_RMS(self):\n\t\t\"\"\"Update RMS voltages.\"\"\"\n\t\ttry:\n\t\t\tself.Vtrms = self.Vtrms_calc()\n\t\t\tself.Vrms_min = self.Vrms = self.Vrms_calc()\n\t\t\tself.Irms = self.Irms_calc()\n\n\t\t\t#Update RMS values\n\t\t\tif self.DO_EXTRA_CALCULATIONS:\n\t\t\t\tpass\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef update_power(self):\n\t\t\"\"\"Update RMS voltages.\"\"\"\n\t\ttry:\n\t\t\t#Update power output\n\t\t\tself.S = self.S_calc()\n\t\t\tself.S_PCC = self.S_PCC_calc()\n\n\t\t\tif self.standAlone:#Update load current and grid voltage source power only in stand alone mode\n\t\t\t\tself.iaload1 = self.iphload1_calc(self.va)\n\t\t\t\n\t\t\t\tself.S_G = self.S_G_calc()\n\t\t\t\tself.S_load1 = self.S_load1_calc()\t \n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef update_Pref(self):\n\t\t\"\"\"Update active power reference\"\"\" \n\t\ttry:\n\t\t\tif not self.use_Pref:\n\t\t\t\tself.Pref = self.Ppv\n\t\t\telse:\n\t\t\t\traise ValueError('{}:User active power reference not implemented!')\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef update_iref(self,t):\n\t\t\"\"\"Update current reference\"\"\"\n\t\ttry:\n\t\t\tif self.current_gradient_limiter:\n\t\t\t\tself.ia_ref = self.get_ramp_limited_iref(t,self.ia_ref_activepower_control())\n\t\t\telse:\n\t\t\t\tself.ia_ref = self.ia_ref_activepower_control() #Get current controller setpoint\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\tdef update_inverter_frequency(self,t):\n\t\t\"\"\"Update inverter PLL frequency.\n\t\tArgs:\n\t\t\t t (float): Simulation time in seconds.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tself.wgrid_measured = self.wgrid_calc(t) #Update grid frequency\n\n\t\t\t#Convert PCC LV side voltage from phasor to alpha-beta domain\n\t\t\tself.valpha = utility_functions.phasor_to_time_1phase(self.va,w=self.wgrid_measured,t=t)\n\t\t\tself.vbeta =utility_functions.phasor_to_time_1phase(self.va*pow(math.e,-1j*(math.pi/2)),w=self.wgrid_measured,t=t)\n\t\t\n\t\t\t#Convert from alpha-beta domain to d-q domain using Parks transformation\n\t\t\tself.vd,self.vq = utility_functions.alpha_beta_to_d_q(self.valpha,self.vbeta,self.wte)\n\t\t\n\t\t\t#Calculate inverter frequency from PLL equation\n\t\t\tself.we = self.we_calc()\n\t\t\tself.winv = self.we\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\n\tdef ODE_model(self,y,t):\n\t\t\"\"\"System of ODE's defining the dynamic DER model.\n\t\tArgs:\n\t\t\t y (list of float): Initial conditions for the states..\n\t\t\t t (float): Simulation time in seconds.\n\t\t\t \n\t\tReturns:\n\t\t\t result (list of float): Derivates for the system of ODE's.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tiaR, iaI, xaR, xaI, uaR, uaI, xP, xQ, xPLL, wte = y # unpack current values of y\n\t\t\n\t\t\tself.update_inverter_states(iaR + 1j*iaI, xaR + 1j*xaI,uaR + 1j*uaI,\n\t\t\t\t\t\t\t\t\t\txP,xQ,\n\t\t\t\t\t\t\t\t\t\txPLL,wte)\n\t\t \n\t\t\tself.update_Ppv(t)\n\t\t\tself.update_Zload1(t) \n\t\t\n\t\t\tself.update_voltages()\n\t\t\tself.update_power()\t\n\t\t\tself.update_RMS()\t\t\n\t\t\n\t\t\tself.update_Qref(t)\t\t\n\t\t\tself.update_iref(t)\n\t\t\n\t\t\tself.update_inverter_frequency(t)\n\t\t\n\t\t\tself.update_ridethrough_flags(t)\n\t\t\tself.disconnect_or_reconnect(t)\n\t\t\n\t\t\t#Phase a inverter output current\n\t\t\tdiaR = (1/self.Lf)*(-self.Rf*self.ia.real - self.va.real + self.vta.real) + (self.winv/self.wbase)*self.ia.imag \n\t\t\tdiaI = (1/self.Lf)*(-self.Rf*self.ia.imag - self.va.imag + self.vta.imag) - (self.winv/self.wbase)*self.ia.real\n\t\t\n\t\t\t#Current controller dynamics\n\t\t\tif abs(self.Kp_GCC*self.ua + self.xa)>self.m_limit:\n\t\t\t\tif np.sign(self.Ki_GCC*self.ua.real) == np.sign(self.xa.real):\n\t\t\t\t\tdxaR = 0.0\n\t\t\t\telse:\n\t\t\t\t\tdxaR = self.Ki_GCC*self.ua.real\n\t\t\t\tif np.sign(self.Ki_GCC*self.ua.imag) == np.sign(self.xa.imag):\n\t\t\t\t\tdxaI = 0.0\n\t\t\t\telse:\n\t\t\t\t\tdxaI = self.Ki_GCC*self.ua.imag\n\t\t\t\t\t#six.print_(dxaR+1j*dxaI,np.sign(self.Ki_GCC*self.ua))\n\t\t\telse:\n\t\t\t\tdxaR = self.Ki_GCC*self.ua.real\n\t\t\t\tdxaI = self.Ki_GCC*self.ua.imag\n\t\t\t\n\t\t\tif abs(self.Kp_GCC*self.ua + self.xa)>self.m_limit:\n\t\t\t\tif np.sign( (self.wp)*(-self.ua.real +self.ia_ref.real - self.ia.real)) == np.sign(self.ua.real):\n\t\t\t\t\tduaR = 0.0\n\t\t\t\telse:\n\t\t\t\t\tduaR = (self.wp)*(-self.ua.real +self.ia_ref.real - self.ia.real)\n\t\t\t\t\n\t\t\t\tif np.sign((self.wp)*(-self.ua.imag +self.ia_ref.imag - self.ia.imag)) == np.sign(self.ua.imag):\n\t\t\t\t\tduaI = 0.0\n\t\t\t\telse:\n\t\t\t\t\tduaI = (self.wp)*(-self.ua.imag +self.ia_ref.imag - self.ia.imag)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tduaR = (self.wp)*(-self.ua.real +self.ia_ref.real - self.ia.real)\n\t\t\t\tduaI = (self.wp)*(-self.ua.imag +self.ia_ref.imag - self.ia.imag)\n\t\t\n\t\t\t#DC link voltage dynamics\n\t\t\tdVdc = 0.0\n\t\t\t\t\n\t\t\tif abs(self.xP + self.Kp_P*(self.Ppv -self.S.real) + 1j*(self.xQ- self.Kp_Q*(self.Q_ref - self.S_PCC.imag)))>self.iref_limit:\n\t\t\t\tif np.sign(self.Ki_P*(self.Ppv -self.S.real)) == np.sign(self.xP):\n\t\t\t\t\tdxP = 0.0\n\t\t\t\telse:\n\t\t\t\t\tdxP = self.Ki_P*(self.Ppv -self.S.real)\n\t\t\telse:\n\t\t\t\tdxP = self.Ki_P*(self.Ppv -self.S.real)\n\t\t\n\t\t\t# Reactive power controller dynamics\n\t\t\tif abs(self.xP + self.Kp_P*(self.Ppv -self.S.real) + 1j*(self.xQ- self.Kp_Q*(self.Q_ref - self.S_PCC.imag)))>self.iref_limit:\n\t\t\t\n\t\t\t\tif np.sign(-self.Ki_Q*(self.Q_ref - self.S_PCC.imag)) == np.sign(self.xQ):\n\t\t\t\t\tdxQ = 0.0\n\t\t\t\telse:\n\t\t\t\t\tdxQ = -self.Ki_Q*(self.Q_ref - self.S_PCC.imag)\n\t\t\telse:\n\t\t\t\tdxQ = -self.Ki_Q*(self.Q_ref - self.S_PCC.imag)\n\t\t\n\t\t\t#SRF-PLL dynamics\n\t\t\tdxPLL = self.Ki_PLL*(self.vd)\n\t\t\n\t\t\t#Frequency integration to get angle\n\t\t\tdwte = self.we\n\t\t\n\t\t\tresult =\t [ diaR,# list of dy/dt=f functions\n\t\t\t\t\t\t diaI,\n\t\t\t\t\t\t dxaR,\n\t\t\t\t\t\t dxaI,\n\t\t\t\t\t\t duaR,\n\t\t\t\t\t\t duaI,\n\t\t\t\t\t\t dxP,\n\t\t\t\t\t\t dxQ,\n\t\t\t\t\t\t dxPLL,\n\t\t\t\t\t\t dwte]\n\n\t\t\treturn np.array(result)\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\n\tdef jac_ODE_model(self,y,t):\n\t\t\"\"\"Jacobian for the system of ODE's.\n\t\tArgs:\n\t\t\t y (list of float): Initial conditions for the states..\n\t\t\t t (float): Simulation time in seconds.\n\t\tReturns:\n\t\t\t result (array of float): An array containing the elements of the Jacobian.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tiaR, iaI, xaR, xaI, uaR, uaI,xP, xQ, xPLL, wte = y # unpack current values of y\n\t\t\n\t\t\t#self.update_inverter_states(iaR,iaI,xaR,xaI,uaR,uaI,\n\t\t\t#\t\t\t\t\t\t\txP,xQ,\n\t\t\t#\t\t\t\t\t\t\txPLL,wte)\n\t\t\tself.update_inverter_states(iaR + 1j*iaI, xaR + 1j*xaI,uaR + 1j*uaI,\n\t\t\t\t\t\t\t\t\t\txP,xQ,\n\t\t\t\t\t\t\t\t\t\txPLL,wte)\n\t\t\tJ = self.J\n\t\t\tvarInd = self.varInd \n\t\t\tself.update_Ppv(t)\n\t\t\t#self.update_Zload1(t) \n\t\t\n\t\t\tself.update_voltages()\n\t\t\tself.update_power()\n\t\t\tself.update_RMS()\n\t\t\n\t\t\tself.update_Qref(t)\n\t\t\t#self.update_Vdc_ref(t)\t\n\t\t\tself.update_iref(t)\n\t\t\n\t\t\t#d-q transformation\n\t\t\tself.update_inverter_frequency(t)\n\t\t\n\t\t\tself.update_ridethrough_flags(t)\n\t\t\tself.disconnect_or_reconnect(t)\n\t\t\t#Phase a inverter output current\n\t\t\n\t\t\tra,theta_a = cmath.polar(self.va)\n\n\t\t\ttheta_a = self.wgrid_measured*t + theta_a - math.pi/2\n\t\t\t\n\t\t\tJ[varInd['iaR'],varInd['iaR']] = -self.Rf/self.Lf\t\t\t\n\t\t\tJ[varInd['iaR'],varInd['iaI']] = (self.xPLL+self.Kp_PLL*self.vd+2*math.pi*60)/self.wbase\n\t\t\tJ[varInd['iaR'],varInd['xaR']] = self.Vdc/(2*self.Lf)\n\t\t\tJ[varInd['iaR'],varInd['uaR']] = (self.Vdc*self.Kp_GCC)/(2*self.Lf)\n\t\t\tJ[varInd['iaR'],varInd['xPLL']] = self.ia.imag/self.wbase\n\t\t\tJ[varInd['iaR'],varInd['wte']] = ((self.Kp_PLL*self.ia.imag*ra)/self.wbase)*(-math.cos(theta_a)*math.sin(self.wte)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ math.cos(theta_a-math.pi/2)*math.cos(self.wte))\n\t\t\n\t\t\tJ[varInd['iaI'],varInd['iaR']]= -(self.xPLL+self.Kp_PLL*self.vd+2*math.pi*60)/self.wbase\n\t\t\tJ[varInd['iaI'],varInd['iaI']]= -self.Rf/self.Lf\n\t\t\tJ[varInd['iaI'],varInd['xaI']]= self.Vdc/(2*self.Lf) \n\t\t\tJ[varInd['iaI'],varInd['uaI']]= (self.Vdc*self.Kp_GCC)/(2*self.Lf)\n\t\t\tJ[varInd['iaI'],varInd['xPLL']]= -self.ia.real/self.wbase\n\t\t\tJ[varInd['iaI'],varInd['wte']] = ((self.Kp_PLL*self.ia.real*ra)/self.wbase)*(-math.cos(theta_a)*math.sin(self.wte)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ math.cos(theta_a-math.pi/2)*math.cos(self.wte))\n\t\t\t\n\t\t\t#Current controller dynamics\n\t\t\tif abs(self.Kp_GCC*self.ua + self.xa)>self.m_limit:\n\t\t\t\tif np.sign(self.Ki_GCC*self.ua.real) == np.sign(self.xa.real):\n\t\t\t\t\tJ[varInd['xaR'],varInd['uaR']]=0.0\n\t\t\t\telse:\n\t\t\t\t\tJ[varInd['xaR'],varInd['uaR']]=self.Ki_GCC\n\t\t\t\tif np.sign(self.Ki_GCC*self.ua.imag) == np.sign(self.xa.imag):\n\t\t\t\t\tJ[varInd['xaI'],varInd['uaI']]=0.0\n\t\t\t\telse:\n\t\t\t\t\tJ[varInd['xaI'],varInd['uaI']]=self.Ki_GCC\n\t\t\t\t\n\t\t\telse:\n\t\t\t\t\tJ[varInd['xaR'],varInd['uaR']]=self.Ki_GCC\n\t\t\t\t\tJ[varInd['xaI'],varInd['uaI']]=self.Ki_GCC\n\t\t\n\t\t\tif abs(self.Kp_GCC*self.ua + self.xa)>self.m_limit:\n\t\t\t\tif np.sign( (self.wp)*(-self.ua.real +self.ia_ref.real - self.ia.real)) == np.sign(self.ua.real):\n\t\t\t\t\tJ[varInd['uaR'],varInd['iaR']]= 0.0\n\t\t\t\t\tJ[varInd['uaR'],varInd['uaR']]= 0.0\n\t\t\t\t\tJ[varInd['uaR'],varInd['xP']]= 0.0 \n\t\t\t\telse:\n\t\t\t\t\t#duaR = (self.wp)*(-self.ua.real +self.ia_ref.real - self.ia.real)\n\t\t\t\t\tJ[varInd['uaR'],varInd['iaR']]= -self.wp\n\t\t\t\t\tJ[varInd['uaR'],varInd['uaR']]= -self.wp\n\t\t\t\t\tJ[varInd['uaR'],varInd['xP']]= self.wp\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\tif np.sign((self.wp)*(-self.ua.imag +self.ia_ref.imag - self.ia.imag)) == np.sign(self.ua.imag):\n\t\t\t\t\t#duaI = 0.0\n\t\t\t\t\tJ[varInd['uaI'],varInd['iaR']]= 0.0\n\t\t\t\t\tJ[varInd['uaI'],varInd['iaI']]= 0.0\n\t\t\t\t\tJ[varInd['uaI'],varInd['uaI']]= 0.0\n\t\t\t\t\tJ[varInd['uaI'],varInd['xQ']]= 0.0\n\n\t\t\t\telse:\n\t\t\t\t\t#duaI = (self.wp)*(-self.ua.imag +self.ia_ref.imag - self.ia.imag)\n\t\t\t\t\tJ[varInd['uaI'],varInd['iaR']]= (self.Kp_Q*self.wp*self.va.imag/2)\n\t\t\t\t\tJ[varInd['uaI'],varInd['iaI']]= -self.wp - (self.Kp_Q*self.wp*self.va.real/2)\n\t\t\t\t\tJ[varInd['uaI'],varInd['uaI']]= -self.wp\n\t\t\t\t\tJ[varInd['uaI'],varInd['xQ']]= self.wp\n\t\t\t\t\n\t\t\telse:\n\t\t\t\t#duaR = (self.wp)*(-self.ua.real +self.ia_ref.real - self.ia.real)\n\t\t\t\t#duaI = (self.wp)*(-self.ua.imag +self.ia_ref.imag - self.ia.imag)\n\t\t\t\tJ[varInd['uaR'],varInd['iaR']]= -self.wp\n\t\t\t\tJ[varInd['uaR'],varInd['uaR']]= -self.wp\n\t\t\t\t#J[varInd['uaR'],varInd['Vdc']]= -self.wp*self.Kp_DC\n\t\t\t\tJ[varInd['uaR'],varInd['xP']]= self.wp \n\t\t\t\t\n\t\t\t\tJ[varInd['uaI'],varInd['iaR']]= (self.Kp_Q*self.wp*self.va.imag/2)\n\t\t\t\tJ[varInd['uaI'],varInd['iaI']]= -self.wp - (self.Kp_Q*self.wp*self.va.real/2)\n\t\t\t\tJ[varInd['uaI'],varInd['uaI']]= -self.wp\n\t\t\t\tJ[varInd['uaI'],varInd['xQ']]= self.wp\n\t\t\t \n\t\t\t#Active power controller dynamics\n\t\t\tif abs(self.xP + self.Kp_P*(self.Ppv -self.S.real) + 1j*(self.xQ- self.Kp_Q*(self.Q_ref - self.S_PCC.imag)))>self.iref_limit:\n\t\t\t\tif np.sign(self.Ki_P*(self.Vdc_ref - self.Vdc)) == np.sign(self.xP):\n\t\t\t\t\t#dxP = 0.0\n\t\t\t\t\tJ[varInd['xP'],varInd['iaR']]= 0.0\n\t\t\t\t\tJ[varInd['xP'],varInd['iaI']]= 0.0\n\t\t\t\telse:\n\t\t\t\t\t#dxP = self.Ki_P*(self.Ppv -self.S.real)\n\t\t\t\t\tJ[varInd['xP'],varInd['iaR']]= (self.Ki_P*self.va.imag/2)\n\t\t\t\t\tJ[varInd['xP'],varInd['iaI']]= -(self.Ki_P*self.va.real/2)\n\t\t\telse:\n\t\t\t\t#dxP = self.Ki_P*(self.Ppv -self.S.real)\n\t\t\t\tJ[varInd['xP'],varInd['iaR']]= (self.Ki_P*self.va.imag/2)\n\t\t\t\tJ[varInd['xP'],varInd['iaI']]= -(self.Ki_P*self.va.real/2)\n\t\t\t\t\t\n\t\t\t# Reactive power controller dynamics\n\t\t\tif abs(self.xP + self.Kp_P*(self.Ppv -self.S.real) + 1j*(self.xQ- self.Kp_Q*(self.Q_ref - self.S_PCC.imag)))>self.iref_limit:\n\t\t\t\tif np.sign(-self.Ki_Q*(self.Q_ref - self.S_PCC.imag)) == np.sign(self.xQ):\n\t\t\t\t\t#dxQ = 0.0\n\t\t\t\t\tJ[varInd['xQ'],varInd['iaR']]= 0.0\n\t\t\t\t\tJ[varInd['xQ'],varInd['iaI']]= 0.0\n\n\t\t\t\telse:\n\t\t\t\t\t#dxQ = -self.Ki_Q*(self.Q_ref - self.S_PCC.imag)\n\t\t\t\t\tJ[varInd['xQ'],varInd['iaR']]= (self.Ki_Q*self.va.imag/2)\n\t\t\t\t\tJ[varInd['xQ'],varInd['iaI']]= -(self.Ki_Q*self.va.real/2)\n\t\t\n\t\t\telse:\n\t\t\t\t#dxQ = -self.Ki_Q*(self.Q_ref - self.S_PCC.imag)\n\t\t\t\tJ[varInd['xQ'],varInd['iaR']]= (self.Ki_Q*self.va.imag/2)\n\t\t\t\tJ[varInd['xQ'],varInd['iaI']]= -(self.Ki_Q*self.va.real/2)\n\t\t\n\t\t\t#SRF-PLL dynamics\n\t\t\t#dxPLL = self.Ki_PLL*(self.vd)\n\t\t\tJ[varInd['xPLL'],varInd['wte']] = (self.Ki_PLL*ra)*(-math.cos(theta_a)*math.sin(self.wte)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ math.cos(theta_a-math.pi/2)*math.cos(self.wte))\n\t\t\n\t\t\t#Frequency integration to get angle\n\t\t\t#dwte = self.we\n\t\t\tJ[varInd['wte'],varInd['xPLL']]= 1\n\t\t\tJ[varInd['wte'],varInd['wte']] = (self.Kp_PLL*ra)*(-math.cos(theta_a)*math.sin(self.wte)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ math.cos(theta_a-math.pi/2)*math.cos(self.wte))\n\n\t\t\treturn J\n\t\texcept:\n\t\t\tLogUtil.exception_handler()\n\n\n"
] | [
[
"numpy.sign",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SidGoyal2014/Real-Estate-Price-Estimator | [
"f97356c7a911853cc9c40640298f6a5ae0f04cb8"
] | [
"app.py"
] | [
"import streamlit as st\r\nimport joblib\r\nimport numpy as np\r\nfrom flask import Flask,jsonify,request\r\nimport requests\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nimport os\r\nimport random\r\n\r\ndef main():\r\n st.title(\"Know the exact price of the house, if you are in Chennai\")\r\n st.subheader(\"ML Based Real Estate Price Estimator\")\r\n st.write(\"_______________________________________________________________________\")\r\n \r\n st.sidebar.title(\"Know the exact price of the house, of you are in Chennai\")\r\n st.sidebar.subheader(\"ML Based Real Estate Price Estimator\")\r\n st.sidebar.write(\"__________________________________________________________\")\r\n \r\n ##### First of all Display some text to give user a feel\r\n st.write(\"The Price of any Real Estate Property depends upon many factors like: \")\r\n st.write(\"1. Locality\")\r\n st.write(\"2. Area\")\r\n st.write(\"3. Distance from Mainroad\")\r\n st.write(\"4. etc.\")\r\n \r\n st.write(\"This ML software takes into account, various factors like Locality, Area, Quality score of rooms etc, for most accurate estimation.\")\r\n \r\n # @st.cache(persist = True)\r\n def take_input():\r\n \r\n # Area selection\r\n area = st.sidebar.selectbox(\"Choose Area:\",(\"Karapakkam\",\"Adyar\",\"Anna Nagar\",\"Chrompet\",\"KK Nagar\",\"T Nagar\",\"Velachery\"))\r\n # st.write(\"The locality is : \",area)\r\n \r\n #\"\"\"\r\n ## def imag():\r\n ## Display the image\r\n #path = os.getcwd()\r\n ##path = path + \"\\Images\" + \"\\\\\" + \"Chennai\\\\\"+ area\r\n #num = random.randint(1,5)\r\n #path = path + \"\\\\\" + str(num) + \".jpg\"\r\n #print(\"path : \",path)\r\n #st.image(path,channels=\"RGB\")\r\n #\"\"\"\r\n \r\n # Int SQFT area\r\n int_sqft = st.sidebar.number_input(\"Enter the area (in SQFT)\",min_value=100)\r\n int_sqft = int(int_sqft)\r\n # st.write(\"The area is : \",int_sqft)\r\n \r\n # DIST_MAINROAD\r\n dist_mainroad = st.sidebar.number_input(\"Enter the distance from the mainroad (in KMs)\",min_value=0.0)\r\n dist_mainroad = int(dist_mainroad)\r\n # st.write(\"The distance from the mainroad is : \",dist_mainroad)\r\n \r\n # Number of Bedrooms (N_BEDROOM)\r\n n_bedroom = st.sidebar.selectbox(\"The number of bedrooms:\",(1,2,3,4,5))\r\n # st.write(\"The number of bedrooms: \",n_bedroom)\r\n \r\n # Number of Bedrooms (N_BATHROOM)\r\n n_bathroom = st.sidebar.selectbox(\"The number of bathrooms:\",(1,2,3,4,5))\r\n # st.write(\"The number of bathrooms: \",n_bathroom)\r\n \r\n # Number of rooms (N_ROOMS)\r\n n_rooms = st.sidebar.selectbox(\"The number of Rooms:\",(1,2,3,4,5,6,7,8,9,10))\r\n # st.write(\"Total number of rooms: \",n_rooms)\r\n \r\n # The sale condition (SALE_COND)\r\n sale_condition = st.sidebar.selectbox(\"Select the sale condition:\",(\"AbNormal\",\"AdjLand\",\"Family\",\"Normal Sale\",\"Partial\"))\r\n # st.write(\"The sale condition of the house: \",sale_condition)\r\n \r\n # Park Facil (PARK_FACIL)\r\n park_facing = st.sidebar.selectbox(\"Select if the house if park facing or not\",(\"Yes\",\"No\"))\r\n # st.write(\"Park Facing : \",park_facing)\r\n \r\n # Buildtype (BUILDTYPE)\r\n buildtype = st.sidebar.selectbox(\"Select the buildtype:\",(\"Commercial\",\"House\",\"Others\"))\r\n # st.write(\"The buildtype is: \",buildtype)\r\n \r\n # utility (UTILITY)\r\n utility = st.sidebar.selectbox(\"Select the utility:\",(\"AllPub\",\"ELO\",\"NoSeWa\",\"NoSewr\"))\r\n # st.write(\"The utility: \",utility)\r\n \r\n # Street type (STREET)\r\n street = st.sidebar.selectbox(\"Select the street:\",(\"Gravel\",\"No Access\",\"Paved\"))\r\n # st.write(\"The street is: \",street)\r\n \r\n # MZZONE\r\n mzzone = st.sidebar.selectbox(\"Select the mzzone:\",(\"A\",\"C\",\"I\",\"RH\",\"RL\",\"RM\",\"If you don't have info about this\"))\r\n # st.write(\"The mzzone: \",mzzone)\r\n \r\n if(mzzone == \"If you don't have info about this\"):\r\n # Seperate procedure\r\n print(\"There is a seperate procedure\")\r\n \r\n # The quality score of rooms (QS_ROOMS)\r\n qs_rooms = st.sidebar.number_input(\"Enter the overall quality score of all rooms (0,5)\",min_value=0.0,max_value=5.0)\r\n # st.write(\"The quality score of rooms: \",qs_rooms)\r\n \r\n # The quality score of bedrooms (QS_BEDROOM)\r\n qs_bedroom = st.sidebar.number_input(\"Enter the Quality score of bedrooms (0-5)\",min_value=0.0,max_value=5.0)\r\n # st.write(\"The quality score of bedrooms: \",qs_bedroom)\r\n \r\n \r\n list_val = [[area,int_sqft,dist_mainroad,n_bedroom,n_bathroom,n_rooms,sale_condition,park_facing,buildtype,utility,street,mzzone,qs_rooms,qs_bedroom]]\r\n list_idx = [\"AREA\",\"INT_SQFT\",\"DIST_MAINROAD\",\"N_BEDROOM\",\"N_BATHROOM\",\"N_ROOM\",\"SALE_COND\",\"PARK_FACIL\",\"BUILDTYPE\",\"UTILITY\",\"STREET\",\"MZZONE\",\"QS_ROOMS\",\"QS_BEDROOM\"]\r\n \r\n return list_val,list_idx\r\n \r\n list_val,list_idx = take_input()\r\n \r\n # print(\"List Value: \",list_val)\r\n # print(\"List Index: \",list_idx)\r\n \r\n @st.cache(persist = True)\r\n def dataframe_prep(list_val,list_idx):\r\n \r\n temp_df = pd.DataFrame(list_val, columns=list_idx)\r\n \r\n temp_df = pd.get_dummies(temp_df)\r\n \r\n ## print(temp_df)\r\n \r\n final_col = ['INT_SQFT', 'DIST_MAINROAD', 'N_BEDROOM', 'N_BATHROOM', 'N_ROOM','QS_ROOMS', 'QS_BEDROOM', 'AREA_Adyar','AREA_Anna Nagar', 'AREA_Chrompet', 'AREA_KK Nagar', 'AREA_Karapakkam','AREA_T Nagar', 'AREA_Velachery', 'SALE_COND_AbNormal','SALE_COND_AdjLand', 'SALE_COND_Family', 'SALE_COND_Normal Sale','SALE_COND_Partial', 'PARK_FACIL_No', 'PARK_FACIL_Yes','BUILDTYPE_Commercial', 'BUILDTYPE_House', 'BUILDTYPE_Others','UTILITY_AVAIL_AllPub', 'UTILITY_AVAIL_ELO', 'UTILITY_AVAIL_NoSeWa','UTILITY_AVAIL_NoSewr ', 'STREET_Gravel', 'STREET_No Access','STREET_Paved', 'MZZONE_A', 'MZZONE_C', 'MZZONE_I', 'MZZONE_RH','MZZONE_RL', 'MZZONE_RM']\r\n \r\n df_final= temp_df.reindex(columns=final_col,fill_value=0)\r\n \r\n poly = PolynomialFeatures(degree = 2)\r\n \r\n df_final = poly.fit_transform(df_final)\r\n \r\n # print(df_final)\r\n return df_final\r\n\r\n @st.cache(persist = True)\r\n def prediction(df_final):\r\n \r\n prediction = lr.predict(df_final)\r\n \r\n prediction = prediction[0]\r\n \r\n return prediction\r\n \r\n # Prepare the dataframe\r\n df_final = dataframe_prep(list_val,list_idx)\r\n \r\n # print(df_final)\r\n \r\n # Predct the price\r\n if(st.sidebar.button(\"Predict\",key=\"Predict\")):\r\n price = prediction(df_final)\r\n price = round(price,2)\r\n st.write(\"The price of the house is: \",price)\r\n \r\nif __name__ == '__main__':\r\n lr = joblib.load(\"model.pkl\")\r\n print(\"Model Loaded\")\r\n model_columns = joblib.load(\"model_columns.pkl\")\r\n print(\"Model Column Loaded\")\r\n main()"
] | [
[
"sklearn.preprocessing.PolynomialFeatures",
"pandas.DataFrame",
"pandas.get_dummies"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
nicolas-hbt/Scratch-ML | [
"799c93d68aa33731cc1b17e8f9c62597bd5d8200"
] | [
"multi-class_classification_lda.py"
] | [
"from __future__ import print_function, division\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import preprocessing\n\nclass MultiClassLDA():\n\n def __init__(self):\n self.W = None\n\n def fit_transform(self, X, y, n_components):\n X = X.values if type(X) is not np.ndarray else X\n n_features = np.shape(X)[1]\n classes = np.unique(y)\n n_classes = len(classes)\n\n ## STEP 1\n mean_vectors = []\n for cl in range(1, n_classes+1):\n mean_vectors.append(np.mean(X[y==cl], axis=0))\n S_W = np.zeros((n_features, n_features)) # within-class scatter matrix\n for cl, mv in zip(range(1, n_classes+1), mean_vectors): \n class_sc_mat = np.zeros((n_features, n_features)) # scatter matrix for every class\n for x in X[y == cl] :\n x, mv = x.reshape(n_features,1), mv.reshape(n_features,1) # make column vectors \n class_sc_mat += (x-mv).dot((x-mv).T)\n S_W += class_sc_mat\n\n ## STEP 2\n overall_mean = np.mean(X, axis=0)\n S_B = np.zeros((n_features, n_features)) # between-class scatter matrix\n for i,mean_vec in enumerate(mean_vectors): \n n = X[y==i+1,:].shape[0] # number of observations for a given label. Start from 1.\n mean_vec, overall_mean = mean_vec.reshape(n_features,1), overall_mean.reshape(n_features,1) # make column vector\n S_B += n * (mean_vec - overall_mean).dot((mean_vec - overall_mean).T)\n\n ## STEP 3\n eigen_vals, eigen_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B))\n\n ## STEP 4\n # Sort the eigenvalues in descending order and keep only the first n_components\n sorted_idx = eigen_vals.argsort()[::-1]\n eigen_vals = eigen_vals[sorted_idx][:n_components]\n eigen_vecs = eigen_vecs[:, sorted_idx][:, :n_components]\n \n # Projection\n X_transformed = X.dot(eigen_vecs).real\n\n return (X_transformed)\n\n def plot_2D(self, X, y, title=\"2D Projection using LDA transformation\"):\n labels = y\n X_transformed = self.fit_transform(X, y, n_components=2)\n X_LD1 = X_transformed[:, 0]\n X_LD2 = X_transformed[:, 1]\n plt.figure(figsize=(10,7))\n label_dict = {}\n keys = range(len(np.unique(y)))\n values = sorted(y.unique().tolist())\n for label in keys:\n label_dict[label] = values[label]\n plt.scatter(X_LD1[y==label+1], X_LD2[y==label+1], alpha=0.7, label=label_dict[label])\n leg = plt.legend(loc='upper right', fancybox=True)\n plt.xlabel('LD1')\n plt.ylabel('LD2')\n if title: plt.title(title)\n plt.grid()\n plt.tight_layout\n plt.show()"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.scatter",
"numpy.unique",
"matplotlib.pyplot.title",
"numpy.linalg.inv",
"matplotlib.pyplot.ylabel",
"numpy.mean",
"numpy.shape",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nguyenhuy1209/espnet | [
"67db7a46c701c96398bb839375da4f1d899c9c38",
"67db7a46c701c96398bb839375da4f1d899c9c38"
] | [
"espnet/nets/pytorch_backend/transducer/transformer_decoder_layer_for_tt.py",
"espnet/nets/beam_search_transducer_for_tt.py"
] | [
"\"\"\"Decoder layer definition for transformer-transducer models.\"\"\"\n\nimport torch\nfrom torch import nn\n\nfrom espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm\n\n\nclass DecoderLayer(nn.Module):\n \"\"\"Single decoder layer module for transformer-transducer models.\n\n Args:\n size (int): input dim\n self_attn (MultiHeadedAttention): self attention module\n feed_forward (PositionwiseFeedForward): feed forward layer module\n dropout_rate (float): dropout rate\n normalize_before (bool): whether to use layer_norm before the first block\n\n \"\"\"\n\n def __init__(\n self, \n size, \n self_attn, \n feed_forward, \n dropout_rate,\n normalize_before=True,\n concat_after=False,\n ):\n \"\"\"Construct an DecoderLayer object.\"\"\"\n super(DecoderLayer, self).__init__()\n\n self.self_attn = self_attn\n self.feed_forward = feed_forward\n\n self.norm1 = LayerNorm(size)\n self.norm2 = LayerNorm(size)\n\n self.dropout = nn.Dropout(dropout_rate)\n\n self.size = size\n\n self.normalize_before = normalize_before\n self.concat_after = concat_after\n if self.concat_after:\n self.concat_linear = nn.Linear(size + size, size)\n\n def forward(self, tgt, tgt_mask, cache=None):\n \"\"\"Compute decoded features.\n\n Args:\n tgt (torch.Tensor): decoded previous target features (B, Lmax, idim)\n tgt_mask (torch.Tensor): mask for tgt (B, Lmax)\n cache (torch.Tensor): cached output (B, Lmax-1, idim)\n\n Returns:\n tgt (torch.Tensor): decoder target features (B, Lmax, odim)\n tgt_mask (torch.Tensor): mask for tgt (B, Lmax)\n \"\"\"\n if isinstance(tgt, tuple):\n tgt, pos_emb = tgt[0], tgt[1]\n else:\n tgt, pos_emb = tgt, None\n\n residual = tgt\n tgt = self.norm1(tgt)\n\n if cache is None:\n tgt_q = tgt\n else:\n assert cache.shape == (\n tgt.shape[0],\n tgt.shape[1] - 1,\n self.size,\n ), f\"{cache.shape} == {(tgt.shape[0], tgt.shape[1] - 1, self.size)}\"\n\n tgt_q = tgt[:, -1:, :]\n residual = residual[:, -1:, :]\n\n if tgt_mask is not None:\n tgt_mask = tgt_mask[:, -1:, :]\n\n if pos_emb is not None:\n tgt_att = self.self_attn(tgt_q, tgt, tgt, pos_emb, tgt_mask)\n else:\n tgt_att = self.self_attn(tgt_q, tgt, tgt, tgt_mask)\n\n if self.concat_after:\n tgt_concat = torch.cat((tgt_q, tgt_att), dim=-1)\n tgt = residual + self.concat_linear(tgt_concat)\n else:\n tgt = residual + self.dropout(tgt_att)\n if not self.normalize_before:\n tgt = self.norm_mha(tgt)\n\n residual = tgt\n if self.normalize_before:\n tgt = self.norm2(tgt)\n tgt = residual + self.dropout(self.feed_forward(tgt))\n if not self.normalize_before:\n tgt = self.norm2(tgt)\n\n if cache is not None:\n tgt = torch.cat([cache, tgt], dim=1)\n\n if pos_emb is not None:\n return (tgt, pos_emb), tgt_mask\n\n return tgt, tgt_mask\n",
"\"\"\"Search algorithms for transducer models.\"\"\"\n\nfrom typing import List\nfrom typing import Union\n\nimport numpy as np\nimport torch\n\nfrom espnet.nets.pytorch_backend.transducer.utils import create_lm_batch_state\nfrom espnet.nets.pytorch_backend.transducer.utils import init_lm_state\nfrom espnet.nets.pytorch_backend.transducer.utils import is_prefix\nfrom espnet.nets.pytorch_backend.transducer.utils import recombine_hyps\nfrom espnet.nets.pytorch_backend.transducer.utils import select_lm_state\nfrom espnet.nets.pytorch_backend.transducer.utils import substract\nfrom espnet.nets.transducer_decoder_interface import Hypothesis\nfrom espnet.nets.transducer_decoder_interface import NSCHypothesis\nfrom espnet.nets.transducer_decoder_interface import TransducerDecoderInterface\n\n\nclass BeamSearchTransducer:\n \"\"\"Beam search implementation for transducer.\"\"\"\n\n def __init__(\n self,\n decoder: Union[TransducerDecoderInterface, torch.nn.Module],\n joint_network: torch.nn.Module,\n beam_size: int,\n lm: torch.nn.Module = None,\n lm_weight: float = 0.1,\n search_type: str = \"default\",\n max_sym_exp: int = 2,\n u_max: int = 50,\n nstep: int = 1,\n prefix_alpha: int = 1,\n score_norm: bool = True,\n nbest: int = 1,\n ):\n \"\"\"Initialize transducer beam search.\n\n Args:\n decoder: Decoder class to use\n joint_network: Joint Network class\n beam_size: Number of hypotheses kept during search\n lm: LM class to use\n lm_weight: lm weight for soft fusion\n search_type: type of algorithm to use for search\n max_sym_exp: number of maximum symbol expansions at each time step (\"tsd\")\n u_max: maximum output sequence length (\"alsd\")\n nstep: number of maximum expansion steps at each time step (\"nsc\")\n prefix_alpha: maximum prefix length in prefix search (\"nsc\")\n score_norm: normalize final scores by length (\"default\")\n nbest: number of returned final hypothesis\n \"\"\"\n self.decoder = decoder\n self.joint_network = joint_network\n\n self.beam_size = beam_size\n self.hidden_size = decoder.dunits\n self.vocab_size = decoder.odim\n self.blank = decoder.blank\n\n if self.beam_size <= 1:\n self.search_algorithm = self.greedy_search\n elif search_type == \"default\":\n self.search_algorithm = self.default_beam_search\n elif search_type == \"tsd\":\n self.search_algorithm = self.time_sync_decoding\n elif search_type == \"alsd\":\n self.search_algorithm = self.align_length_sync_decoding\n elif search_type == \"nsc\":\n self.search_algorithm = self.nsc_beam_search\n else:\n raise NotImplementedError\n\n self.lm = lm\n self.lm_weight = lm_weight\n\n if lm is not None:\n self.use_lm = True\n self.is_wordlm = True if hasattr(lm.predictor, \"wordlm\") else False\n self.lm_predictor = lm.predictor.wordlm if self.is_wordlm else lm.predictor\n self.lm_layers = len(self.lm_predictor.rnn)\n else:\n self.use_lm = False\n\n self.max_sym_exp = max_sym_exp\n self.u_max = u_max\n self.nstep = nstep\n self.prefix_alpha = prefix_alpha\n self.score_norm = score_norm\n\n self.nbest = nbest\n\n def __call__(self, h: torch.Tensor, beam, beam_k, dec_state, kept_hyps, cache) -> Union[List[Hypothesis], List[NSCHypothesis]]:\n \"\"\"Perform beam search.\n\n Args:\n h: Encoded speech features (T_max, D_enc)\n\n Returns:\n nbest_hyps: N-best decoding results\n\n \"\"\"\n self.decoder.set_device(h.device)\n\n if not hasattr(self.decoder, \"decoders\"):\n self.decoder.set_data_type(h.dtype)\n\n nbest_hyps = self.search_algorithm(h, beam, beam_k, dec_state, kept_hyps, cache)\n\n return nbest_hyps\n\n def sort_nbest(\n self, hyps: Union[List[Hypothesis], List[NSCHypothesis]]\n ) -> Union[List[Hypothesis], List[NSCHypothesis]]:\n \"\"\"Sort hypotheses by score or score given sequence length.\n\n Args:\n hyps: list of hypotheses\n\n Return:\n hyps: sorted list of hypotheses\n\n \"\"\"\n if self.score_norm:\n hyps.sort(key=lambda x: x.score / len(x.yseq), reverse=True)\n else:\n hyps.sort(key=lambda x: x.score, reverse=True)\n\n return hyps[: self.nbest]\n\n def greedy_search(self, h: torch.Tensor) -> List[Hypothesis]:\n \"\"\"Greedy search implementation for transformer-transducer.\n\n Args:\n h: Encoded speech features (T_max, D_enc)\n\n Returns:\n hyp: 1-best decoding results\n\n \"\"\"\n # dec_state = self.decoder.init_state(1)\n\n # hyp = Hypothesis(score=0.0, yseq=[self.blank], dec_state=dec_state)\n # cache = {}\n\n # y, state, _ = self.decoder.score(hyp, cache)\n\n for i, hi in enumerate(h):\n ytu = torch.log_softmax(self.joint_network(hi, y), dim=-1)\n logp, pred = torch.max(ytu, dim=-1)\n\n if pred != self.blank:\n hyp.yseq.append(int(pred))\n hyp.score += float(logp)\n\n hyp.dec_state = state\n\n y, state, _ = self.decoder.score(hyp, cache)\n\n return [hyp]\n\n def default_beam_search(self, h: torch.Tensor, beam, beam_k, dec_state, kept_hyps, cache) -> List[Hypothesis]:\n \"\"\"Beam search implementation.\n\n Args:\n x: Encoded speech features (T_max, D_enc)\n\n Returns:\n nbest_hyps: N-best decoding results\n\n \"\"\"\n # beam = min(self.beam_size, self.vocab_size)\n # beam_k = min(beam, (self.vocab_size - 1))\n\n # dec_state = self.decoder.init_state(1)\n\n # kept_hyps = [Hypothesis(score=0.0, yseq=[self.blank], dec_state=dec_state)]\n # cache = {}\n # print(kept_hyps)\n for hi in h:\n hyps = kept_hyps\n kept_hyps = []\n\n while True:\n max_hyp = max(hyps, key=lambda x: x.score)\n hyps.remove(max_hyp)\n y, state, lm_tokens = self.decoder.score(max_hyp, cache)\n\n ytu = torch.log_softmax(self.joint_network(hi, y), dim=-1)\n top_k = ytu[1:].topk(beam_k, dim=-1)\n\n kept_hyps.append(\n Hypothesis(\n score=(max_hyp.score + float(ytu[0:1])),\n yseq=max_hyp.yseq[:],\n dec_state=max_hyp.dec_state,\n lm_state=max_hyp.lm_state,\n )\n )\n\n if self.use_lm:\n lm_state, lm_scores = self.lm.predict(max_hyp.lm_state, lm_tokens)\n else:\n lm_state = max_hyp.lm_state\n\n for logp, k in zip(*top_k):\n score = max_hyp.score + float(logp)\n\n if self.use_lm:\n score += self.lm_weight * lm_scores[0][k + 1]\n\n hyps.append(\n Hypothesis(\n score=score,\n yseq=max_hyp.yseq[:] + [int(k + 1)],\n dec_state=state,\n lm_state=lm_state,\n )\n )\n\n hyps_max = float(max(hyps, key=lambda x: x.score).score)\n kept_most_prob = sorted(\n [hyp for hyp in kept_hyps if hyp.score > hyps_max],\n key=lambda x: x.score,\n )\n # print(kept_most_prob[0].yseq)\n if len(kept_most_prob) >= beam:\n kept_hyps = kept_most_prob\n break\n # print(kept_hyps[0])\n return self.sort_nbest(kept_hyps)\n\n def time_sync_decoding(self, h: torch.Tensor) -> List[Hypothesis]:\n \"\"\"Time synchronous beam search implementation.\n\n Based on https://ieeexplore.ieee.org/document/9053040\n\n Args:\n h: Encoded speech features (T_max, D_enc)\n\n Returns:\n nbest_hyps: N-best decoding results\n\n \"\"\"\n beam = min(self.beam_size, self.vocab_size)\n\n beam_state = self.decoder.init_state(beam)\n\n B = [\n Hypothesis(\n yseq=[self.blank],\n score=0.0,\n dec_state=self.decoder.select_state(beam_state, 0),\n )\n ]\n cache = {}\n\n if self.use_lm and not self.is_wordlm:\n B[0].lm_state = init_lm_state(self.lm_predictor)\n\n for hi in h:\n A = []\n C = B\n\n h_enc = hi.unsqueeze(0)\n\n for v in range(self.max_sym_exp):\n D = []\n\n beam_y, beam_state, beam_lm_tokens = self.decoder.batch_score(\n C,\n beam_state,\n cache,\n self.use_lm,\n )\n\n beam_logp = torch.log_softmax(self.joint_network(h_enc, beam_y), dim=-1)\n beam_topk = beam_logp[:, 1:].topk(beam, dim=-1)\n\n seq_A = [h.yseq for h in A]\n\n for i, hyp in enumerate(C):\n if hyp.yseq not in seq_A:\n A.append(\n Hypothesis(\n score=(hyp.score + float(beam_logp[i, 0])),\n yseq=hyp.yseq[:],\n dec_state=hyp.dec_state,\n lm_state=hyp.lm_state,\n )\n )\n else:\n dict_pos = seq_A.index(hyp.yseq)\n\n A[dict_pos].score = np.logaddexp(\n A[dict_pos].score, (hyp.score + float(beam_logp[i, 0]))\n )\n\n if v < (self.max_sym_exp - 1):\n if self.use_lm:\n beam_lm_states = create_lm_batch_state(\n [c.lm_state for c in C], self.lm_layers, self.is_wordlm\n )\n\n beam_lm_states, beam_lm_scores = self.lm.buff_predict(\n beam_lm_states, beam_lm_tokens, len(C)\n )\n\n for i, hyp in enumerate(C):\n for logp, k in zip(beam_topk[0][i], beam_topk[1][i] + 1):\n new_hyp = Hypothesis(\n score=(hyp.score + float(logp)),\n yseq=(hyp.yseq + [int(k)]),\n dec_state=self.decoder.select_state(beam_state, i),\n lm_state=hyp.lm_state,\n )\n\n if self.use_lm:\n new_hyp.score += self.lm_weight * beam_lm_scores[i, k]\n\n new_hyp.lm_state = select_lm_state(\n beam_lm_states, i, self.lm_layers, self.is_wordlm\n )\n\n D.append(new_hyp)\n\n C = sorted(D, key=lambda x: x.score, reverse=True)[:beam]\n\n B = sorted(A, key=lambda x: x.score, reverse=True)[:beam]\n\n return self.sort_nbest(B)\n\n def align_length_sync_decoding(self, h: torch.Tensor) -> List[Hypothesis]:\n \"\"\"Alignment-length synchronous beam search implementation.\n\n Based on https://ieeexplore.ieee.org/document/9053040\n\n Args:\n h: Encoded speech features (T_max, D_enc)\n\n Returns:\n nbest_hyps: N-best decoding results\n\n \"\"\"\n beam = min(self.beam_size, self.vocab_size)\n\n h_length = int(h.size(0))\n u_max = min(self.u_max, (h_length - 1))\n\n beam_state = self.decoder.init_state(beam)\n\n B = [\n Hypothesis(\n yseq=[self.blank],\n score=0.0,\n dec_state=self.decoder.select_state(beam_state, 0),\n )\n ]\n final = []\n cache = {}\n\n if self.use_lm and not self.is_wordlm:\n B[0].lm_state = init_lm_state(self.lm_predictor)\n\n for i in range(h_length + u_max):\n A = []\n\n B_ = []\n h_states = []\n for hyp in B:\n u = len(hyp.yseq) - 1\n t = i - u + 1\n\n if t > (h_length - 1):\n continue\n\n B_.append(hyp)\n h_states.append((t, h[t]))\n\n if B_:\n beam_y, beam_state, beam_lm_tokens = self.decoder.batch_score(\n B_,\n beam_state,\n cache,\n self.use_lm,\n )\n\n h_enc = torch.stack([h[1] for h in h_states])\n\n beam_logp = torch.log_softmax(self.joint_network(h_enc, beam_y), dim=-1)\n beam_topk = beam_logp[:, 1:].topk(beam, dim=-1)\n\n if self.use_lm:\n beam_lm_states = create_lm_batch_state(\n [b.lm_state for b in B_], self.lm_layers, self.is_wordlm\n )\n\n beam_lm_states, beam_lm_scores = self.lm.buff_predict(\n beam_lm_states, beam_lm_tokens, len(B_)\n )\n\n for i, hyp in enumerate(B_):\n new_hyp = Hypothesis(\n score=(hyp.score + float(beam_logp[i, 0])),\n yseq=hyp.yseq[:],\n dec_state=hyp.dec_state,\n lm_state=hyp.lm_state,\n )\n\n A.append(new_hyp)\n\n if h_states[i][0] == (h_length - 1):\n final.append(new_hyp)\n\n for logp, k in zip(beam_topk[0][i], beam_topk[1][i] + 1):\n new_hyp = Hypothesis(\n score=(hyp.score + float(logp)),\n yseq=(hyp.yseq[:] + [int(k)]),\n dec_state=self.decoder.select_state(beam_state, i),\n lm_state=hyp.lm_state,\n )\n\n if self.use_lm:\n new_hyp.score += self.lm_weight * beam_lm_scores[i, k]\n\n new_hyp.lm_state = select_lm_state(\n beam_lm_states, i, self.lm_layers, self.is_wordlm\n )\n\n A.append(new_hyp)\n\n B = sorted(A, key=lambda x: x.score, reverse=True)[:beam]\n B = recombine_hyps(B)\n\n if final:\n return self.sort_nbest(final)\n else:\n return B\n\n def nsc_beam_search(self, h: torch.Tensor) -> List[NSCHypothesis]:\n \"\"\"N-step constrained beam search implementation.\n\n Based and modified from https://arxiv.org/pdf/2002.03577.pdf.\n Please reference ESPnet (b-flo, PR #2444) for any usage outside ESPnet\n until further modifications.\n\n Note: the algorithm is not in his \"complete\" form but works almost as\n intended.\n\n Args:\n h: Encoded speech features (T_max, D_enc)\n\n Returns:\n nbest_hyps: N-best decoding results\n\n \"\"\"\n beam = min(self.beam_size, self.vocab_size)\n beam_k = min(beam, (self.vocab_size - 1))\n\n beam_state = self.decoder.init_state(beam)\n\n init_tokens = [\n NSCHypothesis(\n yseq=[self.blank],\n score=0.0,\n dec_state=self.decoder.select_state(beam_state, 0),\n )\n ]\n\n cache = {}\n\n beam_y, beam_state, beam_lm_tokens = self.decoder.batch_score(\n init_tokens,\n beam_state,\n cache,\n self.use_lm,\n )\n\n state = self.decoder.select_state(beam_state, 0)\n\n if self.use_lm:\n beam_lm_states, beam_lm_scores = self.lm.buff_predict(\n None, beam_lm_tokens, 1\n )\n lm_state = select_lm_state(\n beam_lm_states, 0, self.lm_layers, self.is_wordlm\n )\n lm_scores = beam_lm_scores[0]\n else:\n lm_state = None\n lm_scores = None\n\n kept_hyps = [\n NSCHypothesis(\n yseq=[self.blank],\n score=0.0,\n dec_state=state,\n y=[beam_y[0]],\n lm_state=lm_state,\n lm_scores=lm_scores,\n )\n ]\n\n for hi in h:\n hyps = sorted(kept_hyps, key=lambda x: len(x.yseq), reverse=True)\n kept_hyps = []\n\n h_enc = hi.unsqueeze(0)\n\n for j, hyp_j in enumerate(hyps[:-1]):\n for hyp_i in hyps[(j + 1) :]:\n curr_id = len(hyp_j.yseq)\n next_id = len(hyp_i.yseq)\n\n if (\n is_prefix(hyp_j.yseq, hyp_i.yseq)\n and (curr_id - next_id) <= self.prefix_alpha\n ):\n ytu = torch.log_softmax(\n self.joint_network(hi, hyp_i.y[-1]), dim=-1\n )\n\n curr_score = hyp_i.score + float(ytu[hyp_j.yseq[next_id]])\n\n for k in range(next_id, (curr_id - 1)):\n ytu = torch.log_softmax(\n self.joint_network(hi, hyp_j.y[k]), dim=-1\n )\n\n curr_score += float(ytu[hyp_j.yseq[k + 1]])\n\n hyp_j.score = np.logaddexp(hyp_j.score, curr_score)\n\n S = []\n V = []\n for n in range(self.nstep):\n beam_y = torch.stack([hyp.y[-1] for hyp in hyps])\n\n beam_logp = torch.log_softmax(self.joint_network(h_enc, beam_y), dim=-1)\n beam_topk = beam_logp[:, 1:].topk(beam_k, dim=-1)\n\n for i, hyp in enumerate(hyps):\n S.append(\n NSCHypothesis(\n yseq=hyp.yseq[:],\n score=hyp.score + float(beam_logp[i, 0:1]),\n y=hyp.y[:],\n dec_state=hyp.dec_state,\n lm_state=hyp.lm_state,\n lm_scores=hyp.lm_scores,\n )\n )\n\n for logp, k in zip(beam_topk[0][i], beam_topk[1][i] + 1):\n score = hyp.score + float(logp)\n\n if self.use_lm:\n score += self.lm_weight * float(hyp.lm_scores[k])\n\n V.append(\n NSCHypothesis(\n yseq=hyp.yseq[:] + [int(k)],\n score=score,\n y=hyp.y[:],\n dec_state=hyp.dec_state,\n lm_state=hyp.lm_state,\n lm_scores=hyp.lm_scores,\n )\n )\n\n V.sort(key=lambda x: x.score, reverse=True)\n V = substract(V, hyps)[:beam]\n\n beam_state = self.decoder.create_batch_states(\n beam_state,\n [v.dec_state for v in V],\n [v.yseq for v in V],\n )\n beam_y, beam_state, beam_lm_tokens = self.decoder.batch_score(\n V,\n beam_state,\n cache,\n self.use_lm,\n )\n\n if self.use_lm:\n beam_lm_states = create_lm_batch_state(\n [v.lm_state for v in V], self.lm_layers, self.is_wordlm\n )\n beam_lm_states, beam_lm_scores = self.lm.buff_predict(\n beam_lm_states, beam_lm_tokens, len(V)\n )\n\n if n < (self.nstep - 1):\n for i, v in enumerate(V):\n v.y.append(beam_y[i])\n\n v.dec_state = self.decoder.select_state(beam_state, i)\n\n if self.use_lm:\n v.lm_state = select_lm_state(\n beam_lm_states, i, self.lm_layers, self.is_wordlm\n )\n v.lm_scores = beam_lm_scores[i]\n\n hyps = V[:]\n else:\n beam_logp = torch.log_softmax(\n self.joint_network(h_enc, beam_y), dim=-1\n )\n\n for i, v in enumerate(V):\n if self.nstep != 1:\n v.score += float(beam_logp[i, 0])\n\n v.y.append(beam_y[i])\n\n v.dec_state = self.decoder.select_state(beam_state, i)\n\n if self.use_lm:\n v.lm_state = select_lm_state(\n beam_lm_states, i, self.lm_layers, self.is_wordlm\n )\n v.lm_scores = beam_lm_scores[i]\n\n kept_hyps = sorted((S + V), key=lambda x: x.score, reverse=True)[:beam]\n\n return self.sort_nbest(kept_hyps)\n"
] | [
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.cat"
],
[
"torch.stack",
"torch.max",
"numpy.logaddexp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
neon-cyan/quantpy | [
"51b462cf0ef28fdd6bcf6b50ee3102209689724a"
] | [
"analysis/plotter.py"
] | [
"import mathutils\nimport numpy as np\nimport sys\nimport os\nimport json\n\nif len(sys.argv) < 5:\n print(f\"\"\"Not enough arguemnts!\\n Use : {sys.argv[0]}\n [/path/manifest.json] \n => [BL=1-2,2-3]\n => [PBL=1-2,2-3]\n => [NM=1,2,3]\n => [CIs=A|1,2,3]\n => [CSFs=A|1,2,3]\n => [CSFv=label:1,1,0,0_label:0,0,1,1]\n => [AVCSFs=A|1,2,3:av_window]\n => [AVCSFv=av_window_label:1,0,0_label:0,0,1]\n => [SD=A|1,2]\n => [MQ=A|1,2]\n => [HM=sd|mq:atom_num:nbins:min_y:max_y]\n => [FFT=cd|mq|csf:CHOP:[START:END]|A:1,2,3|A]\n [width/panel, height]\n [Output x11 | filename.png]\n \"\"\")\n sys.exit(-1)\n\nATOMICLABELS = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', \n 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', \n 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', \n 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', \n 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', \n 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', \n 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og'] # Yes *all* of the elements\n\nmanifest_path = sys.argv[1]\ncommands = sys.argv[2:-2]\nwpp, height = [float(i) for i in sys.argv[-2].split(',')]\nOUTPUT = sys.argv[-1] # Either plot to a file or x11 window\n\nassert(os.path.exists(manifest_path))\nwith open(manifest_path, 'r') as f:\n manifest = json.load(f)\nbasepath = os.path.dirname(manifest_path)\n\ntimes = np.load(os.path.join(basepath, 'times'))\nnms = np.load(os.path.join(basepath, 'nm_ave'))\ndiabats = np.load(os.path.join(basepath, 'csf_ave'))\nadiabats = np.load(os.path.join(basepath, 'ci_ave'))\navegeom = np.load(os.path.join(basepath, 'xyz_ave'))\nmq = np.load(os.path.join(basepath, 'mq_ave'))\nsd = np.load(os.path.join(basepath, 'sd_ave'))\nnsteps = manifest['steps']\n\n\n# DO PLOTTING\n\nimport matplotlib.pyplot as plt\n\n# Define custom default colours - keep consistent between plots\n# List lossely based on https://sashamaps.net/docs/resources/20-colors/\n# Do this for the CSFs/CIs/FFT/NMs/MQ/SD\ndef get_nth_col(idx):\n cols =['#e6194B', '#3cb44b', '#FFC800', '#4363d8', '#f58231', '#42d4f4', '#f032e6', '#fabed4', '#469990', '#dcbeff', '#9A6324', '#800000', '#aaffc3', '#000075', '#a9a9a9']\n return cols[idx%len(cols)]\n\nfig, axes = plt.subplots(1, len(commands), num=manifest_path, figsize=(wpp * len(commands), height))\nif len(commands) == 1 : axes = [axes] # MPL messes with array if only one plot => Need to re-array\n\nfor n, c in enumerate(commands):\n cmd, ins = c.split('=')\n # GEOMETRICS\n if cmd == 'BL':\n BPS = []\n for x in ins.split(','):\n a, b = [int(z) for z in x.split('-')]\n BPS.append([a,b])\n for a in BPS:\n dp = []\n for x in range(nsteps):\n dp.append(mathutils.MathUtils.bond_length(avegeom[x, a[0]-1],avegeom[x, a[1]-1] ))\n\n try: alab1 = ATOMICLABELS[manifest['atomnos'][str(a[0])]-1]\n except: alab1 = '?'\n try: alab2 = ATOMICLABELS[manifest['atomnos'][str(a[1])]-1]\n except: alab2 = '?'\n\n axes[n].plot(times, dp, label=f'{alab1}[{a[0]}] - {alab2}[{a[1]}]')\n axes[n].set_title('Bond lengths')\n axes[n].set_ylabel('Bond length (Å)')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'PBL':\n BPS = []\n for x in ins.split(','):\n a, b = [int(z) for z in x.split('-')]\n BPS.append([a,b])\n for a in BPS:\n dp = []\n init_bl = mathutils.MathUtils.bond_length(avegeom[0, a[0]-1],avegeom[0, a[1]-1] )\n for x in range(nsteps):\n bl = mathutils.MathUtils.bond_length(avegeom[x, a[0]-1],avegeom[x, a[1]-1] )\n dp.append((bl - init_bl) / init_bl)\n\n try: alab1 = ATOMICLABELS[manifest['atomnos'][str(a[0])]-1]\n except: alab1 = '?'\n try: alab2 = ATOMICLABELS[manifest['atomnos'][str(a[1])]-1]\n except: alab2 = '?'\n\n axes[n].plot(times, dp, label=f'{alab1}[{a[0]}] - {alab2}[{a[1]}]')\n axes[n].set_title('Bond lengths (fractional)')\n axes[n].set_ylabel('Fractional change')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n\n elif cmd == 'NM':\n for x in [int(i) for i in ins.split(',')]:\n axes[n].plot(times, nms[x-1], label=f'NM{x}', color=get_nth_col(x-1))\n axes[n].set_title('Normal mode evolution')\n axes[n].set_ylabel('Normal mode excitation')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'BA':\n BPS = []\n for x in ins.split(','):\n a, b, c = [int(z) for z in x.split('-')]\n BPS.append([a,b,c])\n\n for a in BPS:\n dp = []\n for x in range(nsteps):\n dp.append(mathutils.MathUtils.bond_angle(avegeom[x, a[0]-1],avegeom[x, a[1]-1], avegeom[x, a[2]-1] ))\n\n try: alab1 = ATOMICLABELS[manifest['atomnos'][str(a[0])]-1]\n except: alab1 = '?'\n try: alab2 = ATOMICLABELS[manifest['atomnos'][str(a[1])]-1]\n except: alab2 = '?'\n try: alab3 = ATOMICLABELS[manifest['atomnos'][str(a[2])]-1]\n except: alab3 = '?'\n\n axes[n].plot(times, dp, label=f'{alab1}[{a[0]}] - {alab2}[{a[1]}] - {alab3}[{a[2]}]')\n axes[n].set_ylabel('Bond angle (rad)')\n axes[n].set_title('Bond angle')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'DA':\n BPS = []\n for x in ins.split(','):\n a, b, c, d = [int(z) for z in x.split('-')]\n BPS.append([a,b,c,d])\n\n for a in BPS:\n dp = []\n for x in range(nsteps):\n dha = mathutils.MathUtils.dihedral([avegeom[x, a[0]-1],avegeom[x, a[1]-1], avegeom[x, a[2]-1], avegeom[x, a[3]-1] ])\n dp.append(dha)\n\n try: alab1 = ATOMICLABELS[manifest['atomnos'][str(a[0])]-1]\n except: alab1 = '?'\n try: alab2 = ATOMICLABELS[manifest['atomnos'][str(a[1])]-1]\n except: alab2 = '?'\n try: alab3 = ATOMICLABELS[manifest['atomnos'][str(a[2])]-1]\n except: alab3 = '?'\n try: alab4 = ATOMICLABELS[manifest['atomnos'][str(a[3])]-1]\n except: alab4 = '?'\n\n axes[n].plot(times, dp, label=f'{alab1}[{a[0]}] - {alab2}[{a[1]}] - {alab3}[{a[2]}] - {alab4}[{a[3]}]')\n axes[n].set_ylabel('Dihedral angle (rad)')\n axes[n].set_title('Bond angle')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n \n # ELECTRONICS\n elif cmd == 'CIs':\n CI_STATES = None if ins=='A' else [int(i) for i in ins.split(',')]\n for i in range(adiabats.shape[0]):\n if CI_STATES == None: pass\n else:\n if i+1 not in CI_STATES: continue\n axes[n].plot(times, adiabats[i], label=f'CI {i+1}', color=get_nth_col(i))\n axes[n].set_title('Adiabatic [CI] state evolution')\n axes[n].set_ylabel('State population')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'CSFs':\n CSF_STATES = None if ins=='A' else [int(i) for i in ins.split(',')]\n for i in range(diabats.shape[0]):\n if CSF_STATES == None: pass\n else:\n if i+1 not in CSF_STATES: continue\n axes[n].plot(times, diabats[i], label=f'CSF {i+1}', color=get_nth_col(i))\n axes[n].set_title('Diabatic [CSF] state evolution')\n axes[n].set_ylabel('State population')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'CSFv':\n # Expect a list of label:1,1,0,0_label:0,0,1,1\n to_plot={}\n for i in ins.split('_'):\n label, nums = i.split(':')\n nums = [float(j) for j in nums.split(',')]\n assert(len(nums)==diabats.shape[0])\n to_plot[label] = np.array(nums)\n for k, v in to_plot.items():\n data = np.dot(v, diabats)\n axes[n].plot(times, data, label=k)\n axes[n].set_title('Diabatic [CSF] state vector evolution')\n axes[n].set_ylabel('State population')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'AVCSFs':\n csfs, av_window = ins.split(':')\n av_window = int(av_window)\n CSF_STATES = None if csfs=='A' else [int(i) for i in csfs.split(',')]\n for i in range(diabats.shape[0]):\n if CSF_STATES == None: pass\n else:\n if i+1 not in CSF_STATES: continue\n mav = mathutils.MathUtils.moving_avg(diabats[i], av_window)\n axes[n].plot(times[:len(mav)], mav, label=f'AVCSF {i+1}', color=get_nth_col(i))\n axes[n].set_title(f'{av_window} point moving average diabatic [CSF] state evolution')\n axes[n].set_ylabel('Averaged state population')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'AVCSFv':\n # Expect format av_window_label:1,0,0_label:0,0,1\n av_window, *toplt = ins.split('_')\n av_window = int(av_window)\n\n to_plot={}\n for i in toplt:\n print(i)\n label, nums = i.split(':')\n nums = [float(j) for j in nums.split(',')]\n assert(len(nums)==diabats.shape[0])\n to_plot[label] = np.array(nums)\n mavs = np.array([mathutils.MathUtils.moving_avg(i, av_window) for i in diabats])\n print(mavs.shape)\n for k, v in to_plot.items():\n data = np.dot(v, mavs)\n axes[n].plot(times[:len(data)], data, label=k)\n axes[n].set_title(f'{av_window} point moving average diabatic [CSF] state custom vector evolution')\n axes[n].set_ylabel('Averaged state population')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'SD':\n SDS = None if ins=='A' else [int(i) for i in ins.split(',')]\n for i in range(len(manifest['spindenmap'])):\n atom_number = manifest['spindenmap'][i]\n if SDS == None : pass\n elif atom_number not in SDS: continue\n \n try: symbol = ATOMICLABELS[manifest['atomnos'][str(atom_number)]-1]\n except: symbol = '?'\n axes[n].plot(times, sd[i], label='{} [{}]'.format(symbol, atom_number), color=get_nth_col(atom_number))\n axes[n].set_title('Spin density evolution (H Summed)')\n axes[n].set_ylabel('Spin density')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n\n elif cmd == 'MQ':\n MQS = None if ins=='A' else [int(i) for i in ins.split(',')]\n for i in range(len(manifest['mullikenmap'])):\n atom_number = manifest['mullikenmap'][i]\n if MQS == None : pass\n elif atom_number not in MQS: continue\n \n try: symbol = ATOMICLABELS[manifest['atomnos'][str(atom_number)]-1]\n except: symbol = '?'\n axes[n].plot(times, mq[i], label='{} [{}]'.format(symbol, atom_number), color=get_nth_col(atom_number))\n axes[n].set_title('Mulliken charge evolution (H Summed)')\n axes[n].set_ylabel('Mulliken charge')\n axes[n].set_xlabel('Time (fs)')\n axes[n].legend(loc='upper right')\n \n # Heatmaps - currently SD/MQ (may want to add BL)\n elif cmd == 'HM':\n def sbin_vals(nb, vals, val_scale, max_val, min_val):\n x = np.zeros(nb)\n step = (max_val-min_val)/nb\n for n, v in enumerate(vals):\n for i in range(nb):\n if (min_val + i * step) < v < (min_val + (i+1) * step):\n x[i] += val_scale[n]\n return x[::-1]\n\n def bin_vals(nb, vals, max_val, min_val):\n val_len = len(vals)\n return sbin_vals (nb, vals, np.repeat(1, val_len), max_val, min_val)\n\n mode, selector, nbins, minval, maxval = ins.split(':')\n nbins = int(nbins)\n minval = float(minval)\n maxval = float(maxval)\n bindata = np.zeros((len(times), nbins))\n\n if mode == 'sd':\n atom_number = int(selector)\n mapper = manifest['spindenmap'].index(atom_number)\n\n try: symbol = ATOMICLABELS[manifest['atomnos'][str(atom_number)]-1]\n except: symbol = '?'\n\n axes[n].set_title(f'Spin denisity (H Summed) heatmap for atom {symbol}[{atom_number}]')\n axes[n].set_xlabel('Spin density (H Summed)')\n\n ave_data = np.load(os.path.join(basepath, 'sd_ave'))[mapper]\n unbinned_data=np.load(os.path.join(basepath, 'sd'))[mapper]\n\n elif mode == 'mq':\n atom_number = int(selector)\n mapper = manifest['mullikenmap'].index(atom_number)\n\n try: symbol = ATOMICLABELS[manifest['atomnos'][str(atom_number)]-1]\n except: symbol = '?'\n\n axes[n].set_title(f'Mulliken charge (H Summed) heatmap for atom {symbol}[{atom_number}]')\n axes[n].set_xlabel('Mulliken charge (H Summed)')\n\n ave_data = np.load(os.path.join(basepath, 'mq_ave'))[mapper]\n unbinned_data=np.load(os.path.join(basepath, 'mq'))[mapper]\n\n else:\n raise Exception(f\"Illegal mode {mode} for heatmap\")\n\n for i, _ in enumerate(times):\n bindata[i] = bin_vals(nbins, unbinned_data[i], maxval, minval)\n\n axes[n].set_xlabel('Time (fs)')\n timewidth = (times[1]-times[0])/2 # Tiny fudging to get heatmap to align nicely\n axes[n].imshow(bindata.T, cmap='inferno', extent=(-timewidth, times[-1]+timewidth, minval, maxval), aspect='auto')\n axes[n].plot(times, ave_data, color='white', linestyle='dotted',linewidth=2)\n\n # FFT\n elif cmd == 'FFT':\n # [FFT=cd|mq|csf:CHOP:[START-END]|A]\n mode, CHOP, RANGE, selector = ins.split(':')\n CHOP=int(CHOP)\n selector = None if selector == 'A' else [int(i) for i in selector.split(',')]\n\n if mode == 'csf': data = diabats\n elif mode == 'mq': data = mq\n elif mode == 'sd': data = sd\n else: raise Exception('Illegal FFT mode')\n\n print(data.shape, len(times))\n assert(data.shape[1] == len(times)) # Make sure extract worked\n\n if RANGE != 'A':\n s_idx, e_idx = [int(i) for i in RANGE.split('-')]\n times_fft = times[s_idx:e_idx]\n data_fft = data.T[s_idx:e_idx].T\n else:\n times_fft = times\n data_fft = data\n\n # Do FFT and plot up\n N = data_fft.shape[1]\n fig = plt.figure(num=manifest_path, figsize=(20.0, 15.0))\n\n for i in range(data_fft.shape[0]):\n if mode=='csf': # CSFs are picked by index\n if selector == None : pass\n elif i+1 not in selector: continue\n\n ft = np.fft.fft(data_fft[i])\n ft = ft.real**2 + ft.imag**2\n freq = np.fft.fftfreq(N, d=times_fft[1]-times_fft[0])\n\n if mode == 'sd' or mode == 'mq': # SD/MQ are picked based on atom number\n if mode == 'sd' : atom_number = manifest['spindenmap'][i]\n else : atom_number = manifest['mullikenmap'][i]\n \n if selector == None : pass\n elif atom_number not in selector: continue\n\n try: symbol = ATOMICLABELS[manifest['atomnos'][str(atom_number)]-1]\n except: symbol = '?'\n label = f'{symbol}[{atom_number}]'\n colour = get_nth_col(atom_number)\n else: \n label = f'CSF {i+1}'\n colour = get_nth_col(i)\n\n axes[n].plot(freq[CHOP:int(N/2)], ft[CHOP:int(N/2)], label=label, color=colour)\n axes[n].set_title(f'FFT {mode}')\n axes[n].set_ylabel('Intensity')\n axes[n].set_xlabel('Frequency PHz')\n axes[n].legend(loc='upper right')\n \n\n else:\n raise Exception(f'Illegal mode {cmd}')\nfig.tight_layout() \nif OUTPUT=='x11' : plt.show()\nelse: plt.savefig(OUTPUT, dpi=500)\n"
] | [
[
"numpy.dot",
"numpy.fft.fft",
"matplotlib.pyplot.savefig",
"numpy.fft.fftfreq",
"numpy.repeat",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
onnoeberhard/eremenko-i | [
"92982f178274c2c92fdd4b69791bb10d2bc9720c"
] | [
"Part 2 - Regression/Section 4 - Simple Linear Regression/section.py"
] | [
"\"\"\"\nSimple Linear Regression\nSection\n\"\"\"\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Salary_Data.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1:].values.ravel() # oder auch y = dataset.iloc[:, len(dataset.axes[1]) - 1].values -- ravel() unwraps die matrix in einen 1d array.\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)\n\n# Fitting Simple Linear Regression to the Training set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = regressor.predict(X_test)\n\nJ = 1 / len(y_test) * sum((y_test - y_pred)**2)\n\n# Visualising the Training set results\n\nxax = np.linspace(0, max(X_train) + 1).reshape(-1, 1)\n\nplt.scatter(X_train, y_train, color = 'red')\nplt.plot(xax, regressor.predict(xax), color = 'blue')\nplt.title('Salary vs Experience (Training set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()\n\n\n# Visualising the Test set results\nplt.scatter(X_test, y_test, color = 'red')\nplt.plot(X_test, y_pred, color = 'blue') # ob x-train oder test oder linspace etc ist egal, geht ja nur um die funktion. ich finde hier aber x-test besser, weil es ja sein könnte, dass die range nicht ganz gleich ist..\nplt.title('Salary vs Experience (Test set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()"
] | [
[
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.plot",
"sklearn.linear_model.LinearRegression",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
lschlessinger1/MS-project | [
"e1c02d1d1a7a2480ff6f14f30625dc42ee3417e3"
] | [
"src/autoks/postprocessing/summarize_group.py"
] | [
"import argparse\nfrom pathlib import Path\nfrom typing import List\n\nimport numpy as np\n\nfrom src.autoks.postprocessing.summary import _parse_experiment\nfrom src.evalg.visualization import plot_distribution\n\n\ndef summarize_exp_group(experiment_group_dir_name):\n \"\"\"Summarize a group of experiments.\"\"\"\n print(f'Summarizing {experiment_group_dir_name}')\n exp_dicts = _parse_experiment_group(experiment_group_dir_name)\n histories = [d['history'] for d in exp_dicts]\n\n create_plots(histories)\n\n\ndef _parse_experiment_group(experiment_group_dir_name) -> List[dict]:\n path = Path(experiment_group_dir_name)\n exp_dicts = [_parse_experiment(str(x)) for x in path.iterdir() if x.is_file()]\n print(f' Found {len(exp_dicts)} experiments')\n return exp_dicts\n\n\ndef create_plots(histories):\n best_scores = [history.stat_book_collection.stat_books['evaluations'].running_max('score') for history in histories]\n\n mean_best = list(np.mean(best_scores, axis=0).tolist())\n mean_std = list(np.std(best_scores, axis=0).tolist())\n\n import matplotlib.pyplot as plt\n plot_distribution(mean_best, mean_std, value_name='Mean best', x_label='evaluations')\n plt.gcf().suptitle(f'Evaluations', y=1)\n plt.gcf().subplots_adjust(top=0.88)\n plt.show()\n\n\ndef _parse_args():\n \"\"\"Parse command-line arguments.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"experiment_group_dirname\", type=str, help=\"Directory name of an experiment group to run \"\n \"postprocessing on.\")\n args = parser.parse_args()\n return args\n\n\ndef main():\n \"\"\"Summarize experiment.\"\"\"\n args = _parse_args()\n summarize_exp_group(args.experiment_group_dirname)\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.std",
"matplotlib.pyplot.show",
"numpy.mean",
"matplotlib.pyplot.gcf"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cipheraxat/buildlytics | [
"9d195e5dd7aa1c222bef430da0a764a0bcdd960f"
] | [
"EDALIB/__init__.py"
] | [
"\nfrom __future__ import division\nfrom collections import OrderedDict\nimport numpy as np\nimport pandas as pd\nimport numpy as np\nimport seaborn as sn\nimport matplotlib.pyplot as plt\nfrom pandas.api import types\nfrom six import string_types\n\n\nclass DataFrameSummary(object):\n ALL = 'ALL'\n INCLUDE = 'INCLUDE'\n EXCLUDE = 'EXCLUDE'\n\n TYPE_BOOL = 'bool'\n TYPE_NUMERIC = 'numeric'\n TYPE_DATE = 'date'\n TYPE_CATEGORICAL = 'categorical'\n TYPE_CONSTANT = 'constant'\n TYPE_UNIQUE = 'unique'\n\n\n\n def __init__(self, df, plot=False,continuous=[],categorical=[]):\n self.df = df\n self.length = len(df)\n self.columns_stats = self._get_stats()\n self.corr = df.corr()\n self.plot = plot\n self.continuous=continuous\n self.categorical=categorical\n\n def __getitem__(self, column):\n if isinstance(column, str) and self._clean_column(column):\n return self._get_column_summary(column)\n\n if isinstance(column, int) and column < self.df.shape[1]:\n return self._get_column_summary(self.df.columns[column])\n\n if isinstance(column, (tuple, list)):\n error_keys = [k for k in column if not self._clean_column(k)]\n if len(error_keys) > 0:\n raise KeyError(', '.join(error_keys))\n return self.df[list(column)].values\n\n if isinstance(column, pd.Index):\n error_keys = [\n k for k in column.values if not self._clean_column(k)]\n if len(error_keys) > 0:\n raise KeyError(', '.join(error_keys))\n return self.df[column].values\n\n if isinstance(column, np.ndarray):\n error_keys = [k for k in column if not self._clean_column(k)]\n if len(error_keys) > 0:\n raise KeyError(', '.join(error_keys))\n return self.df[column].values\n\n raise KeyError(column)\n\n def _get_pairplot(self):\n for i in self.df.columns:\n if(self.df[i].nunique()/self.df.shape[0])*100>20:\n self.continuous.append(i)\n else:\n self.categorical.append(i)\n cn=self.df.drop(columns=self.categorical,axis=1)\n return sn.pairplot(cn,corner=True,kind=\"scatter\")\n \n \n def _get_scatterplot(self,x,y,hue=None,style=None):\n return sn.scatterplot(x=x,y=y,hue=hue)\n\n\n @property\n def columns_types(self):\n return pd.value_counts(self.columns_stats.loc['types'])\n\n def summary(self):\n return pd.concat([self.df.describe(), self.columns_stats], sort=True)[self.df.columns]\n\n @staticmethod\n def _number_format(x):\n eps = 0.000000001\n num_format = '{0:,.0f}' if abs(int(x) - x) < eps else '{0:,.2f}'\n return num_format.format(x)\n\n @classmethod\n def _percent(cls, x):\n x = cls._number_format(100 * x)\n return '{}%'.format(x)\n\n def _clean_column(self, column):\n if not isinstance(column, (int, string_types)):\n raise ValueError('{} is not a valid column'.format(column))\n return column in self.df.columns\n\n def _get_stats(self):\n counts = self.df.count()\n counts.name = 'counts'\n uniques = self._get_uniques()\n missing = self._get_missing(counts)\n stats = pd.concat([counts, uniques, missing], axis=1, sort=True)\n\n # settings types\n stats['types'] = ''\n columns_info = self._get_columns_info(stats)\n for ctype, columns in columns_info.items():\n stats.loc[columns, 'types'] = ctype\n return stats.transpose()[self.df.columns]\n\n def _get_uniques(self):\n return pd.Series(dict((c, self.df[c].nunique()) for c in self.df.columns), name='uniques')\n\n def _get_missing(self, counts):\n count = self.length - counts\n count.name = 'missing'\n perc = (count / self.length).apply(self._percent)\n perc.name = 'missing_perc'\n return pd.concat([count, perc], axis=1, sort=True)\n\n def _get_columns_info(self, stats):\n column_info = {}\n column_info[self.TYPE_CONSTANT] = stats['uniques'][stats['uniques'] == 1].index\n column_info[self.TYPE_BOOL] = stats['uniques'][stats['uniques'] == 2].index\n rest_columns = self.get_columns(self.df,\n self.EXCLUDE,\n column_info['constant'].union(column_info['bool']))\n column_info[self.TYPE_NUMERIC] = pd.Index([c for c in rest_columns\n if types.is_numeric_dtype(self.df[c])])\n rest_columns = self.get_columns(\n self.df[rest_columns], self.EXCLUDE, column_info['numeric'])\n column_info[self.TYPE_DATE] = pd.Index([c for c in rest_columns\n if types.is_datetime64_dtype(self.df[c])])\n rest_columns = self.get_columns(\n self.df[rest_columns], self.EXCLUDE, column_info['date'])\n unique_columns = stats['uniques'][rest_columns] == stats['counts'][rest_columns]\n column_info[self.TYPE_UNIQUE] = stats['uniques'][rest_columns][unique_columns].index\n column_info[self.TYPE_CATEGORICAL] = stats['uniques'][rest_columns][~unique_columns].index\n return column_info\n\n \"\"\" Column summaries \"\"\"\n\n def _get_deviation_of_mean(self, series, multiplier=3):\n \"\"\"\n Returns count of values deviating of the mean, i.e. larger than `multiplier` * `std`.\n :type series:\n :param multiplier:\n :return:\n \"\"\"\n capped_series = np.minimum(\n series, series.mean() + multiplier * series.std())\n count = pd.value_counts(series != capped_series)\n count = count[True] if True in count else 0\n perc = self._percent(count / self.length)\n return count, perc\n\n def _get_median_absolute_deviation(self, series, multiplier=3):\n \"\"\"\n Returns count of values larger than `multiplier` * `mad`\n :type series:\n :param multiplier:\n :return (array):\n \"\"\"\n capped_series = np.minimum(\n series, series.median() + multiplier * series.mad())\n count = pd.value_counts(series != capped_series)\n count = count[True] if True in count else 0\n perc = self._percent(count / self.length)\n return count, perc\n\n def _get_top_correlations(self, column, threshold=0.65, top=3):\n column_corr = np.fabs(self.corr[column].drop(column)).sort_values(ascending=False,\n inplace=False)\n top_corr = column_corr[(column_corr > threshold)][:top].index\n correlations = self.corr[column][top_corr].to_dict()\n return ', '.join('{}: {}'.format(col, self._percent(val)) for\n col, val in correlations.items())\n\n def _get_numeric_summary(self, column):\n series = self.df[column]\n\n if self.plot:\n try:\n series.hist()\n except ImportError:\n pass\n\n stats = OrderedDict()\n stats['mean'] = series.mean()\n stats['std'] = series.std()\n stats['variance'] = series.var()\n stats['min'] = series.min()\n stats['max'] = series.max()\n stats['mode'] = series.mode()[0]\n\n for x in np.array([0.05, 0.25, 0.5, 0.75, 0.95]):\n stats[self._percent(x)] = series.quantile(x)\n\n stats['iqr'] = stats['75%'] - stats['25%']\n stats['kurtosis'] = series.kurt()\n stats['skewness'] = series.skew()\n stats['sum'] = series.sum()\n stats['mad'] = series.mad()\n stats['cv'] = stats['std'] / stats['mean'] if stats['mean'] else np.nan\n stats['zeros_num'] = self.length - np.count_nonzero(series)\n stats['zeros_perc'] = self._percent(stats['zeros_num'] / self.length)\n deviation_of_mean, deviation_of_mean_perc = self._get_deviation_of_mean(\n series)\n stats['deviating_of_mean'] = deviation_of_mean\n stats['deviating_of_mean_perc'] = deviation_of_mean_perc\n deviating_of_median, deviating_of_median_perc = self._get_median_absolute_deviation(\n series)\n stats['deviating_of_median'] = deviating_of_median\n stats['deviating_of_median_perc'] = deviating_of_median_perc\n stats['top_correlations'] = self._get_top_correlations(column)\n return pd.concat([pd.Series(stats, name=column),\n self.columns_stats[column]],\n sort=True)\n\n def _get_date_summary(self, column):\n series = self.df[column]\n stats = {'min': series.min(), 'max': series.max()}\n stats['range'] = stats['max'] - stats['min']\n return pd.concat([pd.Series(stats, name=column),\n self.columns_stats[column]],\n sort=True)\n\n def _get_categorical_summary(self, column):\n series = self.df[column]\n # Only run if at least 1 non-missing value\n value_counts = series.value_counts()\n stats = {\n 'top': '{}: {}'.format(value_counts.index[0], value_counts.iloc[0]),\n }\n return pd.concat([pd.Series(stats, name=column),\n self.columns_stats[column]],\n sort=True)\n\n def _get_constant_summary(self, column):\n return 'This is a constant value: {}'.format(self.df[column][0])\n\n def _get_bool_summary(self, column):\n series = self.df[column]\n\n stats = {}\n for class_name, class_value in dict(series.value_counts()).items():\n stats['\"{}\" count'.format(class_name)] = '{}'.format(class_value)\n stats['\"{}\" perc'.format(class_name)] = '{}'.format(\n self._percent(class_value / self.length))\n\n return pd.concat([pd.Series(stats, name=column),\n self.columns_stats[column]],\n sort=True)\n def _get_heatmap(self ,data):\n # create correlation matrix with abs values\n self.data=data\n corr_matrix = self.data.corr().abs()\n # change this value as needed, if 0.5 does not work for your scenario\n threshold = 0.5\n filtered_corr_df = corr_matrix[(corr_matrix >= threshold) & (corr_matrix != 1.000)] \n plt.figure(figsize=(30,10))\n plt.show()\n return sn.heatmap(filtered_corr_df, annot=True, cmap=\"Reds\")\n\n def _get_unique_summary(self, column):\n return self.columns_stats[column]\n\n def _get_column_summary(self, column):\n column_type = self.columns_stats.loc['types'][column]\n if column_type == self.TYPE_NUMERIC:\n return self._get_numeric_summary(column)\n if column_type == self.TYPE_CATEGORICAL:\n return self._get_categorical_summary(column)\n if column_type == self.TYPE_BOOL:\n return self._get_bool_summary(column)\n if column_type == self.TYPE_UNIQUE:\n return self._get_unique_summary(column)\n if column_type == self.TYPE_DATE:\n return self._get_date_summary(column)\n if column_type == self.TYPE_CONSTANT:\n return self._get_constant_summary(column)\n\n @property\n def constants(self):\n return self.df.columns[self.columns_stats.loc['types'] == 'constant']\n\n @property\n def categoricals(self):\n return self.df.columns[self.columns_stats.loc['types'] == 'categorical']\n\n @property\n def numerics(self):\n return self.df.columns[self.columns_stats.loc['types'] == 'numeric']\n\n @property\n def uniques(self):\n return self.df.columns[self.columns_stats.loc['types'] == 'unique']\n\n @property\n def bools(self):\n return self.df.columns[self.columns_stats.loc['types'] == 'bool']\n\n @property\n def missing_frac(self):\n return self.columns_stats.loc['missing'].apply(lambda x: float(x) / self.length)\n\n def get_columns(self, df, usage, columns=None):\n \"\"\"\n Returns a `data_frame.columns`.\n :param df: dataframe to select columns from\n :param usage: should be a value from [ALL, INCLUDE, EXCLUDE].\n this value only makes sense if attr `columns` is also set.\n otherwise, should be used with default value ALL.\n :param columns: * if `usage` is all, this value is not used.\n * if `usage` is INCLUDE, the `df` is restricted to the intersection\n between `columns` and the `df.columns`\n * if usage is EXCLUDE, returns the `df.columns` excluding these `columns`\n :return: `data_frame` columns, excluding `target_column` and `id_column` if given.\n `data_frame` columns, including/excluding the `columns` depending on `usage`.\n \"\"\"\n columns_excluded = pd.Index([])\n columns_included = df.columns\n\n if usage == self.INCLUDE:\n try:\n columns_included = columns_included.intersection(pd.Index(columns))\n except TypeError:\n pass\n elif usage == self.EXCLUDE:\n try:\n columns_excluded = columns_excluded.union(pd.Index(columns))\n except TypeError:\n pass\n\n columns_included = columns_included.difference(columns_excluded)\n return columns_included.intersection(df.columns)\n\n \n\n\n "
] | [
[
"pandas.concat",
"pandas.api.types.is_datetime64_dtype",
"pandas.Series",
"pandas.Index",
"pandas.api.types.is_numeric_dtype",
"numpy.count_nonzero",
"pandas.value_counts",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
MixXxyZ/RITnet | [
"08241800841ddded3b7acbeb2e4598651ad66932"
] | [
"mixnet.py"
] | [
"import torch\nfrom torch import nn\nimport math\n\nclass _GlobalConvModule(nn.Module):\n def __init__(self, in_dim, out_dim, kernel_size, squeeze_ratio=8):\n super(_GlobalConvModule, self).__init__()\n\n assert(kernel_size[0] % 2 != 0 and kernel_size[1] % 2 != 0) # to prevent incompatible pad size\n\n pad0 = int((kernel_size[0] - 1) / 2)\n pad1 = int((kernel_size[1] - 1) / 2)\n # kernel size had better be odd number so as to avoid alignment error\n super(_GlobalConvModule, self).__init__()\n\n squeeze_channels = out_dim // squeeze_ratio\n self.conv_l1 = nn.Sequential(*[\n nn.Conv2d(in_dim, squeeze_channels, kernel_size=1),\n nn.BatchNorm2d(squeeze_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(squeeze_channels, out_dim, kernel_size=(kernel_size[0], 1), padding=(pad0, 0)),\n nn.BatchNorm2d(out_dim),\n nn.ReLU(inplace=True)\n ])\n self.conv_l2 = nn.Sequential(*[\n nn.Conv2d(out_dim, squeeze_channels, kernel_size=1),\n nn.BatchNorm2d(squeeze_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(squeeze_channels, out_dim, kernel_size=(1, kernel_size[1]), padding=(0, pad1)),\n nn.BatchNorm2d(out_dim),\n nn.ReLU(inplace=True)\n ])\n self.conv_r1 = nn.Sequential(*[\n nn.Conv2d(in_dim, squeeze_channels, kernel_size=1),\n nn.BatchNorm2d(squeeze_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(squeeze_channels, out_dim, kernel_size=(1, kernel_size[1]), padding=(0, pad1)),\n nn.BatchNorm2d(out_dim),\n nn.ReLU(inplace=True)\n ])\n self.conv_r2 = nn.Sequential(*[\n nn.Conv2d(out_dim, squeeze_channels, kernel_size=1),\n nn.BatchNorm2d(squeeze_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(squeeze_channels, out_dim, kernel_size=(kernel_size[0], 1), padding=(pad0, 0)),\n nn.BatchNorm2d(out_dim),\n nn.ReLU(inplace=True)\n ])\n\n def forward(self, x):\n x_l = self.conv_l1(x)\n x_l = self.conv_l2(x_l)\n x_r = self.conv_r1(x)\n x_r = self.conv_r2(x_r)\n x = x_l + x_r\n return x\n\nclass _BoundaryRefineModule(nn.Module):\n def __init__(self, dim, squeeze_ratio=8, expand1x1_ratio=0.5, dilation_paths=1):\n super(_BoundaryRefineModule, self).__init__()\n \n # self.conv1 = nn.Sequential(*[\n # nn.Conv2d(dim, dim, kernel_size=3, padding=1),\n # nn.BatchNorm2d(dim),\n # nn.ReLU(inplace=True)\n # ])\n # self.conv2 = nn.Sequential(*[\n # nn.Conv2d(dim, dim, kernel_size=3, padding=1),\n # nn.BatchNorm2d(dim),\n # nn.ReLU(inplace=True)\n # ])\n\n self.conv1 = _FirePath(dim, dim, 2, squeeze_ratio=squeeze_ratio, expand1x1_ratio=expand1x1_ratio, dilation_paths=dilation_paths)\n\n def forward(self, x):\n # residual = self.conv1(x)\n # residual = self.conv2(residual)\n # out = x + residual\n # return out\n\n return self.conv1(x)\n\nclass _FireBlock(nn.Module):\n\n def __init__(self, inplanes, squeeze_planes,\n expand1x1_planes, expand3x3_planes, dilation=1, padding=1):\n super(_FireBlock, self).__init__()\n self.inplanes = inplanes\n self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1)\n self.squeeze_batchNorm = nn.BatchNorm2d(squeeze_planes)\n self.squeeze_activation = nn.ReLU(inplace=True)\n self.expand1x1_planes = expand1x1_planes\n if expand1x1_planes > 0:\n self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes,\n kernel_size=1)\n self.expand1x1_batchNorm = nn.BatchNorm2d(expand1x1_planes)\n self.expand1x1_activation = nn.ReLU(inplace=True)\n\n self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes, kernel_size=3, dilation=dilation, padding=padding)\n self.expand3x3_batchNorm = nn.BatchNorm2d(expand3x3_planes)\n self.expand3x3_activation = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.squeeze_activation(self.squeeze_batchNorm(self.squeeze(x)))\n if self.expand1x1_planes > 0:\n return torch.cat([\n self.expand1x1_activation(self.expand1x1_batchNorm(self.expand1x1(x))),\n self.expand3x3_activation(self.expand3x3_batchNorm(self.expand3x3(x)))\n ], 1)\n else:\n return self.expand3x3_activation(self.expand3x3_batchNorm(self.expand3x3(x)))\n\nclass _FirePath(nn.Module):\n def __init__(self, in_channels, out_channels, num_fire_blocks, squeeze_ratio=8, expand1x1_ratio=0.5, dilation_rates=[1]):\n super(_FirePath, self).__init__()\n assert(num_fire_blocks > 0)\n\t\t\n self.in_channels = in_channels\n self.out_channels = out_channels\n squeeze_channels = out_channels // squeeze_ratio\n expand1x1_channels = int(out_channels * expand1x1_ratio)\n expand3x3_channels = out_channels - expand1x1_channels\n self.residual_block_list = nn.ModuleList()\n self.residual_block_list.append(_FireBlock(in_channels, squeeze_channels, expand1x1_channels, expand3x3_channels, dilation=dilation_rates[0], padding=dilation_rates[0]))\n for i in range(1, num_fire_blocks):\n rate_idx = i % len(dilation_rates)\n self.residual_block_list.append(_FireBlock(out_channels, squeeze_channels, expand1x1_channels, expand3x3_channels, dilation=dilation_rates[rate_idx], padding=dilation_rates[rate_idx]))\n \n def forward(self, x):\n\n for i, layer in enumerate(self.residual_block_list):\n if i==0 and self.in_channels != self.out_channels:\n x = layer(x)\n else:\n residual = layer(x)\n x = x + residual\n\n return x\n\nclass UpsamplingBottleneck(nn.Module):\n \"\"\"The upsampling bottlenecks upsample the feature map resolution using max\n pooling indices stored from the corresponding downsampling bottleneck.\n\n Main branch:\n 1. 1x1 convolution with stride 1 that decreases the number of channels by\n ``internal_ratio``, also called a projection;\n 2. max unpool layer using the max pool indices from the corresponding\n downsampling max pool layer.\n\n Extension branch:\n 1. 1x1 convolution with stride 1 that decreases the number of channels by\n ``internal_ratio``, also called a projection;\n 2. transposed convolution (by default, 3x3);\n 3. 1x1 convolution which increases the number of channels to\n ``out_channels``, also called an expansion;\n 4. dropout as a regularizer.\n\n Keyword arguments:\n - in_channels (int): the number of input channels.\n - out_channels (int): the number of output channels.\n - internal_ratio (int, optional): a scale factor applied to ``in_channels``\n used to compute the number of channels after the projection. eg. given\n ``in_channels`` equal to 128 and ``internal_ratio`` equal to 2 the number\n of channels after the projection is 64. Default: 4.\n - kernel_size (int, optional): the kernel size of the filters used in the\n convolution layer described above in item 2 of the extension branch.\n Default: 3.\n - padding (int, optional): zero-padding added to both sides of the input.\n Default: 0.\n - dropout_prob (float, optional): probability of an element to be zeroed.\n Default: 0 (no dropout).\n - bias (bool, optional): Adds a learnable bias to the output if ``True``.\n Default: False.\n - relu (bool, optional): When ``True`` ReLU is used as the activation\n function; otherwise, PReLU is used. Default: True.\n\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n internal_ratio=4,\n kernel_size=3,\n padding=0,\n dropout_prob=0,\n bias=False,\n relu=True):\n super().__init__()\n\n # Check in the internal_scale parameter is within the expected range\n # [1, channels]\n if internal_ratio <= 1 or internal_ratio > in_channels:\n raise RuntimeError(\"Value out of range. Expected value in the \"\n \"interval [1, {0}], got internal_scale={1}. \"\n .format(in_channels, internal_ratio))\n\n internal_channels = in_channels // internal_ratio\n\n if relu:\n activation = nn.ReLU()\n else:\n activation = nn.PReLU()\n\n # Main branch - max pooling followed by feature map (channels) padding\n self.main_conv1 = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=bias),\n nn.BatchNorm2d(out_channels))\n\n # Remember that the stride is the same as the kernel_size, just like\n # the max pooling layers\n self.main_unpool1 = nn.MaxUnpool2d(kernel_size=(2, 2), stride=(2, 2), padding=(0, 0))\n\n # Extension branch - 1x1 convolution, followed by a regular, dilated or\n # asymmetric convolution, followed by another 1x1 convolution. Number\n # of channels is doubled.\n\n # 1x1 projection convolution with stride 1\n self.ext_conv1 = nn.Sequential(\n nn.Conv2d(\n in_channels, internal_channels, kernel_size=1, bias=bias),\n nn.BatchNorm2d(internal_channels), activation)\n\n # Transposed convolution\n self.ext_conv2 = nn.Sequential(\n nn.ConvTranspose2d(\n internal_channels,\n internal_channels,\n kernel_size=kernel_size,\n stride=2,\n padding=padding,\n # output_padding=1, # Modified by MixXxyZ\n bias=bias), nn.BatchNorm2d(internal_channels), activation)\n\n # 1x1 expansion convolution\n self.ext_conv3 = nn.Sequential(\n nn.Conv2d(\n internal_channels, out_channels, kernel_size=1, bias=bias),\n nn.BatchNorm2d(out_channels), activation)\n\n self.ext_regul = nn.Dropout2d(p=dropout_prob)\n\n # PReLU layer to apply after concatenating the branches\n self.out_activation = activation\n\n def forward(self, x, max_indices):\n # Main branch shortcut\n \"\"\" (original)\n main = self.main_conv1(x)\n main = self.main_unpool1(main, max_indices)\n \"\"\"\n main = self.main_unpool1(x, max_indices)\n main = self.main_conv1(main)\n # Extension branch\n ext = self.ext_conv1(x)\n ext = self.ext_conv2(ext)\n ext = self.ext_conv3(ext)\n ext = self.ext_regul(ext)\n\n # Add main and extension branches\n out = main + ext\n\n return self.out_activation(out)\n\nclass MixNet(nn.Module):\n def __init__(self, in_channels=1, out_channels=4, init_weights=False):\n super(MixNet, self).__init__()\n \n self.enc1 = nn.Sequential(*[\n nn.Conv2d(in_channels, 16, kernel_size=3, padding=1),\n nn.BatchNorm2d(16),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=False, return_indices=True),\n ])\n # Assume input image size = (224, 224) !!! 224 * (0.5) = 112\n # We use kernel size = 111 which is compatible for GCN module (accept odd number for kernel size)\n # and make the output size equals to the input size\n #self.gcn1 = _GlobalConvModule(16, 8, (111, 111)) \n # self.brm1 = _BoundaryRefineModule(16, dilation_paths=1)\n #############################################\n self.enc2 = nn.Sequential(*[\n _FirePath(16, 64, 4, dilation_rates=[1,2,3,5]),\n nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=False, return_indices=True),\n ])\n #self.gcn2 = _GlobalConvModule(64, 32, (55, 55)) # Assume input image size = (224, 224) !!! 224 * (0.5)^2 = 56\n # self.brm2 = _BoundaryRefineModule(64, dilation_paths=1)\n #############################################\n self.enc3 = nn.Sequential(*[\n _FirePath(64, 128, 16, dilation_rates=[1,2,3,5]),\n nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=False, return_indices=True),\n ])\n #self.gcn3 = _GlobalConvModule(128, 64, (27, 27)) # Assume input image size = (224, 224) !!! 224 * (0.5)^3 = 28\n # self.brm3 = _BoundaryRefineModule(128, dilation_paths=1)\n #############################################\n self.unpool3 = UpsamplingBottleneck(128, 64, internal_ratio=4, kernel_size=2, padding=0, dropout_prob=0, bias=True, relu=True) # in_channels = 128 --> from enc3 only !!!\n self.dec3 = _FirePath(64, 64, 2, dilation_rates=[1,2,3,5])\n # self.brm3_dec = _BoundaryRefineModule(64, dilation_paths=1)\n #############################################\n self.unpool2 = UpsamplingBottleneck(128, 16, internal_ratio=4, kernel_size=2, padding=0, dropout_prob=0, bias=True, relu=True) # in_channels = 128 --> from enc2 and dec3 (see *1)\n self.dec2 = _FirePath(16, 16, 1, dilation_rates=[1,2,3,5])\n # self.brm2_dec = _BoundaryRefineModule(16, dilation_paths=1)\n #############################################\n self.unpool1 = UpsamplingBottleneck(32, out_channels, internal_ratio=4, kernel_size=2, padding=0, dropout_prob=0, bias=True, relu=True) # in_channels = 32 --> from enc1 and dec2 (see *2)\n self.dec1 = nn.Sequential(\n *[nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)]\n )\n # self.brm1_dec = _BoundaryRefineModule(out_channels, squeeze_ratio=1, expand1x1_ratio=0, dilation_paths=1)\n #############################################\n\n if init_weights:\n self._initialize_weights()\n \n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n def forward(self, x):\n enc1, pool_idx1 = self.enc1(x)\n # enc1_skip = self.brm1(self.gcn1(enc1))\n # enc1_skip = self.gcn1(enc1)\n enc2, pool_idx2 = self.enc2(enc1)\n # enc2_skip = self.brm2(self.gcn2(enc2))\n # enc3 = self.brm3(self.gcn3(self.enc3(enc2)))\n # enc2_skip = self.gcn2(enc2)\n # enc3 = self.gcn3(self.enc3(enc2))\n enc3, pool_idx3 = self.enc3(enc2)\n\n # dec3 = self.brm3_dec(self.dec3(enc3))\n # dec2 = self.brm2_dec(self.dec2(torch.cat([enc2_skip, dec3], 1))) # *1\n # dec1 = self.brm1_dec(self.dec1(torch.cat([enc1_skip, dec2], 1))) # *2\n \n dec3 = self.dec3(self.unpool3(enc3, pool_idx3))\n pool_idx2 = torch.cat([pool_idx2, pool_idx2], 1)\n dec2 = self.dec2(self.unpool2(torch.cat([enc2, dec3], 1), pool_idx2)) # *1\n pool_idx1 = torch.cat([pool_idx1, pool_idx1], 1)\n dec1 = self.dec1(self.unpool1(torch.cat([enc1, dec2], 1), pool_idx1)) # *2\n return dec1"
] | [
[
"torch.nn.Dropout2d",
"torch.nn.ConvTranspose2d",
"torch.nn.MaxUnpool2d",
"torch.cat",
"torch.nn.PReLU",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
juijan/banddownfolder | [
"889e9542f46a4647e2ced0eda9a2035a0197e3f8"
] | [
"banddownfolder/wrapper/ijR.py"
] | [
"import os\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport copy\nfrom scipy.linalg import eigh\nfrom scipy.sparse import csr_matrix\nfrom netCDF4 import Dataset\nfrom collections import defaultdict\nfrom scipy.optimize import curve_fit\nfrom banddownfolder.utils.supercell import SupercellMaker\nfrom scipy.sparse import coo_matrix\nfrom itertools import groupby\nfrom ase.dft.kpoints import bandpath\n\nclass ijR(object):\n def __init__(self,\n nbasis,\n cell=np.eye(3, dtype=float),\n data=None,\n positions=None,\n sparse=False,\n double_site_energy=2.0):\n self.cell = cell\n self.nbasis = nbasis\n if data is not None:\n self.data = data\n else:\n self.data = defaultdict(lambda: np.zeros(\n (nbasis, nbasis), dtype=float))\n if positions is None:\n self.positions = np.zeros((nbasis, 3))\n else:\n self.positions = positions\n self.sparse = sparse\n self.double_site_energy = double_site_energy\n if sparse:\n self._matrix = csr_matrix\n\n def to_sparse(self):\n for key, val in self.data:\n self.data[key] = self._matrix(val)\n\n def make_supercell(self, supercell_matrix=None, scmaker=None):\n if scmaker is None:\n scmaker = SupercellMaker(sc_matrix=supercell_matrix)\n ret = ijR(nbasis=self.nbasis * scmaker.ncell)\n if self.positions is None:\n ret.positions = None\n else:\n ret.positions = scmaker.sc_pos(self.positions)\n ret.cell = scmaker.sc_cell(self.cell)\n ret.sparse = self.sparse\n ret.double_site_energy = self.double_site_energy\n for R, mat in self.data.items():\n for i in range(self.nbasis):\n for j in range(self.nbasis):\n for sc_i, sc_j, sc_R in scmaker.sc_ijR_only(\n i, j, R, self.nbasis):\n ret.data[sc_R][sc_i, sc_j] = mat[i, j]\n return ret\n\n @property\n def Rlist(self):\n return list(self.data.keys())\n\n @property\n def nR(self):\n return len(self.Rlist)\n\n @property\n def site_energies(self):\n return self.data[(0, 0, 0)].diagonal() * self.double_site_energy\n\n @property\n def hoppings(self):\n data = copy.deepcopy(self.data)\n np.fill_diagonal(data[(0, 0, 0)], 0.0)\n return data\n\n @staticmethod\n def _positive_R_mat(R, mat):\n \"\"\"\n if R<0: M(-R) = Mdagger\n if R=0: (M+Mdagger)/2\n if R>0 : M(R) = Mdagger\n \"\"\"\n nzR = np.nonzero(R)[0]\n if len(nzR) != 0 and R[nzR[0]] < 0:\n newR = tuple(-np.array(R))\n newmat = mat.T.conj()\n elif len(nzR) == 0:\n newR = R\n newmat = (mat + mat.T.conj()) / 2.0\n else:\n newR = R\n newmat = mat\n return newR, newmat\n\n def _to_positive_R(self):\n new_ijR = ijR(self.nbasis,\n cell=self.cell,\n positions=self.positions,\n sparse=self.sparse)\n for R, mat in self.data:\n newR, newmat = self._positive_R_mat(R, mat)\n new_ijR.data[newR] = newmat\n return new_ijR\n\n def shift_position(self, rpos):\n pos = self.positions\n shift = np.zeros((self.nbasis, 3), dtype='int')\n shift[:, :] = np.round(pos - rpos)\n newpos = copy.deepcopy(pos)\n for i in range(self.nbasis):\n newpos[i] = pos[i] - shift[i]\n d = ijR(self.nbasis)\n d.positions = newpos\n for R, v in self.data.items():\n for i in range(self.nbasis):\n for j in range(self.nbasis):\n sR = tuple(np.array(R) - shift[i] + shift[j])\n nzR = np.nonzero(sR)[0]\n if len(nzR) != 0 and sR[nzR[0]] < 0:\n newR = tuple(-np.array(sR))\n d.data[newR][j, i] += v[i, j]\n elif len(nzR) == 0:\n newR = sR\n d.data[newR][i, j] += v[i, j] * 0.5\n d.data[newR][j, i] += np.conj(v[i, j]) * 0.5\n else:\n d.data[sR][i, j] += v[i, j]\n return d\n\n def save(self, fname):\n try:\n from netCDF4 import Dataset\n except ImportError():\n print(\"Warning: \")\n root = Dataset(fname, 'w', format=\"NETCDF4\")\n root.createDimension(\"nR\", self.nR)\n root.createDimension(\"three\", 3)\n root.createDimension(\"nbasis\", self.nbasis)\n R = root.createVariable(\"R\", 'i4', (\"nR\", \"three\"))\n data = root.createVariable(\"data\", 'f8', (\"nR\", \"nbasis\", \"nbasis\"))\n positions = root.createVariable(\"positions\", 'f8', (\"nbasis\", \"three\"))\n cell = root.createVariable(\"cell\", 'f8', (\"three\", \"three\"))\n R[:] = np.array(self.Rlist)\n data[:] = np.array(tuple(self.data.values()))\n positions[:] = np.array(self.positions)\n cell[:] = np.array(self.cell)\n root.close()\n\n def write_txt(self, fname):\n with open(fname, 'w') as myfile:\n myfile.write(f\"Number_of_R: {self.nR}\\n\")\n myfile.write(f\"Number_of_basis_functions: {self.nbasis}\\n\")\n myfile.write(f\"Cell parameter: {self.cell}\\n\")\n myfile.write(f\"Hamiltonian: \\n\" + \"=\"*60+'\\n')\n for iR,R in enumerate(self.Rlist):\n myfile.write(f\"index of R: {iR}. R = {R}\\n\")\n d=self.data[R]\n for i in rang(nbais):\n for j in range(nbasis):\n myfile.write(f\"R = {R}\\t. i = {i}, j={j}, H(i,j,R)= {d[i,j]}\")\n myfile.write('-'*60+'\\n')\n\n @staticmethod\n def load_ijR(fname):\n root = Dataset(fname, 'r')\n nbasis = root.dimensions['nbasis'].size\n Rlist = root.variables['R'][:]\n m = ijR(nbasis)\n mdata = root.variables['data'][:]\n for iR, R in enumerate(Rlist):\n m.data[tuple(R)] = mdata[iR]\n m.positions = root.variables['positions'][:]\n m.cell = root.variables['cell'][:]\n return m\n\n @staticmethod\n def from_tbmodel(model):\n ret = ijR(nbasis=model.size)\n for R, v in model.hop.items():\n ret.data[R] = v\n ret.positions = np.reshape(model.pos, (model.size, 3))\n ret.cell = model.uc\n return ret\n\n @staticmethod\n def from_tbmodel_hdf5(fname):\n from tbmodels import Model\n m = Model.from_hdf5_file(fname)\n ret = ijR(nbasis=m.size)\n for R, v in m.hop.items():\n ret.data[R] = v\n ret.positions = np.reshape(m.pos, (m.size, 3))\n ret.cell = m.uc\n return ret\n\n def to_spin_polarized(self, order=1):\n \"\"\"\n repeat \n order =1 : orb1_up, orb1_dn, orb2_up, orb2_dn...\n order =2 : orb1_up, orb2_up, ... orb1_dn, orb2_dn...\n \"\"\"\n ret = ijR(self.nbasis * 2)\n if self.positions is None:\n ret.positions = None\n else:\n ret.positions = np.repeat(self.positions, 2, axis=0)\n for R, mat in self.data.items():\n ret.data[R][::2, ::2] = mat\n ret.data[R][1::2, 1::2] = mat\n return ret\n\n def gen_ham(self, k):\n Hk = np.zeros((self.nbasis, self.nbasis), dtype='complex')\n np.fill_diagonal(Hk, self.site_energies)\n for R, mat in self.hoppings.items():\n phase = np.exp(2j * np.pi * np.dot(k, R))\n Hk += mat * phase + (mat * phase).T.conj()\n return Hk\n\n def solve_all(self, kpts):\n nk = len(kpts)\n evals = np.zeros((nk, self.nbasis))\n evecs = np.zeros((nk, self.nbasis, self.nbasis),dtype=complex)\n for ik, k in enumerate(kpts):\n evals_k, evecs_k = eigh(self.gen_ham(k))\n evals[ik, :] = evals_k\n evecs[ik, :, :] = evecs_k\n return evals, evecs\n\n def plot_band(self,\n kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0],\n [0, 0, 0], [.5, .5, .5]]),\n knames=['$\\Gamma$', 'X', 'M', '$\\Gamma$', 'R'],\n supercell_matrix=None,\n npoints=100,\n efermi=None,\n ax=None):\n if ax is None:\n _fig, ax = plt.subplots()\n if supercell_matrix is not None:\n kvectors = [np.dot(k, supercell_matrix) for k in kvectors]\n kpts, x, X = bandpath(kvectors, self.cell, npoints)\n evalues, _evecs = self.solve_all(kpts=kpts)\n for i in range(evalues.shape[1]):\n ax.plot(x, evalues[:, i], color='blue', alpha=1)\n\n if efermi is not None:\n plt.axhline(self.get_fermi_level(), linestyle='--', color='gray')\n else:\n try:\n plt.axhline(self.get_fermi_level(), linestyle='--', color='gray')\n except:\n pass\n ax.set_xlabel('k-point')\n ax.set_ylabel('Energy (eV)')\n ax.set_xlim(x[0], x[-1])\n ax.set_xticks(X)\n ax.set_xticklabels(knames)\n for x in X:\n ax.axvline(x, linewidth=0.6, color='gray')\n return ax\n\n def validate(self):\n # make sure all R are 3d.\n for R in self.data.keys():\n if len(R) != 3:\n raise ValueError(\"R should be 3d\")\n\n\ndef ijR_to_model(model, dijR):\n model._hoppings = dijR.hoppings\n model._site_energies = dijR.site_energies\n return model\n"
] | [
[
"numpy.dot",
"numpy.conj",
"numpy.nonzero",
"numpy.reshape",
"numpy.eye",
"matplotlib.pyplot.subplots",
"numpy.round",
"numpy.fill_diagonal",
"numpy.repeat",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Tecnarca/patectsdgym | [
"7ed2c7a7d37d5d0c2a44b050d74958284cf9493d"
] | [
"evaluation/dpbench/metrics/sra.py"
] | [
"import numpy as np\nimport pandas as pd\n\ndef sra(real, synth):\n \"\"\"\n SRA can be thought of as the (empirical) probability of a\n comparison on the synthetic data being ”correct” (i.e. the same as\n the comparison would be on the real data).\n\n From \"Measuring the quality of Synthetic data for use in competitions\"\n https://arxiv.org/pdf/1806.11345.pdf\n\n (NOTE: SRA requires at least 2 accuracies per list to work)\n\n :param real: list of accuracies on models of real data\n :type real: list of floats\n :param synth: list of accuracies on models of synthetic data\n :type synth: list of floats\n :return: sra score\n :rtype: float\n \"\"\"\n k = len(real)\n sum_I = 0\n for i in range(k):\n R_vals = np.array([real[i]-rj if i != k else None for k, rj in enumerate(real)])\n S_vals = np.array([synth[i]-sj if i != k else None for k, sj in enumerate(synth)])\n I = (R_vals[R_vals != np.array(None)] * S_vals[S_vals != np.array(None)])\n I[I >= 0] = 1\n I[I < 0] = 0\n sum_I += I\n return np.sum((1 / (k * (k-1))) * sum_I)"
] | [
[
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
GalAvineri/MelMedic | [
"af9142d0fabd86b6c87a345a49dfb167b9765225"
] | [
"main.py"
] | [
"from data.dataset import Dataset\nfrom auxilleries import IO\nfrom metrics import Precision, Recall, F1\n\nfrom tensorflow import keras\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint\nfrom sklearn.metrics import classification_report\nfrom sklearn.utils import class_weight\n\nimport numpy as np\nimport os\nfrom os.path import join\n\n# Create the base pre-trained model\nbase_model = InceptionV3(weights='imagenet', include_top=False)\n\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\npredictions = Dense(2, activation='softmax')(x)\nmodel = Model(inputs=base_model.input, outputs=predictions)\n\n# We would like to train only the newly added layers and freeze all lower layers\nfor layer in base_model.layers:\n layer.trainable = False\n\nmetrics = [Precision(class_ind=0, name='p0'), Recall(class_ind=0, name='r0'), F1(class_ind=0, name='f1_0'),\n Precision(class_ind=1, name='p1'), Recall(class_ind=1, name='r1'), F1(class_ind=1, name='f1_1')]\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'] + metrics)\n\n# data\nbatch_size = 32\ndata_dir = join(os.pardir, 'Data', 'suites')\ntrain = Dataset(join(data_dir, 'train'))\nval = Dataset(join(data_dir, 'val'))\ntest = Dataset(join(data_dir, 'test'))\n\ntrain_iter = train.dataset.shuffle(train.size).map(Dataset.parse_sample, num_parallel_calls=4) \\\n .batch(batch_size).repeat().prefetch(batch_size)\nval_iter = val.dataset.map(Dataset.parse_sample, num_parallel_calls=4).batch(batch_size).repeat().prefetch(batch_size)\ntest_iter = test.dataset.map(Dataset.parse_sample, num_parallel_calls=4).batch(batch_size).prefetch(batch_size)\n\n# Training configurations\nepochs = 100\nclass_weights = class_weight.compute_class_weight('balanced', np.unique(train.labels), train.labels)\n\n# Results configutation\nresults_dir = join(os.pardir, 'Results')\nweights_file = join(results_dir, 'best_model_weights')\ncallbacks = [EarlyStopping(patience=10), ReduceLROnPlateau(), ModelCheckpoint(weights_file, save_best_only=True)]\nIO.create_if_none(results_dir)\n\n# Train the model\nmodel.fit(train_iter, validation_data=val_iter, epochs=epochs,\n steps_per_epoch=train.size // batch_size, validation_steps=val.size // batch_size,\n class_weight=class_weights,\n callbacks=callbacks\n )\n\n# Load best model weights\nmodel.load_weights(weights_file)\n# Evaluate the model\npreds = model.predict(test_iter, steps=test.size // batch_size)\npreds = np.argmax(preds, axis=1)\nprint(classification_report(test.labels[:len(preds)], preds))\n"
] | [
[
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.layers.GlobalAveragePooling2D",
"tensorflow.keras.models.Model",
"numpy.unique",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.callbacks.ReduceLROnPlateau",
"numpy.argmax",
"tensorflow.keras.callbacks.EarlyStopping",
"tensorflow.keras.applications.inception_v3.InceptionV3"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
frodofine/lemon | [
"f874857cb8f1851313257b25681ad2a254ada8dc"
] | [
"dubs/dubs.py"
] | [
"from candiy_lemon import lemon\nimport sys, os\nimport numpy as np\nimport pandas as pd\n\n# List of dictionaries to keep track of parts of the file\n\n# Key: reference pdbid, Value: path to .mmtf file\npathDict = {}\n# Key: reference pdbID, Value: chemical ID of ligand bound to reference protein for removal\nreferenceLigandDict = {}\n# Key: reference pdbID, Value: list of sm or non-sm protein\nreferenceDict = {}\n# Key: reference pdbID, Value: list of proteins to aling to reference (like in pinc)\nalignProtDict = {}\n# Key: align protein pdbID, Value: ligand chemical ID code for ligand removal \nalignProtLigandDict = {}\n# Key: pdbID, Value: chemical id for SM ligand\npdbIDSMDict = {}\n# Key: pdbID, Value: tuple(resCode, chainID, residue ID)\npdbIDNonSMDict = {}\n# Key: pdbID, Value: chemical id for SM ligand\nnoAlignSMDict = {}\n# Key: pdbID, Value: tuple(resCode, chainID, residue ID)\nnoAlignNonSMDict = {}\n\n# Maximum distance allowed between a residue and the ligand\nmaximumResidueDistance = 25.0\n\nentries = set()\n\n# Method for getting binding affinity information\n# Input is list of tuple with each tuple -> (pdb_id,lig_code)\ndef get_bind_affinty(bind_tup_list):\n # We can get the csv file directly from a url using pandas\n # Use custom columns due to some of the columns not being needed\n binding_moad_url = \"http://bindingmoad.org/files/csv/every_bind.csv\"\n binding_moad_data = pd.read_csv(binding_moad_url,usecols=[0,2,3,4,5,7,8,9],header=None)\n\n # Set the columns manually because there is no header given\n binding_moad_data.columns = [\"ec\",\"pdb_id\",\"lig_code\",\"validity\",\"affnty_type\",\"affnty_val\",\"affnty_units\",\"SMILES\"]\n\n # Create our dictionaries and varaibles here\n pdb_id_dict = {}\n lig_id_dict = {}\n cur_pdb_id = \"\"\n\n # Go through each of the row and add the data to the dictionaries\n for index,row in binding_moad_data.iterrows():\n if pd.isna(row[\"pdb_id\"]) == False:\n cur_pdb_id = row[\"pdb_id\"]\n elif (pd.isna(row[\"lig_code\"]) == False) and (pd.isna(row[\"affnty_type\"]) == False) and (pd.isna(row[\"affnty_val\"]) == False) and (pd.isna(row[\"affnty_units\"]) == False):\n simple_lig_code = row[\"lig_code\"].split(\":\")[0]\n simple_lig_code = simple_lig_code.split(\" \")\n\n for code in simple_lig_code:\n\n if pdb_id_dict.get(cur_pdb_id,0) == 0:\n pdb_id_dict[cur_pdb_id] = [code]\n else:\n if simple_lig_code not in pdb_id_dict[cur_pdb_id]:\n pdb_id_dict[cur_pdb_id].append(code)\n\n if lig_id_dict.get((cur_pdb_id,code),0) == 0:\n lig_id_dict[(cur_pdb_id,code)] = [[row[\"lig_code\"],row[\"affnty_type\"],row[\"affnty_val\"],row[\"affnty_units\"]]]\n else:\n lig_id_dict[(cur_pdb_id,code)].append([row[\"lig_code\"],row[\"affnty_type\"],row[\"affnty_val\"],row[\"affnty_units\"]])\n\n #To access the ligand we need to first check to see if the ligand exists in pdb_id_dict\n # If this is one of the ligands availibe, then we access the tuple in the lig_id_dict with the binding affinity\n ret_dict = {}\n for pair in bind_tup_list:\n pdb_id = pair[0]\n lig_code = pair[1]\n\n if lig_id_dict.get((pdb_id,lig_code),0) == 0:\n ret_dict[(pdb_id,lig_code)] = \"No Binding Information Found!\"\n else:\n ret_dict[(pdb_id,lig_code)] = lig_id_dict[(pdb_id,lig_code)]\n\n # Return the final dict, key -> (pdb_id,lig_code) and value is information on that ligand interaction\n return ret_dict\n\n# Method for parsing a formated input file\ndef parse_input_file(fname):\n # Open file and initialize flags to 0\n f = open(fname,\"r\")\n curRefPdbID = \"\"\n flag = 0\n\n global maximumResidueDistance\n global referenceLigandDict\n global referenceDict\n global alignProtDict\n\n for line in f:\n # Check to see if the line contains any of the tags\n # Set appropriate flags if it does\n if line.startswith(\"#\"):\n continue\n elif line.startswith(\"@<reference>\"):\n flag = 1\n continue\n elif line.startswith(\"@<align_prot>\"):\n flag = 2\n continue\n elif line.startswith(\"@<align_sm_ligands>\"):\n flag = 3\n continue\n elif line.startswith(\"@<align_non_sm_ligands>\"):\n flag = 4\n continue\n elif line.startswith(\"@<no_align_sm_ligands>\"):\n flag = 5\n continue\n elif line.startswith(\"@<no_align_non_sm_ligands>\"):\n flag = 6\n continue\n elif line.startswith(\"@<maximum_residue_distance>\"):\n flag = 7\n continue\n elif line.startswith(\"@<end>\"):\n flag = 0\n continue\n elif line.startswith(\"@\"):\n print(\"Invalid tag (@<>) detected, please check all tags are in the proper format\")\n sys.exit()\n\n # If the line does not contain a flag\n # Add info to appropriate dictionary based of set flags\n if flag == 1:\n # Error Check\n if len(line.split(\" \")) < 2:\n print(\"Invalid input under @<reference> tag, please check to ensure proper input\")\n sys.exit(1)\n\n pdbID = line.split(\" \")[0].strip().upper()\n path = line.split(\" \")[1].strip()\n curRefPdbID = pdbID\n pathDict[pdbID] = path\n\n if len(line.split(\" \")) >= 3:\n chemID = line.split(\" \")[2].strip().upper()\n referenceLigandDict[pdbID] = chemID \n \n elif flag == 2:\n if len(line.split(\" \")) < 2:\n print(\"Invalid input under @<align_prot> tag, please check to ensure proper input\")\n sys.exit(1)\n\n pdbID = line.split(\" \")[0].strip()\n chemID = line.split(\" \")[1].strip()\n\n if alignProtDict.get(curRefPdbID,0) == 0:\n alignProtDict[curRefPdbID] = [pdbID]\n else:\n alignProtDict[curRefPdbID].append(pdbID)\n\n if alignProtLigandDict.get(pdbID, 0) == 0:\n alignProtLigandDict[pdbID] = [chemID]\n else:\n alignProtLigandDict[pdbID].append(chemID)\n\n entries.add(pdbID)\n\n elif flag == 3:\n if len(line.split(\" \")) < 2:\n print(\"Invalid input under @<align_sm_ligands> tag, please check to ensure proper input\")\n sys.exit(1)\n\n pdbID = line.split(\" \")[0].strip()\n chemID = line.split(\" \")[1].strip()\n\n if referenceDict.get(curRefPdbID,0) == 0:\n referenceDict[curRefPdbID] = [pdbID]\n else:\n referenceDict[curRefPdbID].append(pdbID)\n \n if pdbIDSMDict.get(pdbID,0) == 0:\n pdbIDSMDict[pdbID] = [chemID]\n else:\n pdbIDSMDict[pdbID].append(chemID)\n\n entries.add(pdbID)\n\n elif flag == 4:\n if len(line.split(\" \")) < 3:\n print(\"Invalid input under @<align_non_sm_ligands> tag, please check to ensure proper input\")\n sys.exit(1)\n\n pdbID = line.split(\" \")[0].strip().upper()\n residueCode = line.split(\" \")[1].split(\"-\")[0].strip().upper()\n chainID = line.split(\" \")[1].split(\"-\")[1].strip().upper()\n residueID = line.split(\" \")[1].split(\"-\")[2].strip().upper()\n\n if referenceDict.get(curRefPdbID,0) == 0:\n referenceDict[curRefPdbID] = [pdbID]\n else:\n referenceDict[curRefPdbID].append(pdbID)\n \n if pdbIDNonSMDict.get(pdbID,0) == 0:\n pdbIDNonSMDict[pdbID] = [tuple([residueCode,chainID,residueID])]\n else:\n pdbIDNonSMDict[pdbID].append(tuple([residueCode,chainID,residueID]))\n\n entries.add(pdbID)\n \n elif flag == 5:\n if len(line.split(\" \")) < 2:\n print(\"Invalid input under @<no_align_sm_ligands> tag, please check to ensure proper input\")\n sys.exit(1)\n\n pdbID = line.split(\" \")[0].strip().upper()\n chemID = line.split(\" \")[1].strip().upper()\n\n if noAlignSMDict.get(pdbID,0) == 0:\n noAlignSMDict[pdbID] = [chemID]\n else:\n noAlignSMDict[pdbID].append(chemID)\n\n entries.add(pdbID)\n\n elif flag == 6:\n if len(line.split(\" \")) < 3:\n print(\"Invalid input under @<no_align_non_sm_ligands> tag, please check to ensure proper input\")\n sys.exit(1)\n\n pdbID = line.split(\" \")[0].strip().upper()\n residueCode = line.split(\" \")[1].split(\"-\")[0].strip().upper()\n chainID = line.split(\" \")[1].split(\"-\")[1].strip()\n residueID = line.split(\" \")[1].split(\"-\")[2].strip()\n\n if noAlignNonSMDict.get(pdbID,0) == 0:\n noAlignNonSMDict[pdbID] = [tuple([residueCode,chainID,residueID])]\n else:\n noAlignNonSMDict[pdbID].append(tuple([residueCode,chainID,residueID]))\n\n entries.add(pdbID)\n \n elif flag == 7:\n maximumResidueDistance = float(line.strip())\n\n# Get from the command line\n# for testing we also can hard set the path\nif len(sys.argv) > 4:\n input_file_path = sys.argv[1]\n hadoop_path = sys.argv[2]\n cores = int(sys.argv[3])\n outdir = sys.argv[4]\nelse:\n #TODO change this if needed for testing\n print(\"You must give the input file, path to RCSB hadoop files, number of cores, and working directory\")\n sys.exit(1)\n\n# Define Lemon workflow class\nclass MyWorkflow(lemon.Workflow):\n def __init__(self):\n lemon.Workflow.__init__(self)\n \n self.reference_structures = {}\n for key, value in pathDict.items():\n self.reference_structures[key] = lemon.open_file(value)\n\n self.noAlignSMDict = noAlignSMDict\n\n self.outdir = outdir\n\n self.write_all_proteins = False\n\n self.maximumResidueDistance = maximumResidueDistance\n\n def extact_ligand_write(self, entry, pdbid, ligand_code):\n ligand_name = ligand_code\n ligand_chain = \"\"\n ligand_altloc = \"A\"\n\n if ligand_code.find(\":\") != -1:\n ligand_split = ligand_code.split(\":\")\n ligand_chain = ligand_split[0]\n ligand_name = ligand_split[1]\n\n if ligand_name.find(\"_\") != -1:\n ligand_split = ligand_name.split(\"_\")\n ligand_name = ligand_split[0]\n ligand_altloc = ligand_split[1]\n\n ligand_ids = \"\"\n\n if ligand_name.startswith(\"+\"):\n ids_to_use = set()\n for my_id in ligand_name.split(\"+\"):\n if my_id.isdigit():\n ids_to_use.add(int(my_id))\n \n ligand_ids = lemon.select_residue_ids(entry, ids_to_use)\n\n ligand_ids = lemon.prune_identical_residues(entry, ligand_ids)\n if ligand_chain:\n ligand_ids = lemon.has_property(entry, ligand_ids, \"chainname\", lemon.Property(ligand_chain))\n \n protein = lemon.Frame()\n ligand = lemon.Frame()\n\n if not os.path.isdir(self.outdir + \"/\" + pdbid):\n os.mkdir(self.outdir + \"/\" + pdbid)\n\n lemon.separate_protein_and_ligands(entry, ligand_ids, self.maximumResidueDistance, protein, ligand, ligand_altloc)\n out_base = self.outdir + \"/\" + pdbid + \"/\" + pdbid + \"_\" + ligand_name\n\n lemon.write_file(protein, out_base + \".pdb\")\n lemon.write_file(ligand, out_base + \".sdf\")\n\n return\n\n rns = set()\n rns.add(lemon.ResidueName(ligand_name))\n ligand_ids = lemon.select_specific_residues(entry, rns)\n\n if ligand_chain:\n ligand_ids = lemon.has_property(entry, ligand_ids, \"chainname\", lemon.Property(ligand_chain))\n\n ligand_ids = lemon.prune_identical_residues(entry, ligand_ids)\n\n for ligand_id in ligand_ids:\n protein = lemon.Frame()\n ligand = lemon.Frame()\n\n if not os.path.isdir(self.outdir + \"/\" + pdbid):\n os.mkdir(self.outdir + \"/\" + pdbid)\n\n lemon.separate_protein_and_ligand(entry, ligand_id, self.maximumResidueDistance, protein, ligand, ligand_altloc)\n out_base = self.outdir + \"/\" + pdbid + \"/\" + pdbid + \"_\" + ligand_name\n\n lemon.write_file(protein, out_base + \".pdb\")\n lemon.write_file(ligand, out_base + \".sdf\")\n\n if len(ligand_ids) > 1:\n print(\"WARNING:It appears that {} in {}\".format(ligand_code, pdbid), file=sys.stderr)\n print(\" is defined multiple times in the same biological assembly,\", file=sys.stderr)\n print(\" only keeping the first time it appears\", file=sys.stderr)\n break\n\n def worker(self, entry, pdbid):\n # Define and assign the reference pdbid\n refpdbid = \"\"\n # mode is 0 unassigned, 1 for alignment for protein, 2 for alignment for ligand\n mode = 0\n\n # Check for pdbID as a protein to be aligned (like in PINC)\n for key, value in alignProtDict.items():\n if pdbid in value:\n refpdbid = key\n mode = 1\n\n # Check for protein-ligand pair for alignment \n for key, value in referenceDict.items():\n if pdbid in value:\n refpdbid = key\n mode = 2\n\n if mode == 0:\n for ligand_code in self.noAlignSMDict.get(pdbid, []):\n self.extact_ligand_write(entry, pdbid, ligand_code)\n return pdbid + \" no alignment\\n\"\n\n elif mode == 1:\n # If we need to align to a protein (like in PINC)\n alignment = lemon.TMscore(entry, self.reference_structures[refpdbid])\n positions = entry.positions()\n lemon.align(positions, alignment.affine)\n\n lemon.write_file(entry, self.outdir + \"/\" + refpdbid + \"_\" + pdbid + \".pdb\")\n\n return \"Align Protein: \" + refpdbid + \"_\" + pdbid + \" to \" + refpdbid + \" with score of \" + str(alignment.score) + \"\\n\"\n\n elif mode == 2:\n # If we are doing ligand alignment, that can be done here\n # Get a list of the ligands associated with the protein we are trying to align\n SM_ligandList = pdbIDSMDict.get(pdbid, []) \n Non_SM_ligandList = pdbIDNonSMDict.get(pdbid, [])\n\n alignment = lemon.TMscore(entry, self.reference_structures[refpdbid])\n positions = entry.positions()\n lemon.align(positions, alignment.affine)\n\n if len(SM_ligandList) > 0:\n\n for ligand_code in SM_ligandList:\n self.extact_ligand_write(entry, pdbid, ligand_code)\n return \"Align Protein: \" + pdbid + \" to \" + refpdbid + \" with score of \" + str(alignment.score) + \"\\n\"\n\n def finalize(self):\n pass\n\n# Parse the input file\nparse_input_file(input_file_path)\nprint(pathDict)\n# Initilize the workflow\nwf = MyWorkflow()\n\n# TODO Get these from the command-line or ask the user\nlemon.launch(wf, hadoop_path, cores, entries)\n"
] | [
[
"pandas.isna",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
majedelhelou/PriorLearning | [
"f66d25993c3b99dd31d9d62abeb3e0a5623e034d"
] | [
"models.py"
] | [
"import torch\nimport torch.nn as nn\nimport os\nfrom util import Kernels\n\nclass CNN_Model(nn.Module):\n def __init__(self, num_of_layers=10, kernel_size=3, padding=1, features=64, gksize=11, gsigma=3):\n super(CNN_Model, self).__init__()\n # We are only interested in grayscale\n channels = 1\n # Padding to keep img size constant\n padding = (kernel_size - 1) // 2\n # Create the gaussian blur kernel\n gkernel = Kernels.kernel_2d(gksize, gsigma)\n\n def Conv2d_train(in_channels, out_channels):\n '''\n Utility method to create a conv2d layer\n '''\n\n return nn.Conv2d(\n in_channels = in_channels,\n out_channels = out_channels,\n kernel_size = kernel_size,\n padding = padding,\n bias = False\n )\n\n def Conv2d_blur(kernel):\n '''\n Utility method to create the gaussian blur layer\n '''\n\n padding = (gksize - 1) // 2\n layer = nn.Conv2d(\n in_channels = channels,\n out_channels = channels,\n kernel_size = kernel.shape,\n padding = padding,\n bias = False\n )\n\n # Set the kernel to the gaussian blur kernel\n w, h = kernel.shape\n gaussian_kernel = torch.ones(1, 1, w, h)\n gaussian_kernel[0, 0] = torch.from_numpy(kernel)\n layer.weight = torch.nn.Parameter(gaussian_kernel)\n\n return layer\n\n layers = []\n layers.append(Conv2d_train(channels, features))\n layers.append(nn.ReLU(inplace=True))\n\n # Add the specified number of layers (conv2d and batch normalization with relu activations)\n for _ in range(num_of_layers-2):\n layers.append(Conv2d_train(features, features))\n layers.append(nn.BatchNorm2d(features))\n layers.append(nn.ReLU(inplace=True))\n\n layers.append(Conv2d_train(features, channels))\n\n layers.append(Conv2d_blur(gkernel))\n\n self.network = nn.Sequential(*layers)\n\n def forward(self, x, **kwargs):\n if 'deblurr' not in kwargs:\n deblurr = False\n else:\n deblurr = kwargs['deblurr']\n\n if deblurr:\n out = self.network[:-1](x)\n else:\n out = self.network(x)\n\n return out\n"
] | [
[
"torch.nn.Sequential",
"torch.nn.Parameter",
"torch.ones",
"torch.nn.Conv2d",
"torch.from_numpy",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
msteijaert/smurff | [
"e6066d51e1640e9aad0118628ba72c9d662919fb"
] | [
"python/data/synthetic/make.py"
] | [
"#!/usr/bin/env python\n\nimport numpy as np\nfrom scipy import sparse\nimport scipy.io as sio\nimport argparse\nimport os\nimport itertools\nimport matrix_io as mio\nfrom sklearn import preprocessing\n\n#parser = argparse.ArgumentParser(description='SMURFF tests')\n#parser.add_argument('--envdir', metavar='DIR', dest='envdir', nargs=1, help='Env dir', default='conda_envs')\n#parser.add_argument('--data', metavar='DIR', dest='datadir', nargs=1, help='Data dir', default='data')\n#parser.add_argument('--outdir', metavar='DIR', dest='outdir', nargs=1, help='Output dir',\n# default = 'work/' + datetime.datetime.today().strftime(\"%Y%m%d-%H%M%S\"))\n#\n#args = parser.parse_args()\n\n# product of two gaussian low-rank matrices + noise\ndef normal_dense(shape, K):\n X = np.random.normal(size=(shape[0],K))\n W = np.random.normal(size=(shape[1],K))\n return np.dot(X, W.transpose()) + np.random.normal(size=shape)\n\n# product of two low-rank 'ones' matrices\ndef ones_dense(shape, K):\n X = np.ones((shape[0],K))\n W = np.ones((shape[1],K))\n return np.dot(X,W.transpose())\n\ndef col_rep(shape, K):\n W = np.arange(shape[1]).reshape(1, shape[1])\n return np.repeat(W, shape[0], 0)\n\n# dense -> sparse\n# or\n# sparse -> even sparser\ndef sparsify(A, density):\n if sparse.issparse(A):\n (I, J, V) = sparse.find(A)\n else:\n V = A.reshape(A.size)\n (I, J) = np.indices(A.shape)\n I = I.reshape(A.size)\n J = J.reshape(A.size)\n\n size = V.size\n num = int(size * density)\n idx = np.random.choice(size, num, replace=False)\n\n return sparse.coo_matrix((V[idx], (I[idx], J[idx])), shape = A.shape)\n\ndef gen_matrix(shape, K, func = \"normal\", density = 1.0 ):\n func_dict = {\n \"normal\": normal_dense,\n \"ones\": ones_dense,\n \"col\": col_rep,\n }\n\n m = func_dict[func] (shape,K)\n\n if density < 1.0:\n m = sparsify(m, density)\n\n return m\n\ndef write_matrix(filename, A):\n if sparse.issparse(A):\n mio.write_sparse_float64(filename + \".sdm\", A)\n else:\n # TRANSPOSE BECAUSE OF INTERNAL REPRESENTATION OF DENSE\n # mio.write_dense_float64(filename + \".ddm\", A.transpose())\n # mio.write_dense_float64(filename + \".ddm\", A)\n mio.write_dense_float64(filename + \".ddm\", A)\n\n sio.mmwrite(filename, A)\n\ndef write_tensor(filename, A):\n if sparse.issparse(A):\n mio.write_sparse_float64_matrix_as_tensor(filename + \".sdt\", A)\n else:\n mio.write_dense_float64_matrix_as_tensor(filename + \".ddt\", A)\n\ndef write_feat(base, features):\n for (indx,F) in enumerate(features):\n write_matrix(\"feat_%d_%d\" % (base, indx), F)\n\ndef write_test_data(dirname, test):\n os.chdir(dirname)\n write_matrix(\"test\", test)\n write_tensor(\"test\", test)\n os.chdir(\"..\")\n\ndef write_train_data(dirname, train, features = ([],[])):\n os.makedirs(dirname)\n os.chdir(dirname)\n write_matrix(\"train\", train)\n write_tensor(\"train\", train)\n for (indx,feat) in enumerate(features):\n write_feat(indx, feat)\n os.chdir(\"..\")\n\ndef gen_test_and_write(m, shape, K,func,density, row_split = 1, col_split = 1, center_list=[\"none\"]):\n # split rows and cols\n rows_blocked = np.array_split(m, row_split, axis=0)\n blocks = [ np.array_split(b, col_split, axis=1) for b in rows_blocked]\n m = blocks[0][0]\n col_feat = [b[0] for b in blocks[1:]]\n row_feat = blocks[0][1:]\n\n assert len(col_feat) == row_split - 1\n assert len(row_feat) == col_split - 1\n\n for r in row_feat: assert r.shape[0] == m.shape[0]\n for r in col_feat: assert r.shape[1] == m.shape[1]\n\n test = sparsify(m, 0.2)\n\n for center in center_list:\n if (func == \"ones\" and center != \"none\"):\n continue\n\n shape_str = \"_\".join(map(str,shape))\n dirname = \"%s_%s_%d_%d_%d_%d_%s\" % (func, shape_str, K, int(density * 100), row_split, col_split, center)\n\n print(\"%s...\" % dirname)\n write_test_data(dirname, test)\n\ndef gen_train_and_write(m, shape, K,func,density, row_split = 1, col_split = 1, center = \"none\"):\n if (func == \"ones\" and center != \"none\"):\n return\n\n shape_str = \"_\".join(map(str,shape))\n dirname = \"%s_%s_%d_%d_%d_%d_%s\" % (func, shape_str, K, int(density * 100), row_split, col_split, center)\n\n if os.path.exists(dirname):\n print(\"Already exists: %s. Skipping\" % dirname)\n return\n\n print(\"%s...\" % dirname)\n\n # split rows and cols\n rows_blocked = np.array_split(m, row_split, axis=0)\n blocks = [ np.array_split(b, col_split, axis=1) for b in rows_blocked]\n m = blocks[0][0]\n col_feat = [b[0] for b in blocks[1:]]\n row_feat = blocks[0][1:]\n\n assert len(col_feat) == row_split - 1\n assert len(row_feat) == col_split - 1\n\n for r in row_feat: assert r.shape[0] == m.shape[0]\n for r in col_feat: assert r.shape[1] == m.shape[1]\n\n # PAY ATTENTION TO AXIS ORDER\n if (center == \"row\"):\n m = preprocessing.scale(m, axis = 0, with_std=False)\n elif (center == \"col\"):\n m = preprocessing.scale(m, axis = 1, with_std=False)\n elif (center == \"global\"):\n m = m - np.mean(m)\n\n for i in range(len(row_feat)):\n if (center == \"row\"):\n row_feat[i] = preprocessing.scale(row_feat[i], axis = 0, with_std=False)\n elif (center == \"col\"):\n row_feat[i] = preprocessing.scale(row_feat[i], axis = 1, with_std=False)\n elif (center == \"global\"):\n row_feat[i] = row_feat[i] - np.mean(row_feat[i])\n\n for i in range(len(col_feat)):\n if (center == \"row\"):\n col_feat[i] = preprocessing.scale(col_feat[i], axis = 0, with_std=False)\n elif (center == \"col\"):\n col_feat[i] = preprocessing.scale(col_feat[i], axis = 1, with_std=False)\n elif (center == \"global\"):\n col_feat[i] = col_feat[i] - np.mean(col_feat[i])\n\n write_train_data(dirname, m, (row_feat, col_feat))\n\ndef gen_matrix_tests():\n shape = [2000,100]\n #shape = [40,30]\n num_latent = 4\n for density in (1, .2):\n for func in (\"normal\", \"ones\"):\n # CALL GEN MATRIX ONLY ONCE\n m = gen_matrix(shape,num_latent,func)\n for row_split in (1,2,3):\n for col_split in (1,2,3,):\n for center in (\"none\", \"global\", \"row\", \"col\"):\n gen_train_and_write(m,shape,num_latent,func,density, row_split, col_split, center)\n # SPARSIFY SHOULD BE CALLED ONLY ONCE\n gen_test_and_write(m,shape,num_latent,func,density, row_split, col_split, (\"none\", \"global\", \"row\", \"col\"))\n\ndef gen_and_write_train_tensor(shape, dirname):\n train_tensor = np.random.normal(size=shape)\n os.makedirs(dirname)\n os.chdir(dirname)\n filename = \"train.ddt\"\n with open(filename, 'wb') as f:\n np.array(len(train_tensor.shape)).astype(np.int64).tofile(f)\n np.array(train_tensor.shape).astype(np.int64).tofile(f)\n f.write(train_tensor.astype(np.float64).tobytes(order='F'))\n os.chdir(\"..\")\n return train_tensor\n\ndef gen_and_write_test_tensor(train_tensor, density, dirname):\n val = train_tensor.reshape(train_tensor.size)\n num = int(val.size * density)\n idx = np.random.choice(val.size, num, replace=False)\n\n os.chdir(dirname)\n filename = \"test.sdt\"\n with open(filename, 'wb') as f:\n np.array(len(train_tensor.shape)).astype(np.uint64).tofile(f)\n np.array(train_tensor.shape).astype(np.uint64).tofile(f)\n np.array(idx.size).astype(np.uint64).tofile(f)\n for i in range(len(train_tensor.shape)):\n indices = np.indices(train_tensor.shape)[i].reshape(train_tensor.size)\n (indices[idx] + 1).astype(np.uint32, copy=False).tofile(f)\n val[idx].astype(np.float64, copy=False).tofile(f)\n os.chdir(\"..\")\n\ndef gen_tensor_tests():\n shape = [200, 50, 10]\n shape_str = \"_\".join(map(str, shape))\n\n for density in (1, .2):\n dirname = \"normal_%s_%d\" % (shape_str, int(density * 100))\n print(\"%s...\" % dirname)\n train_tensor = gen_and_write_train_tensor(shape, dirname)\n gen_and_write_test_tensor(train_tensor, density, dirname)\n\nif __name__ == \"__main__\":\n gen_matrix_tests()\n #gen_tensor_tests()"
] | [
[
"numpy.array",
"scipy.sparse.coo_matrix",
"scipy.sparse.issparse",
"scipy.sparse.find",
"numpy.random.choice",
"numpy.arange",
"numpy.indices",
"scipy.io.mmwrite",
"numpy.ones",
"numpy.random.normal",
"numpy.mean",
"sklearn.preprocessing.scale",
"numpy.repeat",
"numpy.array_split"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
douding123986/aiostar | [
"a7fa73820ea13c81062081ea9b8445c2dab1986f"
] | [
"aiostar/spiders/yz/demo.py"
] | [
"\"\"\"\nAuthor : blu\n@Description : demo\n数据源:http://www.boyar.cn/column/5.html\n\"\"\"\nimport aiohttp\nimport asyncio\nfrom lxml import etree\nfrom aiostar.spiders import BaseSpider\nfrom urllib.parse import urljoin\nfrom aiostar.tasks.Request import Request\nfrom aiostar.tasks.Result import ResultTask\nimport json\nimport datetime\nimport pandas as pd\nfrom pprint import pprint\nimport re\n\n\nclass Spider(BaseSpider):\n _type = \"restful\"\n headers = {\n 'Connection': 'keep-alive',\n 'Cache-Control': 'max-age=0',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Referer': 'http://www.boyar.cn/column/6.html',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n }\n end_data = \"\"\n date = \"\"\n\n async def fetch(self, client, url):\n async with client.get(url, headers=self.headers) as resp:\n assert resp.status == 200\n text = await resp.text()\n return text\n\n async def on_message(self, msg):\n async with aiohttp.ClientSession() as client:\n html = await self.fetch(client, 'http://www.boyar.cn/column/5.html')\n tree = etree.HTML(html)\n url = \"http://www.boyar.cn\"\n need = tree.xpath(r'//a[contains(text(), \"港口大豆分销价格\")]/@href')[:2]\n title = tree.xpath(r'//a[contains(text(), \"港口大豆分销价格\")]/text()')[0]\n pattern = re.compile(r\"\\d{4}(?:年)\\d{1,2}(?:月)\\d{1,2}(?:日)\")\n date = pattern.findall(title)\n now_html = await self.fetch(client, urljoin(url, need[0]))\n now = pd.read_html(now_html)\n table = pd.DataFrame(now[0])\n self.end_data = [\n {\n \"name\": result[1],\n \"price\": result[4],\n \"up_down\": result[3]\n }\n for result in table.itertuples()\n ][1:]\n self.date = date[0]\n self.logger(\"日志测试\")\n print(self.end_data)\n\n def on_end(self):\n self.results = {\n \"result\": self.end_data,\n \"date\": self.date\n }\n print(self.results)\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.run_until_complete(Spider().on_message('111'))\n"
] | [
[
"pandas.read_html",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
susumuasaga/Python-Web-Scraping-Cookbook | [
"dcb6241c5ead11070648b9c829b18f4e0d90f464"
] | [
"Chapter08/04_so_word_cloud.py"
] | [
"from bs4 import BeautifulSoup\nimport json\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom tech2grams import tech_2grams\nfrom punctuation import remove_punctuation\n\nwith open(\"spacex-job-listing.html\", \"r\") as file:\n content = file.read()\n\nbs = BeautifulSoup(content, \"lxml\")\nscript_tag = bs.find(\"script\", {\"type\": \"application/ld+json\"})\n\n\njob_listing_contents = json.loads(script_tag.contents[0])\nprint(job_listing_contents)\n\ndesc_bs = BeautifulSoup(job_listing_contents[\"description\"], \"lxml\")\nprint(desc_bs)\n\njust_text = desc_bs.find_all(text=True)\nprint(just_text)\n\njoined = ' '.join(just_text)\ntokens = word_tokenize(joined)\n\nstop_list = stopwords.words('english')\nwith_no_stops = [word for word in tokens if word.lower() not in stop_list]\ntwo_grammed = tech_2grams(with_no_stops)\ncleaned = remove_punctuation(two_grammed)\nprint(cleaned)\n\nfrom wordcloud import WordCloud\nfrom nltk.probability import FreqDist\n\nfreq_dist = FreqDist(cleaned)\nwordcloud = WordCloud(width=1200, height=800).generate_from_frequencies(freq_dist)\n\n# Display the generated image:\n# the matplotlib way:\nimport matplotlib.pyplot as plt\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\n\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Iam-prog/Optimum_Number_of_Cluster_Machine_learning | [
"9a42a1951efc0d350a09e94a5150185dcae89c83"
] | [
"Clustering.py"
] | [
"# Finding the optimum number of clusters for the given dataset using Elbow Method.\n\n# Instruction\n\n# Use Switch ( -d ) for Dataset\n# Use Switch ( -sk ) to start Number of K\n# Use Switch ( -sk ) to end Number of K\n# Use Switch ( -xl ) for xLevel; like what is X point\n# Use Switch ( -ol ) for OutputLevel; like y or target or y point\n# Example of an input given below -->\n# py Clustering.py -d Clustering.csv -sk 2 -ek 10 -xl X -ol Y\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom kneed import KneeLocator\n\nimport Class\n\nif __name__ == '__main__':\n NumOfParams = len(sys.argv)\n print(\"\\nNumber of Parameter is : \", NumOfParams)\n\n Class.Clustering.set_default_value(0)\n Class.Clustering.read_switch(NumOfParams)\n\n print(\"Dataset Name is (-b) : \", Class.Clustering.datasetName)\n print(\"Starting K value (-sk) : \", Class.Clustering.sk)\n print(\"Ending K value (-ek) : \", Class.Clustering.ek)\n print(\"X Level is (-xl) : \", Class.Clustering.xLevel)\n print(\"OutputLevel is (-ol) : \", Class.Clustering.outputLevel)\n\n dataset = Class.Clustering.read_dataset(Class.Clustering.datasetName)\n\n print(\"\\n-> Given X values <- \\n\", Class.Clustering.x)\n print(\"\\n-> Given Y values <- \\n\", Class.Clustering.y)\n\n x = (Class.Clustering.x.to_numpy()).T.flatten()\n y = (Class.Clustering.y.to_numpy()).T.flatten()\n\n if len(x) < int(Class.Clustering.ek) or int(Class.Clustering.ek) < 3:\n print(\"\\n**************************************** Warning ****************************************\\n\")\n print(\"*** Value of Ending K is higher than X size or less then 3 which is not acceptable. ***\")\n print(\"*** Highest Ending K acceptable for this dataset is : \", len(x), \" ***\")\n print(\"*** So, taking highest Ending k value ***\")\n print(\"\\n**************************************** Warning ****************************************\\n\")\n Class.Clustering.ek = str(len(x))\n\n if len(x) <= int(Class.Clustering.sk) or int(Class.Clustering.sk) < 1:\n print(\"\\n************************************* Warning *************************************\\n\")\n print(\"*** Value of Starting K is higher or equal to X size or less then 1. ***\")\n print(\"*** Which is not possible. So, taking default Starting k value 1. ***\")\n print(\"\\n************************************* Warning *************************************\\n\")\n Class.Clustering.sk = str(1)\n\n all_points = Class.Clustering.select(x, y, len(x))\n print(\"\\n---> So, All 2D points <---\")\n print(all_points)\n\n all_cost = [0] * (int(Class.Clustering.sk))\n all_new_cost =[]\n\n print(\"\\n\\n---> Algorithm -> K-Means <---\")\n\n for n in range(int(Class.Clustering.sk), int(Class.Clustering.ek) + 1):\n print(\"\\n\\n\\n*********************************************\")\n print(\"\\n******* When the value of K is: \", n, \" *******\")\n print(\"\\n*********************************************\")\n\n minimum_Distance_index_number = np.arange(0, len(all_points))\n\n selected_Centroid = Class.Clustering.select(x, y, n)\n print(\"\\n\")\n print(\"---> Input Cluster Centroid Points <---\")\n print(selected_Centroid)\n\n count = 1\n while True:\n previous_minimum_Distance_index_number = minimum_Distance_index_number\n print(\"\\n\\n\\n********* Iterations Number : \", count, \"*********\")\n flag = True\n all_Calculated_Distance = Class.Clustering.all_distance(selected_Centroid, all_points)\n minimum_Distance_index_number = Class.Clustering.cluster_points_minimum_distance_index_number(\n all_Calculated_Distance)\n\n for i in range(len(minimum_Distance_index_number)):\n if minimum_Distance_index_number[i] != previous_minimum_Distance_index_number[i]:\n flag = False\n\n if flag:\n print(\"\\n---> As Current Cluster Centroid points are the same as previous Cluster Centroid points. We \"\n \"can stop the process now. <---\")\n break\n\n selected_Centroid = Class.Clustering.new_selected_centroid_points(selected_Centroid, all_points,\n minimum_Distance_index_number)\n count += 1\n\n print(\"\\n\\n--> So, The Final Cluster Centroid Points <---\")\n print(selected_Centroid)\n\n print(\"\\n---> So, The Final Cluster Points with the Cost <---\")\n cost = Class.Clustering.cost(selected_Centroid, all_points, minimum_Distance_index_number,\n all_Calculated_Distance)\n all_cost.append(cost)\n all_new_cost.append(cost)\n\n print(all_cost)\n\n print(\"\\n\\n---> All Costs based on the K values <---\\n\")\n for i in range(int(Class.Clustering.sk) , int(Class.Clustering.ek) + 1):\n print(\"Cost for k\", i,\" is ->\", all_cost[i])\n\n k_value = np.arange(int(Class.Clustering.sk) , int(Class.Clustering.ek) + 1)\n\n Class.Clustering.visualization(x, y, k_value, all_new_cost)\n\n try:\n optimum_number_of_cluster = KneeLocator(k_value, all_new_cost, curve='convex', direction='decreasing')\n optimum_number_of_cluster_value = optimum_number_of_cluster.knee\n plt.vlines(optimum_number_of_cluster_value, plt.ylim()[0], plt.ylim()[1], linestyles='dashed', colors='black')\n print(\"\\nAs we can see from the Graph.\")\n print(\"The Optimum number of Clusters for the given dataset using\"\n \" Elbow Method is: \", optimum_number_of_cluster_value)\n except:\n print(\"\\nAn exception occurred.\")\n print(\"As we can see from the Graph. There is no specific bend (knee / elbow) found in the plot.\")\n print(\"So, we can not get the 'Optimum number' of Clusters for the given dataset using Elbow Method for \"\n \"these k values.\")\n\n print(\"\\n--> Visualization <--\\n\")\n plt.show()\n"
] | [
[
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JKrehl/Electrons.py | [
"33d2b84a668b60009e731643214d826422d06ae3"
] | [
"Electrons/Scattering/Operators/Propagators/FresnelFourier.py"
] | [
"#!/usr/bin/env python\n\"\"\"\nCopyright (c) 2015 Jonas Krehl <[email protected]>\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\"\"\"\n\nimport numpy\nimport numexpr\nfrom scipy import ndimage\nfrom ....Mathematics import FourierTransforms as FT\nfrom ....Utilities import Physics\n\nfrom ...Operators import IntervalOperator\nfrom ...Operators import AbstractArray\n\nclass FresnelFourier(IntervalOperator):\n\tdef __init__(self, zi, zf,\n\t kk = None, ky = None, kx = None,\n\t k = None, energy = None,\n\t y = None, x = None,\n\t factory = False):\n\t\tsuper().__init__(zi, zf)\n\n\t\tif kk is None:\n\t\t\tif ky is None: ky = FT.reciprocal_coords(y)\n\t\t\tif kx is None: kx = FT.reciprocal_coords(x)\n\t\t\tself.kk = numpy.add.outer(ky**2, kx**2)\n\t\telse:\n\t\t\tself.kk = kk\n\n\t\tif k is None: self.k = Physics.wavenumber(energy)\n\t\telse: self.k = k\n\n\tdef derive(self, zi, zf, **kwargs):\n\t\targs = dict(k=self.k, kk=self.kk)\n\t\targs.update(kwargs)\n\n\t\treturn self.__class__(zi, zf, **args)\n\n\tdef apply(self, wave, out=None):\n\t\tif isinstance(wave, AbstractArray):\n\t\t\twave = wave._as(\"numpy\")\n\n\t\tre = FT.ifft(numexpr.evaluate('wave_f*exp(-1j*dis/(2*wn)*kk)', local_dict={'wave_f':FT.fft(wave), 'pi':numpy.pi, 'dis':self.zf-self.zi, 'wn':self.k, 'kk':self.kk}))\n\n\t\tif out is None:\n\t\t\treturn re\n\t\telse:\n\t\t\tout[...] = re\n\t\t\treturn out\n\n\tdef split(self, z):\n\t\treturn self.derive(self.zi, z), self.derive(z, self.zf)\n"
] | [
[
"numpy.add.outer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jackz314/openpilot | [
"60f6d700dda07807bac12370e6b3706d77f961ca"
] | [
"selfdrive/camerad/test/frame_test.py"
] | [
"#!/usr/bin/env python3\nimport numpy as np\nimport cereal.messaging as messaging\nfrom PIL import ImageFont, ImageDraw, Image\n\n# font = ImageFont.truetype(\"arial\", size=72)\ndef get_frame(idx):\n img = np.zeros((874, 1164, 3), np.uint8)\n img[100:400, 100:100+(idx % 10) * 100] = 255\n\n # big number\n im2 = Image.new(\"RGB\", (200, 200))\n draw = ImageDraw.Draw(im2)\n draw.text((10, 100), \"%02d\" % idx)\n img[400:600, 400:600] = np.array(im2.getdata()).reshape((200, 200, 3))\n return img.tostring()\n\nif __name__ == \"__main__\":\n from common.realtime import Ratekeeper\n rk = Ratekeeper(20)\n\n pm = messaging.PubMaster(['roadCameraState'])\n frm = [get_frame(x) for x in range(30)]\n idx = 0\n while 1:\n print(\"send %d\" % idx)\n dat = messaging.new_message('roadCameraState')\n dat.valid = True\n dat.frame = {\n \"frameId\": idx,\n \"image\": frm[idx % len(frm)],\n }\n pm.send('roadCameraState', dat)\n\n idx += 1\n rk.keep_time()\n #time.sleep(1.0)\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jonathanzjl/cam-vision | [
"d1bd865b147ea1137979b624c64a6baa4a4b0714"
] | [
"lib/mobilenet.py"
] | [
"#! /usr/bin/env python3\n# Copyright (C) 2018 Zhijin Li\n\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n## ---------------------------------------------------------------------------\n##\n## File: mobilenet.py for Cam-Vision\n##\n## Created by Zhijin Li\n## E-mail: <[email protected]>\n##\n## Started on Sun Oct 28 21:06:23 2018 Zhijin Li\n## Last update Mon Oct 29 22:34:54 2018 Zhijin Li\n## ---------------------------------------------------------------------------\n\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef __load_mobilenet_base(width_mult):\n \"\"\"\n\n Load MobileNet with weights pretrained\n ImageNet.\n\n width_mult: float\n Width multiplier used for decreasing the\n number of filters in conv layers.\n\n Returns\n ----------\n tf.keras.models.Model\n Loaded MobileNet model.\n\n \"\"\"\n res = tf.keras.applications.mobilenet.MobileNet(\n include_top=True,\n weights='imagenet',\n alpha=width_mult,\n pooling='avg')\n return res\n\n\ndef __load_mobilenet_empty(width_mult, pooling):\n \"\"\"\n\n Load MobileNet without weights.\n\n Parameters\n ----------\n width_mult: float\n Width multiplier used for decreasing the\n number of filters in conv layers.\n\n pooling: str\n The final global pooling type. Either\n `global_avg` or `global_max`.\n\n Returns\n ----------\n tf.keras.models.Model\n Loaded MobileNet model.\n\n \"\"\"\n if pooling not in ['global_avg', 'global_max']:\n raise AttributeError(\n 'pooling must be global_avg or global_max.')\n\n res = tf.keras.applications.mobilenet.MobileNet(\n input_shape=(None,None,3),\n include_top=False,\n weights=None,\n alpha=width_mult,\n depth_multiplier=1, # Current keras impl seems to only works for 1.\n pooling=pooling.split('_')[-1])\n return res\n\n\ndef __get_global2dpooling(model):\n \"\"\"\n\n Get the first global 2D pooling layer.\n\n Parameters\n ----------\n model: tf.keras.models.Model\n The input keras model.\n\n Returns\n ----------\n The first global pooling layer.\n\n \"\"\"\n __lay = None\n for __l in model.layers:\n if (isinstance(__l,tf.keras.layers.GlobalMaxPooling2D) or\n isinstance(__l,tf.keras.layers.GlobalAveragePooling2D)):\n __lay = __l\n return __lay\n\n\ndef __customize_mobilenet(base_model, empty_model):\n \"\"\"\n\n Customize MobileNet for inference mode with\n arbitrary input image size.\n\n Parameters\n ----------\n base_model: tf.keras.models.Model\n The input base model with weights pretrained\n on ImageNet.\n\n empty_model: tf.keras.models.Model\n The input empty model without pretrained weights,\n configured for arbitrary input image size.\n\n Returns\n ----------\n tf.keras.models.Model\n The customized model, with weights copied\n from the base model.\n\n \"\"\"\n intercept = empty_model.output\n __s = empty_model.layers[-1].get_output_shape_at(0)[-1]\n intercept = tf.keras.layers.Reshape((1,1,__s))(intercept)\n intercept = tf.keras.layers.Conv2D(\n name='prediction', filters=1000, kernel_size=(1,1),\n strides=(1,1), padding='same',activation='softmax')(\n intercept)\n intercept = tf.keras.layers.Flatten()(intercept)\n model = tf.keras.models.Model(\n inputs=empty_model.input, outputs=intercept)\n\n for idx in range(len(empty_model.layers)):\n model.layers[idx].set_weights(\n base_model.layers[idx].get_weights())\n __w = base_model.get_layer('conv_preds').get_weights()\n model.get_layer('prediction').set_weights(__w)\n return model\n\n\ndef load_mobilenet_anysize(width_mult, pooling):\n \"\"\"\n\n Load a MobileNet for images of any size.\n\n Copy weights of a loaded base MobileNet\n to an anysize empty MobileNet and return it.\n\n Parameters\n ----------\n width_mult: float\n Width multiplier used for decreasing the\n number of filters in conv layers.\n\n pooling: str\n The final global pooling type. Either\n `global_avg` or `global_max`.\n\n Returns\n ----------\n tf.keras.models.Model\n Loaded MobileNet model.\n\n \"\"\"\n print(\n ('\\nloading MobileNet with\\n'\n '- {:25s}: {}\\n- {:25s}: {}\\n').format(\n 'width multiplier', width_mult,\n 'pooling type', pooling))\n __base = __load_mobilenet_base(width_mult)\n __res = __load_mobilenet_empty(width_mult,pooling)\n __res = __customize_mobilenet(__base,__res)\n print('model loaded.')\n return __res\n"
] | [
[
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.applications.mobilenet.MobileNet",
"tensorflow.keras.layers.Flatten"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
eliavw/nba-anomaly-generator | [
"a1e162095b76a3406411925093381e9ace9258c7"
] | [
"src/nba_anomaly_generator/anom/utils.py"
] | [
"import numpy as np\nimport pandas as pd\n\n\n# Prepare dataframe\ndef assert_and_rng_and_prep_df(df, rng=None, random_state=42):\n \"\"\"These steps are always identical\n \"\"\"\n assert isinstance(random_state, int)\n assert isinstance(df, pd.DataFrame)\n\n # Fix dataframe\n df = _init_df(df)\n\n # Fix random number generator\n rng = init_rng(rng=rng, random_state=random_state)\n return rng, df\n\n\ndef _init_df(df):\n columns = df.columns.tolist()\n\n if columns[-1] == \"a_lbl\":\n return df\n else:\n df = _init_anomaly_column(df, name=\"a_lbl\", value=0)\n return df\n\n\ndef _init_anomaly_column(df, name=\"a_lbl\", value=np.nan):\n df[name] = value\n return df\n\n\n# rng\ndef init_rng(rng=None, random_state=42):\n if rng is None:\n return np.random.default_rng(random_state)\n else:\n return rng\n\n\n# Location in dataframe\ndef init_row_idx(rng, df, row=None):\n return _init_idx(rng, df, row_or_col=row, kind=\"row\")\n\n\ndef init_col_idx(rng, df, col=None):\n return _init_idx(rng, df, row_or_col=col, kind=\"col\")\n\n\ndef _init_idx(rng, df, row_or_col=None, kind=\"row\"):\n axes = dict(row=0, col=1)\n axis = axes[kind]\n\n if row_or_col is None:\n return rng.integers(df.shape[axis], dtype=int)\n elif isinstance(row_or_col, str) and kind in {\"col\"}:\n assert (\n row_or_col in df.columns\n ), \"If you give a string, this column needs to present in the DataFrame.\"\n return df.columns.get_loc(row_or_col)\n elif isinstance(row_or_col, str) and kind in {\"row\"}:\n assert (\n row_or_col in df.index\n ), \"If you give a string, this row needs to present in the index of the DataFrame.\"\n return df.index.get_loc(row_or_col)\n else:\n assert isinstance(row_or_col, int)\n assert row_or_col < df.shape[axis], \"Size must be feasible.\"\n\n return row_or_col\n\n\n# Draw\ndef draw_val(rng, val_list, val_dist):\n assert isinstance(val_list, np.ndarray)\n\n return rng.choice(val_list, p=val_dist)\n\n\n# Values list\ndef init_val_list(df, col_idx, val_list=None):\n\n if val_list is None:\n # Take all the given values as possible options.\n val_list = df.iloc[:, col_idx].values\n else:\n assert isinstance(val_list, np.ndarray)\n # TODO: maybe assert types of elements\n val_list = val_list\n return val_list\n\n\n# Dist\ndef init_val_dist(df, col_idx, val_list, val_dist=None):\n assert isinstance(val_list, np.ndarray)\n if val_dist in {None, \"uniform\"}:\n val_dist = _uniform_dist(val_list)\n else:\n assert isinstance(val_dist, np.ndarray)\n assert val_dist.shape == val_list.shape\n return val_dist\n\n\ndef _uniform_dist(val_list):\n assert isinstance(val_list, np.ndarray)\n n_vals = val_list.shape[0]\n assert n_vals > 0, \"val_list needs to contain values.\"\n return np.ones(n_vals) * (1 / n_vals)\n"
] | [
[
"numpy.random.default_rng",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZJULiHongxin/two-hand-pose-est | [
"e531faacd9cdddcb716b614b832038d079b9663f"
] | [
"lib/fp16_utils/core/inference.py"
] | [
"# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Bin Xiao ([email protected])\n# ------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport numpy as np\n\nfrom utils.transforms import transform_preds\n\n\ndef get_max_preds(batch_heatmaps):\n '''\n get predictions from score maps\n heatmaps: numpy.ndarray([batch_size, num_joints, height, width])\n '''\n assert isinstance(batch_heatmaps, np.ndarray), \\\n 'batch_heatmaps should be numpy.ndarray'\n assert batch_heatmaps.ndim == 4, 'batch_images should be 4-ndim'\n\n batch_size = batch_heatmaps.shape[0]\n num_joints = batch_heatmaps.shape[1]\n width = batch_heatmaps.shape[3]\n heatmaps_reshaped = batch_heatmaps.reshape((batch_size, num_joints, -1))\n idx = np.argmax(heatmaps_reshaped, 2)\n maxvals = np.amax(heatmaps_reshaped, 2)\n\n maxvals = maxvals.reshape((batch_size, num_joints, 1))\n idx = idx.reshape((batch_size, num_joints, 1))\n\n preds = np.tile(idx, (1, 1, 2)).astype(np.float32)\n\n preds[:, :, 0] = (preds[:, :, 0]) % width\n preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)\n\n pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))\n pred_mask = pred_mask.astype(np.float32)\n\n preds *= pred_mask\n return preds, maxvals\n\n\ndef get_final_preds(config, batch_heatmaps, center, scale):\n coords, maxvals = get_max_preds(batch_heatmaps)\n\n heatmap_height = batch_heatmaps.shape[2]\n heatmap_width = batch_heatmaps.shape[3]\n\n # post-processing\n if config.TEST.POST_PROCESS:\n for n in range(coords.shape[0]):\n for p in range(coords.shape[1]):\n hm = batch_heatmaps[n][p]\n px = int(math.floor(coords[n][p][0] + 0.5))\n py = int(math.floor(coords[n][p][1] + 0.5))\n if 1 < px < heatmap_width-1 and 1 < py < heatmap_height-1:\n diff = np.array(\n [\n hm[py][px+1] - hm[py][px-1],\n hm[py+1][px]-hm[py-1][px]\n ]\n )\n coords[n][p] += np.sign(diff) * .25\n\n preds = coords.copy()\n\n # Transform back\n for i in range(coords.shape[0]):\n preds[i] = transform_preds(\n coords[i], center[i], scale[i], [heatmap_width, heatmap_height]\n )\n \n # def transform_preds(coords, center, scale, output_size):\n # target_coords = np.zeros(coords.shape)\n # trans = get_affine_transform(center, scale, 0, output_size, inv=1)\n # for p in range(coords.shape[0]):\n # target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans)\n # return target_coords\n return preds, maxvals\n"
] | [
[
"numpy.amax",
"numpy.greater",
"numpy.tile",
"numpy.sign",
"numpy.argmax",
"numpy.floor",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
andrewjh9/CenBench | [
"afd960b77ade05be2d2368bed3b47d54f7e229b6"
] | [
"plot_creation_scripts/centrality_historgrams/MLP_lap_cen_dis_400_epochs_cifar10.py"
] | [
"import matplotlib.pyplot as plt\nimport numpy as np\nimport tikzplotlib\n\n\naxis_label_size = 14\nfont = {'family' : 'normal',\n 'weight' : 'bold',\n 'size' : axis_label_size}\n\nplt.rc('font', **font)\n\nread_dataset_0_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_0__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_25_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_25__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_50_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_50__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_75_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_75__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_100_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_100__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_125_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_125__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_150_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_150__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_175_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_175__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_200_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_200__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_225_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_225__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_250_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_250__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_275_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_275__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_300_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_300__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_325_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_325__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_350_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_350__mlp_saving_dis_at_multi_25.csv',delimiter='')\nread_dataset_375_cifar10 = np.genfromtxt('results/base_line_MLP/cifar10/MLP__cifar10_for_400_epochs_20210604-191037_num_sd_None_cen_dis_lap_epoch_375__mlp_saving_dis_at_multi_25.csv',delimiter='')\n\n# read_dataset_set = np.genfromtxt('results/zeta/CenSET_laplacian_accuracy_cifar10_for_100_epochs_20210522-190343_zeta_0.0.csv',delimiter='')\n# 30\n\nmax = max(max(read_dataset_0_cifar10),max(read_dataset_25_cifar10),max(read_dataset_50_cifar10),max(read_dataset_75_cifar10),max(read_dataset_100_cifar10),max(read_dataset_125_cifar10),max(read_dataset_150_cifar10),max(read_dataset_175_cifar10),max(read_dataset_200_cifar10),max(read_dataset_225_cifar10),max(read_dataset_250_cifar10),max(read_dataset_275_cifar10),max(read_dataset_300_cifar10),max(read_dataset_325_cifar10),max(read_dataset_350_cifar10),max(read_dataset_375_cifar10),)\nmax = 40\n\nmin = min(min(read_dataset_0_cifar10),min(read_dataset_25_cifar10),min(read_dataset_50_cifar10),min(read_dataset_75_cifar10),min(read_dataset_100_cifar10),min(read_dataset_125_cifar10),min(read_dataset_150_cifar10),min(read_dataset_175_cifar10),min(read_dataset_200_cifar10),min(read_dataset_225_cifar10),min(read_dataset_250_cifar10),min(read_dataset_275_cifar10),min(read_dataset_300_cifar10),min(read_dataset_325_cifar10),min(read_dataset_350_cifar10),min(read_dataset_375_cifar10),)\n\n\n\nmin = -20\n\n# max = max(read_dataset_375_cifar10)\n# min = min(read_dataset_375_cifar10)\n# max = int(max)\n# min = int(min)\ninternal = 0.5\n\n# plt.hist(read_dataset_375_cifar10 , bins= np.arange(min, max, internal), label=\"375\")\n# plt.hist(read_dataset_350_cifar10 , bins= np.arange(min, max, internal), label=\"350\")\n# plt.hist(read_dataset_325_cifar10 , bins= np.arange(min, max, internal), label=\"325\")\n# plt.hist(read_dataset_300_cifar10 , bins= np.arange(min, max, internal), label=\"300\")\n# plt.hist(read_dataset_275_cifar10 , bins= np.arange(min, max, internal), label=\"275\")\n# plt.hist(read_dataset_250_cifar10 , bins= np.arange(min, max, internal), label=\"250\") \n# plt.hist(read_dataset_225_cifar10 , bins= np.arange(min, max, internal), label=\"225\")\n# plt.hist(read_dataset_200_cifar10 , bins= np.arange(min, max, internal), label=\"200\")\n# plt.hist(read_dataset_175_cifar10 , bins= np.arange(min, max, internal), label=\"175\")\n# plt.hist(read_dataset_150_cifar10 , bins= np.arange(min, max, internal), label=\"150\")\n# plt.hist(read_dataset_125_cifar10 , bins= np.arange(min, max, internal), label=\"125\")\n# plt.hist(read_dataset_100_cifar10 , bins= np.arange(min, max, internal), label=\"100\")\n# plt.hist(read_dataset_75_cifar10 , bins= np.arange(min, max, internal), label=\"75\")\n# plt.hist(read_dataset_50_cifar10 , bins= np.arange(min, max, internal), label=\"50\")\n# plt.hist(read_dataset_25_cifar10 , bins= np.arange(min, max, internal), label=\"25\")\n\n# plt.hist(read_dataset_0_cifar10 , bins= np.arange(min, max, internal), label=\"0\")\n\n# plt.legend( title=\"At Epoch[#]\")\n\nfig, axes = plt.subplots(nrows=4,ncols=4, sharex=True)\n\n\naxes[0][0].hist(read_dataset_0_cifar10 , bins= np.arange(min, max, 0.5), label=\"0\", color=\"k\")\naxes[0][0].set_ylim([0,700])\n\naxes[0][1].hist(read_dataset_25_cifar10 , bins= np.arange(min, max, 0.5), label=\"25\", color=\"k\") \naxes[0][1].set_ylim([0,700]) \n\naxes[0][2].hist(read_dataset_50_cifar10 , bins= np.arange(min, max, 0.5), label=\"50\", color=\"k\")\naxes[0][2].set_ylim([0,700]) \n\naxes[0][3].hist(read_dataset_75_cifar10 , bins= np.arange(min, max, 0.5), label=\"75\", color=\"k\") \naxes[0][3].set_ylim([0,700])\n\naxes[1][0].hist(read_dataset_100_cifar10 , bins= np.arange(min, max, 0.5), label=\"100\", color=\"k\") \naxes[1][0].set_ylim([0,700])\n\naxes[1][1].hist(read_dataset_125_cifar10 , bins= np.arange(min, max, 0.5), label=\"125\", color=\"k\")\naxes[1][1].set_ylim([0,700])\n\naxes[1][2].hist(read_dataset_150_cifar10 , bins= np.arange(min, max, 0.5), label=\"150\", color=\"k\") \naxes[1][2].set_ylim([0,700])\n\naxes[1][3].hist(read_dataset_175_cifar10 , bins= np.arange(min, max, 0.5), label=\"175\", color=\"k\")\naxes[1][3].set_ylim([0,700])\n\naxes[2][0].hist(read_dataset_200_cifar10 , bins= np.arange(min, max, 0.5), label=\"200\", color=\"k\") \naxes[2][0].set_ylim([0,700])\n\naxes[2][1].hist(read_dataset_225_cifar10 , bins= np.arange(min, max, 0.5), label=\"225\", color=\"k\")\naxes[2][1].set_ylim([0,700])\n\naxes[2][2].hist(read_dataset_250_cifar10 , bins= np.arange(min, max, 0.5), label=\"250\", color=\"k\") \naxes[2][2].set_ylim([0,700])\n\naxes[2][3].hist(read_dataset_275_cifar10 , bins= np.arange(min, max, 0.5), label=\"275\", color=\"k\")\naxes[2][3].set_ylim([0,700])\n\naxes[3][0].hist(read_dataset_300_cifar10 , bins= np.arange(min, max, 0.5), label=\"300\", color=\"k\") \naxes[3][0].set_ylim([0,700])\n\naxes[3][1].hist(read_dataset_325_cifar10 , bins= np.arange(min, max, 0.5), label=\"325\", color=\"k\")\naxes[3][1].set_ylim([0,700])\n\naxes[3][2].hist(read_dataset_350_cifar10 , bins= np.arange(min, max, 0.5), label=\"350\", color=\"k\") \naxes[3][2].set_ylim([0,700])\n\naxes[3][3].hist(read_dataset_375_cifar10 , bins= np.arange(min, max, 0.5), label=\"375\", color=\"k\")\naxes[3][3].set_ylim([0,700])\n# plt.set_ylim([0,700])\n\nplt.xlabel(\"Laplacian centrality\", fontsize=axis_label_size-2)\nplt.ylabel(\"Frequency\", fontsize=axis_label_size-2)\n# plt.title(\"Frequency Distribution of Laplacian Centrality of Nodes in MLP on FashionMNIST at Epoch 175\")\nplt.tight_layout()\n\n# plt.show()\n\nplt.savefig(\"plots/svg/histogram_lap/mlp_historgram_cfiar10.svg\")\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.genfromtxt",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
warthan07/Nemaktis | [
"54b1e64c1d40668e6dc22b11eac5487a09b58478"
] | [
"HighLevelPythonInterface/examples/benchmarks/3D/03_plot_errors.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\n\nerr_idx = 3\nlabels = []\ndata = []\nfor diff in [1,3,5]:\n raw = np.loadtxt(\"results/errors_and_times_dtmm_diff=%d.dat\" % (diff,))\n data.append({\"dy\":raw[:,1],\"t\":raw[:,2],\"err\":raw[:,err_idx]})\n labels.append(\"DTMM(%d)\" % (diff,))\n\nraw = np.loadtxt(\"results/errors_and_times_bpm.dat\")\ndata.append({\"dy\":raw[:,1],\"t\":raw[:,2],\"err\":raw[:,err_idx]})\nlabels.append(\"BPM\")\n\nNd = len(labels)\nx = np.arange(Nd)\nw = 0.35\n\ni = 1\n\nplt.subplot(2,1,1)\nplt.bar(x, [d[\"err\"][i] for d in data], w)\nplt.gca().set_xticks(x)\nplt.gca().set_xticklabels(labels)\nplt.gca().set_yscale('log')\n\nplt.subplot(2,1,2)\nplt.bar(x, [d[\"t\"][i] for d in data], w)\nplt.gca().set_xticks(x)\nplt.gca().set_xticklabels(labels)\n\nplt.show()\n"
] | [
[
"matplotlib.pyplot.gca",
"numpy.arange",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.show",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
YerongLi2/ContrastiveLosses4VRD | [
"33a859bc24b776cb16326b96ada70d2c5d2bc144"
] | [
"lib/datasets_rel/task_evaluation_vg_and_vrd.py"
] | [
"\"\"\"\nWritten by Ji Zhang, 2019\nSome functions are adapted from Rowan Zellers\nOriginal source:\nhttps://github.com/rowanz/neural-motifs/blob/master/lib/evaluation/sg_eval.py\n\"\"\"\n\nimport os\nimport numpy as np\nimport logging\nfrom six.moves import cPickle as pickle\nimport json\nimport csv\nfrom tqdm import tqdm\n\nfrom core.config import cfg\nfrom functools import reduce\nfrom utils.boxes import bbox_overlaps\nfrom utils_rel.boxes_rel import boxes_union\n\nfrom .pytorch_misc import intersect_2d, argsort_desc\n\nnp.set_printoptions(precision=3)\n\nlogger = logging.getLogger(__name__)\n\n\ntopk = 100\n\n\ndef eval_rel_results(all_results, output_dir, do_val):\n if cfg.TEST.DATASETS[0].find('vg') >= 0:\n prd_k_set = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20)\n elif cfg.TEST.DATASETS[0].find('vrd') >= 0:\n prd_k_set = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 70)\n else:\n prd_k_set = (1, 2, 3, 4, 5, 6, 7, 8, 9)\n\n if cfg.TEST.DATASETS[0].find('vg') >= 0:\n eval_sets = (False,)\n else:\n eval_sets = (False, True)\n\n for phrdet in eval_sets:\n eval_metric = 'phrdet' if phrdet else 'reldet'\n print('================== {} =================='.format(eval_metric))\n\n for prd_k in prd_k_set:\n print('prd_k = {}:'.format(prd_k))\n\n recalls = {20: 0, 50: 0, 100: 0}\n if do_val:\n all_gt_cnt = 0\n\n topk_dets = []\n for im_i, res in enumerate(tqdm(all_results[:2000])):\n\n # in oi_all_rel some images have no dets\n if 'prd_scores' in res and res['prd_scores'] is None:\n det_boxes_s_top = np.zeros((0, 4), dtype=np.float32)\n det_boxes_o_top = np.zeros((0, 4), dtype=np.float32)\n det_labels_s_top = np.zeros(0, dtype=np.int32)\n det_labels_p_top = np.zeros(0, dtype=np.int32)\n det_labels_o_top = np.zeros(0, dtype=np.int32)\n det_scores_top = np.zeros(0, dtype=np.float32)\n else:\n det_boxes_sbj = res['sbj_boxes'] # (#num_rel, 4)\n det_boxes_obj = res['obj_boxes'] # (#num_rel, 4)\n det_labels_sbj = res['sbj_labels'] # (#num_rel,)\n det_labels_obj = res['obj_labels'] # (#num_rel,)\n det_scores_sbj = res['sbj_scores'] # (#num_rel,)\n det_scores_obj = res['obj_scores'] # (#num_rel,)\n if 'prd_scores_ttl' in res:\n det_scores_prd = res['prd_scores_ttl'][:, 1:]\n else:\n det_scores_prd = res['prd_scores'][:, 1:]\n\n det_labels_prd = np.argsort(-det_scores_prd, axis=1)\n det_scores_prd = -np.sort(-det_scores_prd, axis=1)\n\n det_scores_so = det_scores_sbj * det_scores_obj\n det_scores_spo = det_scores_so[:, None] * det_scores_prd[:, :prd_k]\n det_scores_inds = argsort_desc(det_scores_spo)[:topk]\n det_scores_top = det_scores_spo[det_scores_inds[:, 0], det_scores_inds[:, 1]]\n det_boxes_so_top = np.hstack(\n (det_boxes_sbj[det_scores_inds[:, 0]], det_boxes_obj[det_scores_inds[:, 0]]))\n det_labels_p_top = det_labels_prd[det_scores_inds[:, 0], det_scores_inds[:, 1]]\n det_labels_spo_top = np.vstack(\n (det_labels_sbj[det_scores_inds[:, 0]], det_labels_p_top, det_labels_obj[det_scores_inds[:, 0]])).transpose()\n\n det_boxes_s_top = det_boxes_so_top[:, :4]\n det_boxes_o_top = det_boxes_so_top[:, 4:]\n det_labels_s_top = det_labels_spo_top[:, 0]\n det_labels_p_top = det_labels_spo_top[:, 1]\n det_labels_o_top = det_labels_spo_top[:, 2]\n\n topk_dets.append(dict(image=res['image'],\n det_boxes_s_top=det_boxes_s_top,\n det_boxes_o_top=det_boxes_o_top,\n det_labels_s_top=det_labels_s_top,\n det_labels_p_top=det_labels_p_top,\n det_labels_o_top=det_labels_o_top,\n det_scores_top=det_scores_top))\n\n if do_val:\n gt_boxes_sbj = res['gt_sbj_boxes'] # (#num_gt, 4)\n gt_boxes_obj = res['gt_obj_boxes'] # (#num_gt, 4)\n gt_labels_sbj = res['gt_sbj_labels'] # (#num_gt,)\n gt_labels_obj = res['gt_obj_labels'] # (#num_gt,)\n gt_labels_prd = res['gt_prd_labels'] # (#num_gt,)\n gt_boxes_so = np.hstack((gt_boxes_sbj, gt_boxes_obj))\n gt_labels_spo = np.vstack((gt_labels_sbj, gt_labels_prd, gt_labels_obj)).transpose()\n # Compute recall. It's most efficient to match once and then do recall after\n # det_boxes_so_top is (#num_rel, 8)\n # det_labels_spo_top is (#num_rel, 3)\n if phrdet:\n det_boxes_r_top = boxes_union(det_boxes_s_top, det_boxes_o_top)\n gt_boxes_r = boxes_union(gt_boxes_sbj, gt_boxes_obj)\n pred_to_gt = _compute_pred_matches(\n gt_labels_spo, det_labels_spo_top,\n gt_boxes_r, det_boxes_r_top,\n phrdet=phrdet)\n else:\n pred_to_gt = _compute_pred_matches(\n gt_labels_spo, det_labels_spo_top,\n gt_boxes_so, det_boxes_so_top,\n phrdet=phrdet)\n all_gt_cnt += gt_labels_spo.shape[0]\n for k in recalls:\n if len(pred_to_gt):\n match = reduce(np.union1d, pred_to_gt[:k])\n else:\n match = []\n recalls[k] += len(match)\n\n topk_dets[-1].update(dict(gt_boxes_sbj=gt_boxes_sbj,\n gt_boxes_obj=gt_boxes_obj,\n gt_labels_sbj=gt_labels_sbj,\n gt_labels_obj=gt_labels_obj,\n gt_labels_prd=gt_labels_prd))\n\n if do_val:\n for k in recalls:\n recalls[k] = float(recalls[k]) / (float(all_gt_cnt) + 1e-12)\n print_stats(recalls)\n\n\ndef print_stats(recalls):\n # print('====================== ' + 'sgdet' + ' ============================')\n for k, v in recalls.items():\n print('R@%i: %.2f' % (k, 100 * v))\n\n\n# This function is adapted from Rowan Zellers' code:\n# https://github.com/rowanz/neural-motifs/blob/master/lib/evaluation/sg_eval.py\n# Modified for this project to work with PyTorch v0.4\ndef _compute_pred_matches(gt_triplets, pred_triplets,\n gt_boxes, pred_boxes, iou_thresh=0.5, phrdet=False):\n \"\"\"\n Given a set of predicted triplets, return the list of matching GT's for each of the\n given predictions\n :param gt_triplets:\n :param pred_triplets:\n :param gt_boxes:\n :param pred_boxes:\n :param iou_thresh:\n :return:\n \"\"\"\n # This performs a matrix multiplication-esque thing between the two arrays\n # Instead of summing, we want the equality, so we reduce in that way\n # The rows correspond to GT triplets, columns to pred triplets\n keeps = intersect_2d(gt_triplets, pred_triplets)\n gt_has_match = keeps.any(1)\n pred_to_gt = [[] for x in range(pred_boxes.shape[0])]\n for gt_ind, gt_box, keep_inds in zip(np.where(gt_has_match)[0],\n gt_boxes[gt_has_match],\n keeps[gt_has_match],\n ):\n boxes = pred_boxes[keep_inds]\n if phrdet:\n gt_box = gt_box.astype(dtype=np.float32, copy=False)\n boxes = boxes.astype(dtype=np.float32, copy=False)\n rel_iou = bbox_overlaps(gt_box[None, :], boxes)[0]\n\n inds = rel_iou >= iou_thresh\n else:\n gt_box = gt_box.astype(dtype=np.float32, copy=False)\n boxes = boxes.astype(dtype=np.float32, copy=False)\n sub_iou = bbox_overlaps(gt_box[None,:4], boxes[:, :4])[0]\n obj_iou = bbox_overlaps(gt_box[None,4:], boxes[:, 4:])[0]\n\n inds = (sub_iou >= iou_thresh) & (obj_iou >= iou_thresh)\n\n for i in np.where(keep_inds)[0][inds]:\n pred_to_gt[i].append(int(gt_ind))\n return pred_to_gt\n"
] | [
[
"numpy.hstack",
"numpy.set_printoptions",
"numpy.vstack",
"numpy.sort",
"numpy.argsort",
"numpy.where",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
diffiii/DFX | [
"ac7581b0a3d1adef1da7176f94abb7f9301a03c0"
] | [
"main.py"
] | [
"from src.core import Core\nfrom tools.compile import Compile\nfrom tools.execute import Execute\nfrom tools.run import Run\nfrom numpy import zeros, ubyte\n\n\nif __name__ == '__main__':\n memory = zeros(256, ubyte)\n core = Core(memory)\n Compile('tools/settings.json', 'program.txt')\n Run(core, 'bin/compiled.txt', 0)\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
YusukeKaihara/Graduate-Research-2021 | [
"a95e88cbd28a19e68dc5fb93f6707999bb1bb52f"
] | [
"KoheiNagao/program/LZT_classification.py"
] | [
"import os, sys, json, shutil, random, copy, pickle, numpy\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\nfrom collections import defaultdict\r\nfrom sklearn import svm, preprocessing, metrics\r\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom halo import Halo\r\n\r\nDICT_SIZE = 12\r\nHEAD = 0\r\n\r\n\r\n\r\n\"\"\"\r\n~要素個数問題について~\r\n辞書に保存できるノードの個数は 2^const.DICT_SIZE 個 (例えば2^2 = 4個)\r\nTrieNodeのcapは2^const.DICT_SIZE(例:4)であり、通常であれば0~3の4個のデータを保存できることになる。\r\nしかし、0はrootが使用しているため、1~3の3個しかノードは保存することができない。\r\nしたがって、len(nodes) - 1 によってrootの分を引いた時のノード数が、2^const.DICT_SIZE(例:4)未満となるようにすることで、個数制限を実装\r\n4のときは、更に追加すると溢れるため、4未満\r\n\"\"\"\r\n\r\n\"\"\"\r\n汎用関数\r\n\"\"\"\r\n##############################\r\ndef ReadApiCall(filename):\r\n\twith open(filename, \"r\") as f:\r\n\t\tdata = f.read()\r\n\treturn data\r\n\r\ndef RandomNoDuplicate(min, max, num, remove_list=list()):\r\n\t\"\"\"\r\n\tmin以上、max以下の数字を重複を許容せずランダムにnum個選択する\r\n\tmin : 返す値の最小値\r\n\tmax : 返す値の最大値\r\n\tnum : 返す値の個数\r\n\tremove_list : min以上max以下の値の中で排除する数字(int型)\r\n\tnd_list : 重複を許容しない数字リスト\r\n\t\"\"\"\r\n\t## 引数の検査 ##\r\n\tif ((max - min + 1) - len(remove_list)) < num:\r\n\t\tprint(\"Error:最大値・最小値・削除リストの値が不正\")\r\n\t\tprint(f\"{max} {min} {num} {remove_list} {len(remove_list)}\")\r\n\t\tsys.exit(1)\r\n\t## num個のランダムな値を取得 ##\r\n\tnd_list = []\r\n\twhile len(nd_list) < num:\r\n\t\tx = random.randint(min, max)\r\n\t\tif (x not in nd_list) and (x not in remove_list):\r\n\t\t\tnd_list.append(x)\r\n\treturn nd_list\r\n\r\ndef CompressionRatio(output_data, apicalls, gamma, dict_size):\r\n\t\"\"\"\r\n\tint型の出力数値列を受け取り、DICT_SIZEとの兼ね合いで\r\n\t圧縮後のサイズを出力する\r\n\t\"\"\"\r\n\tASCII_SIZE = 8 ## 1文字8bit ##\r\n\r\n\t## 圧縮前のデータサイズ ##\r\n\tapi_size = len(apicalls) * ASCII_SIZE\r\n\r\n\t## 圧縮後のデータサイズ ##\r\n\tdata_size = len(output_data) * dict_size\r\n\r\n\t## 対象ファミリ圧縮率 ##\r\n\tcompress_ratio = (data_size + gamma) / (api_size + gamma)\r\n\r\n\treturn compress_ratio\r\n\r\ndef OutCsvFile(df, path=\"./\", file_name=\"NewFile\"):\r\n\t\"\"\"\r\n\tデータフレームのCSVファイル出力関数\r\n\tdf: 対象データフレーム (pandas.df)\r\n\tbuffer_path: 出力ファイルパス\r\n\tbuffer_file_name=\"出力ファイル名\"\r\n\t\"\"\"\r\n\tprint(\"Save the csv file about compression ratio ...\")\r\n\tif path[-1] != \"/\":\r\n\t\tpath = path + \"/\"\r\n\t## 結果の出力 ##\r\n\tfile = path + file_name + \".csv\"\r\n\tprint(f\"Save to : {file}\")\r\n\tdf.to_csv(file)\r\n\tprint(\"Collect!\", end=\"\\n\\n\")\r\n\r\ndef ReadCsvFile(filepath):\r\n\t\"\"\"\r\n\tcsvファイルをpd_dataframeにして返す\r\n\t0行目にヘッダ、0列目にindexがあることを想定\r\n\t\"\"\"\r\n\tdf = pd.read_csv(filepath, header=0, index_col=0)\r\n\treturn df\r\n\r\ndef GetFamilyList(dataset_path):\r\n\treturn [family_name for family_name in os.listdir(dataset_path)]\r\n##############################\r\n\r\n\r\n\r\n\r\n\r\n\r\n################################################################### LZT関連 ################################################################################\r\nclass TrieNode(object):\r\n \"\"\"\r\n Trie木の1ノードを表すクラス\r\n \"\"\"\r\n WORD_SIZE = 64 ## underbar + space + alphabets + number ##\r\n def __init__(self, depth = 0, item = None):\r\n self.item = item\r\n self.depth = depth\r\n # 子ノードのリストはとりあえずintリストとして保持 #\r\n self.children = [-1 for i in range(TrieNode.WORD_SIZE)]\r\n\r\n def is_leaf(self):\r\n \"\"\"\r\n そのノードが葉であればTrueを,\r\n そうでなければFalseを返す\r\n \"\"\"\r\n for index in self.children:\r\n if index != -1:\r\n return False\r\n return True\r\n\r\n\r\nclass Trie(object):\r\n \"\"\"\r\n Trir木全体を表すクラス\r\n TrieNodeクラスと併用して用いる\r\n nodes自体は、あるノードと、その子ノードを持っている\r\n 配列の添え字がアルファベットを表し、そこに入る番号がnode_indexを表す\r\n \"\"\"\r\n def __init__(self, init_alphabets=None):\r\n ## 追加可能ノード数の計算 ##\r\n self.max_dict_cap = 2 ** DICT_SIZE\r\n #print(f\"Maximum number of words : {self.max_dict_cap}\")\r\n ## 根ノードの作成 ##\r\n root = TrieNode()\r\n self.nodes = [root]\r\n # rootのindexは0 #\r\n node_index = 0\r\n ## 初期辞書の登録 ##\r\n if init_alphabets == None:\r\n init_alphabets = list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_ \")\r\n ## 出力文字列(int) ##\r\n #self.output_data = []\r\n for item_alp in init_alphabets:\r\n char_num = self._get_char_num(item_alp)\r\n new_node = TrieNode(depth = 1, item = item_alp)\r\n # ノード追加後なので、 1からWORD_SIZE-1 が帰ってくる #\r\n next_node_index = self._add_node(new_node)\r\n self.nodes[node_index].children[char_num] = next_node_index\r\n ## 初期辞書登録時の辞書bit_size(更新(未実装)を実装する場合に使用されたい) ##\r\n self.bit_size, self.max_dict_cap_n = self._near_pow2(len(init_alphabets))\r\n\r\n ## private ##\r\n def __ret_parent_node_index(self, node_index):\r\n \"\"\"\r\n 引数のindexのノードの、親ノードのイデックスを返す\r\n 親ノードが存在しない場合はルートノードの親ノードを捜索したときのみであるため、\r\n エラーメッセージとともにプログラムは停止する\r\n \"\"\"\r\n for i, t_node in enumerate(self.nodes):\r\n ## i: node_index, t_node: target node ##\r\n for child_index in t_node.children:\r\n if child_index == node_index:\r\n return i\r\n print(\"Unexpected error:親ノードが存在しないノードを参照:node_index=\",end=\"\")\r\n print(node_index)\r\n sys.exit(1)\r\n\r\n def _get_char_num(self, c):\r\n \"\"\"\r\n 文字のidを返す(配列実装のため)\r\n A:0, B:1, ..., Z:25, a:26, b:27, ..., z:51, 0:52, ..., 9:61, _:62, \" \":63\r\n \"\"\"\r\n ## 出現する特別な文字 ##\r\n if c == \"_\":\r\n return 62\r\n if c == \" \":\r\n ## spaceのidは63 ##\r\n return 63\r\n ## アルファベット ##\r\n if c.isalpha():\r\n if c.isupper():\r\n return ord(c) - ord('A')\r\n if c.islower():\r\n return ord(c) - ord('a') + 26\r\n ## 数字も出現したため追加実装 ##\r\n if c.isdecimal():\r\n return ord(c) - ord('0') + 52\r\n ## いずれかに分類されない場合は読み込みエラー ##\r\n print(f\"読み込めない文字:{c}\")\r\n sys.exit(1)\r\n\r\n def _add_node(self, node):\r\n \"\"\"\r\n nodesのノードを追加する\r\n \"\"\"\r\n self.nodes.append(node)\r\n return len(self.nodes) - 1\r\n\r\n\r\n def _delete_node(self, index):\r\n \"\"\"\r\n 指定indexのノードを削除する\r\n 1. ノード自身の削除\r\n 2. 親ノードの子ノードリストからの削除\r\n 3. 子ノードリストの番号の再割り当て(なくなった番号以降のノードインデックスを1減算する)\r\n \"\"\"\r\n ## ノード自身の削除 ##\r\n del self.nodes[index]\r\n ## 親ノードの子ノードリストから削除 ##\r\n error_flg = True ## 子ノードの削除検知 ##\r\n parent_node_index = self.__ret_parent_node_index(index)\r\n for i, child_index in enumerate(self.nodes[parent_node_index].children):\r\n if child_index == index:\r\n ## initialize ##\r\n self.nodes[parent_node_index].children[i] = -1\r\n error_flg = False\r\n break\r\n ## 子ノードリストから何も削除されない場合は異常 ##\r\n if error_flg:\r\n print(\"Unexpected error:親ノードの保有する子ノードリストからの削除に失敗\")\r\n sys.exit(1)\r\n ## 子ノードリストの番号再割り当て ##\r\n for i, t_node in enumerate(self.nodes):\r\n for j, child_index in enumerate(t_node.children):\r\n if child_index == index:\r\n print(\"Unexpected error:親ノードの保有する子ノードリストからの削除が不完全\")\r\n self.output_tree(0)\r\n sys.exit(1)\r\n if child_index > index:\r\n self.nodes[i].children[j] -= 1\r\n\r\n def _near_pow2(self, n):\r\n \"\"\"\r\n ビット数更新プログラム\r\n \"\"\"\r\n if n <= 0:\r\n return 0\r\n bit_size = 1\r\n i = 2\r\n while i <= n:\r\n bit_size += 1\r\n i *= 2\r\n return bit_size, i\r\n\r\n ## methods ##\r\n def encoding(self, word, char_index = 0, node_index = 0, stdout=False):\r\n \"\"\"\r\n Trieに新しい単語を\"登録せず\"に符号後を返す\r\n Parameterはinsert_encodingと同じ\r\n \"\"\"\r\n output_data = []\r\n while True:\r\n parent_depth = self.nodes[node_index].depth\r\n char_num = self._get_char_num(word[char_index])\r\n next_node_index = self.nodes[node_index].children[char_num]\r\n if next_node_index == -1: ## 辿れなくなった場合 ##\r\n ## 符号語の出力 & 出力の保存 ##\r\n if stdout:\r\n print(\"{0}\".format(node_index), end=\" \")\r\n output_data.append(node_index)\r\n node_index = 0\r\n continue\r\n else: ## 辿れる時 ##\r\n if char_index < len(word) - 1:\r\n char_index += 1\r\n node_index = next_node_index\r\n continue\r\n else: ## 最後の文字であれば ##\r\n if stdout:\r\n print(next_node_index)\r\n output_data.append(next_node_index)\r\n break\r\n return output_data\r\n\r\n def output_tree(self, node_index, depth = 0):\r\n \"\"\"\r\n Trie木の表示\r\n debug 及び 動作確認 用\r\n \"\"\"\r\n ##############\r\n def __my_space(depth):\r\n for i in range(depth):\r\n if i != 0:\r\n print(\" \", end=\"\")\r\n ##############\r\n\r\n child_list = []\r\n if node_index == 0:\r\n print(\"\\n親ノード:root\\n\")\r\n else:\r\n print()\r\n __my_space(depth)\r\n print(\"Node: {0}\".format(node_index))\r\n __my_space(depth)\r\n print(\" depth: {0}\".format(self.nodes[node_index].depth))\r\n __my_space(depth)\r\n print(\" item: {0}\".format(self.nodes[node_index].item))\r\n for itr, x in enumerate(self.nodes[node_index].children):\r\n if x != -1: ## 次の頂点が存在すれば\r\n __my_space(depth)\r\n print(\" child node: {0}\".format(x))\r\n child_list.append(x)\r\n for x in child_list:\r\n self.output_tree(x, depth+1)\r\n\r\n## 双方向リストによるキュー ##\r\nclass Queue:\r\n\r\n def __init__(self):\r\n self.prev = [None] * (2 ** DICT_SIZE + 1)\r\n self.next = [None] * (2 ** DICT_SIZE + 1)\r\n self.prev[HEAD] = HEAD\r\n self.next[HEAD] = HEAD\r\n self.data_num = 0\r\n\r\n ## 最後尾に追加 ##\r\n def insert(self, x):\r\n last = self.prev[HEAD]\r\n self.prev[x] = last\r\n self.next[x] = HEAD\r\n self.next[last] = x\r\n self.prev[HEAD] = x\r\n self.data_num += 1\r\n\r\n ## 削除 ##\r\n def delete(self, x):\r\n p = self.prev[x]\r\n q = self.next[x]\r\n self.next[p] = q\r\n self.prev[q] = p\r\n\r\n ## 巡回 ##\r\n def traverse(self):\r\n n = self.next[HEAD]\r\n while n != HEAD:\r\n yield n\r\n n = self.next[n]\r\n\r\n def slide_number(self, n):\r\n for i, item in enumerate(self.prev):\r\n if item == None:\r\n continue\r\n if item > n:\r\n self.prev[i] -= 1\r\n if i > n:\r\n self.prev[i-1] = self.prev[i]\r\n\r\n for i, item in enumerate(self.next):\r\n if item == None:\r\n continue\r\n if item > n:\r\n self.next[i] -= 1\r\n if i > n:\r\n self.next[i-1] = self.next[i]\r\n\r\n\r\n\r\n\r\n### LZT関連 ###\r\nclass Trie_LZT(Trie):\r\n \"\"\"\r\n こんな感じでLZTを追加してもらって\r\n \"\"\"\r\n def __init__(self, init_alphabets=None):\r\n super().__init__(init_alphabets)\r\n self.queue = Queue()\r\n for index in range(1, len(self.nodes)):\r\n self.queue.insert(index)\r\n\r\n def insert_encoding(self, word, char_index=0, node_index=0, stdout=False):\r\n output_data = []\r\n while True:\r\n ## 子ノードの深さを与えるために、親の深さを取得 ##\r\n parent_depth = self.nodes[node_index].depth\r\n\r\n ## 文字の番号表現を取得 ##\r\n char_num = super()._get_char_num(word[char_index])\r\n\r\n ## 現在のノードの子ノードに、次の文字が存在するかを確認 ##\r\n next_node_index = self.nodes[node_index].children[char_num]\r\n\r\n ## 辿れなくなった場合 ##\r\n if next_node_index == -1:\r\n if stdout:\r\n print(\"{0}\".format(node_index), end = \" \")\r\n output_data.append(node_index)\r\n\r\n ## 辞書が埋まった場合 ##\r\n if len(self.nodes)-1 == self.max_dict_cap:\r\n for s_node_index in self.queue.traverse():\r\n \r\n ## 葉であるかの確認 ##\r\n if self.nodes[s_node_index].is_leaf() and self.nodes[s_node_index].depth != 1:\r\n \r\n ## 使用されていない辞書情報の削除 ##\r\n super()._delete_node(s_node_index)\r\n self.queue.delete(s_node_index)\r\n self.queue.slide_number(s_node_index)\r\n if node_index > s_node_index:\r\n node_index -= 1\r\n break\r\n \r\n ## 辿れなくなった語を木に追加 ##\r\n new_node = TrieNode(parent_depth+1, item = word[char_index])\r\n next_node_index = super()._add_node(new_node)\r\n self.nodes[node_index].children[char_num] = next_node_index\r\n\r\n ## 登録した辞書番号をqueueに追加 ##\r\n self.queue.insert(next_node_index)\r\n node_index = 0\r\n continue\r\n\r\n\r\n ## 辿れる場合 ##\r\n else:\r\n if char_index < len(word) - 1:\r\n self.queue.delete(next_node_index)\r\n self.queue.insert(next_node_index)\r\n char_index += 1\r\n node_index = next_node_index\r\n continue\r\n\r\n ## 最後の文字 ##\r\n else:\r\n if stdout:\r\n print(next_node_index)\r\n output_data.append(next_node_index)\r\n break\r\n return output_data\r\n\r\n\r\n\"\"\"\r\n実験用関数\r\n- データセット作成関連:PreprocessDataset\r\n- 辞書登録:RegistrationFeatureExtraction\r\n- 圧縮率の計算:CalculateCompressRatio\r\n~参考~\r\npickle : https://www.delftstack.com/ja/howto/python/python-save-dictionary/\r\n\"\"\"\r\n##############################\r\n## データセット作成関連 ##\r\ndef PreprocessDataset(dataset_path=\"./Dataset/\", buffer_path=\"./Buffer/\", read_mode=False, LZW_flag=False):\r\n\t\"\"\"\r\n\tデータセットの検体を,特徴抽出用検体と実験用検体に分ける\r\n\t返り値:sample_feature_ex(特徴抽出用検体), dataset_list_as(実験用検体[ファミリ毎に1:1に成形済み])\r\n\t連想配列によって束ねたものを返すが、その形式は実験モードにより異なるため,形式を変更した場合は本関数以下の関数も修正が必要である(改正済み)\r\n\tdataset_path : データセットのフォルダパス\r\n\tbuffer_path : 出力バッファのフォルダパス\r\n\tread_mode : 既にデータセットを作成している上で、その条件を変更せずpickleを使用してバッファから読み込み実験を行う場合はTrue\r\n\t\"\"\"\r\n\tMINIMUM_SAMPLE_NUM = 100 ## データセットの最小許容検体数\r\n\tFEATURE_EXTRACTION_MULTIV = 10 ## 特徴抽出用検体数(LZT)\r\n\r\n\t## inner function ### \r\n\tdef MakeDatasetInformation(dataset_path):\r\n\t\tfamily_counter_as = {}\r\n\t\tfor family_name in os.listdir(dataset_path):\r\n\t\t\t## ファイルの個数を調査 ##\r\n\t\t\tcur_dir = dataset_path+family_name+\"/\"\r\n\t\t\tsample_num = sum(os.path.isfile(os.path.join(cur_dir, file)) for file in os.listdir(cur_dir))\r\n\t\t\tif sample_num < MINIMUM_SAMPLE_NUM:\r\n\t\t\t\tprint(f\"Unexpected error: 検体数が不足 (MINIMUM_SAMPLE_NUM:{MINIMUM_SAMPLE_NUM}\")\r\n\t\t\t\tsys.exit(1)\r\n\t\t\tfamily_counter_as[family_name] = sample_num\r\n\t\treturn family_counter_as\r\n\r\n\tdef GetShortApiSamples(dataset_path, minimum):\r\n\t\tshort_sample_as = {}\r\n\t\tfor family_name in os.listdir(dataset_path):\r\n\t\t\tshort_sample_as[family_name] = []\r\n\t\t\tcur_dir = dataset_path+family_name+\"/\"\r\n\t\t\tfor file in os.listdir(cur_dir):\r\n\t\t\t\t## ファイルサイズを取得 ##\r\n\t\t\t\tsize = os.path.getsize(cur_dir+file)\r\n\t\t\t\tif size < minimum:\r\n\t\t\t\t\t## 検体番号取得関数がint型で受け取るため,整数値で格納 ##\r\n\t\t\t\t\tshort_sample_as[family_name].append(int(file.split(\".\")[0]))\r\n\t\treturn short_sample_as\r\n\r\n\tdef OutBufferFile(as_array, out_path=None, filename=\"Buffer\", out_mode=\"pkl\"):\r\n\t\t\"\"\"\r\n\t\t同一検体での実験再現を可能とするため、外部ファイルへ保存する\r\n\t\tここでは漬物化、可視性を考慮してjsonでも良い\r\n\t\t\"\"\"\r\n\t\t## モードチェック ##\r\n\t\tif out_path != None:\r\n\t\t\tif out_path[-1] != \"/\":\r\n\t\t\t\tout_path = out_path + \"/\"\r\n\t\t\tif not os.path.exists(out_path):\r\n\t\t\t\tprint(f\"Error : フォルダが存在しません({dataset_path})\")\r\n\t\t\t\tsys.exit(1)\r\n\t\t\tif not os.path.isdir(out_path):\r\n\t\t\t\tprint(f\"Error : フォルダではありません({out_path})\")\r\n\t\t\t\tsys.exit(1)\r\n\t\telse:\r\n\t\t\tout_path = \"./\"\r\n\t\tif out_mode == \"pkl\":\r\n\t\t\t## pickle で保存 ##\r\n\t\t\twith open(out_path+filename+\".pkl\", \"wb\") as f:\r\n\t\t\t\tpickle.dump(as_array, f)\r\n\t\telif out_mode == \"json\":\r\n\t\t\twith open(out_path+filename+\".json\", \"w\") as f:\r\n\t\t\t\tjson.dump(as_array, f, indent=4)\r\n\t#####################\r\n\r\n\tprint(\"Preparing the dataset ...\")\r\n\r\n\t## 読み込みモード ##\r\n\t### jsonに修正 ##\r\n\tif read_mode:\r\n\t\t## とりあえず必要ないので省略 ##\r\n\t\tprint(\"Error : Skip implementation.\")\r\n\t\tsys.exit(1)\r\n\r\n\t## 作成モード(デフォルト) ##\r\n\t## フォルダの準備 ##\r\n\tif dataset_path[-1] != \"/\":\r\n\t\tdataset_path += \"/\"\r\n\tif not os.path.exists(dataset_path):\r\n\t\tprint(os.listdir(\"./\"))\r\n\t\tprint(f\"Error : フォルダが存在しません({dataset_path})\")\r\n\t\tsys.exit(1)\r\n\tif os.path.exists(buffer_path):\r\n\t\tprint(f\"フォルダの中身が削除されます:{buffer_path}\")\r\n\t\tprint(\"(y/n):\", end=\"\")\r\n\t\ty_n = input().strip()\r\n\t\tif y_n == \"y\" or y_n == \"yes\":\r\n\t\t\tshutil.rmtree(buffer_path)\r\n\t\telse:\r\n\t\t\tprint(\"Process Stop...\")\r\n\t\t\tsys.exit(1)\r\n\tos.makedirs(buffer_path)\r\n\r\n\t## 各ファミリの検体数を取得 (連想配列{str(familyname):int(num)}) ##\r\n\tfamily_counter_as = MakeDatasetInformation(dataset_path)\r\n\tsample_feature_ex = {}\r\n\tdataset_list_as = {}\r\n\r\n\t## 検体の比率調整パラメータ(ファミリ数が32だったら、31を作っておけば31:31が表現できるようになる) ##\r\n\tappend_parameter = len(family_counter_as) - 1\r\n\t## 整合性検査(少なくとも特徴抽出(append_parameter) + 1データセット単位(appendparameter)は必要) ##\r\n\tif 2*append_parameter > MINIMUM_SAMPLE_NUM:\r\n\t\tprint(\"検体数が不足\")\r\n\t\tsys.exit(1)\r\n\tt_remove_list_as = {} ## 重複防止用検体番号格納変数\r\n\t## sample_feature_ex:{str(target family):list[sample file]}\r\n\t## LZWの場合の12ビット分保存できるまで検体を取得するモード ##\r\n\tif LZW_flag == True:\r\n\t\tfor t_family, sample_num in family_counter_as.items():\r\n\t\t\t## 長尾君のでは必要ないので省略 ##\r\n\t\t\tprint(\"Error : Skip implementation.\")\r\n\t\t\tsys.exit(1)\r\n\t## 10検体を見るモード ##\r\n\telse:\r\n\t\tfor t_family, sample_num in family_counter_as.items():\r\n\t\t\tx1 = RandomNoDuplicate(1, sample_num, FEATURE_EXTRACTION_MULTIV)\r\n\t\t\tt_remove_list_as[t_family] = list(x1)\r\n\t\t\tsample_feature_ex[t_family] = [dataset_path+t_family+\"/\"+str(i)+\".txt\" for i in x1]\r\n\t\t\tmax_sample_num = sample_num - FEATURE_EXTRACTION_MULTIV\r\n\r\n\t## この辺で32:32のデータセットを作成してる筈 ##\r\n\tremove_list_extend = {}\r\n\tfor t_family in family_counter_as.keys():\r\n\t\tdataset_list_as[t_family] = {}\r\n\t\tremove_list_extend[t_family] = copy.deepcopy(t_remove_list_as)\r\n\t\tprint(f\" target:{t_family}\")\r\n\t\tgap_flg = True ## 次回実行可能判定フラグ ##\r\n\t\twhile gap_flg:\r\n\t\t\tfor key, sample_num in family_counter_as.items():\r\n\t\t\t\tif key not in dataset_list_as[t_family].keys():\r\n\t\t\t\t\tdataset_list_as[t_family][key] = []\r\n\t\t\t\t## 対象ファミリの場合 ##\r\n\t\t\t\tif key == t_family:\r\n\t\t\t\t\t## 特徴抽出用検体の検体数 ##\r\n\t\t\t\t\tfeature_extraction_num = len(sample_feature_ex[key])\r\n\t\t\t\t\t## append_parameter個のkey内乱数取得(特徴抽出用検体を除く) ##\r\n\t\t\t\t\tx = RandomNoDuplicate(1, sample_num, append_parameter, remove_list=remove_list_extend[t_family][key])\r\n\t\t\t\t\tfilename = [dataset_path+key+\"/\"+str(i)+\".txt\" for i in x]\r\n\t\t\t\t\tdataset_list_as[t_family][key].extend(filename)\r\n\t\t\t\t\tnext_len = len(dataset_list_as[t_family][key]) + append_parameter\r\n\t\t\t\t## 対象ファミリ以外の場合 ##\r\n\t\t\t\telse:\r\n\t\t\t\t\t## 特徴抽出用検体の検体数 ##\r\n\t\t\t\t\tfeature_extraction_num = len(sample_feature_ex[key])\r\n\t\t\t\t\tx = RandomNoDuplicate(1, sample_num, 1, remove_list=remove_list_extend[t_family][key])\r\n\t\t\t\t\tfilename = [dataset_path+key+\"/\"+str(i)+\".txt\" for i in x]\r\n\t\t\t\t\tdataset_list_as[t_family][key].extend(filename)\r\n\t\t\t\t\tnext_len = len(dataset_list_as[t_family][key]) + 1\r\n\t\t\t\t## 重複防止連想配列の更新 ##\r\n\t\t\t\tremove_list_extend[t_family][key].extend(x)\r\n\t\t\t\t## 次回実行可能判定 ##\r\n\t\t\t\tif next_len > sample_num - feature_extraction_num:\r\n\t\t\t\t\tgap_flg = False\r\n\r\n\t## 選択した検体の出力 ##\r\n\tOutBufferFile(sample_feature_ex, out_path=buffer_path, filename=\"FeatureExtractionLists_MultiClassification\", out_mode=\"json\")\r\n\tOutBufferFile(dataset_list_as, out_path=buffer_path, filename=\"DatasetLists_MultiClassification\", out_mode=\"json\")\r\n\r\n\tprint(\"Collect!\", end=\"\\n\\n\")\r\n\treturn sample_feature_ex, dataset_list_as\r\n\r\n\r\n## 辞書登録関連 ##\t\t\r\ndef RegistrationFeatureExtractionMultivalued(sample_as, compress_mode=\"lzt\"):\r\n\t\"\"\"\r\n\t選択された特徴抽出用検体を引数にとり(sample_as)、辞書に登録して、ファミリ毎の辞書の連想配列を返す。\r\n\t\"\"\"\r\n\tprint(\"Registering to the Trie tree ...\")\r\n\ttrie_as = {} ## dict{str(family):Trie obj}\r\n\tfor t_family, t_sample_list in tqdm(sample_as.items()):\r\n\t\t## targetファミリ用のTrie tree ##\r\n\t\tif compress_mode == \"lzt\":\r\n\t\t\ttarget_trie = Trie_LZT()\r\n\t\telse:\r\n\t\t\tprint(\"Error : Skip implementation.\")\r\n\t\t\tsys.exit(1)\r\n\t\tfor t_sample in t_sample_list:\r\n\t\t\tapicalls = ReadApiCall(t_sample).strip()\r\n\t\t\ttarget_trie.insert_encoding(apicalls)\r\n\t\ttrie_as[t_family] = target_trie\r\n\treturn_value = trie_as\r\n\tprint(\"Collect!!\", end=\"\\n\\n\")\r\n\treturn return_value ## dict{trie trees of feature extraction}\r\n\r\n\r\n## 圧縮率計算関連 ##\r\ndef CalculateCompressRatioMultivalued(trie_as, dataset_as, gamma=0, dict_size_check=False, stdout=False, buffer_path=\"./Buffer/\"):\r\n\t\"\"\"\r\n\tCaluculateCompressRatioBinaryの多次元ベクトルversion\r\n\t後でdataframeを簡単に扱うために、同じ検体であっても再計算する方式をとってる。\r\n\t実行時間が果てしなく長くなるので、先に圧縮率を計算してからdataframe化した方がよい。\r\n\tその実装については、時間に余裕がないので、また検討されたい。\r\n\t\"\"\"\r\n\tprint(\"Calculation of compression ratio ...\")\r\n\r\n\t## 出力結果データフレームの準備 ##\r\n\tdf_result = pd.DataFrame({\r\n\t\"target_family\":[],\r\n\t\"sample_family\":[],\r\n\t\"label\":[],\r\n\t\"sample_file_path\":[],\r\n\t})\r\n\tfor item in trie_as.keys():\r\n\t\tdf_result[\"Z_\"+str(item)] = []\r\n\r\n\t## 圧縮率を求め、データフレームに出力 ##\r\n\t## trie_as : {\"family\":obj(trietree), \"family\":obj...} ##\r\n\t## dataset_as : {targetfamily:{family:[datafile path]}} ##\r\n\tcounter = 1\r\n\tfor t_family, dataset in dataset_as.items():\r\n\t\tprint(f\"target family : {t_family} ... ({counter}/{len(dataset_as)})\")\r\n\t\tcounter+=1\r\n\t\tfor family, path_list in tqdm(dataset.items()):\r\n\t\t\tif dict_size_check:\r\n\t\t\t\tprint(\"未実装\")\r\n\t\t\t\tsys.exit(1)\r\n\t\t\telse:\r\n\t\t\t\tpass\r\n\t\t\tfor data_path in path_list:\r\n\t\t\t\t## apiコールの取得 ##\r\n\t\t\t\tapicalls = ReadApiCall(data_path).strip()\r\n\t\t\t\t## treeに対してencoding ##\r\n\t\t\t\toutputs = {}\r\n\t\t\t\tz_family = []\r\n\t\t\t\tfor fam in trie_as.keys():\r\n\t\t\t\t\toutputs[fam] = trie_as[fam].encoding(apicalls)\r\n\t\t\t\t\t## 圧縮率の計算 ##\r\n\t\t\t\t\tz_family.append(CompressionRatio(outputs[fam], apicalls, gamma, DICT_SIZE))\r\n\t\t\t\tif stdout:\r\n\t\t\t\t\tprint(\"未実装\")\r\n\t\t\t\t\tsys.exit(1)\r\n\t\t\t\t## ラベルの付与 ##\r\n\t\t\t\tif t_family == family:\r\n\t\t\t\t\tlabel = \"target\"\r\n\t\t\t\telse:\r\n\t\t\t\t\tlabel = \"other\"\r\n\t\t\t\t## 出力用DataFrameへの追加 ##\r\n\t\t\t\tbuf_list = [t_family, family, label, data_path]\r\n\t\t\t\tbuf_list.extend(z_family)\r\n\t\t\t\tdf_result.loc[len(df_result)] = buf_list\r\n\t\t\tpass\r\n\t\tprint(\"\")\r\n\t\tpass\r\n\r\n\t## 結果のcsv出力 ##\r\n\tOutCsvFile(df_result, path=buffer_path, file_name=\"CompressionRatio\")\r\n\r\n\tprint(\"Collect!\", end=\"\\n\\n\")\r\n\treturn df_result\r\n\r\n\r\n## 散布図出力関連 ##\r\n# 出力フォルダ準備 #\r\ndef PrepareOutputFolder(result_path):\r\n\tprint(\"Error : Skip implementation.\")\r\n\tsys.exit(1)\r\n##############################\r\n\r\n\r\n\"\"\"\r\n機械学習関連\r\n\"\"\"\r\n##############################\r\nclass ANT_MachineLearning:\r\n\tdef __init__(self, buffer_path, result_path, k=4, repro=False, scaling=True, stdout=True):\r\n\t\t\"\"\"\r\n\t\tSVM学習・検証用クラス\r\n\t\tbuffer_path : bufferファイル出力先フォルダ\r\n\t\tresult_path : 結果出力フォルダ\r\n\t\tk : k-fold validation の k\r\n\t\texoeriment_mode : 実験モード(binary or multivalued)\r\n\t\t\"\"\"\r\n\t\tself.buffer_path = buffer_path\r\n\t\tself.k = k\r\n\r\n\t\t## 保存フォルダの形式統一 ##\r\n\t\tif result_path[-1] != \"/\":\r\n\t\t\tresult_path = result_path + \"/\"\r\n\t\t## SVM用のフォルダ階層作成 ##\r\n\t\tself.result_path = result_path\r\n\t\t## Spreadsheet用のフォルダ階層作成 ##\r\n\t\tself.spread_path = result_path + \"SpreadSheet/\"\r\n\r\n\t\t## buffer_pathの形式統一 ##\r\n\t\tif buffer_path[-1] != \"/\":\r\n\t\t\tbuffer_path = buffer_path + \"/\"\r\n\t\tself.buffer_path = buffer_path\r\n\r\n\t\t\"\"\"\r\n\t\t[Warning!]\r\n\t\tChange the \"gridparameter\" carefully, \r\n\t\tbecause it may change the value of the replicated experiment later.\r\n\t\t\"\"\"\r\n\t\t#self.grid_parameters = [\r\n\t\t#{'C': [1, 5, 10, 50],\r\n\t\t#'gamma': [0.001, 0.0001]}\r\n\t\t#]\r\n\t\tself.grid_parameters = [\r\n\t\t{'C':[2**i for i in range(-5, 16)],\r\n\t\t'gamma':[2**i for i in range(-15, 4)]}\r\n\t\t]\r\n\t\tself.scaling = scaling\r\n\t\tself.stdout = stdout\r\n\r\n\t\tself.accuracy_avg = -1.0\r\n\t\tprint(\"\")\r\n\r\n\r\n\t## main methods ##\r\n\tdef MachineLearningSvmExtend(self, df): ## LZWで平均正解率 87% 程度 ##\r\n\t\t## 32次元での2値分類の実験を行うメソッド ##\r\n\t\tif self.stdout:\r\n\t\t\tprint(\"Classification by svm (binary extend)...\")\r\n\t\tresult_path = self.result_path + \"SVM/\"\r\n\t\tspread_path = self.spread_path + \"SVM/\"\r\n\t\tif os.path.exists(result_path):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"Delete folder : {result_path}\")\r\n\t\t\tshutil.rmtree(result_path)\r\n\t\tos.makedirs(result_path)\r\n\t\tbuffer_path = self.buffer_path + \"SVM/\"\r\n\t\tif os.path.exists(buffer_path):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"Delete folder : {buffer_path}\")\r\n\t\t\tshutil.rmtree(buffer_path)\r\n\t\tos.makedirs(buffer_path)\r\n\t\tif os.path.exists(spread_path):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"Delete folder : {spread_path}\")\r\n\t\t\tshutil.rmtree(spread_path)\r\n\t\tos.makedirs(spread_path)\r\n\r\n\t\tif self.stdout:\r\n\t\t\tprint(f\"The result file will be saved : {result_path}\")\r\n\t\t\tprint(f\"The buffer file will be saved : {buffer_path}\", end=\"\\n\\n\")\r\n\t\t## Check工程は省いたので自分で確認しましょう ##\r\n\r\n\t\t## 結果保存用 ##\r\n\t\taccuracy_dict = {}\r\n\t\trecall_dict = {}\r\n\t\tprecision_dict = {}\r\n\r\n\t\t## 対象ファミリ毎の実験 ##\r\n\t\tfamily_length = len(df.groupby('target_family').groups)\r\n\t\tfor ite, family in enumerate(df.groupby('target_family').groups):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"target family : {family} ({ite+1}/{family_length})\")\r\n\t\t\t## 再現用バッファ ##\r\n\t\t\tbuffer_dict = {}\r\n\t\t\tb_json_file_name = buffer_path + family + \".json\"\r\n\t\t\tb_json_f = open(b_json_file_name, \"w\")\r\n\t\t\t## 結果保存用 ##\r\n\t\t\tresult_dict = {}\r\n\t\t\tjson_file_name = result_path + family + \".json\"\r\n\t\t\tjson_f = open(json_file_name, \"w\")\r\n\t\t\taccuracy_dict[family] = []\r\n\t\t\trecall_dict[family] = []\r\n\t\t\tprecision_dict[family] = []\r\n\r\n\t\t\t## 分割交差検証用にk個に分ける ##\r\n\t\t\tx_all_dict, t_all_dict, b_all_dict = self.__PreprocessForClf(df.groupby('target_family').get_group(family))\r\n\r\n\t\t\t## k-fold cross validation ##\r\n\t\t\tfor k_count in range(self.k):\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tprint(f\"k-fold cross validation : ({k_count+1}/{self.k})...\")\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)] = {}\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)] = {}\r\n\t\t\t\t## train test split ##\r\n\t\t\t\tx_train, t_train, b_train = [], [], []\r\n\t\t\t\tfor key in b_all_dict.keys():\r\n\t\t\t\t\tif key == k_count:\r\n\t\t\t\t\t\tx_test, t_test, b_test = x_all_dict[key], t_all_dict[key], b_all_dict[key]\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tx_train.extend(x_all_dict[key])\r\n\t\t\t\t\t\tt_train.extend(t_all_dict[key])\r\n\t\t\t\t\t\tb_train.extend(b_all_dict[key])\r\n\t\t\t\t## 学習データの依存関係保持シャッフル ##\r\n\t\t\t\tx_train, t_train, b_train = self.__ShuffleKeepDepend(x_train, t_train, b_train)\r\n\t\t\t\t## ndarray化 ##\r\n\t\t\t\tx_train, t_train = self.__ToNumpyForClf(x_train, t_train)\r\n\t\t\t\tx_test, t_test = self.__ToNumpyForClf(x_test, t_test)\r\n\t\t\t\t## スケーリング ##\r\n\t\t\t\tif self.scaling:\r\n\t\t\t\t\tx_train, x_test = self.__Scaling(x_train, x_test)\r\n\t\t\t\t## gridsearch ##\r\n\t\t\t\tsvc = svm.SVC()\r\n\t\t\t\tclf = GridSearchCV(svc, self.grid_parameters, cv=4)\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tspinner = Halo(text='Parameter optimization by k-fold cross validation', spinner='line')\r\n\t\t\t\t\tspinner.start()\r\n\t\t\t\tclf.fit(x_train, t_train)\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tspinner.stop()\r\n\t\t\t\t\tprint(\"+ Parameter optimization by k-fold cross validation\")\r\n\t\t\t\tt_true, t_pred = t_test, clf.predict(x_test)\r\n\t\t\t\t## 結果の出力 ##\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tprint(\"True labels:\")\r\n\t\t\t\t\tprint(t_true)\r\n\t\t\t\t\tprint(\"Predict labels:\")\r\n\t\t\t\t\tprint(t_pred)\r\n\t\t\t\t\tprint(f\"best parameters : {clf.best_params_}\")\r\n\t\t\t\t\tprint(f\"train best score : {clf.best_score_}\")\r\n\t\t\t\t\tprint(\"predict score : {0}\".format(metrics.accuracy_score(t_true, t_pred)), end=\"\\n\\n\")\r\n\t\t\t\t## for spread sheet ##\r\n\t\t\t\taccuracy_dict[family].append(metrics.accuracy_score(t_true, t_pred)*100.0)\r\n\t\t\t\trecall_dict[family].append(recall_score(t_true, t_pred))\r\n\t\t\t\tprecision_dict[family].append(precision_score(t_true, t_pred))\r\n\t\t\t\t## Generate key for json output ##\r\n\t\t\t\ttrain_keys = [str(i) for i in range(1, len(b_train)+1)]\r\n\t\t\t\tresult_keys = [str(i) for i in range(1, len(b_test)+1)]\r\n\t\t\t\t## 再現バッファ出力(スケーリング処理後データを格納) ##\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['train_sample'] = dict(zip(train_keys, b_train))\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['train_label'] = dict(zip(train_keys, self.__ToStringList(t_train)))\r\n\t\t\t\t#buffer_dict['CV_'+str(k_count+1)]['train_data'] = self.__GenerateXData(x_train)\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['test_sample'] = dict(zip(result_keys, b_test))\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['test_label'] = dict(zip(result_keys, self.__ToStringList(t_true)))\r\n\t\t\t\t#buffer_dict['CV_'+str(k_count+1)]['test_data'] = self.__GenerateXData(x_test)\r\n\t\t\t\t## json 出力 ##\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['sample'] = dict(zip(result_keys, b_test))\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['true_label'] = dict(zip(result_keys, self.__ToStringList(t_true)))\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['predict_label'] = dict(zip(result_keys, self.__ToStringList(t_pred)))\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['best_parameter'] = clf.best_params_\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['train_best_score'] = clf.best_score_\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['predict_score'] = metrics.accuracy_score(t_true, t_pred)\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['recall_score'] = recall_score(t_true, t_pred)\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['precision_score'] = precision_score(t_true, t_pred)\r\n\t\t\tjson.dump(result_dict, json_f, indent=4)\r\n\t\t\tjson.dump(buffer_dict, b_json_f, indent=4)\r\n\t\t\tb_json_f.close()\r\n\t\t\tjson_f.close()\r\n\r\n\t\t## Spreadsheet 作成 ##\r\n\t\tself.__MakeSpreadSheet(accuracy_dict, path=spread_path+\"accuracy_svm.xlsx\")\r\n\t\tself.__MakeSpreadSheet(recall_dict, path=spread_path+\"recall_svm.xlsx\")\r\n\t\tself.__MakeSpreadSheet(precision_dict, path=spread_path+\"precision_svm.xlsx\")\r\n\r\n\t\t## 必要に応じてaccuracyの値を取得 ##\r\n\t\tbuf = 0.0\r\n\t\tfor family in accuracy_dict.keys():\r\n\t\t\tbuf += float(sum(accuracy_dict[family])/len(accuracy_dict[family]))\r\n\t\tself.accuracy_avg = float(buf / len(accuracy_dict.keys()))\r\n\r\n\t\tif self.stdout:\r\n\t\t\tprint(\"Collect!\")\r\n\r\n\r\n\tdef MachineLearningRfExtend(self, df):\r\n\t\t## 32次元での2値分類の実験を行うメソッド(ランダムフォレスト) ##\r\n\t\tif self.stdout:\r\n\t\t\tprint(\"Classification by RandomForest (binary extend)...\")\r\n\t\tresult_path = self.result_path + \"RF/\"\r\n\t\tspread_path = self.spread_path + \"RF/\"\r\n\t\tif os.path.exists(result_path):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"Delete folder : {result_path}\")\r\n\t\t\tshutil.rmtree(result_path)\r\n\t\tos.makedirs(result_path)\r\n\t\tbuffer_path = self.buffer_path + \"RF/\"\r\n\t\tif os.path.exists(buffer_path):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"Delete folder : {buffer_path}\")\r\n\t\t\tshutil.rmtree(buffer_path)\r\n\t\tos.makedirs(buffer_path)\r\n\t\tif os.path.exists(spread_path):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"Delete folder : {spread_path}\")\r\n\t\t\tshutil.rmtree(spread_path)\r\n\t\tos.makedirs(spread_path)\r\n\t\tif self.stdout:\r\n\t\t\tprint(f\"The result file will be saved : {result_path}\")\r\n\t\t\tprint(f\"The buffer file will be saved : {buffer_path}\", end=\"\\n\\n\")\r\n\t\t## Check工程は省いたので自分で確認しましょう ##\r\n\r\n\t\t## 結果保存用 ##\r\n\t\taccuracy_dict = {}\r\n\t\trecall_dict = {}\r\n\t\tprecision_dict = {}\r\n\r\n\t\t## 対象ファミリ毎の実験 ##\r\n\t\tfamily_length = len(df.groupby('target_family').groups)\r\n\t\tfor ite, family in enumerate(df.groupby('target_family').groups):\r\n\t\t\tif self.stdout:\r\n\t\t\t\tprint(f\"target family : {family} ({ite+1}/{family_length})\")\r\n\t\t\t## 再現用バッファ ##\r\n\t\t\tbuffer_dict = {}\r\n\t\t\tb_json_file_name = buffer_path + family + \".json\"\r\n\t\t\tb_json_f = open(b_json_file_name, \"w\")\r\n\t\t\t## 結果保存用 ##\r\n\t\t\tresult_dict = {}\r\n\t\t\tjson_file_name = result_path + family + \".json\"\r\n\t\t\tjson_f = open(json_file_name, \"w\")\r\n\t\t\taccuracy_dict[family] = []\r\n\t\t\trecall_dict[family] = []\r\n\t\t\tprecision_dict[family] = []\r\n\r\n\t\t\t## 分割交差検証用にk個に分ける ##\r\n\t\t\tx_all_dict, t_all_dict, b_all_dict = self.__PreprocessForClf(df.groupby('target_family').get_group(family))\r\n\r\n\t\t\t## k-fold cross validation ##\r\n\t\t\tfor k_count in range(self.k):\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tprint(f\"k-fold cross validation : ({k_count+1}/{self.k})...\")\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)] = {}\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)] = {}\r\n\t\t\t\t## train test split ##\r\n\t\t\t\tx_train, t_train, b_train = [], [], []\r\n\t\t\t\tfor key in b_all_dict.keys():\r\n\t\t\t\t\tif key == k_count:\r\n\t\t\t\t\t\tx_test, t_test, b_test = x_all_dict[key], t_all_dict[key], b_all_dict[key]\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tx_train.extend(x_all_dict[key])\r\n\t\t\t\t\t\tt_train.extend(t_all_dict[key])\r\n\t\t\t\t\t\tb_train.extend(b_all_dict[key])\r\n\t\t\t\t## 学習データの依存関係保持シャッフル ##\r\n\t\t\t\tx_train, t_train, b_train = self.__ShuffleKeepDepend(x_train, t_train, b_train)\r\n\t\t\t\t## ndarray化 ##\r\n\t\t\t\tx_train, t_train = self.__ToNumpyForClf(x_train, t_train)\r\n\t\t\t\tx_test, t_test = self.__ToNumpyForClf(x_test, t_test)\r\n\t\t\t\t## スケーリング ##\r\n\t\t\t\tif self.scaling:\r\n\t\t\t\t\tx_train, x_test = self.__Scaling(x_train, x_test)\r\n\t\t\t\t## 学習 ##\r\n\t\t\t\tmodel = RandomForestClassifier(n_estimators=5000, max_features=\"sqrt\")\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tspinner = Halo(text='Parameter optimization by k-fold cross validation', spinner='line')\r\n\t\t\t\t\tspinner.start()\r\n\t\t\t\tmodel.fit(x_train, t_train)\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tspinner.stop()\r\n\t\t\t\t\tprint(\"+ Parameter optimization by k-fold cross validation\")\r\n\t\t\t\tt_true, t_pred = t_test, model.predict(x_test)\r\n\t\t\t\t## 結果の出力 ##\r\n\t\t\t\tif self.stdout:\r\n\t\t\t\t\tprint(\"True labels:\")\r\n\t\t\t\t\tprint(t_true)\r\n\t\t\t\t\tprint(\"Predict labels:\")\r\n\t\t\t\t\tprint(t_pred)\r\n\t\t\t\t\t#print(f\"best parameters : {model.best_params_}\")\r\n\t\t\t\t\t#print(f\"train best score : {model.best_score_}\")\r\n\t\t\t\t\tprint(\"predict score : {0}\".format(metrics.accuracy_score(t_true, t_pred)), end=\"\\n\\n\")\r\n\t\t\t\t## for spread sheet ##\r\n\t\t\t\taccuracy_dict[family].append(metrics.accuracy_score(t_true, t_pred)*100.0)\r\n\t\t\t\trecall_dict[family].append(recall_score(t_true, t_pred))\r\n\t\t\t\tprecision_dict[family].append(precision_score(t_true, t_pred))\r\n\t\t\t\t## Generate key for json output ##\r\n\t\t\t\ttrain_keys = [str(i) for i in range(1, len(b_train)+1)]\r\n\t\t\t\tresult_keys = [str(i) for i in range(1, len(b_test)+1)]\r\n\t\t\t\t## 再現バッファ出力(スケーリング処理後データを格納) ##\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['train_sample'] = dict(zip(train_keys, b_train))\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['train_label'] = dict(zip(train_keys, self.__ToStringList(t_train)))\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['train_data'] = self.__GenerateXData(x_train)\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['test_sample'] = dict(zip(result_keys, b_test))\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['test_label'] = dict(zip(result_keys, self.__ToStringList(t_true)))\r\n\t\t\t\tbuffer_dict['CV_'+str(k_count+1)]['test_data'] = self.__GenerateXData(x_test)\r\n\t\t\t\t## json 出力 ##\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['sample'] = dict(zip(result_keys, b_test))\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['true_label'] = dict(zip(result_keys, self.__ToStringList(t_true)))\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['predict_label'] = dict(zip(result_keys, self.__ToStringList(t_pred)))\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['best_parameter'] = None\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['train_best_score'] = None\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['predict_score'] = metrics.accuracy_score(t_true, t_pred)\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['recall_score'] = recall_score(t_true, t_pred)\r\n\t\t\t\tresult_dict['CV_'+str(k_count+1)]['precision_score'] = precision_score(t_true, t_pred)\r\n\t\t\tjson.dump(result_dict, json_f, indent=4)\r\n\t\t\tjson.dump(buffer_dict, b_json_f, indent=4)\r\n\t\t\tb_json_f.close()\r\n\t\t\tjson_f.close()\r\n\t\t## Spreadsheet 作成 ##\r\n\t\tself.__MakeSpreadSheet(accuracy_dict, path=spread_path+\"accuracy_rf.xlsx\")\r\n\t\tself.__MakeSpreadSheet(recall_dict, path=spread_path+\"recall_rf.xlsx\")\r\n\t\tself.__MakeSpreadSheet(precision_dict, path=spread_path+\"precision_rf.xlsx\")\r\n\r\n\t\t## 必要に応じてaccuracyの値を取得 ##\r\n\t\tbuf = 0.0\r\n\t\tfor family in accuracy_dict.keys():\r\n\t\t\tbuf += float(sum(accuracy_dict[family])/len(accuracy_dict[family]))\r\n\t\tself.accuracy_avg = float(buf / len(accuracy_dict.keys()))\r\n\r\n\t\tif self.stdout:\r\n\t\t\tprint(\"Collect!\")\r\n\r\n\tdef GetAccuracyAverage(self):\r\n\t\t\"\"\"\r\n\t\t正解率の平均値を取得\r\n\t\t\"\"\"\r\n\t\tif self.accuracy_avg == -1.0:\r\n\t\t\tprint(\"No Data : accuracy average\")\r\n\t\telse:\r\n\t\t\treturn self.accuracy_avg\r\n\r\n\r\n\t## privates ##\r\n\tdef __CheckOnce(self):\r\n\t\t\"\"\"\r\n\t\t2回以上の学習は別のインスタンスを作成する必要がある\r\n\t\t\"\"\"\r\n\t\tif self.accuracy_avg != -1.0:\r\n\t\t\tprint(\"2回以上の学習は別のインスタンスを作成する必要があります\")\r\n\t\t\tsys.exit(1)\r\n\r\n\tdef __GenerateXData(self, x):\r\n\t\t\"\"\"\r\n\t\tx_trainを辞書型に再構成\r\n\t\tbuffer出力用\r\n\t\t可視性のため関数化\r\n\t\t\"\"\"\r\n\t\tdictionary = {}\r\n\t\tfor index, items in enumerate(x):\r\n\t\t\tdictionary[str(index+1)] = {\"targetCR\":str(items[0]), \"otherCR\":str(items[1])}\r\n\t\treturn dictionary\r\n\r\n\tdef __PreprocessForClf(self, df):\r\n\t\t\"\"\"\r\n\t\tDataFrameから学習・テストデータとラベルを生成(k-fold-crossvalidation)\r\n\t\tx:学習・テストデータ\r\n\t\tt:学習・テストラベル\r\n\t\tb:検体情報の順序保持\r\n\t\t\"\"\"\r\n\t\tx, t, b = {}, {}, {}\r\n\t\tdf_target = df.groupby('label').get_group('target')\r\n\t\tdf_other = df.groupby('label').get_group('other')\r\n\t\t## 正例 ##\r\n\t\tfor index, data in zip(range(len(df_target)), df_target.itertuples()):\r\n\t\t\tkey = index % self.k\r\n\t\t\tif key not in x.keys():\r\n\t\t\t\tx[key], t[key], b[key] = [], [], []\r\n\t\t\t## 規定通りなら5個目以降のデータが圧縮率 ##\r\n\t\t\tx[key].append(list(data[5:]))\r\n\t\t\tt[key].append(1)\r\n\t\t\ttmp = data.sample_file_path.split(\"/\")\r\n\t\t\tb[key].append(tmp[-2] + \"_\" + tmp[-1])\r\n\t\t## 負例 ##\r\n\t\tfor index, data in zip(range(len(df_other)), df_other.itertuples()):\r\n\t\t\tkey = index % self.k\r\n\t\t\tif key not in x.keys():\r\n\t\t\t\tprint(\"Error : Possibility that the allocation of the positive example has failed.\")\r\n\t\t\t\tsys.exit(1)\r\n\t\t\tx[key].append(list(data[5:]))\r\n\t\t\tt[key].append(0)\r\n\t\t\ttmp = data.sample_file_path.split(\"/\")\r\n\t\t\tb[key].append(tmp[-2] + \"_\" + tmp[-1])\r\n\t\treturn x, t, b\r\n\r\n\tdef __ToNumpyForClf(self, train, test):\r\n\t\t\"\"\"\r\n\t\tndarrayにして返す\r\n\t\t第一引数にfloat32型データ,第二引数に教師データを与える\r\n\t\t\"\"\"\r\n\t\tr_train = numpy.array(train).astype('float32')\r\n\t\tr_test = numpy.array(test)\r\n\t\treturn r_train, r_test\r\n\r\n\tdef __ShuffleKeepDepend(self, x, t, b):\r\n\t\t\"\"\"\r\n\t\t3リストの依存関係を保持したままシャッフルする\r\n\t\tx:学習\r\n\t\t\"\"\"\r\n\t\tall_list = list(zip(x, t, b))\r\n\t\trandom.shuffle(all_list)\r\n\t\tx, t, b = zip(*all_list)\r\n\t\treturn x, t, b\r\n\r\n\tdef __Scaling(self, train, test):\r\n\t\t\"\"\"\r\n\t\t学習用データでスケーリングを行い,その時のパラメータで推論データをスケーリングする.\r\n\t\tここでは,スケーリングとして標準化を用いる.\r\n\t\t\"\"\"\r\n\t\tscaler = preprocessing.StandardScaler()\r\n\t\tscaler.fit(train)\r\n\t\ttrain = scaler.transform(train)\r\n\t\ttest = scaler.transform(test)\r\n\t\treturn train, test\r\n\r\n\tdef __ToStringList(self, l):\r\n\t\t\"\"\"\r\n\t\tリストの要素を文字列に変換\r\n\t\tl : リスト\r\n\t\t\"\"\"\r\n\t\treturn [str(item) for item in l]\r\n\r\n\tdef __MakeSpreadSheet(self, accuracy_dict, path=\"./accuracy.xlsx\"):\r\n\t\t\"\"\"\r\n\t\tfamily毎に記録されたaccuracy_dictに則り,\r\n\t\texcelシートを作成する\r\n\t\t\"\"\"\r\n\t\tif self.stdout:\r\n\t\t\tprint(\"Make Spread Sheet...\")\r\n\t\t\tprint(f\"{path}\")\r\n\t\tData = []\r\n\t\trow_index = []\r\n\t\tcol_index = [\"k=\"+str(i+1) for i in range(self.k)]\r\n\t\tcol_index.append(\"Avg.\")\r\n\t\tfor family in accuracy_dict.keys():\r\n\t\t\tbuf = float(sum(accuracy_dict[family])/len(accuracy_dict[family]))\r\n\t\t\taccuracy_dict[family].append(buf)\r\n\t\t\tData.append(accuracy_dict[family])\r\n\t\t\trow_index.append(family)\r\n\t\tdf = pd.DataFrame(Data)\r\n\t\tdf.columns = col_index\r\n\t\tdf.index = row_index\r\n\t\tdf.to_excel(path, float_format='%.2f')\r\n\t\tif self.stdout:\r\n\t\t\tprint(\"Collect!\", end=\"\\n\\n\")\r\n\r\n\r\n## main ##\r\n\r\nif __name__=='__main__':\r\n\t\r\n\tdataset = PreprocessDataset(dataset_path=\"./Dataset/\", buffer_path=\"./Buffer/\")\r\n\r\n\ttree_set = RegistrationFeatureExtractionMultivalued(dataset[0], compress_mode=\"lzt\")\r\n\r\n\tdata_frame = CalculateCompressRatioMultivalued(tree_set, dataset[1], gamma=30)\r\n\r\n\tmachin= ANT_MachineLearning(\"./Buffer/\", \"./Result/\")\r\n\r\n\tmachin.MachineLearningSvmExtend(data_frame)"
] | [
[
"sklearn.model_selection.GridSearchCV",
"pandas.read_csv",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.metrics.precision_score",
"pandas.DataFrame",
"sklearn.svm.SVC",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"sklearn.metrics.recall_score",
"sklearn.metrics.accuracy_score"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
CruddyShad0w/StockBot | [
"e8e321bc7c6c694afc04fa2d48690a96c49a680c"
] | [
"quantopian/algo.py"
] | [
"from pylivetrader.api import (\n attach_pipeline,\n date_rules,\n get_datetime,\n time_rules,\n order,\n get_open_orders,\n cancel_order,\n pipeline_output,\n schedule_function,\n)\nfrom pipeline_live.data.iex.pricing import USEquityPricing\nfrom pipeline_live.data.iex.fundamentals import IEXCompany, IEXKeyStats\nfrom pipeline_live.data.iex.factors import (\n SimpleMovingAverage, AverageDollarVolume,\n)\nfrom pipeline_live.data.polygon.filters import (\n IsPrimaryShareEmulation as IsPrimaryShare,\n)\nfrom pylivetrader.finance.execution import LimitOrder\nfrom zipline.pipeline import Pipeline\n\nimport numpy as np # needed for NaN handling\nimport math # ceil and floor are useful for rounding\n\nfrom itertools import cycle\n\nimport logbook\n\nlog = logbook.Logger('algo')\n\n\ndef record(*args, **kwargs):\n print('args={}, kwargs={}'.format(args, kwargs))\n\n\ndef initialize(context):\n\n context.MaxCandidates = 100\n context.MaxBuyOrdersAtOnce = 30\n context.MyLeastPrice = 3.00\n context.MyMostPrice = 25.00\n context.MyFireSalePrice = context.MyLeastPrice\n context.MyFireSaleAge = 6\n\n print(len(context.portfolio.positions))\n\n # Rebalance\n EveryThisManyMinutes = 10\n TradingDayHours = 6.5\n TradingDayMinutes = int(TradingDayHours * 60)\n for minutez in range(\n 1,\n TradingDayMinutes,\n EveryThisManyMinutes\n ):\n schedule_function(\n my_rebalance,\n date_rules.every_day(),\n time_rules.market_open(\n minutes=minutez))\n\n # Prevent excessive logging of canceled orders at market close.\n schedule_function(\n cancel_open_orders,\n date_rules.every_day(),\n time_rules.market_close(\n hours=0,\n minutes=1))\n\n # Record variables at the end of each day.\n schedule_function(\n my_record_vars,\n date_rules.every_day(),\n time_rules.market_close())\n\n # Create our pipeline and attach it to our algorithm.\n my_pipe = make_pipeline(context)\n attach_pipeline(my_pipe, 'my_pipeline')\n\n\ndef make_pipeline(context):\n \"\"\"\n Create our pipeline.\n \"\"\"\n\n # Filter for primary share equities. IsPrimaryShare is a built-in filter.\n primary_share = IsPrimaryShare()\n\n # Not when-issued equities.\n not_wi = ~IEXCompany.symbol.latest.endswith('.WI')\n\n # Equities without LP in their name, .matches does a match using a regular\n # expression\n not_lp_name = ~IEXCompany.companyName.latest.matches('.* L[. ]?P.?$')\n\n # Equities whose most recent Morningstar market cap is not null have\n # fundamental data and therefore are not ETFs.\n have_market_cap = IEXKeyStats.marketcap.latest >= 1\n\n # At least a certain price\n price = USEquityPricing.close.latest\n AtLeastPrice = (price >= context.MyLeastPrice)\n AtMostPrice = (price <= context.MyMostPrice)\n\n # Filter for stocks that pass all of our previous filters.\n tradeable_stocks = (\n primary_share\n & not_wi\n & not_lp_name\n & have_market_cap\n & AtLeastPrice\n & AtMostPrice\n )\n\n LowVar = 6\n HighVar = 40\n\n log.info(\n '''\nAlgorithm initialized variables:\n context.MaxCandidates %s\n LowVar %s\n HighVar %s''' %\n (context.MaxCandidates, LowVar, HighVar))\n\n # High dollar volume filter.\n base_universe = AverageDollarVolume(\n window_length=20,\n mask=tradeable_stocks\n ).percentile_between(LowVar, HighVar)\n\n # Short close price average.\n ShortAvg = SimpleMovingAverage(\n inputs=[USEquityPricing.close],\n window_length=3,\n mask=base_universe\n )\n\n # Long close price average.\n LongAvg = SimpleMovingAverage(\n inputs=[USEquityPricing.close],\n window_length=45,\n mask=base_universe\n )\n\n percent_difference = (ShortAvg - LongAvg) / LongAvg\n\n # Filter to select securities to long.\n stocks_worst = percent_difference.bottom(context.MaxCandidates)\n securities_to_trade = (stocks_worst)\n\n return Pipeline(\n columns={\n 'stocks_worst': stocks_worst\n },\n screen=(securities_to_trade),\n )\n\n\ndef my_compute_weights(context):\n \"\"\"\n Compute ordering weights.\n \"\"\"\n # Compute even target weights for our long positions and short positions.\n stocks_worst_weight = 1.00 / len(context.stocks_worst)\n\n return stocks_worst_weight\n\n\ndef before_trading_start(context, data):\n # over simplistic tracking of position age\n if not hasattr(context, 'age') or not context.age:\n context.age = {}\n\n today = get_datetime().floor('1D')\n last_date = getattr(context, 'last_date', None)\n if today != last_date:\n # Gets our pipeline output every day.\n context.output = pipeline_output('my_pipeline')\n\n context.stocks_worst = context.output[\n context.output['stocks_worst']].index.tolist()\n\n context.stocks_worst_weight = my_compute_weights(context)\n\n context.MyCandidate = cycle(context.stocks_worst)\n\n context.LowestPrice = context.MyLeastPrice # reset beginning of day\n print(len(context.portfolio.positions))\n for stock in context.portfolio.positions:\n CurrPrice = float(data.current([stock], 'price'))\n if CurrPrice < context.LowestPrice:\n context.LowestPrice = CurrPrice\n if stock in context.age:\n context.age[stock] += 1\n else:\n context.age[stock] = 1\n for stock in context.age:\n if stock not in context.portfolio.positions:\n context.age[stock] = 0\n message = 'stock.symbol: {symbol} : age: {age}'\n log.info(\n message.format(\n symbol=stock.symbol,\n age=context.age[stock]))\n context.last_date = today\n\n\ndef my_rebalance(context, data):\n BuyFactor = .99\n SellFactor = 1.01\n cash = context.portfolio.cash\n\n cancel_open_buy_orders(context, data)\n\n # Order sell at profit target in hope that somebody actually buys it\n for stock in context.portfolio.positions:\n if not get_open_orders(stock):\n StockShares = context.portfolio.positions[stock].amount\n CurrPrice = float(data.current([stock], 'price'))\n CostBasis = float(context.portfolio.positions[stock].cost_basis)\n SellPrice = float(\n make_div_by_05(\n CostBasis *\n SellFactor,\n buy=False))\n\n if np.isnan(SellPrice):\n pass # probably best to wait until nan goes away\n elif (stock in context.age and context.age[stock] == 1):\n pass\n elif (\n stock in context.age\n and context.MyFireSaleAge <= context.age[stock]\n and (\n context.MyFireSalePrice > CurrPrice\n or CostBasis > CurrPrice\n )\n ):\n if (stock in context.age and context.age[stock] < 2):\n pass\n elif stock not in context.age:\n context.age[stock] = 1\n else:\n SellPrice = float(\n make_div_by_05(.95 * CurrPrice, buy=False))\n order(stock, -StockShares,\n style=LimitOrder(SellPrice)\n )\n else:\n if (stock in context.age and context.age[stock] < 2):\n pass\n elif stock not in context.age:\n context.age[stock] = 1\n else:\n\n order(stock, -StockShares,\n style=LimitOrder(SellPrice)\n )\n\n WeightThisBuyOrder = float(1.00 / context.MaxBuyOrdersAtOnce)\n for ThisBuyOrder in range(context.MaxBuyOrdersAtOnce):\n stock = next(context.MyCandidate)\n PH = data.history([stock], 'price', 20, '1d')\n PH_Avg = float(PH.mean())\n CurrPrice = float(data.current([stock], 'price'))\n if np.isnan(CurrPrice):\n pass # probably best to wait until nan goes away\n else:\n if CurrPrice > float(1.25 * PH_Avg):\n BuyPrice = float(CurrPrice)\n else:\n BuyPrice = float(CurrPrice * BuyFactor)\n BuyPrice = float(make_div_by_05(BuyPrice, buy=True))\n StockShares = int(WeightThisBuyOrder * cash / BuyPrice)\n order(stock, StockShares,\n style=LimitOrder(BuyPrice)\n )\n\n# if cents not divisible by .05, round down if buy, round up if sell\n\n\ndef make_div_by_05(s, buy=False):\n s *= 20.00\n s = math.floor(s) if buy else math.ceil(s)\n s /= 20.00\n return s\n\n\ndef my_record_vars(context, data):\n \"\"\"\n Record variables at the end of each day.\n \"\"\"\n\n # Record our variables.\n record(leverage=context.account.leverage)\n record(positions=len(context.portfolio.positions))\n if 0 < len(context.age):\n MaxAge = context.age[max(\n list(context.age.keys()), key=(lambda k: context.age[k]))]\n print(MaxAge)\n record(MaxAge=MaxAge)\n record(LowestPrice=context.LowestPrice)\n\n\ndef log_open_order(StockToLog):\n oo = get_open_orders()\n if len(oo) == 0:\n return\n for stock, orders in oo.items():\n if stock == StockToLog:\n for o in orders:\n message = 'Found open order for {amount} shares in {stock}'\n log.info(message.format(amount=o.amount, stock=stock))\n\n\ndef log_open_orders():\n oo = get_open_orders()\n if len(oo) == 0:\n return\n for stock, orders in oo.items():\n for o in orders:\n message = 'Found open order for {amount} shares in {stock}'\n log.info(message.format(amount=o.amount, stock=stock))\n\n\ndef cancel_open_buy_orders(context, data):\n oo = get_open_orders()\n if len(oo) == 0:\n return\n for stock, orders in oo.items():\n for o in orders:\n # message = 'Canceling order of {amount} shares in {stock}'\n # log.info(message.format(amount=o.amount, stock=stock))\n if 0 < o.amount: # it is a buy order\n cancel_order(o)\n\n\ndef cancel_open_orders(context, data):\n oo = get_open_orders()\n if len(oo) == 0:\n return\n for stock, orders in oo.items():\n for o in orders:\n # message = 'Canceling order of {amount} shares in {stock}'\n # log.info(message.format(amount=o.amount, stock=stock))\n cancel_order(o)\n\n# This is the every minute stuff\n\n\ndef handle_data(context, data):\n pass"
] | [
[
"numpy.isnan"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
denred0/action-recognition-pytorch | [
"a66766689c68eb93fad0722ea3c6fd4976a1a248"
] | [
"models/twod_models/temporal_modeling.py"
] | [
"\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\n\nclass SEModule(nn.Module):\n\n def __init__(self, channels, dw_conv):\n super().__init__()\n ks = 1\n pad = (ks - 1) // 2\n self.fc1 = nn.Conv2d(channels, channels, kernel_size=ks,\n padding=pad, groups=channels if dw_conv else 1, bias=False)\n\n def forward(self, x):\n x = self.fc1(x)\n return x\n\n\nclass TAM(nn.Module):\n\n def __init__(self, duration, channels, dw_conv=True, blending_frames=3, blending_method='sum'):\n super().__init__()\n self.blending_frames = blending_frames\n self.blending_method = blending_method\n\n if blending_frames == 3:\n self.prev_se = SEModule(channels, dw_conv)\n self.next_se = SEModule(channels, dw_conv)\n self.curr_se = SEModule(channels, dw_conv)\n else:\n self.blending_layers = nn.ModuleList([SEModule(channels, dw_conv) for _ in range(blending_frames)])\n self.relu = nn.ReLU(inplace=True)\n self.duration = duration\n\n def name(self):\n return \"TAM-b{}-{}\".format(self.blending_frames, self.blending_method)\n\n def forward(self, x):\n\n if self.blending_frames == 3:\n prev_x = self.prev_se(x)\n curr_x = self.curr_se(x)\n next_x = self.next_se(x)\n prev_x = prev_x.view((-1, self.duration) + prev_x.size()[1:])\n curr_x = curr_x.view((-1, self.duration) + curr_x.size()[1:])\n next_x = next_x.view((-1, self.duration) + next_x.size()[1:])\n\n prev_x = F.pad(prev_x, (0, 0, 0, 0, 0, 0, 1, 0))[:, :-1, ...]\n next_x = F.pad(next_x, (0, 0, 0, 0, 0, 0, 0, 1))[:, 1:, ...]\n\n out = torch.stack([prev_x, curr_x, next_x], dim=0)\n else:\n # multiple blending\n xs = [se(x) for se in self.blending_layers]\n xs = [x.view((-1, self.duration) + x.size()[1:]) for x in xs]\n\n shifted_xs = []\n for i in range(self.blending_frames):\n shift = i - (self.blending_frames // 2)\n x_temp = xs[i]\n n, t, c, h, w = x_temp.shape\n start_index = 0 if shift < 0 else shift\n end_index = t if shift < 0 else t + shift\n padding = None\n if shift < 0:\n padding = (0, 0, 0, 0, 0, 0, abs(shift), 0)\n elif shift > 0:\n padding = (0, 0, 0, 0, 0, 0, 0, shift)\n shifted_xs.append(F.pad(x_temp, padding)[:, start_index:end_index, ...]\n if padding is not None else x_temp)\n\n out = torch.stack(shifted_xs, dim=0)\n\n if self.blending_method == 'sum':\n out = torch.sum(out, dim=0)\n elif self.blending_method == 'max':\n out, _ = torch.max(out, dim=0)\n else:\n raise ValueError('Blending method %s not supported' % (self.blending_method))\n\n out = self.relu(out)\n # [N, T, C, N, H]\n n, t, c, h, w = out.shape\n out = out.view((-1, ) + out.size()[2:])\n # out = out.contiguous()\n\n return out\n\n\ndef temporal_modeling_module(name, duration, channels, dw_conv=True,\n blending_frames=3, blending_method='sum'):\n if name is None or name == 'TSN':\n return None\n\n if name == 'TAM':\n return TAM(duration, channels, dw_conv, blending_frames, blending_method)\n else:\n raise ValueError('incorrect tsm module name %s' % name)\n\n"
] | [
[
"torch.max",
"torch.nn.Conv2d",
"torch.sum",
"torch.stack",
"torch.nn.ReLU",
"torch.nn.functional.pad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amandadumi/chemreps | [
"717796d7ef0b56803407147ff72921329fa91d79"
] | [
"tests/just_bonds_test.py"
] | [
"import numpy as np\nimport pytest as pt\nfrom collections import OrderedDict\nimport chemreps.just_bonds as jb\nfrom chemreps.bagger import BagMaker\n\n\ndef test_just_bonds():\n bags_true = OrderedDict([('C', 16), ('CC', 13), ('H', 18), ('HC', 16), ('N', 2),\n ('NC', 5), ('NH', 1), ('O', 5), ('OC', 6), ('OH', 2), ('S', 1), ('SC', 2)])\n\n jbs_true = np.array([36.84 , 36.84 , 36.84 , 36.84 , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 23.38 , 23.38 , 23.33 , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.5 ,\n 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 ,\n 0.5 , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 5.492, 5.492, 5.492, 5.492, 5.492, 5.492,\n 5.492, 5.492, 5.492, 5.492, 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. ], dtype=np.float16)\n\n bagger = BagMaker('JustBonds', 'data/sdf/')\n assert bagger.bag_sizes == bags_true\n\n rep = jb.bonds('data/sdf/butane.sdf', bagger.bags, bagger.bag_sizes)\n assert np.allclose(rep, jbs_true, 1e-4) == True\n\n rep = jb.bonds('data/cml/butane.cml', bagger.bags, bagger.bag_sizes)\n assert np.allclose(rep, jbs_true, 1e-4) == True\n\n with pt.raises(NotImplementedError):\n jbs = jb.bonds('data/xyz/butane.xyz', bagger.bags, bagger.bag_sizes)\n\n with pt.raises(NotImplementedError):\n bagger = BagMaker('JustBonds', 'data/xyz/')\n\n\nif __name__ == \"__main__\":\n print(\"This is a test of the bag of bonds representation in chemreps to be evaluated with pytest\")\n"
] | [
[
"numpy.array",
"numpy.allclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PouyaGhahramanian/goowe-python | [
"926e36061cc8d20ce0164c4fae3dfa2f492bc487"
] | [
"Goowe.py"
] | [
"import numpy as np\r\nfrom skmultiflow.core.base import StreamModel\r\n#from skmultiflow.core.base import BaseEstimator\r\nfrom skmultiflow.trees import HoeffdingTree\r\nfrom skmultiflow.utils.data_structures import InstanceWindow, FastBuffer\r\n\r\n\r\nclass Goowe(StreamModel):\r\n#class Goowe(BaseEstimator):\r\n \"\"\" GOOWE (Geometrically Optimum Online Weighted Ensemble), as it is\r\n described in Bonab and Can (2017). Common notation in the code is\r\n as follows:\r\n K for maximum number of classifiers in the ensemble.\r\n N for data instances.\r\n A, d as they are, in the aforementioned paper.\r\n\r\n\r\n Parameters\r\n ----------\r\n n_max_components: int\r\n Ensemble size limit. Maximum number of component classifiers.\r\n chunk_size: int\r\n The amount of instances necessary for ensemble to learn concepts from.\r\n At each chunk_size many instances, some training is done.\r\n window_size: int\r\n Size of sliding window, which keeps record of the last k instances\r\n that are encountered in the data stream.\r\n \"\"\"\r\n\r\n def __init__(self, n_max_components: int = 10,\r\n chunk_size: int = 500, window_size: int = 100, logging = True):\r\n super().__init__()\r\n self._num_of_max_classifiers = n_max_components\r\n self._chunk_size = chunk_size\r\n self._Logging = logging\r\n self._num_of_current_classifiers = 0\r\n self._num_of_processed_instances = 0\r\n self._classifiers = np.empty((self._num_of_max_classifiers),\r\n dtype=object)\r\n self._weights = np.zeros((self._num_of_max_classifiers,))\r\n\r\n # What to save from current Data Chunk --> will be used for\r\n # adjusting weights, pruning purposes and so on.\r\n # Individual predictions of components, overall prediction of ensemble,\r\n # and ground truth info.\r\n self._chunk_comp_preds = FastBuffer(max_size=chunk_size)\r\n self._chunk_ensm_preds = FastBuffer(max_size=chunk_size)\r\n\r\n # chunk_data has instances in the chunk and their ground truth.\r\n # To be initialized after receiving n_features, n_targets\r\n self._chunk_data = None\r\n # self._chunk_truths = FastBuffer(max_size=chunk_size)\r\n\r\n # some external stuff that is about the data we are dealing with\r\n # but useful for recording predictions\r\n self._num_classes = None\r\n self._target_values = None # Required to correctly train HTs\r\n self._record = False # Boolean for keeping records to files\r\n\r\n # TODO: Implement Sliding Window Continuous Evaluator.\r\n # What to save at Sliding Window (last n instances) --> will be\r\n # used for continuous evaluation.\r\n # self._sliding_window_ensemble_preds =FastBuffer(max_size=window_size)\r\n # self._sliding_window_truths = FastBuffer(max_size=window_size)\r\n\r\n def prepare_post_analysis_req(self, num_features, num_targets, num_classes, target_values, record=False):\r\n # Need to get the dataset information but we do not want to\r\n # take it as an argument to the classifier itself, nor we do want to\r\n # ask it at each data instance. Hence we take dataset info from user\r\n # explicitly to create _chunk_data entries.\r\n #chunk_size = self._chunk_size\r\n self._chunk_data = InstanceWindow(n_features = num_features,\r\n n_targets = num_targets,\r\n max_size = self._chunk_size)\r\n #self._chunk_data = chunk_data\r\n # num_targets shows how many columns you want to predict in the data.\r\n # num classes is eqv to possible number of values that that column\r\n # can have.\r\n self._num_classes = num_classes\r\n self._target_values = target_values\r\n self._record = record\r\n\r\n if(self._record):\r\n # Create files that keeps record of:\r\n # - weights at each chunk\r\n # - individual component results for every instance\r\n # - ground truths for every instance.\r\n self._f_comp_preds = open(\"component_predictions.csv\", \"w+\")\r\n self._f_truths = open(\"ground_truths.csv\", \"w+\")\r\n self._f_weights = open(\"weights.csv\", \"w+\")\r\n\r\n self._f_comp_preds.write(str(self._chunk_size) + '\\n')\r\n\r\n self._f_comp_preds.close()\r\n self._f_truths.close()\r\n self._f_weights.close()\r\n return\r\n\r\n def _get_components_predictions_for_instance(self, inst):\r\n \"\"\" For a given data instance, takes predictions of\r\n individual components from the ensemble as a matrix.\r\n\r\n Parameters\r\n ----------\r\n inst: data instance for which votes of components are delivered.\r\n\r\n Returns\r\n ----------\r\n numpy.array\r\n A 2-d numpy array where each row corresponds to predictions of\r\n each classifier.\r\n \"\"\"\r\n preds = np.zeros((self._num_of_current_classifiers, self._num_classes))\r\n # print(np.shape(preds))\r\n for k in range(len(preds)):\r\n kth_comp_pred = self._classifiers[k].predict_proba(inst)\r\n # print(kth_comp_pred[0])\r\n # print(preds)\r\n # print(\"Component {}'s Prediction: {}\".format(k, kth_comp_pred))\r\n preds[k, :] = kth_comp_pred[0]\r\n if(self._Logging):\r\n print('Component Predictions:')\r\n print(preds)\r\n return preds\r\n\r\n def _adjust_weights(self):\r\n \"\"\" Weight adustment by solving linear least squares, as it is\r\n described in Bonab and Can (2017).\r\n \"\"\"\r\n # Prepare variables for Weight Adjustment\r\n # print('number of current classifiers: {}'.format(self._num_of_current_classifiers))\r\n A = np.zeros(shape=(self._num_of_current_classifiers,\r\n self._num_of_current_classifiers))\r\n d = np.zeros(shape=(self._num_of_current_classifiers,))\r\n\r\n # Go over all the data chunk, calculate values of (S_i x S_j) for A.\r\n # (S_i x O) for d.\r\n y_all = self._chunk_data.get_targets_matrix().astype(int)\r\n # print(y_all)\r\n for i in range(len(y_all)):\r\n class_index = y_all[i]\r\n comp_preds = self._chunk_comp_preds.get_next_element()\r\n #print(\"{} components predictions:\".format(i))\r\n #print(comp_preds)\r\n\r\n A = A + comp_preds.dot(comp_preds.T)\r\n d = d + comp_preds[0][class_index]\r\n\r\n # A and d are filled. Now, the linear system Aw=d to be solved\r\n # to get our desired weights. w is of size K.\r\n # print(\"Solving Aw=d\")\r\n # print(A)\r\n # print(d)\r\n w = np.linalg.lstsq(A, d, rcond=None)[0]\r\n\r\n # _weights has maximum size but what we found can be\r\n # smaller. Therefore, need to put the values of w to global weights\r\n if(self._num_of_current_classifiers < self._num_of_max_classifiers):\r\n for i in range(len(w)):\r\n self._weights[i] = w[i]\r\n else: # If full size, there is no problem.\r\n self._weights = w\r\n # print(\"After solving Aw=d weights:\")\r\n # print(self._weights)\r\n return\r\n\r\n def _normalize_weights(self):\r\n \"\"\" Normalizes the weights of the ensemble to (0, 1) range.\r\n Performs (x_i - min(x)) / (max(x) - min(x)) on the nonzero elements\r\n of the weight vector.\r\n \"\"\"\r\n min = np.amin(self._weights[:self._num_of_current_classifiers])\r\n max = np.amax(self._weights[:self._num_of_current_classifiers])\r\n\r\n if(min == max): # all weights are the same\r\n for i in range(self._num_of_current_classifiers):\r\n self._weights[i] = 1. / self._num_of_current_classifiers\r\n else:\r\n for i in range(self._num_of_current_classifiers):\r\n self._weights[i] = (self._weights[i] - min) / (max - min)\r\n return\r\n\r\n def _normalize_weights_softmax(self):\r\n \"\"\" Normalizes the weights of the ensemble to (0, 1) range.\r\n Performs (x_i - min(x)) / (max(x) - min(x)) on the nonzero elements\r\n of the weight vector.\r\n \"\"\"\r\n cur_weights = self._weights[:self._num_of_current_classifiers]\r\n self._weights[:self._num_of_current_classifiers] = np.exp(cur_weights) / sum(np.exp(cur_weights))\r\n\r\n return\r\n\r\n def _process_chunk(self):\r\n \"\"\" A subroutine that runs at the end of each chunk, allowing\r\n the components to be trained and ensemble weights to be adjusted.\r\n Until the first _process_chunk call, the ensemble is not yet ready.\r\n At first call, the first component is learned.\r\n At the rest of the calls, new components are formed, and the older ones\r\n are trained by the given chunk.\r\n If the ensemble size is reached, then the lowest weighted component is\r\n removed from the ensemble.\r\n \"\"\"\r\n new_clf = HoeffdingTree() # with default parameters for now\r\n new_clf.reset()\r\n\r\n # Save records of previous chunk\r\n if(self._record and self._num_of_current_classifiers > 0):\r\n self._record_truths_this_chunk()\r\n self._record_comp_preds_this_chunk()\r\n self._record_weights_this_chunk()\r\n\r\n # Case 1: No classifier in the ensemble yet, first chunk:\r\n if(self._num_of_current_classifiers == 0):\r\n self._classifiers[0] = new_clf\r\n self._weights[0] = 1.0 # weight is 1 for the first clf\r\n self._num_of_current_classifiers += 1\r\n else:\r\n # First, adjust the weights of the old component classifiers\r\n # according to what happened in this chunk.\r\n self._adjust_weights()\r\n # Case 2: There are classifiers in the ensemble but\r\n # the ensemble size is still not capped.\r\n if(self._num_of_current_classifiers < self._num_of_max_classifiers):\r\n # Put the new classifier to ensemble with the weight of 1\r\n self._classifiers[self._num_of_current_classifiers] = new_clf\r\n self._weights[self._num_of_current_classifiers] = float(1.0)\r\n self._num_of_current_classifiers += 1\r\n\r\n # Case 3: Ensemble size is capped. Need to replace the component\r\n # with lowest weight.\r\n else:\r\n assert (self._num_of_current_classifiers\r\n == self._num_of_max_classifiers), \"Ensemble not full.\"\r\n index_of_lowest_weight = np.argmin(self._weights)\r\n self._classifiers[index_of_lowest_weight] = new_clf\r\n self._weights[index_of_lowest_weight] = 1.0\r\n\r\n # Normalizing weigths to simplify numbers\r\n self._normalize_weights_softmax() # maybe useful. we'll see.\r\n if(self._Logging):\r\n print(\"After normalization weights: \")\r\n print(self._weights)\r\n # Ensemble maintenance is done. Now train all classifiers\r\n # in the ensemble from the current chunk.\r\n # Can be parallelized.\r\n data_features = self._chunk_data.get_attributes_matrix()\r\n data_truths = self._chunk_data.get_targets_matrix()\r\n data_truths = data_truths.astype(int).flatten()\r\n\r\n if(self._Logging):\r\n print(\"Starting training the components with the current chunk...\")\r\n for k in range(self._num_of_current_classifiers):\r\n print(\"Training classifier {}\".format(k))\r\n self._classifiers[k].partial_fit(data_features, data_truths,\r\n classes=self._target_values)\r\n print(\"Training the components with the current chunk completed...\")\r\n else:\r\n for k in range(self._num_of_current_classifiers):\r\n self._classifiers[k].partial_fit(data_features, data_truths, classes=self._target_values)\r\n return\r\n\r\n def _record_truths_this_chunk(self):\r\n f = open(\"ground_truths.csv\", \"ab\")\r\n\r\n data_truths = self._chunk_data.get_targets_matrix()\r\n data_truths = data_truths.astype(int).flatten()\r\n\r\n # Default behaviour is to store list of lists for savetxt.\r\n # Hence, to prevent newline after each element of list, we surround\r\n # the truth array with one more set of bracketts.\r\n np.savetxt(f, [data_truths], delimiter=\",\", fmt='%d')\r\n\r\n f.close()\r\n return\r\n\r\n def _record_comp_preds_this_chunk(self):\r\n f = open(\"component_predictions.csv\", \"a+\")\r\n np.savetxt(f, [self._num_of_current_classifiers], fmt='%d')\r\n\r\n comp_preds = np.array(self._chunk_comp_preds.get_queue())\r\n\r\n for i in range(len(comp_preds)):\r\n np.savetxt(f, comp_preds[i], delimiter=',', fmt='%1.5f')\r\n f.close()\r\n return\r\n\r\n def _record_weights_this_chunk(self):\r\n f = open(\"weights.csv\", \"a+\")\r\n np.savetxt(f, [self._num_of_current_classifiers], fmt='%d')\r\n\r\n weights = self._weights\r\n np.savetxt(f, [weights], delimiter=',', fmt='%1.5f')\r\n f.close()\r\n return\r\n\r\n # --------------------------------------------------\r\n # Overridden methods from the parent (StreamModel)\r\n # --------------------------------------------------\r\n def fit(self, X, y, classes=None, weight=None):\r\n raise NotImplementedError(\"For now, only the stream version \"\r\n \"is implemented. Use partial_fit()\")\r\n\r\n def partial_fit(self, X, y, classes=None, weight=None):\r\n # This method should work with individual instances, as well as bunch\r\n # of instances, since there can be pre-training for warm start.\r\n\r\n # If an individual instance is inputted, then just save X and y to\r\n # train from them later.\r\n if(len(X) == 1):\r\n # Save X and y to train classifiers later\r\n # y is required to be 1x1, and hence the square bracketts.\r\n y_i = np.array([y])\r\n # print(type(X))\r\n # print(type(y_i))\r\n # print(X)\r\n # print(y_i)\r\n self._chunk_data.add_element(X, y_i)\r\n\r\n # If still filling the chunk, then just add the instance to the\r\n # current data chunk, wait for it to be filled.\r\n self._num_of_processed_instances += 1\r\n\r\n # If at the end of a chunk, start training components\r\n # and adjusting weights using information in this chunk.\r\n if(self._num_of_processed_instances % self._chunk_size == 0):\r\n print(\"Instance {}\".format(self._num_of_processed_instances))\r\n self._process_chunk()\r\n elif(len(X) > 1):\r\n # Input is a chunk. Add them individually.\r\n for i in range(len(X)):\r\n X_i = np.array([X[i]])\r\n y_i = np.array([[y[i]]])\r\n # print(X_i)\r\n # print(y_i)\r\n self._chunk_data.add_element(X_i, y_i)\r\n self._num_of_processed_instances += 1\r\n\r\n # If at the end of a chunk, start training components\r\n # and adjusting weights using information in this chunk.\r\n if(self._num_of_processed_instances % self._chunk_size == 0):\r\n print(\"Instance {}\".format(self._num_of_processed_instances))\r\n self._process_chunk()\r\n else:\r\n print(\"Something wrong with the data...\")\r\n print(\"len(X) is: {}\".format(len(X)))\r\n return\r\n\r\n def predict(self, X):\r\n \"\"\" For a given data instance, yields the prediction values.\r\n\r\n Parameters\r\n ----------\r\n X: numpy.ndarray of shape (n_samples, n_features)\r\n Samples for which we want to predict the labels.\r\n\r\n Returns\r\n -------\r\n numpy.array\r\n Predicted labels for all instances in X.\r\n \"\"\"\r\n predictions = []\r\n if(len(X) == 1):\r\n predictions.append(np.argmax(self.predict_proba(X)))\r\n elif(len(X) > 1):\r\n # Add many predictions\r\n for i in range(len(X)):\r\n relevance_scores = self.predict_proba(X[i])\r\n predictions.append(np.argmax(relevance_scores))\r\n # print(np.argmax(relevance_scores))\r\n if(self._Logging):\r\n print('Ensemble Prediction:')\r\n print(np.array(predictions))\r\n return np.array(predictions) #, one_hot\r\n\r\n def predict_proba(self, X):\r\n \"\"\" For a given data instance, takes WEIGHTED combination\r\n of components to get relevance scores for each class.\r\n\r\n Parameters\r\n ----------\r\n X: data instance for which weighted combination is delivered.\r\n\r\n Returns\r\n ----------\r\n numpy.array\r\n A vector with number_of_classes elements where each element\r\n represents class score of corresponding class for this instance.\r\n \"\"\"\r\n weights = np.array(self._weights)\r\n\r\n # get only the useful weights\r\n weights = weights[:self._num_of_current_classifiers]\r\n components_preds = self._get_components_predictions_for_instance(X)\r\n #print('*****************************')\r\n #print(components_preds)\r\n #print('*****************************')\r\n # Save individual component predictions and ensemble prediction\r\n # for later analysis.\r\n self._chunk_comp_preds.add_element([components_preds])\r\n\r\n #print(weights)\r\n #print(components_preds)\r\n #print(self.get_classifiers())\r\n weighted_ensemble_vote = np.dot(weights, components_preds)\r\n # print(\"Weighted Ensemble vote: {}\".format(weighted_ensemble_vote))\r\n self._chunk_ensm_preds.add_element(weighted_ensemble_vote)\r\n\r\n return weighted_ensemble_vote\r\n\r\n def reset(self):\r\n pass\r\n\r\n def score(self, X, y):\r\n pass\r\n\r\n def get_info(self):\r\n return 'The Ensemble GOOWE (Bonab and Can, 2017) with' + \\\r\n ' - n_max_components: ' + str(self._num_of_max_classifiers) + \\\r\n ' - num_of_current_components: ' + str(self._num_of_current_classifiers) + \\\r\n ' - chunk_size: ' + str(self._chunk_size) + \\\r\n ' - num_dimensions_in_label_space(num_classes): ' + str(self._num_classes) + \\\r\n ' - recording: ' + str(self._record)\r\n\r\n def get_class_type(self):\r\n pass\r\n\r\n # Some getters and setters..\r\n def get_number_of_current_classifiers(self):\r\n return self._num_of_current_classifiers\r\n\r\n def get_number_of_max_classifiers(self):\r\n return self._num_of_max_classifiers\r\n\r\n # Helper methods for GooweMS\r\n def get_classifiers(self):\r\n return self._classifiers\r\n\r\n def set_classifiers(self, classifiers):\r\n self._classifiers = classifiers\r\n\r\n def get_weights(self):\r\n return self._weights\r\n"
] | [
[
"numpy.dot",
"numpy.amax",
"numpy.amin",
"numpy.exp",
"numpy.linalg.lstsq",
"numpy.argmax",
"numpy.argmin",
"numpy.savetxt",
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
huschen/walk_prosthetics | [
"436deecf2d70cc7766099f2ff7682c47c5a2d437"
] | [
"ddpg/training.py"
] | [
"import os\nimport time\nimport datetime\n\nimport numpy as np\nfrom mpi4py import MPI\n\nfrom common import logger\nfrom common.misc_util import dbg_tf_init\nimport common.tf_util as tf_util\nfrom ddpg.pretrain import pretrain_demo, load_history\n\n\ndef train(env, eval_env, agent, render=False, render_eval=False, sanity_run=False,\n nb_epochs=500, nb_epoch_cycles=20, nb_rollout_steps=100, nb_train_steps=50,\n param_noise_adaption_interval=50, hist_files=None, start_ckpt=None, demo_files=None):\n\n rank = MPI.COMM_WORLD.Get_rank()\n mpi_size = MPI.COMM_WORLD.Get_size()\n if rank == 0:\n logdir = logger.get_dir()\n else:\n logdir = None\n\n memory = agent.memory\n batch_size = agent.batch_size\n\n with tf_util.single_threaded_session() as sess:\n # Prepare everything.\n agent.initialize(sess, start_ckpt=start_ckpt)\n sess.graph.finalize()\n agent.reset()\n dbg_tf_init(sess, agent.dbg_vars)\n\n total_nb_train = 0\n total_nb_rollout = 0\n total_nb_eval = 0\n\n # pre-train demo and critic_step\n # train_params: (nb_steps, lr_scale)\n total_nb_train = pretrain_demo(agent, env, demo_files, total_nb_train,\n train_params=[(100, 1.0)], start_ckpt=start_ckpt)\n load_history(agent, env, hist_files)\n\n # main training\n obs = env.reset()\n reset = False\n episode_step = 0\n last_episode_step = 0\n\n for i_epoch in range(nb_epochs):\n t_epoch_start = time.time()\n logger.info('\\n%s epoch %d starts:' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), i_epoch))\n for i_cycle in range(nb_epoch_cycles):\n logger.info('\\n%s cycles_%d of epoch_%d' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),\n i_cycle, i_epoch))\n\n # rollout\n rcd_obs, rcd_action, rcd_r, rcd_new_obs, rcd_done = [], [], [], [], []\n if not sanity_run and mpi_size == 1 and last_episode_step != 0:\n # todo: use mpi_max(last_episode_step)\n # dynamically set nb_rollout_steps\n nb_rollout_steps = max(last_episode_step * 4, batch_size)\n logger.info('[%d, %d] rollout for %d steps.' % (total_nb_rollout, memory.nb_entries, nb_rollout_steps))\n t_rollout_start = time.time()\n\n for i_rollout in range(nb_rollout_steps):\n rollout_log = i_cycle == 0\n # 50% param_noise, 40% action_noise\n action, q = agent.pi(obs, total_nb_rollout, compute_Q=True, rollout_log=rollout_log,\n apply_param_noise=i_rollout % 10 < 5, apply_action_noise=i_rollout % 10 > 5)\n assert action.shape == env.action_space.shape\n new_obs, r, done, reset, info = env.step(action)\n\n if rank == 0 and render:\n env.render()\n\n episode_step += 1\n total_nb_rollout += 1\n\n if rollout_log:\n summary_list = [('rollout/%s' % tp, info[tp]) for tp in ['rwd_walk', 'rwd_total']]\n tp = 'rwd_agent'\n summary_list += [('rollout/%s_x%d' % (tp, info['rf_agent']), info[tp] * info['rf_agent'])]\n summary_list += [('rollout/q', q)]\n if r != 0:\n summary_list += [('rollout/q_div_r', q / r)]\n agent.add_list_summary(summary_list, total_nb_rollout)\n\n # store at the end of cycle to speed up MPI rollout\n # agent.store_transition(obs, action, r, new_obs, done)\n rcd_obs.append(obs)\n rcd_action.append(action)\n rcd_r.append(r)\n rcd_new_obs.append(new_obs)\n rcd_done.append(done)\n\n obs = new_obs\n if reset:\n # Episode done.\n last_episode_step = episode_step\n episode_step = 0\n\n agent.reset()\n obs = env.reset()\n\n agent.store_multrans(memory, rcd_obs, rcd_action, rcd_r, rcd_new_obs, rcd_done)\n\n t_train_start = time.time()\n steps_per_second = float(nb_rollout_steps) / (t_train_start - t_rollout_start)\n agent.add_list_summary([('rollout/steps_per_second', steps_per_second)], total_nb_rollout)\n\n # Train.\n if not sanity_run:\n # dynamically set nb_train_steps\n if memory.nb_entries > batch_size * 20:\n # using 1% of data for training every step?\n nb_train_steps = max(int(memory.nb_entries * 0.01 / batch_size), 1)\n else:\n nb_train_steps = 0\n logger.info('[%d] training for %d steps.' % (total_nb_train, nb_train_steps))\n for _ in range(nb_train_steps):\n # Adapt param noise, if necessary.\n if memory.nb_entries >= batch_size and total_nb_train % param_noise_adaption_interval == 0:\n agent.adapt_param_noise(total_nb_train)\n\n agent.train_main(total_nb_train)\n agent.update_target_net()\n total_nb_train += 1\n\n if i_epoch == 0 and i_cycle < 5:\n rollout_duration = t_train_start - t_rollout_start\n train_duration = time.time() - t_train_start\n logger.info('rollout_time(%d) = %.3fs, train_time(%d) = %.3fs' % (\n nb_rollout_steps, rollout_duration, nb_train_steps, train_duration))\n logger.info('rollout_speed=%.3fs/step, train_speed = %.3fs/step' % (\n np.divide(rollout_duration, nb_rollout_steps), np.divide(train_duration, nb_train_steps)))\n\n logger.info('')\n mpi_size = MPI.COMM_WORLD.Get_size()\n # Log stats.\n stats = agent.get_stats(memory)\n combined_stats = stats.copy()\n\n def as_scalar(x):\n if isinstance(x, np.ndarray):\n assert x.size == 1\n return x[0]\n elif np.isscalar(x):\n return x\n else:\n raise ValueError('expected scalar, got %s' % x)\n combined_stats_sums = MPI.COMM_WORLD.allreduce(np.array([as_scalar(x) for x in combined_stats.values()]))\n combined_stats = {k: v / mpi_size for (k, v) in zip(combined_stats.keys(), combined_stats_sums)}\n\n # exclude logging zobs_dbg_%d, zobs_dbg_%d_normalized\n summary_list = [(key, combined_stats[key]) for key, v in combined_stats.items() if 'dbg' not in key]\n agent.add_list_summary(summary_list, i_epoch)\n\n # only print out train stats for epoch_0 for sanity check\n if i_epoch > 0:\n combined_stats = {}\n\n # Evaluation and statistics.\n if eval_env is not None:\n logger.info('[%d, %d] run evaluation' % (i_epoch, total_nb_eval))\n total_nb_eval = eval_episode(eval_env, render_eval, agent, combined_stats, total_nb_eval)\n\n logger.info('epoch %d duration: %.2f mins' % (i_epoch, (time.time() - t_epoch_start) / 60))\n for key in sorted(combined_stats.keys()):\n logger.record_tabular(key, combined_stats[key])\n logger.dump_tabular()\n logger.info('')\n\n if rank == 0:\n agent.store_ckpt(os.path.join(logdir, '%s.ckpt' % 'ddpg'), i_epoch)\n\n\ndef eval_episode(eval_env, render_eval, agent, combined_stats, total_nb_eval=0):\n steps = 0\n submit_episode_reward = 0.\n reset = False\n obs = eval_env.reset()\n\n while not reset:\n action, q = agent.pi(obs, total_nb_eval, apply_param_noise=False, apply_action_noise=False, compute_Q=True)\n obs, r, _, reset, info = eval_env.step(action)\n\n steps += 1\n total_nb_eval += 1\n if render_eval:\n eval_env.render()\n submit_episode_reward += r\n\n summary_list = [('the_action/%d_eval' % i, a) for i, a in enumerate(action)]\n summary_list += [('eval/q', q)]\n if r != 0:\n summary_list += [('eval/q_div_r', q / r)]\n\n summary_list += [('eval/%s' % tp, info[tp]) for tp in ['rwd_walk', 'rwd_total',\n 'rwd_blnc', 'rwd_dist', 'rwd_enrg']]\n tp = 'rwd_agent'\n summary_list += [('eval/%s_x%d' % (tp, info['rf_agent']), info[tp] * info['rf_agent'])]\n summary_list += [('eval_obs/%d' % i, o) for i, o in enumerate(obs[:agent.nb_demo_kine])]\n agent.add_list_summary(summary_list, total_nb_eval)\n\n agent.add_list_summary([('eval/episode_steps', steps)], total_nb_eval)\n combined_stats['eval/episode_return'] = submit_episode_reward\n combined_stats['eval/episode_steps'] = steps\n return total_nb_eval\n\n\n# MPI not used in testing mode\ndef test(eval_env, agent, render_eval=True, nb_epochs=1, start_ckpt=None, **kwargs):\n logger.info('Start testing:', start_ckpt, '\\n')\n with tf_util.single_threaded_session() as sess:\n agent.initialize(sess, start_ckpt=start_ckpt)\n sess.graph.finalize()\n\n for _ in range(nb_epochs):\n combined_stats = {}\n eval_episode(eval_env, render_eval, agent, combined_stats)\n\n for key in sorted(combined_stats.keys()):\n logger.record_tabular(key, combined_stats[key])\n logger.dump_tabular()\n logger.info('')\n\n\ndef config(group):\n group.add_argument('--nb_epochs', type=int, default=1)\n group.add_argument('--nb_epoch_cycles', type=int, default=2)\n group.add_argument('--nb_rollout_steps', type=int, default=25)\n group.add_argument('--nb_train_steps', type=int, default=10)\n group.add_argument('--start_ckpt', type=str, default='')\n group.add_argument('--hist_files', type=str, default='')\n group.add_argument('--demo_files', type=str,\n default='demo/train_pos.csv,demo/train_neg.csv,demo/test0.csv,demo/test1.csv,demo/test2.csv')\n"
] | [
[
"numpy.divide",
"numpy.isscalar"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AtsushiSakai/PyOptSamples | [
"c498e8978c64496be2dfe3c6a3b328b33da4b2c1"
] | [
"NonlinearOptimization/NewtonMethod/NewtonMethod.py"
] | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\ndelta = 0.1\nminXY=-5.0\nmaxXY=5.0\nnContour=50\nalpha=0.01\n\ndef Hessian(state):\n u\"\"\"\n Hessian matrix of Himmelblau's function\n \"\"\"\n x=state[0]\n y=state[1]\n dxx=12*x**2+4*y-42;\n dxy=4*x+4*y\n dyy=4*x+12*y**2-26\n H=np.array([[dxx,dxy],[dxy,dyy]])\n return H\n \n\ndef Jacob(state):\n u\"\"\"\n jacobi matrix of Himmelblau's function\n \"\"\"\n x=state[0]\n y=state[1]\n dx=4*x**3+4*x*y-44*x+2*x+2*y**2-14\n dy=2*x**2+4*x*y+4*y**3-26*y-22\n J=[dx,dy]\n return J\n\ndef HimmelblauFunction(x,y):\n u\"\"\"\n Himmelblau's function\n see Himmelblau's function - Wikipedia, the free encyclopedia \n http://en.wikipedia.org/wiki/Himmelblau%27s_function\n \"\"\"\n return (x**2+y-11)**2+(x+y**2-7)**2\n\ndef CreateMeshData():\n x = np.arange(minXY, maxXY, delta)\n y = np.arange(minXY, maxXY, delta)\n X, Y = np.meshgrid(x, y)\n Z=[HimmelblauFunction(x,y) for (x,y) in zip(X,Y)]\n return(X,Y,Z)\n\ndef NewtonMethod(start,Jacob):\n u\"\"\"\n Newton Method Optimization\n \"\"\"\n\n result=start\n x=start\n\n while 1:\n J=Jacob(x)\n H=Hessian(x)\n sumJ=sum([abs(alpha*j) for j in J])\n if sumJ<=0.01:\n print(\"OK\")\n break\n\n grad=-np.linalg.inv(H).dot(J) \n print(grad)\n\n x=x+[alpha*j for j in grad]\n \n result=np.vstack((result,x))\n\n return result\n\n# Main\nstart=np.array([random.uniform(minXY,maxXY),random.uniform(minXY,maxXY)])\n\nresult=NewtonMethod(start,Jacob)\n(X,Y,Z)=CreateMeshData()\nCS = plt.contour(X, Y, Z,nContour)\n# plt.clabel(CS, inline=1, fontsize=10)\n# plt.title('Simplest default with labels')\n\nplt.plot(start[0],start[1],\"xr\");\n\noptX=[x[0] for x in result]\noptY=[x[1] for x in result]\nplt.plot(optX,optY,\"-r\");\n\nplt.show()\n\n"
] | [
[
"numpy.meshgrid",
"numpy.linalg.inv",
"numpy.arange",
"numpy.vstack",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.contour",
"numpy.array",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gdahia/ufba-ai-minesweeper | [
"ba87df32c430481672a55a5b2c421cd6f97ad443"
] | [
"plot.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom six.moves import range\n\nimport os\nimport sys\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plot(board_spec,\n n_mines,\n tl_spec,\n n_samples,\n wins,\n losses,\n tles,\n labels,\n path=None):\n indices = np.arange(n_samples)\n width = 0.45\n\n p_wins = plt.bar(indices, wins, width=width, color=(0, 0, 0.8))\n p_losses = plt.bar(\n indices, losses, bottom=wins, width=width, color=(0.8, 0, 0))\n p_tles = plt.bar(\n indices, tles, width=width, bottom=wins + losses, color=(0.7, 0, 0.7))\n\n plt.ylabel('Partidas (em %)')\n plt.title(\n 'Performance de agentes em campo minado\\nTabuleiro {}x{}, {} Minas\\nTempo limite = {}s'.\n format(board_spec[0], board_spec[1], n_mines, tl_spec))\n plt.xticks(indices, labels)\n plt.yticks(np.arange(111, step=10), np.arange(101, step=10))\n plt.legend(\n (p_wins[0], p_losses[0], p_tles[0]), ('Vitorias', 'Derrotas',\n 'Tempo excedido'),\n loc='upper left')\n\n if path is None:\n path = '.'\n path = os.path.abspath(path)\n\n plt.savefig(\n os.path.join(path, 'b{}x{}-m{}-t{}.png'.format(\n board_spec[0], board_spec[1], n_mines, tl_spec)),\n bbox_inches='tight')\n\n\ndef beautify(user, heur):\n if user == 'user':\n user = 'Humano'\n elif user == 'logical':\n user = 'Logico'\n\n if heur is None:\n return user\n elif heur == 'model_counting':\n return user + ' com contagem de modelos'\n\n\ndef retrieve_data(folder_path, board_spec, n_mines, tl_spec):\n # inicializa listas\n n_samples = 0\n wins = []\n losses = []\n tles = []\n labels = []\n\n # itera sobre os jsons da pasta dada\n for filename in sorted(os.listdir(folder_path)):\n if filename.endswith('.json'):\n # abre arquivo json\n data = json.load(open(os.path.join(folder_path, filename)))\n\n # checa se conforma com especificacao dada\n if board_spec == data['board'] and n_mines == data['n_mines'] and tl_spec == data['time_limit']:\n # converte para porcentagem\n total = data['wins'] + data['losses'] + data['tles']\n\n # converte dados\n wins.append(100 * data['wins'] // total)\n losses.append(100 * data['losses'] // total)\n tles.append(100 * data['tles'] // total)\n labels.append(beautify(data['player_type'], data['heuristic']))\n n_samples += 1\n\n return n_samples, np.array(wins), np.array(losses), np.array(tles), labels\n\n\nif __name__ == '__main__':\n folder_path = sys.argv[1]\n save_path = sys.argv[2]\n\n for board_spec, n_mines, tl_spec in [([8, 8], 10, 59), ([8, 8], 10, 98),\n ([8, 8], 10, 136), ([8, 8], 10, 175)]:\n n_samples, wins, losses, tles, labels = retrieve_data(\n folder_path, board_spec, n_mines, tl_spec)\n plot(board_spec, n_mines, tl_spec, n_samples, wins, losses, tles, labels,\n save_path)\n"
] | [
[
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xticks",
"numpy.array",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jzuhone/kadi | [
"de4885327d256e156cfe42b2b1700775f5b4d6cf"
] | [
"kadi/commands/observations.py"
] | [
"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport os\nfrom collections import defaultdict\nimport logging\nfrom pathlib import Path\n\nimport numpy as np\nfrom cxotime import CxoTime\nimport astropy.units as u\nfrom astropy.table import Table, unique as table_unique\n\n# kadi.commands.commands_v2 is also a dependency but encapsulated in the\n# functions to reduce top-level imports for v1-compatibility\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = ['get_starcats', 'get_observations', 'get_starcats_as_table']\n\nAGASC_FILE = Path(os.environ['SKA'], 'data', 'agasc', 'proseco_agasc_1p7.h5')\n\nTYPE_MAP = ['ACQ', 'GUI', 'BOT', 'FID', 'MON']\nIMGSZ_MAP = ['4x4', '6x6', '8x8']\nRAD_TO_DEG = 180 / np.pi * 3600\nPAR_MAPS = [\n ('imnum', 'slot', int),\n ('type', 'type', lambda n: TYPE_MAP[n]),\n ('imgsz', 'sz', lambda n: IMGSZ_MAP[n]),\n ('maxmag', 'maxmag', float),\n ('yang', 'yang', lambda x: x * RAD_TO_DEG),\n ('zang', 'zang', lambda x: x * RAD_TO_DEG),\n ('dimdts', 'dim', int),\n ('restrk', 'res', int),\n]\n\n# Cache of observations by scenario\nOBSERVATIONS = {}\n\n# Cache of important columns in proseco_agasc_1p7.h5\nSTARS_AGASC = None\n\n\ndef set_detector_and_sim_offset(aca, simpos):\n \"\"\"Get detector from SIM position.\n\n Finds the detector with nominal SIM position closest to ``simpos``.\n Taken from fot_matlab_tools/MissionScheduling/axafutil/getSIFromPosition.m.\n\n :param aca: ACATable\n Input star catalog\n :param simpos: int, SIM position (steps)\n \"\"\"\n from proseco import characteristics_fid as FID\n sim_offsets = [simpos - simpos_nom for simpos_nom in FID.simpos.values()]\n idx = np.argmin(np.abs(sim_offsets))\n detector = list(FID.simpos.keys())[idx]\n sim_offset = sim_offsets[idx]\n aca.detector = detector\n aca.sim_offset = sim_offset\n\n\ndef set_fid_ids(aca):\n from proseco.fid import get_fid_positions\n from kadi.commands import conf\n fid_yangs, fid_zangs = get_fid_positions(\n detector=aca.detector, focus_offset=0, sim_offset=aca.sim_offset)\n\n idxs_aca = np.where(aca['type'] == 'FID')[0]\n for idx_aca in idxs_aca:\n yang = aca['yang'][idx_aca]\n zang = aca['zang'][idx_aca]\n dys = np.abs(yang - fid_yangs)\n dzs = np.abs(zang - fid_zangs)\n # Match fid positions in a box. Default is a very loose tolerance of 40\n # arcsec. The fids are widely spaced and there was a ~20 arcsec change\n # in fid positions in 2007.\n halfw = conf.fid_id_match_halfwidth\n idxs_fid = np.where((dys < halfw) & (dzs < halfw))[0]\n n_idxs_fid = len(idxs_fid)\n if n_idxs_fid == 1:\n aca[idx_aca]['id'] = idxs_fid[0] + 1\n aca[idx_aca]['mag'] = 7.0\n elif n_idxs_fid > 1:\n logger.warning(f'WARNING: found {n_idxs_fid} fids in obsid {aca.obsid} at '\n f'{aca.date}\\n{aca[idx_aca]}')\n # Note that no fids found happens normally for post SCS-107 observations\n # because the SIM is translated so don't warn in this case.\n\n\ndef set_star_ids(aca):\n \"\"\"Find the star ID for each star in the ACA.\n\n This set the ID in-place to the brightest star within 1.5 arcsec of the\n commanded position.\n\n :param aca: ACATable\n Input star catalog\n \"\"\"\n from chandra_aca.transform import radec_to_yagzag\n from Quaternion import Quat\n from kadi.commands import conf\n q_att = Quat(aca.att)\n stars = get_agasc_cone_fast(q_att.ra, q_att.dec, radius=1.2, date=aca.date)\n yang_stars, zang_stars = radec_to_yagzag(stars['RA_PMCORR'], stars['DEC_PMCORR'], q_att)\n idxs_aca = np.where(np.isin(aca['type'], ('ACQ', 'GUI', 'BOT')))[0]\n for idx_aca in idxs_aca:\n yang = aca['yang'][idx_aca]\n zang = aca['zang'][idx_aca]\n dys = np.abs(yang - yang_stars)\n dzs = np.abs(zang - zang_stars)\n\n # Get the brightest star within a box (default = 1.5 arcsec halfwidth)\n halfw = conf.star_id_match_halfwidth\n ok = (dys < halfw) & (dzs < halfw)\n if np.any(ok):\n idx = np.argmin(stars['MAG_ACA'][ok])\n aca[idx_aca]['id'] = stars['AGASC_ID'][ok][idx]\n aca[idx_aca]['mag'] = stars['MAG_ACA'][ok][idx]\n else:\n logger.info(f'WARNING: star idx {idx_aca + 1} not found in obsid {aca.obsid} at '\n f'{aca.date}')\n\n\ndef convert_aostrcat_to_acatable(obs, params, as_dict=False):\n \"\"\"Convert dict of AOSTRCAT parameters to an ACATable.\n\n The dict looks like::\n\n 2009:032:11:13:42.800 | 8023994 0 | MP_STARCAT | TLMSID= AOSTRCAT, CMDS=\n 49, IMNUM1= 0, YANG1= -3.74826751e-03, ZANG1= -8.44541515e-03, MAXMAG1=\n 8.00000000e+00, MINMAG1= 5.79687500e+00, DIMDTS1= 1, RESTRK1= 1, IMGSZ1=2,\n TYPE1= 3, ...\n\n IMNUM: slot\n RESTRK: box size resolution, always 1 (high) in loads for non-MON slot\n DIMDTS: (halfwidth - 20) / 5 # assumes AQRES='H'\n TYPE: 4 => mon, 3 => fid, 2 => bot, 1 => gui, 0 => acq\n YANG: yang in radians\n ZANG: zang in radians\n IMGSZ: 0=4x4, 1=6x6, 2=8x8\n MINMAG = min mag\n MAXMAG = max mag\n\n :param obs: dict of observation (OBS command) parameters\n :param params: dict of AOSTRCAT parameters\n :returns: ACATable\n \"\"\"\n from proseco.catalog import ACATable\n from proseco.acq import AcqTable\n from proseco.guide import GuideTable\n from Chandra.Time import date2secs\n\n for idx in range(1, 17):\n if params[f'minmag{idx}'] == params[f'maxmag{idx}'] == 0:\n break\n\n max_idx = idx\n cols = defaultdict(list)\n for par_name, col_name, func in PAR_MAPS:\n for idx in range(1, max_idx):\n cols[col_name].append(func(params[par_name + str(idx)]))\n\n aca = ACATable(cols)\n aca.acqs = AcqTable()\n aca.guides = GuideTable()\n aca.add_column(np.arange(1, max_idx), index=1, name='idx')\n\n aca.obsid = obs['obsid']\n aca.att = obs['targ_att']\n aca.date = obs['starcat_date']\n aca.duration = date2secs(obs['obs_stop']) - date2secs(obs['obs_start'])\n\n # Make the catalog more complete and provide stuff temps needed for plot()\n aca.t_ccd = -20.0\n aca.acqs.t_ccd = -20.0\n aca.guides.t_ccd = -20.0\n\n halfws = 20 + np.where(aca['res'], 5, 40) * aca['dim']\n halfws[aca['type'] == 'MON'] = 25\n aca['halfw'] = halfws\n\n return aca\n\n\ndef get_starcats_as_table(start=None, stop=None, *, obsid=None, unique=False,\n scenario=None, cmds=None):\n \"\"\"Get a single table of star catalog entries corresponding to input parameters.\n\n This function calls ``get_starcats`` with the same parameters and then\n concatenates the results into a single table for convenience. In addition\n to the usual star catalog columns, the ``obsid`` and ``starcat_date`` are\n included.\n\n The ``unique`` parameter can be set to ``True`` to only return unique star\n catalog entries. There are numerous instances of a single commanded star\n catalogs that is associated with two ObsIDs, for instance ACIS undercover\n observations. To get only the first one, set ``unique=True``.\n\n In the following example we get every unique commanded guide star in 2020\n and then join that with the corresponding observation information::\n\n >>> from kadi.commands import get_starcats_as_table, get_observations\n >>> from astropy import table\n >>> start='2020:001'\n >>> stop='2021:001'\n >>> aces = get_starcats_as_table(start, stop, unique=True)\n >>> ok = np.isin(aces['type'], ['GUI', 'BOT'])\n >>> guides = aces[ok]\n >>> obss = table.Table(get_observations(start, stop))\n >>> obss = obss[~obss['starcat_date'].mask] # keep only obs with starcat\n >>> guides = table.join(guides, obss, keys=['starcat_date', 'obsid'])\n\n :param start: CxoTime-like, None Start time (default=beginning of commands)\n :param stop: CxoTime-like, None Stop time (default=end of commands)\n :param obsid: int, None ObsID\n :param unique: bool, if True return remove duplicate entries\n :param scenario: str, None Scenario\n :param cmds: CommandTable, None Use this command table instead of querying\n the archive.\n :returns: astropy ``Table`` star catalog entries for matching observations.\n\n \"\"\"\n starcats = get_starcats(obsid=obsid, start=start, stop=stop, scenario=scenario,\n cmds=cmds, as_dict=True)\n out = defaultdict(list)\n for starcat in starcats:\n n_cat = len(starcat['slot'])\n out['obsid'].append([starcat['meta']['obsid']] * n_cat)\n out['starcat_date'].append([starcat['meta']['date']] * n_cat)\n for name, vals in starcat.items():\n if name != 'meta':\n out[name].append(vals)\n\n for name in out:\n out[name] = np.concatenate(out[name])\n\n out = Table(out)\n if unique:\n out = table_unique(out, keys=['starcat_date', 'idx'])\n\n return out\n\n\ndef get_starcats(start=None, stop=None, *, obsid=None, scenario=None,\n cmds=None, as_dict=False):\n \"\"\"Get a list of star catalogs corresponding to input parameters.\n\n The ``start``, ``stop`` and ``obsid`` parameters serve as matching filters\n on the list of star catalogs that is returned.\n\n By default the result is a list of ``ACATable`` objects similar to the\n output of ``proseco.get_aca_catalog``. If ``as_dict`` is ``True`` then the\n the result is a list of dictionaries with the same keys as the table columns.\n This is substantially faster than the default.\n\n There are numerous instances of multiple observations with the same obsid,\n so this function always returns a list of star catalogs even when ``obsid``\n is specified. In most cases you can just use the first element.\n\n The ``mag`` column corresponds to the AGASC magnitude *without* the AGASC\n supplement.\n\n Star ID's are determined by finding the brightest AGASC star within a search\n box centered at the catalog location. The search box is 1.5 arcsec halfwidth\n in size, but it can be changed by setting the ``star_id_match_halfwidth``\n configuration parameter. Fid ID's are determined similarly by computing fid\n locations given the commanded SIM-Z position. The default box size is 40\n arcsec halfwidth, but it can be changed by setting the\n ``fid_id_match_halfwidth`` configuration parameter.\n\n The first time each particular star catalog is fetched, the star and fid\n ID's are computed which is relatively slow. The resulting star catalog is\n (by default) cached in the ``~/.kadi/starcats.db`` file. Subsequent calls\n are significantly faster.\n\n Example::\n\n >>> from kadi.commands import get_starcats\n >>> cat = get_starcats(obsid=8008)[0]\n >>> cat\n [<ACATable length=11>\n slot idx id type sz mag maxmag yang zang dim res\n int64 int64 int64 str3 str3 float64 float64 float64 float64 int64 int64\n ----- ----- -------- ---- ---- ------- ------- -------- -------- ----- -----\n 0 1 1 FID 8x8 7.00 8.00 937.71 -829.17 1 1\n 1 2 5 FID 8x8 7.00 8.00 -1810.42 1068.87 1 1\n 2 3 6 FID 8x8 7.00 8.00 403.68 1712.93 1 1\n 3 4 31075128 BOT 6x6 9.35 10.86 -318.22 1202.41 20 1\n 4 5 31076560 BOT 6x6 9.70 11.20 -932.79 -354.55 20 1\n 5 6 31463496 BOT 6x6 9.46 10.97 2026.85 1399.61 20 1\n 6 7 31983336 BOT 6x6 8.64 10.14 890.71 -1600.39 20 1\n 7 8 32374896 BOT 6x6 9.17 10.66 2023.08 -2021.72 13 1\n 0 9 31075368 ACQ 6x6 9.13 10.64 54.04 754.79 20 1\n 1 10 31982136 ACQ 6x6 10.19 11.70 562.06 -186.39 20 1\n 2 11 32375384 ACQ 6x6 9.79 11.30 1612.28 -428.24 20 1]\n\n :param start: CxoTime-like, None Start time (default=beginning of commands)\n :param stop: CxoTime-like, None Stop time (default=end of commands)\n :param obsid: int, None ObsID\n :param scenario: str, None Scenario\n :param cmds: CommandTable, None Use this command table instead of querying\n the archive.\n :param as_dict: bool, False Return a list of dictionaries instead of a list\n of ACATable objects.\n :returns: list of ACATable List star catalogs for matching observations.\n \"\"\"\n import shelve\n from contextlib import ExitStack\n from kadi.commands.commands_v2 import REV_PARS_DICT\n from kadi.commands.core import decode_starcat_params\n from kadi.paths import STARCATS_CACHE_PATH\n from kadi.commands import conf\n from proseco.catalog import ACATable\n from proseco.acq import AcqTable\n from proseco.guide import GuideTable\n\n obss = get_observations(obsid=obsid, start=start, stop=stop,\n scenario=scenario, cmds=cmds)\n starcats = []\n rev_pars_dict = REV_PARS_DICT if cmds is None else cmds.rev_pars_dict()\n\n with ExitStack() as context_stack:\n if conf.cache_starcats:\n starcats_db = context_stack.enter_context(\n shelve.open(str(STARCATS_CACHE_PATH())))\n else:\n # Defining as a dict provides the same interface as shelve but\n # precludes caching.\n starcats_db = {}\n\n for obs in obss:\n if (idx := obs.get('starcat_idx')) is None:\n continue\n\n db_key = '{}-{}-{:05d}'.format(\n obs['starcat_date'], obs['source'], obs['obsid'])\n if db_key in starcats_db:\n # From the cache\n starcat_dict = starcats_db[db_key]\n if as_dict:\n starcat = starcat_dict\n else:\n meta = starcat_dict.pop('meta')\n starcat = ACATable(starcat_dict)\n starcat.meta = meta\n starcat.acqs = AcqTable()\n starcat.guides = GuideTable()\n else:\n # From the commands archive, building ACATable from backstop params\n params = rev_pars_dict[idx]\n if isinstance(params, bytes):\n params = decode_starcat_params(params)\n starcat = convert_aostrcat_to_acatable(obs, params)\n set_detector_and_sim_offset(starcat, obs['simpos'])\n starcat.add_column(-999, index=2, name='id')\n starcat.add_column(-999.0, index=5, name='mag')\n set_fid_ids(starcat)\n set_star_ids(starcat)\n\n starcat_dict = {name: starcat[name].tolist() for name in starcat.colnames}\n starcat_dict['meta'] = starcat.meta\n del starcat_dict['meta']['acqs']\n del starcat_dict['meta']['guides']\n\n if as_dict:\n starcat = starcat_dict\n\n starcats_db[db_key] = starcat_dict\n\n starcats.append(starcat)\n\n return starcats\n\n\ndef get_observations(start=None, stop=None, *, obsid=None, scenario=None, cmds=None):\n \"\"\"Get observations corresponding to input parameters.\n\n The ``start``, ``stop`` and ``obsid`` parameters serve as matching filters\n on the list of observations that is returned.\n\n Over the mission there are thousands of instances of multiple observations\n with the same obsid, so this function always returns a list of observation\n parameters even when ``obsid`` is specified. This most frequently occurs\n after any unexpected stoppage of the observng loads (SCS-107) which\n therefore cancels subsequent obsid commanding. In many cases you can just\n use the first element.\n\n Examples::\n\n >>> from kadi.commands import get_observations\n >>> obs = get_observations(obsid=8008)[0]\n >>> obs\n {'obsid': 8008,\n 'simpos': 92904,\n 'obs_stop': '2007:002:18:04:28.965',\n 'manvr_start': '2007:002:04:31:48.216',\n 'targ_att': (0.149614271, 0.490896707, 0.831470649, 0.21282047),\n 'npnt_enab': True,\n 'obs_start': '2007:002:04:46:58.056',\n 'prev_att': (0.319214732, 0.535685207, 0.766039803, 0.155969017),\n 'starcat_idx': 144398,\n 'source': 'DEC2506C'}\n\n >>> obs_all = get_observations() # All observations in commands archive\n\n # Might be convenient to handle this as a Table\n >>> from astropy.table import Table\n >>> obs_all = Table(obs_all)\n\n :param start: CxoTime-like, None\n Start time (default=beginning of commands)\n :param stop: CxoTime-like, None\n Stop time (default=end of commands)\n :param obsid: int, None\n ObsID\n :param scenario: str, None\n Scenario\n :param cmds: CommandTable, None\n Use this command table instead of querying the archive.\n :returns: list of dict\n Observation parameters for matching observations.\n \"\"\"\n from kadi.commands.commands_v2 import get_cmds\n start = CxoTime('1999:001' if start is None else start)\n stop = (CxoTime.now() + 1 * u.year) if stop is None else CxoTime(stop)\n\n if cmds is None:\n if scenario not in OBSERVATIONS:\n cmds = get_cmds(scenario=scenario)\n cmds_obs = cmds[cmds['tlmsid'] == 'OBS']\n obsids = []\n for cmd in cmds_obs:\n if cmd['params'] is None:\n _obsid = cmd['obsid']\n else:\n _obsid = cmd['params']['obsid']\n obsids.append(_obsid)\n\n cmds_obs['obsid'] = obsids\n OBSERVATIONS[scenario] = cmds_obs\n else:\n cmds_obs = OBSERVATIONS[scenario]\n else:\n cmds_obs = cmds[cmds['tlmsid'] == 'OBS']\n\n # Get observations in date range with padding\n i0, i1 = cmds_obs.find_date([(start - 7 * u.day).date,\n (stop + 7 * u.day).date])\n cmds_obs = cmds_obs[i0:i1]\n\n if obsid is not None:\n cmds_obs = cmds_obs[cmds_obs['obsid'] == obsid]\n if len(cmds_obs) == 0:\n raise ValueError(f'No matching observations for {obsid=}')\n\n obss = [cmd['params'].copy() for cmd in cmds_obs]\n for obs, cmd_obs in zip(obss, cmds_obs):\n obs['source'] = cmd_obs['source']\n\n # Filter observations by date to include any observation that intersects\n # the date range.\n datestart = start.date\n datestop = stop.date\n obss = [obs for obs in obss\n if obs['obs_start'] <= datestop and obs['obs_stop'] >= datestart]\n\n return obss\n\n\ndef get_agasc_cone_fast(ra, dec, radius=1.5, date=None):\n \"\"\"\n Get AGASC catalog entries within ``radius`` degrees of ``ra``, ``dec``.\n\n This is a fast version of agasc.get_agasc_cone() that keeps the key columns\n in memory instead of accessing the H5 file each time.\n\n :param dec: Declination (deg)\n :param radius: Cone search radius (deg)\n :param date: Date for proper motion (default=Now)\n\n :returns: astropy Table of AGASC entries\n \"\"\"\n global STARS_AGASC\n\n agasc_file = AGASC_FILE\n from agasc.agasc import get_ra_decs, sphere_dist, add_pmcorr_columns\n import tables\n\n ra_decs = get_ra_decs(agasc_file)\n\n if STARS_AGASC is None:\n with tables.open_file(agasc_file, 'r') as h5:\n dat = h5.root.data[:]\n cols = {'AGASC_ID': dat['AGASC_ID'],\n 'RA': dat['RA'],\n 'DEC': dat['DEC'],\n 'PM_RA': dat['PM_RA'],\n 'PM_DEC': dat['PM_DEC'],\n 'EPOCH': dat['EPOCH'],\n 'MAG_ACA': dat['MAG_ACA']}\n STARS_AGASC = Table(cols)\n del dat # Explicitly delete to free memory (?)\n\n idx0, idx1 = np.searchsorted(ra_decs.dec, [dec - radius, dec + radius])\n\n dists = sphere_dist(ra, dec, ra_decs.ra[idx0:idx1], ra_decs.dec[idx0:idx1])\n ok = dists <= radius\n stars = STARS_AGASC[idx0:idx1][ok]\n\n add_pmcorr_columns(stars, date)\n\n return stars\n"
] | [
[
"numpy.abs",
"numpy.arange",
"numpy.concatenate",
"numpy.argmin",
"numpy.any",
"numpy.searchsorted",
"numpy.where",
"numpy.isin"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jeromechiu/Travel_Salesman_Proble | [
"dd447600b8e1426d99f891936cd47bafff578417"
] | [
"travel_point_grouping.py"
] | [
"import numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\n\n\ndest_coord = [[0, (24.993484, 121.497134)], \n [1, (25.0007671, 121.4879088)], \n [3, (24.9986295, 121.5007544)], \n [2, (24.99663, 121.4869139)]]\n\ndef get_cartesian(lat=None,lon=None):\n lat, lon = np.deg2rad(lat), np.deg2rad(lon)\n R = 6371 # radius of the earth\n x = R * np.cos(lat) * np.cos(lon)\n y = R * np.cos(lat) * np.sin(lon)\n z = R *np.sin(lat)\n return x,y,z\n \n\ndef wgs84_to_cartesian(wgs84_points):\n cart_coord = dict()\n for i in range(len(wgs84_points)):\n id, (lat, long) = wgs84_points[i]\n x, y, z = get_cartesian(lat=lat,lon=long)\n cart_coord[id] = (x,y,z)\n return cart_coord\n\ndef grouping(cart_coord, wgs84_points=None):\n x = list()\n y= list()\n for i in cart_coord.keys():\n x.append(cart_coord[i][0])\n y.append(cart_coord[i][1])\n df = pd.DataFrame(\n {\n 'x':x,\n 'y':y\n }\n )\n \n kmeans = KMeans(n_clusters=3)\n kmeans.fit(df)\n labels = kmeans.predict(df)\n centroids = kmeans.cluster_centers_\n \n \n colmap = {1:'r',2:'g',3:'b'}\n fig = plt.figure(figsize=(5,5))\n colors = map(lambda x: colmap[x+1], labels)\n \n plt.scatter(df['x'], df['y'], color=list(colors), alpha=0.5, edgecolor='k')\n for idx, centroid in enumerate(centroids):\n plt.scatter(*centroid, color=colmap[idx+1])\n plt.xlim(df['x'].min()-1, df['x'].max()+1)\n plt.ylim(df['y'].min()-1, df['y'].max()+1)\n plt.show()\n \n # print(wgs84_points)\n \n df['id'] = cart_coord.keys()\n df['group'] = labels\n \n if wgs84_points != None:\n df.set_index('id', inplace=True)\n for i in range(len(wgs84_points)):\n id, (lat, long) = wgs84_points[i]\n df.loc[id,'lat'] = lat\n df.loc[id, 'long'] = long\n return df\n \n \n \n"
] | [
[
"sklearn.cluster.KMeans",
"matplotlib.pyplot.scatter",
"numpy.cos",
"pandas.DataFrame",
"numpy.sin",
"numpy.deg2rad",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
armsp/covid19-vis | [
"18fb10ab100bae13033b3a033b6612a8dab10d53"
] | [
"map.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\nimport glob\nfrom datetime import date\n#import webbrowser\nimport pandas as pd\nimport folium\nfrom folium import plugins\nmap_kwargs = {\"zoomSnap\": 0.5}\nm = folium.Map(location=[22.7041, 79.1025], tiles='CartoDB Positron', zoom_start=4.5, **map_kwargs)#, prefer_canvas=True)\n\nlist_of_files = glob.glob('./datasets/statewise_distribution/*.csv') # * means all if need specific format then *.csv\n#latest_file = max(list_of_files, key=lambda x: x.split('.')[1].split('-')[2])\n#print(list_of_files)\nsorted_files = sorted(list_of_files, key=lambda d: tuple(map(int, d.split('/')[-1].split('.')[0].split('-'))))\n#print(latest_file)\n#data_file = f'./datasets/statewise_distribution/{str(date.today())}.csv'\ndata_file = sorted_files[-1]\ndf = pd.read_csv(data_file)\nkwargs = {'stroke': True, 'weight': 1.5, 'opacity': 0.8, 'bubblingMouseEvents': False}\n#https://leafletjs.com/reference-1.3.4.html#path-weight\nfor lon, lat, territory, cases, recovered, deaths in zip(list(df['Lon']), list(df['Lat']), list(df.iloc[:,1]), list(df.iloc[:,2]), list(df.iloc[:,3]), list(df.iloc[:,4])):\n popup_html=f\"\"\"\n<table border-spacing: 0; border-collapse: collapse; display: block; width: 100%; overflow: auto;\">\n <thead>\n <tr>\n <th colspan=\"3\" style=\"padding: 6px 13px;font-weight: 600; border: 1px solid #dfe2e5;\">{territory}</th>\n </tr>\n <tr style=\"border-top: 1px solid #c6cbd1; background-color: #fff; font-weight: bolder;\">\n <td style=\"color: darkorange; padding: 0px 5px;\n border: 1px solid #dfe2e5;\">Active Cases</td>\n <td style=\"padding: 0px 5px; color: red;\n border: 1px solid #dfe2e5;\">Deaths</td>\n <td style=\"padding: 0px 5px; color: mediumseagreen;\n border: 1px solid #dfe2e5;\">Recovered</td>\n </tr>\n </thead>\n <tbody>\n <tr style=\"border-top: 1px solid #c6cbd1; background-color: #fff; font-weight: bolder;\">\n <td style=\"padding: 6px 13px;\n border: 1px solid #dfe2e5;\">{cases}</td>\n <td style=\"padding: 6px 13px;\n border: 1px solid #dfe2e5;\">{deaths}</td>\n <td style=\"padding: 6px 13px;\n border: 1px solid #dfe2e5;\">{recovered}</td>\n </tr>\n </tbody>\n</table>\n\"\"\"\n folium.Circle(radius = (int(cases))*50,location=[lat, lon],color='crimson',fill=True,popup=folium.Popup(popup_html),**kwargs).add_to(m)\n\nplugins.ScrollZoomToggler().add_to(m)\n #folium.CircleMarker(\n # location=[lat, lon],\n # radius=(ind+forei)/4,\n # #popup='Laurelhurst Park',\n # color='crimson',\n # fill=True,\n # fill_color='crimson',\n # **kwargs\n #).add_to(m)\nm.save('foliummap.html')\n#webbrowser.open('foliummap.html')"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
KAIST-AILab/End-to-End-Enc-Dec_DSTC9 | [
"43882de251866c3793009293c7d190c0a3714797"
] | [
"gpt2/models.py"
] | [
"from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss\nimport torch.nn as nn\nfrom transformers import GPT2Model, GPT2PreTrainedModel\nfrom transformers.modeling_utils import SequenceSummary\n\n\nclass GPT2End2EndModel(GPT2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n config.num_labels = 1\n self.transformer = GPT2Model(config)\n self.detection_head = SequenceSummary(config)\n self.selection_head = SequenceSummary(config)\n self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n\n self.init_weights()\n self.task = 'generation' # None, 'detection', 'selection', 'generation'\n\n def get_task(self):\n return self.task\n\n def set_task(self, task=None):\n if task not in ['detection', 'selection', 'generation']:\n task = None\n self.task = task\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def forward(\n self,\n input_ids=None,\n past=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n mc_token_ids=None,\n labels=None,\n reduction='mean',\n use_cache=True,\n ):\n \"\"\"\n input_ids: `torch.LongTensor` of shape (bach_size, sequence_length) for detection and generation and (batch_size, num_candidates, sequence_length) for selection.\n Input sequence tokens.\n mc_token_ids: `torch.LongTensor` of shape (batch_size,) for detection and (batch_size, num_candidates) for selection.\n Indices of the classification token in each input sequence for detection or selection task.\n labels: `torch.LongTensor` of shape (bach_size,) for detection and selection and (batch_size, sequence_length) for generation.\n Labels for each task.\n For detection task, labels should be 0 or 1.\n For selection task, labels should be in [0, num_candidates) where `num_candidates` is the size of the second dimension of the input tensors.\n For generation task, all labels set to ``-100`` are ignored (masked).\n\n Return:\n loss (optional, returned when `labels` is provided): scalar `torch.FloatTensor`.\n Loss for the task.\n prediction_scores: `torch.FloatTensor` of shape (batch_size,) for detection, (batch_size, num_candidates) for selection and (batch_size, sequence_length, config.vocab_size) for generation.\n Prediction scores for the task.\n past: `List[torch.FloatTensor]` of length `config.n_layers`.\n Contains pre-computed hidden-states (key and values in the attention blocks).\n hidden_states (optional, returned when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer).\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (optional, returned when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n \"\"\"\n if self.task == 'selection':\n batch_size, n_cand = input_ids.shape[:2]\n input_ids = input_ids.view(batch_size * n_cand, -1)\n token_type_ids = token_type_ids.view(batch_size * n_cand, -1)\n\n transformer_outputs = self.transformer(\n input_ids,\n past=past,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n use_cache=use_cache,\n )\n if self.task is None:\n return transformer_outputs\n hidden_states = transformer_outputs[0]\n\n if self.task == 'detection':\n outputs = self._forward_detection_head(\n hidden_states, mc_token_ids, labels, reduction)\n elif self.task == 'selection':\n hidden_states = hidden_states.view(\n batch_size, n_cand, -1, hidden_states.shape[-1])\n outputs = self._forward_selection_head(\n hidden_states, mc_token_ids, labels, reduction)\n else:\n outputs = self._forward_generation_head(\n hidden_states, labels, reduction)\n outputs = outputs + transformer_outputs[1:]\n # (loss), logits, presents, (all hidden_states), (attentions)\n return outputs\n\n def _forward_detection_head(self, hidden_states, mc_token_ids, labels=None, reduction='mean'):\n logits = self.detection_head(hidden_states, mc_token_ids).squeeze(-1)\n outputs = (logits,)\n if labels is not None:\n loss_fct = BCEWithLogitsLoss(reduction=reduction)\n loss = loss_fct(logits, labels)\n outputs = (loss,) + outputs\n return outputs\n\n def _forward_selection_head(self, hidden_states, mc_token_ids, labels=None, reduction='mean'):\n logits = self.selection_head(hidden_states, mc_token_ids).squeeze(-1)\n outputs = (logits,)\n if labels is not None:\n loss_fct = BCEWithLogitsLoss(reduction=reduction)\n loss = loss_fct(logits, labels.float())\n outputs = (loss,) + outputs\n return outputs\n\n def _forward_generation_head(self, hidden_states, labels=None, reduction='mean'):\n logits = self.lm_head(hidden_states)\n outputs = (logits,)\n if labels is not None:\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n _logits = shift_logits.view(-1, shift_logits.size(-1))\n _labels = shift_labels.view(-1)\n\n loss_fct = CrossEntropyLoss(reduction=reduction)\n loss = loss_fct(_logits, _labels)\n outputs = (loss,) + outputs\n return outputs\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.nn.Linear",
"torch.nn.BCEWithLogitsLoss"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lehy/chainertools | [
"0df54f10a7ef5624380fbcdb180d59fa121d910d"
] | [
"chainertools/train.py"
] | [
"import gc\nimport os\nimport copy\nimport glob\nimport chainer\nimport logging\nimport functools\nimport numpy as np\nimport pandas as pd\nfrom . import utils\n\nlog = logging.getLogger(__name__)\n\n\nclass OnlineEvaluator(chainer.training.extensions.Evaluator):\n \"\"\"An evaluator that evaluates one batch at a time.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(OnlineEvaluator, self).__init__(*args, **kwargs)\n\n @staticmethod\n def _reset_iterator(iterator):\n if hasattr(iterator, 'reset'):\n iterator.reset()\n return iterator\n else:\n return copy.copy(iterator)\n\n def evaluate(self):\n iterator = self._iterators['main']\n eval_func = self.eval_func or self._targets['main']\n if self.eval_hook:\n self.eval_hook(self)\n try:\n batch = next(iterator)\n except StopIteration:\n iterator = self._reset_iterator(iterator)\n batch = next(iterator)\n\n summary = chainer.reporter.DictSummary()\n\n observation = {}\n with chainer.reporter.report_scope(observation):\n in_arrays = self.converter(batch, self.device)\n with chainer.function.no_backprop_mode():\n if isinstance(in_arrays, tuple):\n eval_func(*in_arrays)\n elif isinstance(in_arrays, dict):\n eval_func(**in_arrays)\n else:\n eval_func(in_arrays)\n\n summary.add(observation)\n\n return summary.compute_mean()\n\n\n# Note that there is a TimeTrigger in chainer, and it probably does\n# exactly this.\nclass TimeTrigger(object):\n def __init__(self, period_s):\n self.period_s = period_s\n self.t_last_triggered = None\n\n def __call__(self, trainer):\n t = trainer.elapsed_time\n if self.t_last_triggered is None or (\n t - self.t_last_triggered) > self.period_s:\n self.t_last_triggered = t\n return True\n else:\n return False\n\n def serialize(self, serializer):\n self.period_s = serializer('period_s', self.period_s)\n self.t_last_triggered = serializer('t_last_triggered',\n self.t_last_triggered)\n\n\ndef trigger_every_iteration_until(max_iterations=256):\n def f(trainer):\n iteration = trainer.updater.iteration\n if iteration < max_iterations:\n return True\n else:\n if iteration == max_iterations:\n log.info(\"reached maximum iterations for printing: %d\",\n max_iterations)\n return False\n\n return f\n\n\ndef extend_log_print(trainer):\n optimizer = trainer.updater.get_optimizer('main')\n\n hyperparams = list(optimizer.hyperparam.get_dict().keys())\n\n for hyperparam in hyperparams:\n\n def getter(trainer, h=hyperparam):\n return getattr(optimizer, h)\n\n trainer.extend(\n chainer.training.extensions.observe_value(hyperparam, getter),\n trigger=(1, 'iteration'))\n\n trainer.extend(\n chainer.training.extensions.observe_value(\n 'finetune',\n lambda _trainer: getattr(chainer.config, 'finetune', False)),\n trigger=(1, 'iteration'))\n\n def get_batch_size(trainer):\n return trainer.updater.get_iterator('main').batch_size\n\n trainer.extend(\n chainer.training.extensions.observe_value('batch_size',\n get_batch_size),\n trigger=(1, 'iteration'))\n\n # This sends observations to the log. The trigger passed to the\n # LogReport init is how often the log is written. Observations are\n # still collected every iteration (which is the default trigger\n # used by extend()).\n trainer.extend(\n chainer.training.extensions.LogReport(trigger=(20, 'iteration')))\n\n # This prints observations to the console.\n observed_variables = [\n 'elapsed_time',\n 'epoch',\n 'iteration',\n 'main/loss',\n 'validation/main/loss',\n 'finetune',\n 'batch_size',\n ] + hyperparams\n model = trainer.updater.get_optimizer('main').target\n if getattr(model, 'compute_accuracy', False):\n observed_variables += ['main/accuracy', 'validation/main/accuracy']\n\n # There is not much sense setting this to a TimeTrigger, since it\n # displays all logged entries since the last time, not one every\n # time it wakes up. TODO: wake up a few times at the beginning\n # every n iterations (or n seconds), then once every epoch (or\n # every 30 mn).\n trainer.extend(\n chainer.training.extensions.PrintReport(observed_variables),\n trigger=trigger_every_iteration_until(128))\n # trigger=(1, 'iteration'))\n\n\ndef extend_evaluation(trainer, iterator, validation_dataset,\n validation_batch_size, evaluation_factor):\n train_batch_size = trainer.updater.get_iterator('main').batch_size\n validation_iter = iterator(\n validation_dataset,\n batch_size=validation_batch_size,\n repeat=False,\n shuffle=False)\n trigger_evaluation = (max(\n int(validation_batch_size / (train_batch_size * evaluation_factor)),\n 1), 'iteration')\n model = trainer.updater.get_optimizer('main').target\n device = getattr(model, '_device_id', None)\n trainer.extend(\n OnlineEvaluator(validation_iter, model, device=device),\n trigger=trigger_evaluation)\n\n\nclass SnapshotOnFinalize(chainer.training.Extension):\n \"\"\"Extension to take a snapshot when training ends.\n\n This triggers even when training is interrupted with C-c.\n \"\"\"\n\n def __init__(self):\n self.trainer = None\n\n def initialize(self, trainer):\n log.info(\"setting up trainer snapshot on finalization\")\n self.trainer = trainer\n gc.collect(\n ) # not a logical place, but potentially useful and harmless\n\n def __call__(self, trainer):\n self.trainer = trainer\n\n def finalize(self):\n \"\"\"XXX TODO check that the written snapshot is reasonable (ie it\n includes a full model).\n \"\"\"\n log.info(\"saving final trainer state\")\n # Save with a different prefix than regular snapshots, to\n # avoid clobbering one of them. We might also want to avoid\n # snapshotting if the model is not initialized.\n chainer.training.extensions.snapshot(\n filename=\"f_snapshot_iter_{.updater.iteration}\")(self.trainer)\n\n\ndef extend_snapshot(trainer):\n # this saves the complete trainer object\n trainer.extend(\n chainer.training.extensions.snapshot(), trigger=TimeTrigger(30 * 60))\n trainer.extend(SnapshotOnFinalize(), trigger=lambda _trainer: False)\n\n\ndef resume_from_snapshot(trainer, snapshot=None):\n gc.collect()\n # Run one dummy update to make sure all parameters that need to be\n # reloaded are created. The reporter thing is the minimal thing\n # that seems necessary for update() to run without problems. (This\n # is copied from the Trainer code.)\n reporter = chainer.reporter.Reporter()\n optimizer = trainer.updater.get_optimizer('main')\n reporter.add_observer('main', optimizer.target)\n reporter.add_observers('main', optimizer.target.namedlinks(skipself=True))\n with reporter.scope({}):\n trainer.updater.update()\n\n if snapshot is None:\n # Using \"snapshot_iter*\" to NOT get the automatic interruption\n # snapshots, which are for the moment sometimes empty if we have a\n # crash before optim starts. The real fix would be to ensure that\n # finalize() snapshots are always valid when writing them.\n snapshots = glob.glob(os.path.join(trainer.out, \"snapshot_iter_*\"))\n if not snapshots:\n log.info(\"did not find snapshot to resume from in directory %s\",\n trainer.out)\n return\n sorted_snapshots = pd.Series(snapshots).str.extract(\n r'^(?P<file>.*/[^/]*snapshot_iter_0*(?P<iteration>\\d+))$')\n sorted_snapshots['iteration'] = sorted_snapshots.iteration.astype(int)\n sorted_snapshots = sorted_snapshots.sort_values(\"iteration\").reset_index(\n drop=True)\n if sorted_snapshots.iteration.iloc[-1] == 0:\n return\n log.info(\"latest available snapshots:\\n%s\", sorted_snapshots.tail(7))\n snapshot = sorted_snapshots.file.iloc[-1]\n\n log.info(\"resuming from snapshot %s\", snapshot)\n chainer.serializers.load_npz(snapshot, trainer)\n\n\ndef create_iterator(name_or_iterator):\n d = dict(\n serial=chainer.iterators.SerialIterator,\n multiprocess=chainer.iterators.MultiprocessIterator,\n multithread=functools.partial(\n chainer.iterators.MultithreadIterator, n_threads=8))\n if name_or_iterator in d:\n return d[name_or_iterator]\n else:\n log.info(\"iterator is not in %s, using iterator as passed: %s\",\n list(d.keys()), name_or_iterator)\n return name_or_iterator\n\n\ndef create_model_with_loss(predictor, classifier, loss_fun, accuracy_fun):\n if classifier is None:\n log.info(\n \"classifier is None, assuming predictor already outputs a loss\")\n return predictor\n\n kwargs = {}\n if loss_fun is not None:\n kwargs['lossfun'] = loss_fun\n\n if accuracy_fun is not None:\n kwargs['accfun'] = accuracy_fun\n\n model = classifier(predictor, **kwargs)\n if 'accfun' not in kwargs:\n log.info('accuracy_fun not passed, disabling accuracy')\n model.compute_accuracy = False\n\n return model\n\n\ndef trainer(predictor,\n data,\n name,\n train_batch_size=128,\n validation_batch_size=None,\n optimizer=None,\n iterator='multithread',\n classifier=chainer.links.Classifier,\n evaluation_factor=0.1,\n loss_fun=None,\n accuracy_fun=None,\n device=0):\n \"\"\"evaluation_factor: evaluate this many samples for each sample\n trained\n \"\"\"\n gc.collect()\n iterator = create_iterator(iterator)\n\n model = create_model_with_loss(predictor, classifier, loss_fun,\n accuracy_fun)\n model.to_gpu(device=device)\n\n if optimizer is None:\n log.warning(\"no optimizer given, using default Adam (no weight decay)\")\n optimizer = chainer.optimizers.Adam()\n optimizer.setup(model)\n\n train_iter = iterator(\n data.train, batch_size=train_batch_size, shuffle=True)\n updater = chainer.training.StandardUpdater(\n train_iter, optimizer, device=device)\n\n name = \"{}-{}-batch{}\".format(name, predictor.__class__.__name__,\n train_batch_size)\n log.info(\"saving model as: %s\", name)\n trainer = chainer.training.Trainer(updater, out=name)\n\n if validation_batch_size is None:\n validation_batch_size = train_batch_size\n extend_evaluation(trainer, iterator, data.validation,\n validation_batch_size, evaluation_factor)\n\n extend_log_print(trainer)\n extend_snapshot(trainer)\n\n return trainer\n\n\nclass UpDownLr(chainer.training.Extension):\n \"\"\"2 epochs going up from max_lr/10 to max_lr, then plateaus of\n constant lr, reduced by 0.3 every 10 epochs. finetune mode after\n 4 cycles of 10 epochs. Optimizer is reset using\n optim.setup(target) at the beginning of each cycle.\n \"\"\"\n\n def __init__(self,\n max_lr,\n factor_min_lr=0.1,\n num_epochs_to_max=2,\n num_epochs_reduce=6,\n reduction=0.3,\n cycles_before_finetune=-1,\n lr_attribute=None):\n super().__init__()\n self.max_lr = max_lr\n self.factor_min_lr = factor_min_lr\n self.num_epochs_to_max = num_epochs_to_max\n self.num_epochs_reduce = num_epochs_reduce\n self.reduction = reduction\n self.lr_attribute = lr_attribute\n self.cycles_before_finetune = cycles_before_finetune\n self.base_iteration = 0\n self.info_emitted = False\n\n def initialize(self, trainer):\n # this is called also after deserializing, keep the current state!\n self(trainer)\n\n def __call__(self, trainer):\n optimizer = trainer.updater.get_optimizer('main')\n train_iter = trainer.updater.get_iterator('main')\n\n iteration = self.base_iteration + optimizer.t\n size_epoch_samples = len(train_iter.dataset)\n batch_size = train_iter.batch_size\n size_epoch_iterations = size_epoch_samples / batch_size\n\n iterations_go_up = self.num_epochs_to_max * size_epoch_iterations\n iterations_constant = self.num_epochs_reduce * size_epoch_iterations\n iterations_before_finetune = (\n self.cycles_before_finetune * self.num_epochs_reduce *\n size_epoch_iterations)\n\n min_lr = self.factor_min_lr * self.max_lr\n\n if not self.info_emitted:\n log.info(\"epoch: %d samples, %d iterations (batch size: %d)\",\n size_epoch_samples, size_epoch_iterations, batch_size)\n log.info(\n \"initial linear scale up of lr \" +\n \"from %g to %g in %g epochs (%g iterations)\", min_lr,\n self.max_lr, self.num_epochs_to_max, iterations_go_up)\n log.info(\n \"then lr has plateaus of %g epochs (%g iterations)\" +\n \", reduced each time by %g\", self.num_epochs_reduce,\n iterations_constant, self.reduction)\n self.info_emitted = True\n\n if iteration < iterations_go_up:\n lr = min_lr + (\n self.max_lr - min_lr) * iteration / float(iterations_go_up)\n else:\n cycle_index = (iteration - iterations_go_up) // iterations_constant\n lr = self.max_lr * (self.reduction**cycle_index)\n\n finetune = (iterations_before_finetune > 0 and (\n (iteration - iterations_go_up) > iterations_before_finetune))\n\n if self.lr_attribute is None:\n if isinstance(optimizer, chainer.optimizers.Adam):\n log.debug(\"detected Adam optimizer, adapting eta\")\n self.lr_attribute = 'eta'\n elif utils.safe_hasattr(optimizer, 'lr'):\n log.debug(\"detected optimizer with lr attribute, adapting lr\")\n self.lr_attribute = 'lr'\n else:\n raise ValueError(\"optimizer has neither lr nor alpha\" +\n \", you must specify lr_attribute at init\")\n\n # Reset the optimizer (Adam state for instance) if at the\n # beginning of a cycle (not the first one though).\n if (iteration > iterations_go_up and lr != self.current_lr(optimizer)):\n log.info(\n \"beginning new cycle with %s = %g (current: %g),\" +\n \" resetting optimizer\", self.lr_attribute, lr,\n self.current_lr(optimizer))\n # Calling setup() resets optimizer.t to zero. Make sure we\n # remember the correct number of iterations done until\n # this point.\n self.base_iteration = iteration\n optimizer.setup(optimizer.target)\n\n self.set_lr(optimizer, lr)\n if getattr(chainer.config, 'finetune', None) != finetune:\n log.info(\"setting finetune=%s\", finetune)\n chainer.config.finetune = finetune\n\n def current_lr(self, optimizer):\n return getattr(optimizer, self.lr_attribute)\n\n def set_lr(self, optimizer, lr):\n setattr(optimizer, self.lr_attribute, lr)\n\n def serialize(self, serializer):\n self.max_lr = serializer('max_lr', self.max_lr)\n self.factor_min_lr = serializer('factor_min_lr', self.factor_min_lr)\n self.num_epochs_to_max = serializer('num_epochs_to_max',\n self.num_epochs_to_max)\n self.num_epochs_reduce = serializer('num_epochs_reduce',\n self.num_epochs_reduce)\n self.reduction = serializer('reduction', self.reduction)\n self.cycles_before_finetune = serializer('cycles_before_finetune',\n self.cycles_before_finetune)\n # Need str() because otherwise we get an ndarray of chars and\n # getattr does not like that.\n self.lr_attribute = str(serializer('lr_attribute', self.lr_attribute))\n self.base_iteration = serializer('base_iteration', self.base_iteration)\n\n\ndef lr_find(\n model,\n datasets,\n start_lr=1e-7,\n end_lr=10,\n num_iter=100,\n num_points=100,\n batch_size=1,\n # test_batch_size=1,\n out='lr_find',\n lr_variable='lr',\n optimizer=None,\n use_validation=False,\n weight_decay=None):\n gc.collect()\n\n model.to_gpu()\n if optimizer is None:\n optimizer = chainer.optimizers.MomentumSGD(lr=start_lr, momentum=0.9)\n optimizer.setup(model)\n\n if weight_decay is not None:\n # This needs to be after the setup() call above.\n optimizer.add_hook(chainer.optimizer.WeightDecay(rate=weight_decay))\n\n out = \"{}_batch{}_{}\".format(out, batch_size, optimizer.__class__.__name__)\n log.info(\"lr_find: output directory: %s\", out)\n\n train_iter = chainer.iterators.SerialIterator(\n datasets.validation, batch_size=batch_size)\n\n updater = chainer.training.updater.StandardUpdater(\n train_iter,\n optimizer,\n # converter=fcis_concat_examples,\n device=0)\n\n trainer = chainer.training.Trainer(\n updater, (num_iter, 'iteration'), out=out)\n\n # lr scheduler\n ratio = (end_lr / start_lr)**(1. / num_points)\n trainer.extend(\n chainer.training.extensions.ExponentialShift(\n lr_variable, ratio, init=start_lr),\n trigger=(max(1, num_iter // num_points), 'iteration'))\n\n if use_validation:\n val_iter = chainer.iterators.SerialIterator(\n datasets.validation,\n batch_size=batch_size,\n repeat=False,\n shuffle=False)\n trainer.extend(\n OnlineEvaluator(val_iter, model, device=0),\n trigger=(1, 'iteration'))\n loss_key = 'validation/main/loss'\n else:\n loss_key = 'main/loss'\n\n # training extensions\n # trainer.extend(\n # chainer.training.extensions.observe_lr(), trigger=(1, 'iteration'))\n trainer.extend(\n chainer.training.extensions.observe_value(\n lr_variable, lambda _: getattr(optimizer, lr_variable)),\n trigger=(1, 'iteration'))\n trainer.extend(\n chainer.training.extensions.LogReport(\n log_name='log.json', trigger=(1, 'iteration')))\n\n lowest_loss = [np.inf]\n\n def stop_on_nan(trainer):\n # log.info(list(trainer.observation.keys()))\n # loss = chainer.cuda.to_cpu(trainer.observation[loss_key].data)\n loss = trainer.observation[loss_key].get()\n if loss < lowest_loss[0]:\n lowest_loss[0] = loss\n if loss > (100. * lowest_loss[0]) or not np.isfinite(loss):\n log.warning(\n \"loss has diverged (current: %g, lowest: %g)\" +\n \", stopping training\", loss, lowest_loss[0])\n # assigning to trainer.trigger does nothing\n trainer.stop_trigger.unit = 'iteration'\n trainer.stop_trigger.period = 1\n\n trainer.extend(stop_on_nan, name='stop_on_nan')\n trainer.extend(\n chainer.training.extensions.PrintReport([\n 'iteration',\n # 'epoch',\n 'elapsed_time',\n lr_variable,\n 'main/loss',\n 'validation/main/loss',\n # 'main/rpn_loc_loss',\n # 'main/rpn_cls_loss',\n # 'main/roi_loc_loss',\n # 'main/roi_cls_loss',\n # 'main/roi_mask_loss',\n # 'validation/main/map',\n ]),\n trigger=(1, 'iteration'))\n # trainer.extend(chainer.training.extensions.ProgressBar(update_interval=1))\n trainer.run()\n return trainer\n"
] | [
[
"pandas.Series",
"numpy.isfinite"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
samchan2022/pytorch | [
"bcf6974c207ac0339bfb8bdfdb0b0ec348f7a22f"
] | [
"test/test_torch.py"
] | [
"# -*- coding: utf-8 -*-\n# Owner(s): [\"module: tests\"]\n\nimport torch\nimport torch.utils.data\nimport numpy as np\n\nimport contextlib\nimport gc\nimport io\nimport inspect\nimport itertools\nimport math\nimport random\nimport re\nimport copy\nimport os\nimport tempfile\nimport unittest\nimport warnings\nimport types\nimport pickle\nimport textwrap\nimport subprocess\nimport weakref\nimport sys\nfrom torch.utils.dlpack import from_dlpack, to_dlpack\nfrom torch._six import inf, nan, string_classes\nfrom itertools import product, combinations, permutations\nfrom functools import partial\nfrom torch import multiprocessing as mp\nfrom torch.testing import make_tensor\nfrom torch.testing._internal.common_utils import (\n TestCase, TEST_WITH_ROCM, run_tests,\n IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN,\n IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, load_tests, slowTest,\n skipCUDAMemoryLeakCheckIf, BytesIOContext, noarchTest,\n skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName,\n wrapDeterministicFlagAPITest, DeterministicGuard, CudaSyncGuard,\n skipIfNotRegistered, bytes_to_scalar, parametrize)\nfrom multiprocessing.reduction import ForkingPickler\nfrom torch.testing._internal.common_device_type import (\n expectedFailureMeta,\n expectedFailureXLA,\n instantiate_device_type_tests,\n skipCUDAVersionIn,\n onlyCUDA, onlyCPU,\n dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast,\n skipMeta,\n PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyNativeDeviceTypes,\n expectedAlertNondeterministic, get_all_device_types, skipXLA)\nfrom typing import Tuple\nimport torch.backends.quantized\nimport torch.testing._internal.data\nfrom torch.testing._internal.common_cuda import (\n tf32_on_and_off, tf32_is_not_fp32, TEST_CUDNN)\nfrom torch.testing._internal.common_dtype import (\n floating_types_and, get_all_math_dtypes, all_types_and_complex_and, complex_types,\n all_types_and, floating_types, floating_and_complex_types, integral_types,\n)\n\n# Protects against includes accidentally setting the default dtype\nassert torch.get_default_dtype() is torch.float32\n\n# load_tests from torch.testing._internal.common_utils is used to automatically filter tests for\n# sharding on sandcastle. This line silences flake warnings\nload_tests = load_tests\n\nAMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32()\n\[email protected]\ndef torch_vital_set(value):\n stash = None\n if 'TORCH_VITAL' in os.environ:\n stash = os.environ['TORCH_VITAL']\n os.environ['TORCH_VITAL'] = value\n try:\n yield\n finally:\n if stash:\n os.environ['TORCH_VITAL'] = stash\n else:\n del os.environ['TORCH_VITAL']\n\n# Tests Vital Signs for Torch\n# FIXME: document or deprecate whatever this is\nclass TestBasicVitalSigns(TestCase):\n def test_basic_vitals(self):\n with torch_vital_set(''):\n self.assertFalse(torch.vitals_enabled())\n with torch_vital_set('ON'):\n self.assertTrue(torch.vitals_enabled())\n\n def test_basic_vitals_read_write(self):\n with torch_vital_set('ON'):\n self.assertTrue(torch.vitals_enabled())\n # This tests the code path of setting a vital\n self.assertTrue(torch.set_vital('Dataloader', 'basic_unit_test', 'TEST_VALUE_STRING'))\n self.assertIn('TEST_VALUE_STRING', torch.read_vitals())\n self.assertIn('CUDA.used', torch.read_vitals())\n\n def test_dataloader_vitals(self):\n with torch_vital_set('ON'):\n inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)\n tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)\n dataset = torch.utils.data.TensorDataset(inps, tgts)\n loader = torch.utils.data.DataLoader(dataset, batch_size=2)\n self.assertIn('Dataloader.enabled\\t\\t True', torch.read_vitals())\n\n# FIXME: document or deprecate whatever this is\nclass TestVitalSignsCuda(TestCase):\n @onlyCUDA\n def test_cuda_vitals_gpu_only(self, device):\n with torch_vital_set('ON'):\n self.assertIn('CUDA.used\\t\\t true', torch.read_vitals())\n\n\nclass TestTorchDeviceType(TestCase):\n exact_dtype = True\n\n # TODO: move all tensor creation to common ops\n def _rand_shape(self, dim, min_size, max_size):\n shape = []\n for i in range(dim):\n shape.append(random.randint(min_size, max_size))\n return tuple(shape)\n\n # Validates that mathematical constants are defined properly, as required by\n # the Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html)\n @onlyCPU\n def test_constants(self, device):\n self.assertIsInstance(torch.e, float)\n self.assertEqual(torch.e, math.e, atol=0, rtol=0)\n\n self.assertIsInstance(torch.pi, float)\n self.assertEqual(torch.pi, math.pi, atol=0, rtol=0)\n\n self.assertIsInstance(torch.nan, float)\n self.assertEqual(torch.nan, math.nan, equal_nan=True)\n\n self.assertIsInstance(torch.inf, float)\n self.assertEqual(torch.inf, math.inf)\n\n @onlyNativeDeviceTypes\n @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64,\n torch.bool, torch.float32, torch.complex64, torch.float64,\n torch.complex128)\n def test_bytes_to_scalar(self, device, dtype):\n def rand_byte():\n if dtype == torch.bool:\n return torch.randint(0, 2, ()).item()\n else:\n return torch.randint(0, 256, ()).item()\n\n element_size = torch._utils._element_size(dtype)\n\n for i in range(10):\n bytes_list = [rand_byte() for _ in range(element_size)]\n scalar = bytes_to_scalar(bytes_list, dtype, device)\n self.assertEqual(scalar.storage()._untyped().tolist(), bytes_list)\n\n @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64,\n torch.bool, torch.float32, torch.complex64, torch.float64,\n torch.complex128)\n def test_storage(self, device, dtype):\n v = make_tensor((3, 5), dtype=dtype, device=device, low=-9, high=9)\n self.assertEqual(v.storage()[0], v[0][0])\n self.assertEqual(v.storage()[14], v[2][4])\n v_s = v.storage()\n\n for el_num in range(v.numel()):\n dim0 = el_num // v.size(1)\n dim1 = el_num % v.size(1)\n self.assertEqual(\n v_s[el_num],\n v[dim0][dim1])\n\n v_s_byte = v.storage()._untyped()\n el_size = v.element_size()\n\n for el_num in range(v.numel()):\n start = el_num * el_size\n end = start + el_size\n dim0 = el_num // v.size(1)\n dim1 = el_num % v.size(1)\n self.assertEqual(\n bytes_to_scalar(v_s_byte[start:end], dtype, device),\n v[dim0][dim1])\n\n @onlyNativeDeviceTypes\n @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64,\n torch.bool, torch.float32, torch.complex64, torch.float64,\n torch.complex128, torch.quint8, torch.qint8, torch.qint32,\n torch.quint4x2)\n def test_storage_setitem(self, device, dtype):\n # Skip quantized dtypes for CUDA, since they're not supported\n if torch.device(device).type == 'cuda':\n if dtype in [torch.quint8, torch.qint8, torch.qint32, torch.quint4x2]:\n return\n\n storage_type_name = torch.storage._dtype_to_storage_type_map()[dtype]\n if torch.device(device).type == 'cuda':\n storage_type = eval('torch.cuda.' + storage_type_name)\n else:\n storage_type = eval('torch.' + storage_type_name)\n\n N = 10\n\n s = storage_type(N)\n s[:] = 0\n l = [0] * N\n self.assertEqual(s, storage_type(l))\n\n for i in range(N):\n s[i] = i\n l[i] = i\n\n self.assertEqual(s, storage_type(l))\n\n l[2:7] = [1] * 5\n s[2:7] = 1\n self.assertEqual(s, storage_type(l))\n\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_tensor_storage_type(self, device, dtype):\n a = make_tensor((10,), dtype=dtype, device=device, low=-9, high=9)\n\n module = torch.cuda if (torch.device(device).type == 'cuda') else torch\n expected_storage_type = getattr(module, torch.storage._dtype_to_storage_type_map()[dtype])\n\n self.assertEqual(a.storage_type(), expected_storage_type)\n\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_tensor_from_storage(self, device, dtype):\n a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9)\n a_s = a.storage()\n b = torch.tensor(a_s, device=device, dtype=dtype).reshape(a.size())\n self.assertEqual(a, b)\n c = torch.tensor(a_s._untyped(), device=device, dtype=dtype).reshape(a.size())\n self.assertEqual(a, c)\n\n for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16):\n if error_dtype == dtype:\n continue\n with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'):\n error_storage = a.to(error_dtype).storage()\n torch.tensor(error_storage, device=device, dtype=dtype)\n\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_set_storage(self, device, dtype):\n a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9)\n a_s = a.storage()\n b = torch.tensor([], device=device, dtype=dtype).set_(a_s).reshape(a.size())\n self.assertEqual(a, b)\n c = torch.tensor([], device=device, dtype=dtype).set_(a_s._untyped()).reshape(a.size())\n self.assertEqual(a, c)\n\n for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16):\n if error_dtype == dtype:\n continue\n with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'):\n error_storage = a.to(error_dtype).storage()\n b = torch.tensor([], device=device, dtype=dtype).set_(error_storage)\n\n @dtypes(torch.float32, torch.complex64)\n def test_deepcopy(self, device, dtype):\n from copy import deepcopy\n a = torch.randn(5, 5, dtype=dtype, device=device)\n b = torch.randn(5, 5, dtype=dtype, device=device)\n c = a.view(25)\n q = [a, [a.storage(), b.storage()], b, c]\n w = deepcopy(q)\n self.assertEqual(w[0], q[0], atol=0, rtol=0)\n self.assertEqual(w[1][0], q[1][0], atol=0, rtol=0)\n self.assertEqual(w[1][1], q[1][1], atol=0, rtol=0)\n self.assertEqual(w[1], q[1], atol=0, rtol=0)\n self.assertEqual(w[2], q[2], atol=0, rtol=0)\n\n # Check that deepcopy preserves sharing\n w[0].add_(1)\n for i in range(a.numel()):\n self.assertEqual(w[1][0][i], q[1][0][i] + 1)\n self.assertEqual(w[3], c + 1)\n w[2].sub_(1)\n for i in range(a.numel()):\n self.assertEqual(w[1][1][i], q[1][1][i] - 1)\n\n # Check that deepcopy preserves attributes\n a.foo = 3\n self.assertEqual(deepcopy(a).foo, 3)\n\n @dtypes(torch.float32, torch.complex64)\n def test_deepcopy_scalar(self, device, dtype):\n from copy import deepcopy\n a = torch.tensor(5, dtype=dtype, device=device)\n self.assertEqual(a.size(), deepcopy(a).size())\n self.assertEqual(a, deepcopy(a))\n\n def check_internal_mem_overlap(self, inplace_op, num_inputs,\n dtype, device,\n expected_failure=False):\n if isinstance(inplace_op, str):\n inplace_op = getattr(torch.Tensor, inplace_op)\n input = torch.randn(1, dtype=dtype, device=device).expand(3, 3)\n inputs = [input] + [torch.randn_like(input)\n for i in range(num_inputs - 1)]\n if not expected_failure:\n with self.assertRaisesRegex(RuntimeError, 'single memory location'):\n inplace_op(*inputs)\n else:\n with self.assertRaises(AssertionError):\n with self.assertRaisesRegex(RuntimeError, 'single memory location'):\n inplace_op(*inputs)\n\n def unary_check_input_output_mem_overlap(self, data, sz, op,\n expected_failure=False):\n\n def _test(op, output, input):\n output_exp = torch.empty_like(output)\n op(input, out=output_exp)\n self.assertEqual(op(input, out=output), output_exp, msg=op.__name__)\n\n # output is identical to input:\n _test(op, output=data[0:sz], input=data[0:sz])\n # output and input are independent:\n _test(op, output=data[0:sz], input=data[sz:2 * sz])\n # output partially overlaps with input:\n if not expected_failure:\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n _test(op, data[0:sz], data[1:sz + 1])\n else:\n with self.assertRaises(AssertionError):\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n _test(op, data[0:sz], data[1:sz + 1])\n # output is transpose of input:\n length = int(math.sqrt(sz))\n input = data[:length**2].view([length, length])\n out = input.t()\n if not expected_failure:\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n _test(op, out, input)\n else:\n with self.assertRaises(AssertionError):\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n _test(op, out, input)\n\n def ternary_check_input_output_mem_overlap(self, op, device,\n expected_failure=False):\n sz = 9\n data = torch.randn(2 * sz, device=device)\n other1 = torch.randn(sz, device=device)\n other2 = torch.randn(sz, device=device)\n\n self.unary_check_input_output_mem_overlap(\n data, sz, lambda input, out:\n op(input, other1.view(input.shape), other2.view(input.shape), out=out),\n expected_failure=expected_failure)\n\n self.unary_check_input_output_mem_overlap(\n data, sz, lambda input, out:\n op(other1.view(input.shape), input, other2.view(input.shape), out=out),\n expected_failure=expected_failure)\n\n self.unary_check_input_output_mem_overlap(\n data, sz, lambda input, out:\n op(other1.view(input.shape), other2.view(input.shape), input, out=out),\n expected_failure=expected_failure)\n\n def _select_broadcastable_dims(self, dims_full=None):\n # select full dimensionality\n if dims_full is None:\n dims_full = []\n ndims = random.randint(1, 4)\n dims_full = [random.randint(1, 8) for _ in range(ndims)]\n else:\n ndims = len(dims_full)\n\n # select actual dimensions for ops:\n # larger: full ndims, individual sizes may be reduced\n # smaller: possibly reduced ndims, sizes may be reduced\n smaller_ndims = random.randint(1, ndims)\n dims_small = []\n dims_large = []\n for i in range(ndims - 1, -1, -1):\n j = random.randint(1, 3)\n if j == 1: # no reduced singleton dimension\n ds = dims_full[i]\n dl = dims_full[i]\n elif j == 2: # larger may have reduced singleton dimension\n ds = dims_full[i]\n dl = 1 if len(dims_small) < smaller_ndims else dims_full[i]\n elif j == 3: # smaller may have reduced singleton dimension\n ds = 1\n dl = dims_full[i]\n dims_large = [dl] + dims_large\n if len(dims_small) < smaller_ndims:\n dims_small = [ds] + dims_small\n return (dims_small, dims_large, dims_full)\n\n # collected tests of ops that used scalar_check in Declarations.cwrap for\n # correctness\n def test_scalar_check(self, device):\n zero_d = torch.randn((), device=device)\n one_d = torch.randn((1,), device=device)\n\n # remainder\n self.assertEqual((), torch.remainder(zero_d, zero_d).shape)\n self.assertEqual((), torch.remainder(zero_d, 2).shape)\n self.assertEqual((1,), torch.remainder(zero_d, one_d).shape)\n self.assertEqual((1,), torch.remainder(one_d, zero_d).shape)\n\n # fmod\n self.assertEqual((), torch.fmod(zero_d, zero_d).shape)\n self.assertEqual((), torch.fmod(zero_d, 2).shape)\n self.assertEqual((1,), torch.fmod(zero_d, one_d).shape)\n self.assertEqual((1,), torch.fmod(one_d, zero_d).shape)\n\n # exp, cos, cosh, tan, atan, tanh, erf, erfc, reciprocal\n self.assertEqual((), torch.exp(zero_d).shape)\n self.assertEqual((), torch.cos(zero_d).shape)\n self.assertEqual((), torch.cosh(zero_d).shape)\n self.assertEqual((), torch.tan(zero_d).shape)\n self.assertEqual((), torch.atan(zero_d).shape)\n self.assertEqual((), torch.acosh(zero_d).shape)\n self.assertEqual((), torch.asinh(zero_d).shape)\n self.assertEqual((), torch.atanh(zero_d).shape)\n self.assertEqual((), torch.tanh(zero_d).shape)\n self.assertEqual((), torch.erf(zero_d).shape)\n self.assertEqual((), torch.erfc(zero_d).shape)\n self.assertEqual((), torch.reciprocal(zero_d).shape)\n self.assertEqual((1,), torch.exp(one_d).shape)\n self.assertEqual((1,), torch.cos(one_d).shape)\n self.assertEqual((1,), torch.cosh(one_d).shape)\n self.assertEqual((1,), torch.tan(one_d).shape)\n self.assertEqual((1,), torch.atan(one_d).shape)\n self.assertEqual((1,), torch.acosh(one_d).shape)\n self.assertEqual((1,), torch.asinh(one_d).shape)\n self.assertEqual((1,), torch.atanh(one_d).shape)\n self.assertEqual((1,), torch.tanh(one_d).shape)\n self.assertEqual((1,), torch.erf(one_d).shape)\n self.assertEqual((1,), torch.erfc(one_d).shape)\n self.assertEqual((1,), torch.reciprocal(one_d).shape)\n\n # clamp\n self.assertEqual((), torch.clamp(zero_d, min=0, max=1).shape)\n self.assertEqual((), torch.clamp(zero_d, min=0).shape)\n self.assertEqual((), torch.clamp(zero_d, max=1).shape)\n self.assertEqual((1,), torch.clamp(one_d, min=0, max=1).shape)\n self.assertEqual((1,), torch.clamp(one_d, min=0).shape)\n self.assertEqual((1,), torch.clamp(one_d, max=1).shape)\n\n # cumsum, cumprod, cummax, cummin\n self.assertEqual((), torch.logcumsumexp(zero_d, 0).shape)\n self.assertEqual((), torch.cumsum(zero_d, 0).shape)\n self.assertEqual((), torch.cumprod(zero_d, 0).shape)\n self.assertEqual((), torch.cummax(zero_d, 0)[0].shape)\n self.assertEqual((), torch.cummin(zero_d, 0)[0].shape)\n\n # sort, topk\n self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, False)])\n self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, True)])\n self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, False)])\n self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, True)])\n\n # max, min\n self.assertEqual((), torch.max(zero_d, zero_d).shape)\n self.assertEqual((1,), torch.max(one_d, zero_d).shape)\n self.assertEqual((1,), torch.max(zero_d, one_d).shape)\n self.assertEqual((), torch.min(zero_d, zero_d).shape)\n self.assertEqual((1,), torch.min(one_d, zero_d).shape)\n self.assertEqual((1,), torch.min(zero_d, one_d).shape)\n\n zero_d_int = torch.tensor(1, device=device)\n one_d_int = torch.tensor([1], device=device)\n\n # lshift, rshift\n self.assertEqual((), (zero_d_int >> zero_d_int).shape)\n self.assertEqual((), (zero_d_int >> 1).shape)\n self.assertEqual((1,), (one_d_int >> zero_d_int).shape)\n self.assertEqual((1,), (zero_d_int >> one_d_int).shape)\n self.assertEqual((1,), (one_d_int >> 1).shape)\n\n self.assertEqual((), (zero_d_int << zero_d_int).shape)\n self.assertEqual((), (zero_d_int << 1).shape)\n self.assertEqual((1,), (one_d_int << zero_d_int).shape)\n self.assertEqual((1,), (zero_d_int << one_d_int).shape)\n self.assertEqual((1,), (one_d_int << 1).shape)\n\n # or\n self.assertEqual((), (zero_d_int | zero_d_int).shape)\n self.assertEqual((), (zero_d_int | 1).shape)\n self.assertEqual((1,), (one_d_int | zero_d_int).shape)\n self.assertEqual((1,), (zero_d_int | one_d_int).shape)\n self.assertEqual((1,), (one_d_int | 1).shape)\n\n # and\n self.assertEqual((), (zero_d_int & zero_d_int).shape)\n self.assertEqual((), (zero_d_int & 1).shape)\n self.assertEqual((1,), (one_d_int & zero_d_int).shape)\n self.assertEqual((1,), (zero_d_int & one_d_int).shape)\n self.assertEqual((1,), (one_d_int & 1).shape)\n\n # clone\n self.assertEqual((), zero_d.clone().shape)\n\n zero_d_bool = torch.tensor(True, device=device)\n one_d_bool = torch.tensor([True], device=device)\n\n # masked_select\n self.assertEqual((1,), torch.masked_select(zero_d_bool, zero_d_bool).shape)\n self.assertEqual((1,), torch.masked_select(zero_d_bool, one_d_bool).shape)\n self.assertEqual((1,), torch.masked_select(one_d_bool, zero_d_bool).shape)\n\n zero_d_uint8 = torch.tensor(1, dtype=torch.uint8, device=device)\n one_d_uint8 = torch.tensor([1], dtype=torch.uint8, device=device)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n self.assertEqual((1,), torch.masked_select(zero_d_uint8, zero_d_uint8).shape)\n self.assertEqual((1,), torch.masked_select(zero_d_uint8, one_d_uint8).shape)\n self.assertEqual((1,), torch.masked_select(one_d_uint8, zero_d_uint8).shape)\n\n # mode\n self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=True)])\n self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=False)])\n self.assertEqual([(1,), (1,)], [x.shape for x in torch.mode(one_d, dim=0, keepdim=True)])\n self.assertEqual([(), ()], [x.shape for x in torch.mode(one_d, dim=0, keepdim=False)])\n\n # max\n self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=True)])\n self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=False)])\n self.assertEqual([(1,), (1,)], [x.shape for x in torch.max(one_d, dim=0, keepdim=True)])\n self.assertEqual([(), ()], [x.shape for x in torch.max(one_d, dim=0, keepdim=False)])\n\n # amax\n self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=True).shape)\n self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=False).shape)\n self.assertEqual((1,), torch.amax(one_d, dim=0, keepdim=True).shape)\n self.assertEqual((), torch.amax(one_d, dim=0, keepdim=False).shape)\n\n # min\n self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=True)])\n self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=False)])\n self.assertEqual([(1,), (1,)], [x.shape for x in torch.min(one_d, dim=0, keepdim=True)])\n self.assertEqual([(), ()], [x.shape for x in torch.min(one_d, dim=0, keepdim=False)])\n\n # amin\n self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=True).shape)\n self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=False).shape)\n self.assertEqual((1,), torch.amin(one_d, dim=0, keepdim=True).shape)\n self.assertEqual((), torch.amin(one_d, dim=0, keepdim=False).shape)\n\n # set_\n zero_d_clone = zero_d.clone()\n one_d_clone = one_d.clone()\n self.assertEqual((), zero_d_clone.set_(one_d.storage(), 0, (), ()).shape)\n self.assertEqual((1,), zero_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape)\n self.assertEqual((), one_d_clone.set_(one_d.storage(), 0, (), ()).shape)\n self.assertEqual((1,), one_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape)\n\n self.assertEqual((), zero_d.clone().set_(zero_d).shape)\n self.assertEqual((), one_d.clone().set_(zero_d).shape)\n self.assertEqual((1,), zero_d.clone().set_(one_d).shape)\n self.assertEqual((1,), one_d.clone().set_(one_d).shape)\n\n # take\n self.assertEqual((), torch.randn((2, 3), device=device).take(zero_d_int).shape)\n self.assertEqual((1,), torch.randn((2, 3), device=device).take(one_d_int).shape)\n\n # gather\n self.assertEqual((), torch.gather(zero_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape)\n self.assertEqual((1,), torch.gather(zero_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape)\n self.assertEqual((), torch.gather(one_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape)\n self.assertEqual((1,), torch.gather(one_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape)\n\n # normal\n # std must be >= 0\n zero_d_ge_0 = torch.rand((), device=device)\n # documentation says out shape matches shape of mean\n self.assertEqual((), torch.normal(zero_d, zero_d_ge_0).shape)\n self.assertEqual((1,), torch.normal(one_d, zero_d_ge_0).shape)\n self.assertEqual((), torch.normal(1, zero_d_ge_0).shape)\n self.assertEqual((), torch.normal(zero_d, 1).shape)\n self.assertEqual((1,), torch.normal(one_d, 1).shape)\n # TODO: this behavior differs on CPU and GPU, see https://github.com/pytorch/pytorch/issues/30480.\n # self.assertEqual((), torch.normal(zero_d, one_d).shape)\n # self.assertEqual((), torch.normal(1, one_d).shape)\n\n # convolutions. Yes, we are testing nn.functional here; seems justified\n # given its similar to the other tests\n w = torch.randn(2, 1, 3, 3, device=device).div_(2).requires_grad_()\n self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=1))\n self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=2))\n\n # nll_loss -- verify input can't be 0-dimensional.\n self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, zero_d, reduction='none'))\n self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, one_d, reduction='none'))\n # verify output is 0-dimensional when reduction != 'none'\n for (input, target) in ((torch.randn(1, 1, device=device), torch.tensor([0], device=device)),\n (torch.randn(1, 1, 1, 1, device=device), torch.tensor([[[0]]], device=device))):\n self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='mean').shape)\n self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='sum').shape)\n\n # multilabel_margin_loss\n for input in (zero_d, one_d, torch.randn(1, 1, device=device)):\n for target in (torch.tensor(0, device=device), torch.tensor([0], device=device), torch.tensor([[0]], device=device)):\n if (input.dim() <= 1 and target.dim() <= 1) or (input.dim() == 2 and target.dim() == 2):\n output_shape = (target.shape[0],) if target.dim() == 2 else ()\n self.assertEqual(output_shape,\n torch.nn.functional.multilabel_margin_loss(input, target, reduction='none').shape)\n self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean').shape)\n self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum').shape)\n else:\n self.assertRaises(RuntimeError,\n lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='none'))\n self.assertRaises(RuntimeError,\n lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean'))\n self.assertRaises(RuntimeError,\n lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum'))\n\n # multi_margin_loss\n for input in (zero_d, one_d, torch.randn(1, 1, device=device)):\n for target in (torch.tensor(0, device=device), torch.tensor([0], device=device)):\n self.assertEqual(target.shape, torch.nn.functional.multi_margin_loss(input, target, reduction='none').shape)\n self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='mean').shape)\n self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='sum').shape)\n\n # Uses mismatched arange out size to trigger a warning\n def test_cpp_warnings_have_python_context(self, device):\n # Creates long string in advance to avoid a too-long Python line\n s = \".+Triggered internally at.+RangeFactories.+\"\n\n def cpp_warn_fn():\n out = torch.empty((5,))\n torch.arange(0, 3, out=out)\n return out\n\n # Checks eager-mode cpp warning\n with warnings.catch_warnings(record=True) as w:\n cpp_warn_fn()\n frameinfo = inspect.getframeinfo(inspect.currentframe())\n warning = w[0]\n\n # Checks for cpp context in the warning message\n self.assertTrue(re.search(s, str(warning.message)) is not None)\n\n # Checks the Python features of the warning\n # Note: the eager mode warning refers to the line in the function\n # that throws the warning.\n self.assertEqual(frameinfo.lineno - 6, warning.lineno)\n self.assertEqual(len(w), 1)\n\n # Checks jitted cpp warning\n with warnings.catch_warnings(record=True) as w:\n scripted_cpp_warn_fn = torch.jit.script(cpp_warn_fn)\n scripted_cpp_warn_fn()\n warning = w[0]\n\n # Checks for cpp context in the warning message\n self.assertTrue(re.search(s, str(warning.message)) is not None)\n\n # Checks the Python features of the warning\n # Note: the jitted warning's lineno refers to the call to the jitted\n # function, which in our test suite has a layer of indirection\n # that makes checking the Python lineno fragile\n self.assertEqual(len(w), 1)\n\n # Checks jitted Python warning\n def warn_fn():\n warnings.warn(\"Warning!\")\n\n # The jit mimics an eager-mode Python warning in this case\n with warnings.catch_warnings(record=True) as w:\n scripted_warn_fn = torch.jit.script(warn_fn)\n scripted_warn_fn()\n frameinfo = inspect.getframeinfo(inspect.currentframe())\n warning = w[0]\n\n self.assertTrue(re.search('Warning!', str(warning.message)) is not None)\n\n # Checks the Python features of the warning\n self.assertEqual(frameinfo.lineno - 6, warning.lineno)\n self.assertEqual(len(w), 1)\n\n # FIXME: move to test_testing\n @onlyCPU\n def test_warn_always_caught(self, device):\n # Check that we can catch a TORCH_WARN_ONCE warning twice\n # since assertWarnsOnceRegex uses set_warn_always(True) which changes\n # TORCH_WARN_ONCE to TORCH_WARN\n a = np.arange(10)\n a.flags.writeable = False\n with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'):\n torch.from_numpy(a)\n\n # OK, got it once, now try again\n with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'):\n torch.from_numpy(a)\n\n # Make sure emitting two warnings will pass the assertWarnsOnceRegex\n # context manager\n with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'):\n torch.from_numpy(a)\n torch.from_numpy(a)\n\n # TODO: this test should be in test_nn.py\n def test_conv_transposed_backward_agnostic_to_memory_format(self, device):\n in_channels = 64\n out_channels = 128\n scale_factor = 8\n batch_size = 8\n length = 16\n\n conv = torch.nn.ConvTranspose1d(\n in_channels, out_channels, kernel_size=scale_factor * 2, stride=scale_factor).to(device)\n layer_norm = torch.nn.LayerNorm(out_channels).to(device)\n\n input_ = torch.randn(batch_size, in_channels, length).to(device).contiguous()\n input_ = conv(input_).contiguous()\n input_ = layer_norm(input_.transpose(1, 2).contiguous()).contiguous()\n input_.sum().backward()\n\n # 3d\n conv = torch.nn.ConvTranspose3d(3, 3, kernel_size=3).to(device)\n input = torch.randn(batch_size, 3, length, length, length, device=device)\n out = conv(input)\n out.backward(torch.ones_like(out).transpose(-2, -1))\n\n # TODO: this test should be in test_nn.py\n @onlyCUDA\n @largeTensorTest('12GB')\n def test_conv_transposed_large(self, device):\n # ConvTranspose3d works for large input tensors (gh-32866)\n in_channels = 64\n out_channels = 128\n kernel_size = 5\n\n conv = torch.nn.ConvTranspose3d(\n in_channels, out_channels, kernel_size=kernel_size,\n stride=2, padding=2, output_padding=1).to(device)\n\n x = torch.rand([1, 64, 8, 128, 172]).to(device)\n y = conv(x)\n\n def test_is_set_to(self, device):\n t1 = torch.empty(3, 4, 9, 10, device=device)\n t2 = torch.empty(3, 4, 9, 10, device=device)\n t3 = torch.tensor([], device=device).set_(t1)\n t4 = t3.clone().resize_(12, 90)\n self.assertFalse(t1.is_set_to(t2))\n self.assertTrue(t1.is_set_to(t3))\n self.assertTrue(t3.is_set_to(t1), \"is_set_to should be symmetric\")\n self.assertFalse(t1.is_set_to(t4))\n self.assertFalse(torch.tensor([]).is_set_to(torch.tensor([])),\n \"Tensors with no storages should not appear to be set \"\n \"to each other\")\n\n t1 = torch.tensor([True, True], dtype=torch.bool, device=device)\n t2 = torch.tensor([0], dtype=torch.bool, device=device).set_(t1)\n self.assertTrue(t1.is_set_to(t2))\n\n # test that sizes must match\n t1 = torch.empty([2, 3, 4], device=device)\n t2 = t1.view(4, 3, 2)\n self.assertFalse(t1.is_set_to(t2))\n self.assertFalse(t2.is_set_to(t1))\n\n # test that legacy empty size behavior used to be respected (i.e. all\n # empty tensors were logically collapsed to size [0]).\n t1 = torch.empty([2, 5, 0], device=device)\n t2 = t1.view([0])\n self.assertFalse(t1.is_set_to(t2))\n self.assertFalse(t2.is_set_to(t1))\n\n # See https://github.com/pytorch/pytorch/issues/72650\n @skipMeta\n @parametrize(\n \"fn\",\n [\n \"dist\", \"atan2\", \"pow\", \"lerp\", \"add\", \"sub\", \"mul\", \"div\", \"fmod\", \"remainder\", \"eq\", \"ge\", \"gt\", \"le\",\n \"lt\", \"max\", \"min\", \"ne\", \"addcdiv\", \"addcmul\", \"masked_scatter\", \"masked_select\", \"masked_fill\", \"map\",\n \"map2\", \"copy\",\n ],\n )\n def test_broadcast(self, fn, device):\n # functions with three tensor arguments\n fns_3_args = {\"map2\"}\n fns_value_kwarg = {\"addcdiv\", \"addcmul\"}\n\n (dims_small, dims_large, dims_full) = self._select_broadcastable_dims()\n full1d = torch.randn(*dims_full, device=device).flatten().float()\n small = torch.randn(*dims_small, device=device).float()\n large = torch.randn(*dims_large, device=device).float()\n small_expanded = small.expand(*dims_full)\n large_expanded = large.expand(*dims_full)\n small2 = None\n small2_expanded = None\n if fn in fns_3_args or fn in fns_value_kwarg:\n # create another smaller tensor\n (dims_small2, _, _) = self._select_broadcastable_dims(dims_full)\n small2 = torch.randn(*dims_small2, device=device).float()\n small2_expanded = small2.expand(*dims_full)\n\n if small.is_cuda and fn in ['map', 'map2']:\n # map and map2 are not implementd on CUDA tensors\n return\n\n if hasattr(large_expanded, fn):\n # run through tensor versions of functions\n # and verify fully expanded inputs give same results\n expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded}\n\n def tensorfn(myfn, t1, t2):\n if fn == \"lerp\":\n return myfn(t1, 0.5)\n elif fn == \"masked_select\":\n return myfn(t1 < 0)\n elif fn == \"masked_scatter\":\n return myfn(t1 < 0.5, full1d)\n elif fn == \"masked_fill\":\n return myfn(t1 < 0.5, 1.0)\n elif fn in fns_3_args:\n return myfn(1, t1, t2)\n elif fn in fns_value_kwarg:\n return myfn(t1, t2, value=1)\n else:\n return myfn(t1)\n\n # test various orders\n for first, second, third in [(large, small, small2), (small, large, small2),\n (small2, small, large), (small2, large, small)]:\n if first is None:\n break # ignore last iter when small2 is None\n method_expanded = getattr(expanded[first], fn)\n method = getattr(first, fn)\n r1 = tensorfn(method_expanded, expanded[second], expanded[third])\n r2 = tensorfn(method, second, third)\n self.assertEqual(r1, r2)\n\n # now for torch. versions of functions\n if hasattr(torch, fn):\n fntorch = getattr(torch, fn)\n expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded}\n\n def torchfn(t1, t2, t3):\n if fn == \"lerp\":\n return fntorch(t1, t2, 0.5)\n elif fn == \"masked_select\":\n return fntorch(t1, t2 < 0)\n elif fn == \"masked_scatter\":\n return fntorch(t1, t2 < 0.5, full1d)\n elif fn == \"masked_fill\":\n return fntorch(t1, t2 < 0.5, 1.0)\n elif fn in fns_3_args:\n return fntorch(t1, 1.0, t2, t3)\n elif fn in fns_value_kwarg:\n return fntorch(t1, t2, t3, value=1.0)\n else:\n return fntorch(t1, t2)\n\n # test various orders\n for first, second, third in [(large, small, small2), (small, large, small2),\n (small2, small, large), (small2, large, small)]:\n if first is None:\n break # ignore last iter when small2 is None\n r1 = torchfn(expanded[first], expanded[second], expanded[third])\n r2 = torchfn(first, second, third)\n self.assertEqual(r1, r2)\n\n # now for in place functions\n # in-place tensor is not broadcastable; test only guaranteed\n # to work by broadcasting other argument(s)\n if not hasattr(large_expanded, fn + \"_\"):\n return\n\n # need to clone largeExpanded so we can reuse, since functions are in-place\n large_expanded_clone = large_expanded.clone()\n\n def tensorfn_inplace(t0, t1, t2=None):\n t0_fn = getattr(t0, fn + \"_\")\n if fn == \"lerp\":\n return t0_fn(t1, 0.5)\n elif fn == \"masked_scatter\":\n return t0_fn(t1 < 0.5, full1d)\n elif fn == \"masked_fill\":\n return t0_fn(t1 < 0.5, 1.0)\n elif fn == \"map\":\n return t0_fn(t1, lambda x, y: x + y)\n elif fn == \"map2\":\n return t0_fn(t1, t2, lambda x, y, z: x + y + z)\n elif fn in fns_3_args:\n return t0_fn(1.0, t1, t2)\n elif fn in fns_value_kwarg:\n return t0_fn(t1, t2, value=1.0)\n else:\n return t0_fn(t1)\n # in-place pointwise operations don't actually work if the in-place\n # tensor is 0-strided (numpy has the same issue)\n if (0 not in large_expanded.stride() and 0 not in large_expanded_clone.stride()):\n r1 = tensorfn_inplace(large_expanded, small_expanded, small2_expanded)\n r2 = tensorfn_inplace(large_expanded_clone, small, small2)\n self.assertEqual(r1, r2)\n\n def broadcastable(t0, t1, t2=None):\n try:\n t1.expand_as(t0)\n if t2 is not None:\n t2.expand_as(t0)\n except RuntimeError:\n return False\n return True\n\n def _test_in_place_broadcastable(t0, t1, t2=None):\n if not broadcastable(t0, t1, t2):\n same_size = t0.numel() == t1.numel() and (t0.numel() == t2.numel() if t2 is not None else True)\n if not same_size:\n self.assertRaises(RuntimeError, lambda: tensorfn_inplace(t0, t1, t2))\n else:\n tensorfn_inplace(t0, t1, t2)\n\n if fn not in fns_3_args and fn not in fns_value_kwarg:\n _test_in_place_broadcastable(small, large_expanded)\n _test_in_place_broadcastable(small, large)\n else:\n _test_in_place_broadcastable(small2, small_expanded, large_expanded)\n _test_in_place_broadcastable(small2, small, large)\n\n @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, \"cublas runtime error\")\n @onlyCUDA\n @wrapDeterministicFlagAPITest\n def test_cublas_config_nondeterministic_alert(self, device):\n test_cases = [\n # (function, (tensor sizes))\n ('mm', ((2, 2), (2, 2),)),\n ('mv', ((2, 2), (2,),)),\n ('bmm', ((1, 2, 2), (1, 2, 2),))]\n\n test_configs = [\n # (CuBLAS workspace config, is deterministic)\n ('garbage', False),\n (None, False),\n (':4096:8', True),\n (':16:8', True)]\n\n cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG'\n is_cuda10_2_or_higher = (\n (torch.version.cuda is not None)\n and ([int(x) for x in torch.version.cuda.split(\".\")] >= [10, 2]))\n\n def test_case_info(fn_name, config):\n return f'function \"{fn_name}\" with config \"{\"\" if config is None else config}\"'\n\n # Create processes to test each combination of test cases and config settings\n processes = []\n for fn_name, arg_sizes in test_cases:\n for config, is_config_deterministic in test_configs:\n env = os.environ.copy()\n if config is None:\n if env.get(cublas_var_name) is not None:\n del env[cublas_var_name]\n else:\n env[cublas_var_name] = config\n should_throw_error = is_cuda10_2_or_higher and not is_config_deterministic\n script = f\"\"\"\nimport torch\ntorch.use_deterministic_algorithms(True)\nfn = torch.{fn_name}\narg_sizes = {arg_sizes}\ndevice = '{device}'\nshould_throw_error = {should_throw_error}\nargs = []\nfor arg_size in arg_sizes:\n args.append(torch.randn(*arg_size, device=device))\ntry:\n fn(*args)\nexcept RuntimeError as e:\n if not should_throw_error:\n raise RuntimeError('Did not expect any error to be raised')\n elif 'Deterministic behavior was enabled with either' not in str(e):\n raise RuntimeError('Expected a CuBLAS nondeterministic error, but got a different error')\nelse:\n if should_throw_error:\n raise RuntimeError('Expected a CuBLAS nondeterministic error, but it was not raised')\n\n\"\"\"\n try:\n subprocess.check_output(\n [sys.executable, '-c', script],\n stderr=subprocess.STDOUT,\n # On Windows, opening the subprocess with the default CWD makes `import torch`\n # fail, so just set CWD to this script's directory\n cwd=os.path.dirname(os.path.realpath(__file__)),\n env=env)\n except subprocess.CalledProcessError as e:\n self.fail(msg=(\n f'Subprocess exception while attempting to run {test_case_info(fn_name, config)}:\\n'\n + e.output.decode(\"utf-8\")))\n\n # FIXME: update OpInfos to support \"nondeterministic samples\" and port these tests\n # to that architecture\n def test_nondeterministic_alert_AvgPool3d(self, device):\n module = torch.nn.AvgPool3d(3)\n input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('avg_pool3d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_AdaptiveAvgPool2d(self, device):\n module = torch.nn.AdaptiveAvgPool2d(3)\n input = torch.randn(2, 3, 3, requires_grad=True, device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('adaptive_avg_pool2d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_AdaptiveAvgPool3d(self, device):\n module = torch.nn.AdaptiveAvgPool3d(3)\n input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('adaptive_avg_pool3d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_MaxPool3d(self, device):\n module = torch.nn.MaxPool3d(3)\n input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('max_pool3d_with_indices_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_AdaptiveMaxPool2d(self, device):\n module = torch.nn.AdaptiveMaxPool2d(3)\n input = torch.randn(2, 3, 3, requires_grad=True, device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('adaptive_max_pool2d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_FractionalMaxPool2d(self, device):\n module = torch.nn.FractionalMaxPool2d(2, output_ratio=0.5)\n input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('fractional_max_pool2d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_FractionalMaxPool3d(self, device):\n module = torch.nn.FractionalMaxPool3d(2, output_ratio=0.5)\n input = torch.randn(2, 3, 3, 3, 3, requires_grad=True, device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('fractional_max_pool3d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_interpolate_linear(self, device):\n input = torch.randn(1, 2, 4, device=device, requires_grad=True)\n res = torch.nn.functional.interpolate(\n input,\n size=12,\n mode='linear',\n align_corners=False)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('upsample_linear1d_backward_out_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_interpolate_bilinear(self, device):\n input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True)\n res = torch.nn.functional.interpolate(\n input,\n size=12,\n mode='bilinear',\n align_corners=False)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('upsample_bilinear2d_backward_out_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_interpolate_bicubic(self, device):\n input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True)\n res = torch.nn.functional.interpolate(\n input,\n size=12,\n mode='bicubic',\n align_corners=False)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('upsample_bicubic2d_backward_out_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_interpolate_trilinear(self, device):\n input = torch.randn(1, 2, 4, 4, 4, device=device, requires_grad=True)\n res = torch.nn.functional.interpolate(\n input,\n size=12,\n mode='trilinear',\n align_corners=False)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('upsample_trilinear3d_backward_out_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_ReflectionPad1d(self, device):\n module = torch.nn.ReflectionPad1d((1, 2))\n input = torch.randn(2, 3, 8, device=device, requires_grad=True)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('reflection_pad1d_backward_out_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_ReflectionPad2d(self, device):\n module = torch.nn.ReflectionPad2d((1, 2, 3, 4))\n input = torch.randn(2, 3, 8, 8, device=device, requires_grad=True)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('reflection_pad2d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_ReflectionPad3d(self, device):\n module = torch.nn.ReflectionPad3d((1, 2, 3, 4, 5, 6))\n input = torch.randn(2, 3, 8, 8, 8, device=device, requires_grad=True)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('reflection_pad3d_backward_out_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_ReplicationPad1d(self, device):\n module = torch.nn.ReplicationPad1d((1, 2))\n input = torch.randn(2, 3, 4, device=device, requires_grad=True)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('replication_pad1d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_ReplicationPad2d(self, device):\n module = torch.nn.ReplicationPad2d((1, 2, 3, 4))\n input = torch.randn(2, 3, 4, 4, device=device, requires_grad=True)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('replication_pad2d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_ReplicationPad3d(self, device):\n module = torch.nn.ReplicationPad3d((1, 2, 3, 4, 5, 6))\n input = torch.randn(2, 3, 4, 4, 4, device=device, requires_grad=True)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('replication_pad3d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_NLLLoss(self, device):\n module = torch.nn.NLLLoss()\n input = torch.randn(2, 3, 5, 5, device=device)\n target = torch.rand(2, 5, 5, device=device).mul(3).floor().long()\n\n @expectedAlertNondeterministic('nll_loss2d_forward_out_cuda_template', ['cuda'])\n def forward_func(slf, device):\n module(input, target)\n\n forward_func(self, device)\n\n def test_nondeterministic_alert_CTCLoss(self, device):\n module = torch.nn.CTCLoss()\n input = torch.randn(50, 3, 15, device=device, requires_grad=True)\n target = torch.randint(0, 14, (3, 30), device=device)\n input_lengths = [50, 50, 50]\n target_lengths = [30, 25, 20]\n res = module(input, target, input_lengths, target_lengths)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('ctc_loss_backward_gpu', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad, retain_graph=True)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_EmbeddingBag_max(self, device):\n module = torch.nn.EmbeddingBag(\n 4, 3, None, 2., False, 'max',\n _weight=torch.randn(4, 3, device=device, requires_grad=True))\n input = torch.randint(0, 3, (4, 3), device=device)\n res = module(input)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('embedding_bag_backward_cuda_max', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_scatter_add(self, device):\n def test_func(op_call):\n input = torch.randn(5, 4, device=device)\n dim = 0\n index = torch.tensor([[3]], device=device)\n src = torch.tensor([[1.0]], device=device)\n\n @expectedAlertNondeterministic('scatter_add_cuda_kernel', ['cuda'])\n def forward_func(slf, device):\n op_call(input, dim, index, src)\n\n forward_func(self, device)\n\n test_func(torch.Tensor.scatter_add_)\n test_func(torch.Tensor.scatter_add)\n test_func(torch.scatter_add)\n\n @expectedFailureMeta # expected a non-determinitic error, but it was not raised\n @onlyNativeDeviceTypes\n def test_nondeterministic_alert_put(self, device):\n def test_func(op_call):\n a = torch.randn(10, device=device)\n indices = torch.tensor([0, 0], device=device)\n values = torch.tensor([0., 1.], device=device)\n\n @expectedAlertNondeterministic('put_')\n def forward_func(slf, device):\n op_call(a, indices, values, accumulate=False)\n\n forward_func(self, device)\n\n test_func(torch.Tensor.put)\n test_func(torch.Tensor.put_)\n\n def test_nondeterministic_alert_put_accumulate(self, device):\n def test_func(op_call):\n a = torch.randn(10, device=device)\n indices = torch.tensor([0, 0], device=device)\n values = torch.tensor([0., 1.], device=device)\n\n @expectedAlertNondeterministic('put_', ['cuda'])\n def forward_func(slf, device):\n op_call(a, indices, values, accumulate=True)\n\n forward_func(self, device)\n\n test_func(torch.Tensor.put)\n test_func(torch.Tensor.put_)\n\n def test_nondeterministic_alert_histc(self, device):\n def test_func(op_call):\n a = torch.tensor([], device=device)\n\n @expectedAlertNondeterministic('_histc_cuda', ['cuda'])\n def forward_func(slf, device):\n res = op_call(a, min=0, max=3)\n\n forward_func(self, device)\n\n test_func(torch.histc)\n test_func(torch.Tensor.histc)\n\n def test_nondeterministic_alert_bincount(self, device):\n def test_func(op_call):\n a = torch.tensor([], device=device, dtype=torch.long)\n\n @expectedAlertNondeterministic('_bincount_cuda', ['cuda'])\n def forward_func(slf, device):\n res = op_call(a)\n\n forward_func(self, device)\n\n test_func(torch.bincount)\n test_func(torch.Tensor.bincount)\n\n # Ensures that kthvalue throws nondeterministic alerts in the correct cases\n @dtypes(torch.double)\n def test_nondeterministic_alert_kthvalue(self, device, dtype):\n @expectedAlertNondeterministic('kthvalue CUDA', ['cuda'])\n def test_func(slf, device, call_type):\n S = 10\n k = 5\n a = torch.randn(S, device=device)\n if call_type == 'function':\n torch.kthvalue(a, k)\n elif call_type == 'method':\n a.kthvalue(k)\n elif call_type == 'out':\n values = torch.empty_like(a)\n indices = torch.empty((), device=device, dtype=torch.long)\n torch.kthvalue(a, k, out=(values, indices))\n else:\n self.fail(f\"'{call_type}' is not a valid call type\")\n\n test_func(self, device, 'function')\n test_func(self, device, 'method')\n test_func(self, device, 'out')\n\n @onlyNativeDeviceTypes\n def test_nondeterministic_alert_gather(self, device):\n def test_func(op_call):\n a = torch.randn(3, 3, device=device, requires_grad=True)\n dim = 0\n index = torch.tensor([[0]], device=device)\n res = op_call(a, dim, index)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('scatter_add_cuda_kernel', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n test_func(torch.gather)\n test_func(torch.Tensor.gather)\n\n def test_nondeterministic_alert_grid_sample_2d(self, device):\n input = torch.empty(1, 1, 2, 2, device=device, requires_grad=True)\n grid = torch.empty(1, 1, 1, 2, device=device)\n res = torch.nn.functional.grid_sample(input, grid, align_corners=False)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('grid_sampler_2d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_nondeterministic_alert_grid_sample_3d(self, device):\n input = torch.empty(1, 1, 2, 2, 2, device=device, requires_grad=True)\n grid = torch.empty(1, 1, 1, 2, 3, device=device)\n res = torch.nn.functional.grid_sample(input, grid, align_corners=False)\n grad = torch.ones_like(res)\n\n @expectedAlertNondeterministic('grid_sampler_3d_backward_cuda', ['cuda'])\n def backward_func(slf, device):\n res.backward(grad)\n\n backward_func(self, device)\n\n def test_invalid_shapes_grid_sampler(self, device):\n make_arg = partial(\n make_tensor, device=device, dtype=torch.float64, requires_grad=True)\n\n inputs = (\n # input, grid\n ((5, 5, 5, 5, 5,), (1, 1, 1, 4, 4,)), # 3d\n ((5, 5, 5, 5,), (1, 1, 4, 4,)), # 2d\n )\n\n interpolation_mode = 0\n padding_mode = 0\n align_corners = True\n\n err = \"expected grid and input to have same batch size\"\n\n for input, grid in inputs:\n input = make_arg(input)\n grid = make_arg(grid, low=-1, high=1)\n\n # Wrapper for the 2d, 3d, and cuDNN functions listed below.\n with self.assertRaisesRegex(RuntimeError, err):\n torch.grid_sampler(\n input, grid, interpolation_mode, padding_mode,\n align_corners)\n\n # Expects 2d input.\n with self.assertRaisesRegex(RuntimeError, err):\n torch.grid_sampler_2d(\n input, grid, interpolation_mode, padding_mode,\n align_corners)\n\n # Expects 3d input.\n with self.assertRaisesRegex(RuntimeError, err):\n torch.grid_sampler_3d(\n input, grid, interpolation_mode, padding_mode,\n align_corners)\n\n # Expects 2d input.\n with self.assertRaisesRegex(RuntimeError, err):\n torch._grid_sampler_2d_cpu_fallback(\n input, grid, interpolation_mode, padding_mode,\n align_corners)\n\n # Expects 2d input, on CUDA.\n # Doesn't work on CPU and ROCm.\n if device != 'cpu' and TEST_CUDNN and not TEST_WITH_ROCM:\n with self.assertRaisesRegex(RuntimeError, err):\n torch.cudnn_grid_sampler(input, grid)\n\n def test_dist(self, device):\n def run_test(x, y):\n for p in [0, 1, 2, 3, 4, inf, -inf]:\n dist_xy = torch.dist(x, y, p)\n dist_xy_norm = torch.norm(x - y, p)\n self.assertEqual(dist_xy, dist_xy_norm)\n\n run_test(torch.randn(5, device=device), torch.randn(5, device=device))\n\n x = torch.zeros(3, device=device)\n y = torch.zeros(3, device=device)\n y[1] = 1.\n run_test(x, y)\n\n # Ensures that median throws nondeterministic alerts in the correct cases\n @dtypes(torch.double)\n def test_nondeterministic_alert_median(self, device, dtype):\n def test_func(slf, device, call_type):\n S = 10\n a = torch.randn(S, device=device)\n if call_type == 'function':\n torch.median(a)\n elif call_type == 'function with indices':\n torch.median(a, 0)\n elif call_type == 'method':\n a.median()\n elif call_type == 'method with indices':\n a.median(0)\n elif call_type == 'out with indices':\n result = torch.empty_like(a)\n indices = torch.empty((), dtype=torch.long, device=device)\n torch.median(a, 0, out=(result, indices))\n else:\n self.fail(f\"'{call_type}' is not a valid call type\")\n\n @expectedAlertNondeterministic('median CUDA with indices output', ['cuda'])\n def test_func_expect_error(slf, device, call_type):\n test_func(slf, device, call_type)\n\n test_func(self, device, 'function')\n test_func_expect_error(self, device, 'function with indices')\n test_func(self, device, 'method')\n test_func_expect_error(self, device, 'method with indices')\n test_func_expect_error(self, device, 'out with indices')\n\n # FIXME: move to test_scatter_gather_ops\n def _test_gather_backward_one_dim(self, device, deterministic: bool = False) -> None:\n with DeterministicGuard(deterministic):\n m = random.randint(2000, 3000)\n elems = random.randint(10 * m, 20 * m)\n dim = 0\n src = torch.randn(m, device=device, requires_grad=True)\n idx = torch.randint(m, (elems,), device=device)\n res = torch.gather(src, dim, idx)\n weight = torch.rand_like(res, device=device) * 10 ** 6\n res.backward(weight)\n grad = src.grad.detach().clone()\n\n if torch.device(device).type == 'cuda':\n for _ in range(2):\n src.grad.data.zero_()\n res = torch.gather(src, dim, idx)\n res.backward(weight)\n self.assertEqual(src.grad, grad, atol=0, rtol=0)\n else:\n expected = torch.zeros_like(src, device=device)\n for i in range(elems):\n expected[idx[i]] += weight[i]\n self.assertEqual(grad, expected, atol=0, rtol=0)\n\n # FIXME: move to test_scatter_gather_ops\n @onlyNativeDeviceTypes\n def test_gather_backward_deterministic_path(self, device) -> None:\n self._test_gather_backward_one_dim(device, True)\n\n # FIXME: move to test_scatter_gather_ops\n @onlyCPU\n def test_gather_backward_one_dim(self, device) -> None:\n self._test_gather_backward_one_dim(device, False)\n\n # FIXME: move to test_scatter_gather_ops\n @onlyNativeDeviceTypes\n def test_scatter_add_one_dim_deterministic(self, device) -> None:\n with DeterministicGuard(True):\n m = random.randint(20, 30)\n elems = random.randint(2000 * m, 3000 * m)\n dim = 0\n src = torch.randn(elems, device=device)\n idx = torch.randint(m, (elems,), device=device)\n\n x = torch.zeros(m, device=device)\n res = x.scatter_add(dim, idx, src)\n\n expected = torch.zeros(m, device=device)\n for i in range(elems):\n expected[idx[i]] += src[i]\n\n self.assertEqual(res, expected, atol=0, rtol=0)\n\n # FIXME: move to test_scatter_gather_ops\n @onlyNativeDeviceTypes\n def test_scatter_zero_size_index(self, device) -> None:\n null_index = torch.zeros((0, 4), dtype=torch.int64)\n null_arr = torch.zeros((0, 4))\n original = torch.arange(4, dtype=torch.float32)\n result = original.scatter(0, null_index, null_arr)\n self.assertEqual(result, original, atol=0, rtol=0)\n\n @onlyCUDA\n def test_sync_warning(self, device):\n\n def _sync_raises_helper(f, level):\n with CudaSyncGuard(level):\n if level == 1:\n with self.assertWarnsRegex(UserWarning, \"called a synchronizing \"):\n f()\n elif level == 2:\n with self.assertRaisesRegex(RuntimeError, \"called a synchronizing \"):\n f()\n\n def _no_sync_helper(f, level):\n with CudaSyncGuard(level):\n f()\n\n def _ind_put_fn(x, ind, val):\n x[ind] = val\n return x\n\n def _ind_get_fn(x, ind):\n return x[ind]\n\n def _cond_fn(x):\n if x: # taking boolean value of a tensor synchronizes\n return x\n else:\n return 2 * x\n\n # prepare inputs for subsequent ops\n size = 4\n x = torch.rand(size, device=device)\n y = torch.rand((), device=device)\n ind = torch.randint(size, (3,), device=device)\n ind_cpu = ind.cpu()\n repeats = torch.full((1,), 2, device=device)\n mask = torch.randint(2, (size,), device=device, dtype=bool)\n expect_no_sync = (lambda: _ind_put_fn(x, mask, 1.),\n lambda: _ind_put_fn(x, ind, y),\n lambda: _ind_get_fn(x, ind),\n lambda: torch.nn.functional.one_hot(ind, num_classes=size),\n lambda: torch.randperm(20000, device=device),\n lambda: torch.repeat_interleave(x, 2, output_size=2 * size),\n lambda: torch.repeat_interleave(x, repeats, output_size=2 * size))\n expect_sync = (lambda: _ind_put_fn(x, mask, y),\n lambda: _ind_put_fn(x, ind_cpu, y),\n lambda: _ind_get_fn(x, mask),\n lambda: _ind_get_fn(x, ind_cpu),\n lambda: x.nonzero(),\n lambda: _cond_fn(y),\n lambda: torch.nn.functional.one_hot(ind),\n lambda: torch.repeat_interleave(x, 2),\n lambda: torch.repeat_interleave(x, repeats))\n for f, level in product(expect_no_sync, (1, 2)):\n _no_sync_helper(f, level)\n for f, level in product(expect_sync, (1, 2)):\n _sync_raises_helper(f, level)\n\n\n @dtypes(*floating_types_and(torch.half, torch.bfloat16))\n def test_log_normal(self, device, dtype):\n a = torch.tensor([10], dtype=dtype, device=device).log_normal_()\n self.assertEqual(a.dtype, dtype)\n self.assertEqual(a.size(), torch.Size([1]))\n\n @dtypes(*all_types_and(torch.half, torch.bfloat16))\n def test_geometric(self, device, dtype):\n a = torch.tensor([10], dtype=dtype, device=device).geometric_(0.5)\n self.assertEqual(a.dtype, dtype)\n self.assertEqual(a.size(), torch.Size([1]))\n\n def test_repeat_interleave(self, device):\n y = torch.tensor([[1, 2], [3, 4]], device=device)\n # exercise single argument function signature\n temp = y.repeat_interleave(2)\n self.assertEqual(torch.Size([8]), temp.size())\n\n for dtype in [torch.int, torch.long]:\n lengths = torch.tensor([1, 2], dtype=dtype, device=device)\n output_size = torch.sum(lengths)\n a = torch.repeat_interleave(\n y,\n lengths,\n dim=0,\n )\n self.assertEqual(a.dtype, y.dtype)\n self.assertEqual(a.size(), torch.Size([3, 2]))\n\n a_with_output = torch.repeat_interleave(\n y,\n lengths,\n dim=0,\n output_size=output_size,\n )\n self.assertEqual(a_with_output.dtype, y.dtype)\n self.assertEqual(a_with_output.size(), torch.Size([3, 2]))\n\n @dtypes(*floating_types())\n @dtypesIfCPU(*floating_types_and(torch.bfloat16))\n @dtypesIfCUDA(*floating_types_and(torch.half))\n def test_bernoulli_p(self, device, dtype):\n for trivial_p in ([0, 1], [1, 0, 1, 1, 0, 1]):\n x = torch.tensor(trivial_p, dtype=dtype, device=device)\n self.assertEqual(x.bernoulli().tolist(), trivial_p)\n\n def isBinary(t):\n return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0\n\n p = torch.rand(5, 5, dtype=dtype, device=device)\n self.assertTrue(isBinary(p.bernoulli()))\n\n p = torch.rand(5, dtype=dtype, device=device).expand(5, 5)\n self.assertTrue(isBinary(p.bernoulli()))\n\n p = torch.rand(5, 5, dtype=dtype, device=device)\n torch.bernoulli(torch.rand_like(p), out=p)\n self.assertTrue(isBinary(p))\n\n # RngUniform not implemented for Integral type in XLA test\n @dtypes(*floating_types())\n @dtypesIfCPU(*all_types_and(torch.bool))\n @dtypesIfCUDA(*all_types_and(torch.bool, torch.half))\n def test_bernoulli_self(self, device, dtype):\n\n def isBinary(t):\n return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0\n\n t = torch.empty(10, 10, dtype=dtype, device=device)\n\n t.fill_(2)\n t.bernoulli_(0.5)\n self.assertTrue(isBinary(t))\n\n for p_dtype in floating_types_and(*[torch.half] if device.startswith('cuda') else []):\n p = torch.rand(10, dtype=p_dtype, device=device).expand(10, 10)\n t.fill_(2)\n t.bernoulli_(p)\n self.assertTrue(isBinary(t))\n\n t.fill_(2)\n torch.bernoulli(torch.rand_like(t, dtype=p_dtype), out=t)\n self.assertTrue(isBinary(t))\n\n t.fill_(2)\n t.bernoulli_(torch.rand_like(t, dtype=p_dtype))\n self.assertTrue(isBinary(t))\n\n @slowTest\n @dtypes(*floating_types())\n @dtypesIfCUDA(*floating_types_and(torch.half))\n def test_bernoulli_edge_cases(self, device, dtype):\n # Need to draw a lot of samples to cover every random floating point number.\n a = torch.zeros(10000, 10000, dtype=dtype, device=device) # probability of drawing \"1\" is 0\n num_ones = (torch.bernoulli(a) == 1).sum()\n self.assertEqual(num_ones, 0)\n\n b = torch.ones(10000, 10000, dtype=dtype, device=device) # probability of drawing \"1\" is 1\n num_zeros = (torch.bernoulli(b) == 0).sum()\n self.assertEqual(num_zeros, 0)\n\n @dtypes(*floating_types_and(torch.half, torch.bfloat16))\n def test_exponential(self, device, dtype):\n a = torch.tensor([10], dtype=dtype, device=device).exponential_(0.5)\n self.assertEqual(a.dtype, dtype)\n self.assertEqual(a.size(), torch.Size([1]))\n\n # Tests extremal behavior\n tests = ((-0, float('inf')), (0, float('inf')), (float('inf'), 0))\n for test in tests:\n t = torch.empty((1,), device=device, dtype=dtype).exponential_(test[0])\n self.assertTrue(t.item() == test[1])\n\n # Tests that negative lambda fails\n with self.assertRaises(RuntimeError):\n torch.empty((1,), device=device, dtype=dtype).exponential_(-0.5)\n\n @onlyCUDA\n @dtypes(torch.half, torch.float)\n def test_exponential_no_zero(self, device, dtype):\n # naively, 0 in exponential can be generated with probability 2^-24\n # so we need more samples to check if it's not generated\n # instead of doing one\n # don't test CPU, that would be a long test\n x = torch.empty(50000000, device=device, dtype=dtype).exponential_()\n self.assertTrue(x.min() > 0)\n\n def _generate_correlation_tensors(self, device, dtype):\n yield make_tensor((0, 0), dtype=dtype, device=device)\n yield make_tensor((1, 0), dtype=dtype, device=device)\n yield make_tensor((0, 1), dtype=dtype, device=device)\n yield make_tensor((2,), dtype=dtype, device=device)\n yield make_tensor((2, 1), dtype=dtype, device=device)\n yield make_tensor((2, 2), dtype=dtype, device=device)\n yield make_tensor((2, 3), dtype=dtype, device=device)\n yield make_tensor((5, 10), dtype=dtype, device=device)\n yield make_tensor((5, 10), dtype=dtype, device=device, noncontiguous=True)\n if dtype != torch.int:\n yield torch.tensor([0, -2, nan, 10.2, inf], dtype=dtype, device=device)\n\n @onlyNativeDeviceTypes\n @dtypes(torch.int, torch.float, torch.cfloat)\n def test_corrcoef(self, device, dtype):\n for x in self._generate_correlation_tensors(device, dtype):\n res = torch.corrcoef(x)\n ref = np.corrcoef(x.cpu().numpy())\n self.assertEqual(res, ref, exact_dtype=False)\n\n @dtypes(torch.int, torch.float, torch.cfloat)\n def test_cov(self, device, dtype):\n def check(t, correction=1, fweights=None, aweights=None):\n res = torch.cov(t, correction=correction, fweights=fweights, aweights=aweights)\n t = t.cpu().numpy()\n fweights = fweights.cpu().numpy() if fweights is not None else None\n aweights = aweights.cpu().numpy() if aweights is not None else None\n ref = np.cov(t, ddof=correction, fweights=fweights, aweights=aweights)\n self.assertEqual(res, ref, atol=1e-05, rtol=1e-05, exact_dtype=False)\n\n for x in self._generate_correlation_tensors(device, dtype):\n check(x)\n num_observations = x.numel() if x.ndim < 2 else x.size(1)\n if num_observations > 0:\n fweights = torch.randint(1, 10, (num_observations,), device=device)\n aweights = make_tensor((num_observations,), dtype=torch.float, device=device, low=1)\n for correction, fw, aw in product([0, 1, 2], [None, fweights], [None, aweights]):\n check(x, correction, fweights, aweights)\n\n @skipIfNoSciPy\n @dtypes(*floating_types_and(torch.half, torch.bfloat16))\n def test_uniform_kstest(self, device, dtype):\n from scipy import stats\n size = 1000\n for from_ in [-42, 0, 4.2]:\n for to_ in [-4.2, 0, 42]:\n if to_ > from_:\n t = torch.empty(size, dtype=dtype, device=device).uniform_(from_, to_)\n res = stats.kstest(t.cpu().to(torch.double), 'uniform', args=(from_, (to_ - from_)))\n self.assertTrue(res.statistic < 0.1)\n\n @skipIfNoSciPy\n @dtypes(*floating_types_and(torch.half))\n @dtypesIfCUDA(*floating_types_and(torch.half, torch.bfloat16))\n def test_normal_kstest(self, device, dtype):\n from scipy import stats\n size = 1000\n for mean in [-10, 0, 50]:\n for std in [1, 5, 10]:\n t = torch.empty(size, dtype=dtype, device=device).normal_(mean=mean, std=std)\n res = stats.kstest(t.cpu().to(torch.double), 'norm', args=(mean, std))\n self.assertTrue(res.statistic < 0.1)\n\n @skipIfNoSciPy\n @dtypes(*floating_types_and(torch.half, torch.bfloat16))\n def test_lognormal_kstest(self, device, dtype):\n from scipy import stats\n size = 1000\n for mean in [-3, 0, 7]:\n for std in [1, 5, 7]:\n t = torch.empty(size, dtype=dtype, device=device).log_normal_(mean=mean, std=std)\n res = stats.kstest(t.cpu().to(torch.double), 'lognorm', args=(std, 0, math.exp(mean)))\n if dtype == torch.half:\n self.assertTrue(res.statistic < 0.3)\n else:\n self.assertTrue(res.statistic < 0.1)\n\n @skipIfNoSciPy\n @dtypes(*floating_types_and(torch.half, torch.bfloat16))\n def test_exponential_kstest(self, device, dtype):\n from scipy import stats\n size = 1000\n for lambd in [0.5, 1.0, 5.0]:\n t = torch.empty(size, dtype=dtype, device=device).exponential_(lambd=lambd)\n res = stats.kstest(t.cpu().to(torch.double), 'expon', args=(0, 1 / lambd,))\n self.assertTrue(res.statistic < 0.1)\n\n @skipIfNoSciPy\n @dtypes(*floating_types_and(torch.half, torch.bfloat16))\n def test_cauchy_kstest(self, device, dtype):\n from scipy import stats\n size = 1000\n for median in [-10, 0, 50]:\n for sigma in [0.5, 1.0, 10.0]:\n t = torch.empty(size, dtype=dtype, device=device).cauchy_(median=median, sigma=sigma)\n res = stats.kstest(t.cpu().to(torch.double), 'cauchy', args=(median, sigma))\n self.assertTrue(res.statistic < 0.1)\n\n @slowTest\n @onlyCUDA\n @dtypes(torch.bfloat16, torch.float32)\n def test_cauchy_no_inf(self, device, dtype):\n # torch.float16 will have `inf` because of its smaller range.\n for _ in range((2**16) * 2):\n x = torch.empty((2**16), dtype=dtype, device=device)\n x.cauchy_()\n self.assertFalse(x.isinf().sum())\n\n @skipIfNoSciPy\n @dtypes(*all_types_and(torch.half, torch.bfloat16))\n def test_geometric_kstest(self, device, dtype):\n from scipy import stats\n size = 1000\n for p in [0.2, 0.5, 0.8]:\n t = torch.empty(size, dtype=dtype, device=device).geometric_(p=p)\n actual = np.histogram(t.cpu().to(torch.double), np.arange(1, 100))[0]\n expected = stats.geom(p).pmf(np.arange(1, 99)) * size\n res = stats.chisquare(actual, expected)\n self.assertEqual(res.pvalue, 1.0, atol=0.1, rtol=0)\n\n # FIXME: find test suite for pdist and cdist\n def test_pairwise_distance_empty(self, device):\n shape = (2, 0)\n x = torch.randn(shape, device=device)\n y = torch.randn(shape, device=device)\n\n self.assertEqual(torch.zeros(2, device=device), torch.pairwise_distance(x, y))\n self.assertEqual(torch.zeros((2, 1), device=device), torch.pairwise_distance(x, y, keepdim=True))\n\n shape = (0, 2)\n x = torch.randn(shape, device=device)\n y = torch.randn(shape, device=device)\n self.assertEqual(torch.zeros(0, device=device), torch.pairwise_distance(x, y))\n self.assertEqual(torch.zeros((0, 1), device=device), torch.pairwise_distance(x, y, keepdim=True))\n\n def test_pdist_empty(self, device):\n shape = (0, 2)\n x = torch.randn(shape, device=device)\n self.assertEqual(torch.empty(0, device=device), torch.pdist(x))\n\n shape = (1, 2)\n x = torch.randn(shape, device=device)\n self.assertEqual(torch.empty(0, device=device), torch.pdist(x))\n\n shape = (3, 0)\n x = torch.randn(shape, device=device)\n self.assertEqual(torch.zeros(3, device=device), torch.pdist(x))\n\n def test_cdist_empty(self, device):\n x = torch.randn((0, 5), device=device)\n y = torch.randn((4, 5), device=device)\n self.assertEqual(torch.empty(0, 4, device=device), torch.cdist(x, y))\n\n x = torch.randn((2, 5), device=device)\n y = torch.randn((0, 5), device=device)\n self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y))\n\n x = torch.randn((2, 0), device=device)\n y = torch.randn((3, 0), device=device)\n self.assertEqual(torch.zeros(2, 3, device=device), torch.cdist(x, y))\n\n x = torch.randn((2, 0), device=device)\n y = torch.randn((0, 0), device=device)\n self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y))\n\n def _brute_cdist(self, x, y, p=2):\n r1 = x.shape[-2]\n r2 = y.shape[-2]\n if r1 == 0 or r2 == 0:\n return torch.empty(r1, r2, device=x.device)\n return torch.norm(x[..., None, :] - y[..., None, :, :], p=p, dim=-1)\n\n def test_cdist_norm(self, device):\n for r1 in [3, 4, 5, 6]:\n for m in [2, 3, 4, 10]:\n for r2 in [4, 6, 7, 8]:\n for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]:\n x = torch.randn(r1, m, device=device)\n y = torch.randn(r2, m, device=device)\n if p == 2:\n for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertEqual(expected, actual, rtol=0, atol=0.02)\n else:\n actual = torch.cdist(x, y, p=p)\n expected = self._brute_cdist(x, y, p=p)\n self.assertEqual(expected, actual)\n\n def test_cdist_norm_batch(self, device):\n for r1 in [3, 4, 5, 6]:\n for m in [2, 3, 4, 10]:\n for r2 in [4, 6, 7, 8]:\n for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]:\n x = torch.randn(2, 3, 6, r1, m, device=device)\n y = torch.randn(2, 3, 6, r2, m, device=device)\n if p == 2:\n for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertEqual(expected, actual, rtol=0, atol=0.02)\n else:\n actual = torch.cdist(x, y, p=p)\n expected = self._brute_cdist(x, y, p=p)\n self.assertEqual(expected, actual)\n\n @onlyCUDA\n def test_cdist_cuda_backward(self, device):\n for l1 in [1, 511, 513]:\n for l2 in [1, 511, 513]:\n for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]:\n x1 = torch.randn(4, l1, 32, device=device, requires_grad=True)\n x2 = x1.clone().detach_().requires_grad_()\n y1 = torch.randn(4, l2, 32, device=device, requires_grad=True)\n y2 = y1.clone().detach_().requires_grad_()\n if p == 2:\n for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n z1 = torch.cdist(x1, y1, p=2, compute_mode=cm).mean()\n z2 = self._brute_cdist(x2, y2, p=2).mean()\n z1.backward()\n z2.backward()\n self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001)\n self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001)\n else:\n z1 = torch.cdist(x1, y1, p=p).mean()\n z2 = self._brute_cdist(x2, y2, p=p).mean()\n self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001)\n self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001)\n\n @tf32_on_and_off(0.005)\n def test_cdist_large(self, device):\n for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n x = torch.randn(1000, 10, device=device)\n y = torch.randn(1000, 10, device=device)\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertEqual(expected, actual)\n\n @slowTest\n @tf32_on_and_off(0.01)\n def test_cdist_large_batch(self, device):\n for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n x = torch.randn(4, 3, 1000, 10, device=device)\n y = torch.randn(4, 3, 1000, 10, device=device)\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertEqual(expected, actual)\n\n @tf32_on_and_off(0.005)\n def test_cdist_non_contiguous(self, device):\n for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n x = torch.randn(5, 7, device=device).mT\n y = torch.randn(5, 3, device=device).mT\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertFalse(x.is_contiguous())\n self.assertFalse(y.is_contiguous())\n self.assertEqual(expected, actual)\n\n x = torch.randn(7, 5, device=device)\n y = torch.randn(5, 3, device=device).t()\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertTrue(x.is_contiguous())\n self.assertFalse(y.is_contiguous())\n self.assertEqual(expected, actual)\n\n x = torch.randn(5, 7, device=device).t()\n y = torch.randn(3, 5, device=device)\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertFalse(x.is_contiguous())\n self.assertTrue(y.is_contiguous())\n self.assertEqual(expected, actual)\n\n @tf32_on_and_off()\n def test_cdist_non_contiguous_batch(self, device):\n for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n x = torch.randn(4, 3, 2, 5, 7, device=device).mT\n y = torch.randn(4, 3, 2, 5, 3, device=device).mT\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertFalse(x.is_contiguous())\n self.assertFalse(y.is_contiguous())\n self.assertEqual(expected, actual)\n\n x = torch.randn(7, 2, 7, 5, device=device)\n y = torch.randn(7, 2, 5, 3, device=device).mT\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertTrue(x.is_contiguous())\n self.assertFalse(y.is_contiguous())\n self.assertEqual(expected, actual)\n\n x = torch.randn(4, 5, 7, device=device).mT\n y = torch.randn(4, 3, 5, device=device)\n actual = torch.cdist(x, y, p=2, compute_mode=cm)\n expected = self._brute_cdist(x, y, p=2)\n self.assertFalse(x.is_contiguous())\n self.assertTrue(y.is_contiguous())\n self.assertEqual(expected, actual)\n\n # Maybe merge into OpInfo?\n def test_cdist_euclidean_large(self, device):\n def _test_euclidean_large_cdist(sizex, sizey=None):\n if sizey is None:\n sizey = sizex\n x = torch.randn(sizex, device=device, dtype=torch.float)\n y = torch.randn(sizey, device=device, dtype=torch.float)\n eps = 1e-6\n # to avoid extremum\n x = x - (((x - y) < eps).float() * 2 * eps)\n x.requires_grad = True\n y.requires_grad = True\n dist = torch.cdist(x, y, p=2)\n # Do a backward pass to check that it is valid for large\n # matrices\n loss = dist.sum()\n loss.backward()\n\n _test_euclidean_large_cdist((2000, 5))\n\n # Ensure that cdist backward with p<1 does not produce NaNs\n def test_cdist_grad_p_lt_1_no_nan(self, device):\n for p in [0.99, 0.7, 0.5, 0.1, 0.01]:\n x = torch.randn(1, 2, device=device)\n y = x.clone().detach() + torch.tensor([[1., 0.]], device=device)\n x.requires_grad = True\n y.requires_grad = True\n result = torch.cdist(x, y, p=p)\n result.backward(torch.ones_like(result))\n self.assertFalse(torch.isnan(x.grad).any())\n self.assertFalse(torch.isnan(y.grad).any())\n\n def test_cdist_same_inputs(self, device):\n # Test to detect issues in cdist gradient calculation\n # When the distances are 0\n sizex = (1, 27, 32)\n for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]:\n x = torch.randn(sizex, device=device, dtype=torch.float)\n dist_grad = torch.randn((1, 27, 27), device=device, dtype=torch.float)\n y = x.clone()\n eps = 1e-6\n x.requires_grad = True\n d = torch.cdist(x, y)\n d.backward(dist_grad)\n # Check that the backward passs does not contain invalid\n # values such as nan or inf\n assert torch.isfinite(x.grad).all()\n\n def test_cumsum(self, device):\n x = torch.rand(100, 100, device=device)\n res1 = torch.cumsum(x, 1)\n res2 = torch.tensor([]).to(device)\n torch.cumsum(x, 1, out=res2)\n self.assertEqual(res1, res2)\n x.cumsum_(1)\n self.assertEqual(res1, x)\n\n a = torch.tensor([[True, False, True],\n [False, False, False],\n [True, True, True]], device=device)\n b = a.byte()\n aRes = torch.cumsum(a, 0)\n bRes = torch.cumsum(b, 0)\n self.assertEqual(aRes, bRes)\n self.assertEqual(aRes, torch.tensor([[1, 0, 1],\n [1, 0, 1],\n [2, 1, 2]]))\n\n aRes = torch.cumsum(a, 1)\n bRes = torch.cumsum(b, 1)\n self.assertEqual(aRes, bRes)\n self.assertEqual(aRes, torch.tensor([[1, 1, 2],\n [0, 0, 0],\n [1, 2, 3]]))\n\n # Check that cummulative sum over a zero length dimension doesn't crash on backprop.\n # Also check that cumsum over other dimensions in a tensor with a zero-length\n # dimensiuon also works\n # Also include a basic suite of similar tests for other bases cases.\n shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]]\n for shape in shapes:\n for dim in range(len(shape)):\n raw_tensor = torch.zeros(*shape, requires_grad=True)\n integrated = raw_tensor.cumsum(dim=dim)\n # Check that backward does not crash\n integrated.sum().backward()\n # Check that output maintained correct shape\n self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape)\n\n # Check a scalar example\n raw_tensor = torch.tensor(3., requires_grad=True)\n integrated = raw_tensor.cumsum(dim=-1)\n self.assertEqual(raw_tensor, integrated)\n # Check that backward does not crash\n integrated.sum().backward()\n # Check that output maintained correct shape\n self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape)\n\n def test_cumprod(self, device):\n x = torch.rand(100, 100, device=device)\n res1 = torch.cumprod(x, 1)\n res2 = torch.tensor([]).to(device)\n torch.cumprod(x, 1, out=res2)\n self.assertEqual(res1, res2)\n x.cumprod_(1)\n self.assertEqual(res1, x)\n\n a = torch.tensor([[True, False, True],\n [False, False, False],\n [True, True, True]], dtype=torch.bool, device=device)\n b = a.byte()\n aRes = torch.cumprod(a, 0)\n bRes = torch.cumprod(b, 0)\n self.assertEqual(aRes, bRes)\n self.assertEqual(aRes, torch.tensor([[1, 0, 1],\n [0, 0, 0],\n [0, 0, 0]]))\n\n aRes = torch.cumprod(a, 1)\n bRes = torch.cumprod(b, 1)\n self.assertEqual(aRes, bRes)\n self.assertEqual(aRes, torch.tensor([[1, 0, 0],\n [0, 0, 0],\n [1, 1, 1]]))\n\n # Check that cummulative prod over a zero length dimension doesn't crash on backprop.\n # Also check that cumprod over other dimensions in a tensor with a zero-length\n # dimensiuon also works\n # Also include a basic suite of similar tests for other bases cases.\n shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]]\n for shape in shapes:\n for dim in range(len(shape)):\n raw_tensor = torch.zeros(*shape, requires_grad=True)\n integrated = raw_tensor.cumprod(dim=dim)\n # Check that backward does not crash\n integrated.sum().backward()\n # Check that output maintained correct shape\n self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape)\n\n # Check a scalar example\n raw_tensor = torch.tensor(3., requires_grad=True)\n integrated = raw_tensor.cumprod(dim=-1)\n self.assertEqual(raw_tensor, integrated)\n # Check that backward does not crash\n integrated.sum().backward()\n # Check that output maintained correct shape\n self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape)\n\n def test_cummax_cummin(self, device):\n def test_ops(op, string_of_function_name, expected_output1, expected_output2):\n x = torch.rand(100, 100, device=device)\n out1 = op(x, 1)\n res2 = torch.empty(0, device=device)\n indices2 = torch.empty(0, dtype=torch.int64, device=device)\n op(x, 1, out=(res2, indices2))\n self.assertEqual(out1[0], res2)\n self.assertEqual(out1[1], indices2)\n\n a = torch.tensor([[True, False, True],\n [False, False, False],\n [True, True, True]], dtype=torch.bool, device=device)\n b = a.byte()\n aRes = op(a, 0)\n bRes = op(b, 0)\n self.assertEqual(aRes[0], bRes[0].bool())\n self.assertEqual(aRes[0], expected_output1.bool())\n\n # test inf and nan input\n x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1])\n xRes = op(x, 0)[0]\n self.assertEqual(xRes, expected_output2)\n\n # op shouldn't support values, indices with a dtype, device type or layout\n # different from that of input tensor\n t = torch.randn(10)\n values = torch.empty(0, dtype=torch.int16)\n indices = torch.empty(0, dtype=torch.int64)\n with self.assertRaisesRegex(\n RuntimeError,\n 'expected scalar_type Float but found Short'):\n op(t, 0, out=(values, indices))\n\n # Check that op over a zero length dimension doesn't crash on backprop.\n # Also check that op over other dimensions in a tensor with a zero-length\n # dimension also works\n # Also include a basic suite of similar tests for other bases cases.\n shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]]\n for shape in shapes:\n for dim in range(len(shape)):\n raw_tensor = torch.zeros(*shape, requires_grad=True)\n integrated = getattr(raw_tensor, string_of_function_name)(dim=dim)\n # Check that backward does not crash\n integrated[0].sum().backward()\n # Check that output maintained correct shape\n self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape)\n\n # Check a scalar example\n raw_tensor = torch.tensor(3., requires_grad=True)\n integrated = getattr(raw_tensor, string_of_function_name)(dim=-1)\n # Check that backward does not crash\n integrated[0].sum().backward()\n # Check that output maintained correct shape\n self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape)\n\n expected_out = torch.tensor([4, inf, inf, inf, inf, nan, nan])\n test_ops(torch.cummax, \"cummax\", torch.tensor([[1, 0, 1],\n [1, 0, 1],\n [1, 1, 1]]), expected_out)\n\n expected_out = torch.tensor([4, 4, 1.5, -inf, -inf, nan, nan])\n test_ops(torch.cummin, \"cummin\", torch.tensor([[1, 0, 1],\n [0, 0, 0],\n [0, 0, 0]]), expected_out)\n\n def test_logcumsumexp(self, device):\n def logcumsumexp(a, axis):\n return torch.cumsum(a.exp(), axis=axis).log_()\n\n axis = -1\n a = torch.randn(100, 100, device=device)\n\n actual = a.logcumsumexp(axis)\n expected = logcumsumexp(a, axis)\n self.assertEqual(a.dtype, actual.dtype)\n self.assertEqual(expected.shape, actual.shape)\n self.assertEqual(expected, actual)\n\n # check -inf and nan handling\n x = torch.tensor([-float('inf'), -float('inf'), 1.0, 1.0, float('inf'),\n float('inf'), float('nan'), 1.0, 1.0], device=device)\n x2d = x.unsqueeze(0).expand(2, -1)\n\n for inp in (x, x2d):\n actual = inp.logcumsumexp(axis)\n expected = logcumsumexp(inp, axis)\n self.assertEqual(expected, actual)\n\n # Check that out is actually inplace\n b = torch.randn(5, 2, device=device)\n inplace_out = torch.zeros(5, 2, device=device)\n\n expected = logcumsumexp(b, axis)\n torch.logcumsumexp(b, axis=axis, out=inplace_out)\n\n self.assertEqual(inplace_out, expected)\n\n # Check input and inplace_output type mismatch\n b = torch.randn(5, 2, device=device, dtype=torch.float64)\n inplace_out = torch.zeros(5, 2, device=device, dtype=torch.float32)\n with self.assertRaisesRegex(\n RuntimeError,\n 'expected scalar_type Double but found Float'):\n torch.logcumsumexp(b, axis, out=inplace_out)\n\n def _test_diff_numpy(self, t, dims=None):\n # Helper for test_diff to compare with NumPy reference implementation\n def to_np(t):\n if t.dtype == torch.bfloat16:\n return t.to(dtype=torch.float, device=\"cpu\").numpy()\n else:\n return t.cpu().numpy()\n\n for dim in dims if dims else range(t.dim()):\n prepend = t.narrow(dim, 0, 1)\n append = t.narrow(dim, 0, 1)\n np_t = to_np(t)\n\n # test when no prepend and append\n for n in range(t.size(dim)):\n actual = torch.diff(t, dim=dim, n=n)\n expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n))\n self.assertEqual(actual, expected.to(t.dtype))\n\n # test when prepend and append's size along dim is 1\n for n in range(1, t.size(dim) + 4):\n actual = torch.diff(t, dim=dim, n=n, prepend=prepend, append=append)\n expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n, prepend=to_np(prepend), append=to_np(append)))\n self.assertEqual(actual, expected.to(t.dtype))\n\n # test when prepend and append's size along dim != 1\n for n in range(1, t.size(dim) * 3):\n actual = torch.diff(t, dim=dim, n=n, prepend=t, append=t)\n expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n, prepend=np_t, append=np_t))\n self.assertEqual(actual, expected.to(t.dtype))\n\n # All tensors appear contiguous on XLA\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool))\n def test_diff_noncontig(self, device, dtype):\n shapes = (\n (1,),\n (1, 5),\n (3, 5),\n (1, 5, 1),\n (2, 3, 5))\n\n for shape in shapes:\n contig = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9)\n\n non_contig = torch.empty(shape + (2, 2), device=device, dtype=dtype)[..., 0]\n non_contig = non_contig.select(-1, -1)\n non_contig.copy_(contig)\n self.assertTrue(not non_contig.is_contiguous() or shape == (1,))\n\n self._test_diff_numpy(non_contig)\n\n # RngNormal not implemented for type f16 for XLA\n @dtypes(*all_types_and_complex_and(torch.bool))\n @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool))\n @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool))\n def test_diff(self, device, dtype):\n shapes = (\n (1,),\n (1, 5),\n (3, 5),\n (1, 5, 1),\n (2, 3, 5))\n\n for shape in shapes:\n contig = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9)\n self._test_diff_numpy(contig)\n\n t = torch.ones(2, 3)\n\n with self.assertRaisesRegex(\n RuntimeError, 'diff expects prepend or append to be the same dimension as input'):\n invalid_prepend = torch.tensor([1, 2, 3], device=device, dtype=dtype)\n t.diff(dim=0, prepend=invalid_prepend)\n\n with self.assertRaisesRegex(\n RuntimeError, 'diff expects the shape of tensor to prepend or append to match that of input'):\n invalid_prepend = torch.tensor([[0, 1]], device=device, dtype=dtype)\n t.diff(dim=0, prepend=invalid_prepend)\n\n with self.assertRaisesRegex(\n RuntimeError, 'diff expects input to be at least one-dimensional'):\n scalar = torch.tensor(2, device=device, dtype=dtype)\n torch.diff(scalar)\n\n # if the given input arg is not a list, it returns a list of single element: [arg]\n def _wrap_to_list(self, input_array):\n return input_array if isinstance(input_array, list) else [input_array]\n\n # To ensure inf, -inf, and nan values do not cause divergence between Numpy and PyTorch.\n # There are two types of possible divergence:\n # 1. When we compute a,b both real numbers and has very small absolute values (i.e. very near to 0.0)\n # then, result of a/b be inf, -inf and nan, and this cause divergence.\n # 2. When we are dividing complex numbers by zero. For example, when a = torch.tensor(3+5j) we have\n # a/0 to be equal to nan + nan*j in PyTorch and inf + inf*j in Numpy.\n def _inf_nan_preprocess(self, actual, expected):\n for i in range(len(expected)):\n expected[i] = np.nan_to_num(expected[i], nan=nan, posinf=nan, neginf=nan)\n # nan_to_num is not defined for complex tensors in PyTorch.\n if actual[i].dtype == torch.complex64 :\n actual[i].real = torch.nan_to_num(actual[i].real, nan=nan, posinf=nan, neginf=nan)\n actual[i].imag = torch.nan_to_num(actual[i].imag, nan=nan, posinf=nan, neginf=nan)\n else:\n actual[i] = torch.nan_to_num(actual[i], nan=nan, posinf=nan, neginf=nan)\n\n return actual, expected\n\n @onlyNativeDeviceTypes\n @dtypes(torch.long, torch.float32, torch.complex64)\n def test_gradient_all(self, device, dtype):\n def create_scalar(shape):\n return make_tensor((1,), device='cpu', dtype=dtype, low=1.).item()\n\n def create_list(shape):\n return make_tensor((len(shape),), device='cpu', dtype=dtype, low=1.).tolist()\n\n def create_coordinate_tensors(shape):\n tensor_list = []\n for i in range(len(shape)):\n tensor_list.append(make_tensor((shape[i],), device=device, dtype=dtype))\n return tensor_list\n\n def filter_shape(shape, dim):\n filtered_shape = []\n for i in range(len(dim)):\n filtered_shape.append(shape[dim[i]])\n return filtered_shape\n\n # shape, dims format\n test_cases = (\n ((5,), (0,)),\n ((4, 4), (0, 1)),\n ((3, 3, 3), (-1, 0)),\n ((4, 4, 4), (2,)),\n ((4, 4, 4), (0, 1)),\n ((4, 4, 4, 3), (0, 2, 3)),\n ((4, 5, 3, 4, 3), (1, 2)),\n ((4, 3, 6, 5, 3), (2, 4)),\n ((4, 3, 3, 5, 3), (0, 1, 2, 3, 4)),\n ((1, 3, 3), (1, 2)),\n ((1, 5), (1,)),\n )\n\n for case, contig, edge_order, space_fn in product(test_cases, [True, False], [1, 2],\n (create_scalar, create_list, create_coordinate_tensors)):\n shape, dims = case\n # filter shape by dims before passing filtered shape to create_* functions\n filtered_shape = filter_shape(shape, dims)\n\n spacing = space_fn(filtered_shape)\n t = make_tensor(shape, device=device, dtype=dtype, noncontiguous=not contig)\n t_np = t.cpu().numpy()\n\n actual = torch.gradient(t, spacing=spacing, dim=dims, edge_order=edge_order)\n if space_fn == create_coordinate_tensors and spacing[0].device != 'cpu':\n spacing = [space.cpu().detach().numpy() for space in spacing]\n expected = np.gradient(t_np, *self._wrap_to_list(spacing), axis=dims, edge_order=edge_order)\n actual, expected = self._inf_nan_preprocess(list(actual), self._wrap_to_list(expected))\n self.assertEqual(actual, expected, equal_nan=True, atol=1e-4, rtol=0, exact_dtype=False)\n\n @onlyNativeDeviceTypes\n @dtypes(torch.long, torch.float32, torch.complex64)\n def test_gradient_extreme_cases(self, device, dtype):\n # Test behaviour for inf and nan values\n actual = torch.gradient(torch.tensor([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan]))\n expected = np.gradient(np.array([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan]))\n self.assertEqual(actual, self._wrap_to_list(expected), exact_dtype=False)\n\n # Test behaviour in very big tensors\n large_size = 100000\n t = make_tensor((large_size,), dtype=dtype, device=device)\n t_np = t.cpu().numpy()\n coordinates_np = list(np.random.randn(large_size))\n coordinates = [torch.tensor(coordinates_np, device=device)]\n actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=1)\n expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=1)]\n self.assertEqual(actual, expected, exact_dtype=False)\n\n actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=2)\n expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=2)]\n self.assertEqual(actual, expected, exact_dtype=False)\n\n @onlyNativeDeviceTypes\n def test_gradient_type_promotion(self, device):\n inputs = (\n make_tensor((4, 4), device=device, dtype=torch.float32),\n make_tensor((4, 4), device=device, dtype=torch.complex64),\n make_tensor((4, 4), device=device, dtype=torch.int64),\n )\n\n spacing = (\n make_tensor((1,), device='cpu', dtype=torch.float32).item(),\n make_tensor((1,), device='cpu', dtype=torch.int64).item(),\n make_tensor((1,), device='cpu', dtype=torch.complex64).item(),\n make_tensor((2,), device='cpu', dtype=torch.float32, low=0.1).tolist(),\n make_tensor((2,), device='cpu', dtype=torch.int64, low=1).tolist(),\n make_tensor((2,), device='cpu', dtype=torch.complex64).tolist(),\n [make_tensor((4,), device=device, dtype=torch.float32),\n make_tensor((4,), device=device, dtype=torch.float32)],\n [make_tensor((4,), device=device, dtype=torch.int64),\n make_tensor((4,), device=device, dtype=torch.int64)],\n [make_tensor((4,), device=device, dtype=torch.complex64),\n make_tensor((4,), device=device, dtype=torch.complex64)],\n )\n\n for input, spacing_or_coord, edge_order in product(inputs, spacing, [1, 2]):\n input_np = input.cpu().numpy()\n input_np = input.cpu().numpy()\n actual = torch.gradient(input, spacing=spacing_or_coord, dim=(0, 1), edge_order=edge_order)\n spacing_or_coord_wrapped = self._wrap_to_list(spacing_or_coord)\n spacing_or_coord_np = []\n if torch.is_tensor(spacing_or_coord_wrapped[0]) and torch.device(spacing_or_coord_wrapped[0].device).type != 'cpu':\n for i in range(len(spacing_or_coord_wrapped)):\n spacing_or_coord_np.append(spacing_or_coord_wrapped[i].detach().clone().cpu().numpy())\n else:\n spacing_or_coord_np = spacing_or_coord_wrapped\n expected = np.gradient(input_np, *spacing_or_coord_np, axis=(0, 1), edge_order=edge_order)\n if actual[0].dtype == torch.complex64 and input.dtype != torch.complex64:\n for i in range(len(actual)):\n self.assertEqual(actual[i].real, expected[i].real, exact_dtype=False)\n # Type promotion fails on Numpy when spacing is given as complex number and input is given as real.\n # Result is given just as real number and all the imaginary parts to be equal to zero.\n self.assertEqual(expected[i].imag, torch.zeros(actual[i].shape), exact_dtype=False)\n else:\n actual, expected = self._inf_nan_preprocess(list(actual), expected)\n self.assertEqual(actual, expected, equal_nan=True, exact_dtype=False)\n\n def _test_large_cum_fn_helper(self, x, fn):\n x_cpu = x.cpu().float()\n expected = fn(x_cpu)\n actual = fn(x).cpu().float()\n self.assertEqual(expected, actual.cpu().float())\n\n @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, \"sandcastle OOM with current tpx gpu/re configuration\")\n @onlyCUDA\n @dtypes(torch.half) # only small dtype not to get oom\n def test_large_cumsum(self, device, dtype):\n # initialization to avoid overflow and half caveats\n x = torch.empty(2**30 + 200, device=device, dtype=dtype)\n x[::3] = -3\n x[1::3] = 2\n x[2::3] = 1\n self._test_large_cum_fn_helper(x, lambda x: torch.cumsum(x, 0))\n\n @onlyCUDA\n @dtypes(torch.half) # only small dtype not to get oom\n def test_large_cumprod(self, device, dtype):\n # initialization to avoid overflow and half caveats\n x = torch.empty(2**30 + 200, device=device, dtype=dtype)\n x[::3] = 8\n x[1::3] = .25\n x[2::3] = .5\n self._test_large_cum_fn_helper(x, lambda x: torch.cumprod(x, 0))\n\n def test_discontiguous_out_cumsum(self, device):\n x = torch.randn(4, 8, device=device)\n y = torch.empty(4, 16, device=device)[:, ::2]\n out = torch.cumsum(x, 0)\n torch.cumsum(x, 0, out=y)\n self.assertFalse(y.is_contiguous())\n self.assertEqual(out, y, atol=0., rtol=0.)\n\n def _test_cumminmax_helper(self, x, fn, expected_val, expected_ind):\n val, ind = fn(x, -1)\n self.assertEqual(val, expected_val, atol=0, rtol=0)\n self.assertEqual(ind, expected_ind, atol=0, rtol=0)\n out_val = torch.empty_like(val).t().contiguous().t()\n out_ind = torch.empty_like(ind).t().contiguous().t()\n fn(x, -1, out=(out_val, out_ind))\n self.assertFalse(out_val.is_contiguous())\n self.assertFalse(out_ind.is_contiguous())\n self.assertEqual(out_val, expected_val, atol=0, rtol=0)\n self.assertEqual(out_ind, expected_ind, atol=0, rtol=0)\n\n def test_cummax_discontiguous(self, device):\n x = torch.tensor([[0, 1, 2, 3, 2, 1], [4, 5, 6, 5, 6, 7]], device=device, dtype=torch.float).t().contiguous().t()\n expected_val = torch.tensor([[0, 1, 2, 3, 3, 3], [4, 5, 6, 6, 6, 7]], device=device, dtype=torch.float)\n expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 2, 4, 5]], device=device, dtype=torch.long)\n self._test_cumminmax_helper(x, torch.cummax, expected_val, expected_ind)\n\n def test_cummin_discontiguous(self, device):\n x = torch.tensor([[3, 2, 1, 0, 1, 2], [7, 6, 5, 4, 5, 2]], device=device, dtype=torch.float).t().contiguous().t()\n expected_val = torch.tensor([[3, 2, 1, 0, 0, 0], [7, 6, 5, 4, 4, 2]], device=device, dtype=torch.float)\n expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 3, 3, 5]], device=device, dtype=torch.long)\n self._test_cumminmax_helper(x, torch.cummin, expected_val, expected_ind)\n\n def test_bool_tensor_value_change(self, device):\n x = torch.tensor([True, False], dtype=torch.bool, device=device)\n x[0] = False\n x[1] = True\n self.assertEqual(x, torch.tensor([False, True], dtype=torch.bool, device=device))\n\n # FIXME: move to shape ops test suite\n def test_unfold_all_devices_and_dtypes(self, device):\n for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16):\n\n if dt == torch.bool:\n x = torch.empty((0, 1, 3, 0), dtype=dt, device=device)\n self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape)\n else:\n x = torch.empty((0, 1, 3, 0), dtype=dt, device=device)\n self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape)\n\n # FIXME: move to shape ops test suite\n def test_unfold_scalars(self, device):\n x = torch.tensor(0.5, device=device)\n # unfold on a 0-dimensional tensor should always return a 1-d dimensional\n # tensor of shape [size] (i.e., the second parameter to unfold)\n\n self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 1))\n self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 2))\n self.assertEqual(torch.tensor([0.5], device=device), x.unfold(0, 1, 1))\n\n # FIXME: move to data movement test suite\n def test_copy_all_dtypes_and_devices(self, device):\n from copy import copy\n for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16):\n x = torch.tensor([1, 2, 3, 4], dtype=dt, device=device)\n x_clone = x.clone()\n y = copy(x)\n y.fill_(1)\n # copy is a shallow copy, only copies the tensor view,\n # not the data\n self.assertEqual(x, y)\n\n # FIXME: move to data movement test suite\n @onlyNativeDeviceTypes\n def test_copy_math_view(self, device):\n for dst_dtype, src_dtype in [\n (torch.float32, torch.float32),\n (torch.float64, torch.float32),\n (torch.int64, torch.int32),\n (torch.complex128, torch.complex64),\n ]:\n src = make_tensor((100,), dtype=src_dtype, device=device)\n dst = torch.empty(100, dtype=dst_dtype, device=device)\n\n dst.copy_(src)\n self.assertEqual(dst, src, exact_dtype=False)\n\n dst.copy_(src._neg_view())\n self.assertEqual(dst, src.neg(), exact_dtype=False)\n\n dst._neg_view().copy_(torch._neg_view(src))\n self.assertEqual(dst, src, exact_dtype=False)\n\n dst._neg_view().copy_(src)\n self.assertEqual(dst, src.neg(), exact_dtype=False)\n\n for dst_dtype, src_dtype in [\n (torch.complex64, torch.complex64),\n (torch.complex128, torch.complex64),\n ]:\n src = make_tensor((100,), dtype=src_dtype, device=device)\n dst = torch.empty(100, dtype=dst_dtype, device=device)\n\n dst.conj().copy_(src)\n self.assertEqual(dst, src.conj_physical(), exact_dtype=False)\n\n dst.conj().copy_(src._neg_view())\n self.assertEqual(dst, src.neg().conj_physical(), exact_dtype=False)\n\n # FIXME: move to data movement test suite\n @onlyNativeDeviceTypes\n @dtypes(torch.int64, torch.float32, torch.complex64)\n def test_copy_transpose_math_view(self, device, dtype):\n src = make_tensor((100, 100), dtype=dtype, device=device).transpose(0, 1)\n dst = torch.empty((100, 100), dtype=dtype, device=device)\n\n dst._neg_view().copy_(src)\n self.assertEqual(dst, -src)\n dst._neg_view().copy_(src._neg_view())\n self.assertEqual(dst, src)\n dst.copy_(src._neg_view())\n self.assertEqual(dst, -src)\n\n if dtype.is_complex:\n dst.conj().copy_(src)\n self.assertEqual(dst, src.conj_physical())\n dst.conj().copy_(src.conj())\n self.assertEqual(dst, src)\n dst.copy_(src.conj())\n self.assertEqual(dst, src.conj_physical())\n\n def test_clone_all_dtypes_and_devices(self, device):\n for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16):\n x = torch.tensor((1, 1), dtype=dt, device=device)\n y = x.clone()\n self.assertEqual(x, y)\n\n def test_clone_zero_stride_dim(self, device):\n # stride zero, size 1 axis, not contiguous\n x = torch.randn(10)\n y = x.as_strided([2, 1, 5], [1, 0, 2])\n self.assertEqual(y, y.clone())\n\n def test_clone_not_memory_dense(self):\n # github issue: https://github.com/pytorch/pytorch/issues/64176\n x = torch.randn(10, 8).t()[::2, ::2]\n y = x.clone()\n # should retain permutation after densification\n self.assertTrue(y.stride() == (1, 4))\n\n # FIXME: move to elementwise ternary test suite\n @dtypesIfCUDA(*set(get_all_math_dtypes('cuda')))\n @dtypes(*set(get_all_math_dtypes('cpu')))\n def test_addcmul(self, device, dtype):\n # Returns floating or integral scalar corresponding to dtype\n def _number(floating, integer, dtype):\n if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]:\n return floating\n elif dtype in [torch.cfloat, torch.cdouble]:\n return floating * (1 + 1j)\n else:\n return integer\n\n def rand_tensor(size, dtype, device):\n if dtype.is_floating_point or dtype.is_complex:\n return torch.rand(size=size, dtype=dtype, device=device)\n if dtype == torch.uint8:\n return torch.randint(1, 5, size=size, dtype=dtype, device=device)\n else:\n return torch.randint(-5, 5, size=size, dtype=dtype, device=device)\n\n a = rand_tensor((2, 2), dtype=dtype, device=device)\n b = rand_tensor((2, 2), dtype=dtype, device=device)\n c = rand_tensor((2, 2), dtype=dtype, device=device)\n\n alpha = _number(0.5, 3, dtype)\n\n actual = torch.addcmul(a, b, c, value=alpha)\n expected = a + alpha * b * c\n\n self.assertEqual(expected, actual)\n\n with self.assertWarnsOnceRegex(\n UserWarning, \"This overload of addcmul is deprecated\"):\n self.assertEqual(actual, torch.addcmul(a, alpha, b, c))\n\n if self.device_type == 'cuda' and dtype == torch.half:\n a = torch.tensor([60000.0], device=device, dtype=dtype)\n b = torch.tensor([60000.0], device=device, dtype=dtype)\n c = torch.tensor([2.0], device=device, dtype=dtype)\n out = torch.addcmul(a, b, c, value=-1)\n self.assertTrue(not (out.isnan() or out.isinf()))\n\n # FIXME: move to shape ops test suite\n def test_narrow_empty(self, device):\n x = torch.randn(2, 3, 4, device=device)\n for d in range(x.dim()):\n y = x.narrow(d, x.size(d), 0)\n sz = list(x.size())\n sz[d] = 0\n self.assertEqual(sz, y.size())\n\n # FIXME: move to test indexing\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_index_copy(self, device, dtype):\n # We just test for num_copy <= num_dest, as otherwise there are repeated indices\n # and the behavior is undefined\n num_copy, num_dest = 3, 5\n\n def make_arg(batch_sizes, n, dim, contig):\n size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:]\n return make_tensor(size_arg, dtype=dtype, device=device, low=None, high=None, noncontiguous=not contig)\n\n def ref_index_copy(tgt, dim, idx, src):\n for i in range(idx.size(0)):\n idx_dest = dim * (slice(None),) + (idx[i],)\n idx_src = dim * (slice(None),) + (i,)\n tgt[idx_dest] = src[idx_src]\n\n # More thorough testing as in index_add\n for dest_contig, src_contig, index_contig in product([True, False], repeat=3):\n for other_sizes in ((), (4, 5)):\n for dim in range(len(other_sizes)):\n dest = make_arg(other_sizes, num_dest, dim, dest_contig)\n src = make_arg(other_sizes, num_copy, dim, src_contig)\n idx = torch.randperm(num_dest, dtype=torch.int64, device=device)[:num_copy]\n if not index_contig:\n idx = torch.repeat_interleave(idx, 2, dim=-1)\n idx = idx[..., ::2]\n dest2 = dest.clone()\n dest.index_copy_(dim, idx, src)\n ref_index_copy(dest2, dim, idx, src)\n self.assertEqual(dest, dest2)\n\n # FIXME: move to test indexing\n # onlyNativeDeviceTypes due to an XLA error:\n # https://github.com/pytorch/pytorch/issues/53256\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_index_copy_scalars(self, device, dtype):\n # Create the 8 possible combinations of scalar sizes for target / index / source\n scalars = ((make_tensor(size_t, dtype=dtype, device=device, low=None, high=None),\n make_tensor(size_i, dtype=torch.int64, device=device, low=0, high=1),\n make_tensor(size_s, dtype=dtype, device=device, low=None, high=None))\n for size_t, size_i, size_s in product([(), (1,)], repeat=3))\n for target, idx, source in scalars:\n target.index_copy_(0, idx, source)\n self.assertEqual(target.item(), source.item())\n\n # FIXME: move to test indexing\n @onlyCPU\n def test_errors_index_copy(self, device):\n # We do not test the GPU as the CUDA_ASSERT would break the CUDA context\n idx_dim = 8\n tgt_dim = 5\n batch_dim = 3\n\n # Too large of an index\n a = torch.randn(batch_dim, tgt_dim, device=device)\n idx = torch.full((idx_dim,), tgt_dim, device=device)\n c = torch.zeros(batch_dim, idx_dim, device=device)\n with self.assertRaises(IndexError):\n a.index_copy_(1, idx, c)\n\n # Too small (negative indices)\n idx = torch.full((idx_dim,), -1, device=device)\n with self.assertRaises(IndexError):\n a.index_copy_(1, idx, c)\n\n # Too small (very negative indices) - they should be unsupported even\n # when support for negative indices is implemented for index_copy_\n idx = torch.full((idx_dim,), -tgt_dim - 1, device=device)\n with self.assertRaises(IndexError):\n a.index_copy_(1, idx, c)\n\n def _prepare_data_for_index_copy_and_add_deterministic(\n self, dim: int, device: torch.device\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n assert (dim >= 0 and dim < 3)\n a = [5, 4, 3]\n a[dim] = 2000\n x = torch.zeros(a, device=device)\n b = a.copy()\n elems = a[dim] * 20\n b[dim] = elems\n src = torch.rand(b, device=device)\n index = torch.randint(a[dim], (elems,), device=device)\n return (x, index, src)\n\n # FIXME: move to test indexing\n @onlyNativeDeviceTypes\n def test_index_copy_deterministic(self, device: torch.device) -> None:\n for dim in range(3):\n x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device)\n with DeterministicGuard(True):\n y0 = torch.index_copy(x, dim, index, src)\n\n x0 = x.clone().detach()\n index_list = index.tolist()\n for i in range(len(index_list)):\n if dim == 0:\n x0[index_list[i], :, :] = src[i, :, :]\n elif dim == 1:\n x0[:, index_list[i], :] = src[:, i, :]\n elif dim == 2:\n x0[:, :, index_list[i]] = src[:, :, i]\n\n self.assertEqual(x0, y0, atol=0, rtol=0)\n\n # FIXME: move to test indexing\n @onlyNativeDeviceTypes\n def test_index_add_deterministic(self, device: torch.device) -> None:\n for dim in range(3):\n x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device)\n alpha = random.random() + 1\n # on CPU it should be deterministic regardless of the deterministic mode\n with DeterministicGuard(True):\n y0 = torch.index_add(x, dim, index, src, alpha=alpha)\n for _ in range(3):\n y = torch.index_add(x, dim, index, src, alpha=alpha)\n self.assertEqual(y, y0, atol=0, rtol=0)\n\n with DeterministicGuard(False):\n for _ in range(3):\n y_nd = torch.index_add(x, dim, index, src, alpha=alpha)\n self.assertEqual(y_nd, y0, atol=1e-3, rtol=1e-5)\n\n # FIXME: find a test suite for the put operator\n @onlyNativeDeviceTypes\n def test_index_put_non_accumulate_deterministic(self, device) -> None:\n with DeterministicGuard(True):\n for i in range(3):\n m = random.randint(10, 20)\n elems = random.randint(20000, 30000)\n values = torch.rand(elems, device=device)\n indices = torch.randint(m, (elems,), device=device)\n input = torch.rand(m, device=device)\n output = input.index_put((indices,), values, accumulate=False)\n\n input_list = input.tolist()\n indices_list = indices.tolist()\n values_list = values.tolist()\n for i, v in zip(indices_list, values_list):\n input_list[i] = v\n\n self.assertEqual(output, input_list)\n\n # FIXME: move to test indexing\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_index_fill(self, device, dtype):\n x = torch.tensor([[1, 2], [4, 5]], dtype=dtype, device=device)\n index = torch.tensor([0], device=device)\n x.index_fill_(1, index, 0)\n self.assertEqual(x, torch.tensor([[0, 2], [0, 5]], dtype=dtype, device=device))\n if not x.is_complex() and not device == \"meta\":\n with self.assertRaisesRegex(RuntimeError, r\"Scalar\"):\n x.index_fill_(1, index, 1 + 1j)\n # Make sure that the result stays 0-dim while applied to\n # a 0-dim input\n x = torch.tensor(1, dtype=dtype, device=device)\n self.assertEqual(0, x.index_fill(0, index, -1).dim())\n self.assertEqual(0, x.index_fill_(0, index, -1).dim())\n\n # FIXME: move to test indexing\n # The test fails for zero-dimensional tensors on XLA\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_index_select(self, device, dtype):\n num_src, num_out = 3, 5\n\n def make_arg(batch_sizes, n, dim, contig):\n size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:]\n return make_tensor(size_arg, dtype=dtype, device=device, low=None, high=None, noncontiguous=not contig)\n\n def ref_index_select(src, dim, idx):\n # bfloat16 is just used on GPU, so it's not supported on numpy\n if dtype == torch.bfloat16:\n src = src.float()\n out = torch.from_numpy(np.take(src.cpu().numpy(), idx.cpu().numpy(), axis=dim))\n if dtype == torch.bfloat16:\n out = out.to(device=device, dtype=dtype)\n return out\n\n for src_contig, idx_contig in product([True, False], repeat=2):\n for other_sizes in ((), (4, 5)):\n for dim in range(len(other_sizes)):\n src = make_arg(other_sizes, num_src, dim, src_contig)\n idx = make_tensor(\n (num_out,), dtype=torch.int64, device=device, low=0, high=num_src, noncontiguous=not idx_contig\n )\n out = torch.index_select(src, dim, idx)\n out2 = ref_index_select(src, dim, idx)\n self.assertEqual(out, out2)\n\n for idx_type in (torch.int32, torch.int64):\n other_sizes = (3, 2)\n dim = 1\n src = make_arg(other_sizes, num_src, dim, True)\n idx = make_tensor((num_out,), dtype=idx_type, device=device, low=0, high=num_src, noncontiguous=False)\n out = torch.index_select(src, dim, idx)\n out2 = ref_index_select(src, dim, idx)\n self.assertEqual(out, out2)\n\n # Create the 4 possible combinations of scalar sizes for index / source\n scalars = ((make_tensor(size_s, dtype=dtype, device=device),\n torch.zeros(size_i, dtype=torch.int64, device=device))\n for size_s, size_i in product([(), (1,)], repeat=2))\n for source, idx in scalars:\n out = source.index_select(0, idx)\n self.assertEqual(out.item(), source.item())\n\n # FIXME: find a test suite for the take operator\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_take(self, device, dtype):\n idx_size = (4,)\n\n make_arg = partial(make_tensor, device=device, dtype=dtype)\n make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64)\n\n def ref_take(src, idx):\n if dtype == torch.bfloat16:\n src = src.half()\n src = src.cpu().numpy()\n idx = idx.cpu().numpy()\n out = torch.from_numpy(np.take(src, idx)).to(device=device, dtype=dtype)\n return out\n\n for src_contig, idx_contig, idx_reshape in product([True, False], repeat=3):\n for src_size in ((5,), (4, 5)):\n src = make_arg(src_size, noncontiguous=not src_contig)\n idx = make_idx(idx_size, high=src.numel(), noncontiguous=not idx_contig)\n if idx_reshape:\n idx = idx.reshape(2, 2)\n out = torch.take(src, idx)\n out2 = ref_take(src, idx)\n self.assertEqual(out, out2)\n\n # Create the 4 possible combinations of scalar sizes for source / index\n for size_s, size_i in product([(), (1,)], repeat=2):\n source = make_arg(size_s)\n idx = make_idx(size_i, high=1)\n out = source.take(idx)\n self.assertEqual(out.item(), source.item())\n\n # FIXME: find a test suite for the put operator\n # The bool instance does not work on GPU. See\n # https://github.com/pytorch/pytorch/issues/54317\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_put(self, device, dtype):\n src_size = (4,)\n\n make_arg = partial(make_tensor, device=device, dtype=dtype)\n make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64)\n\n def ref_put(dst, idx, src, accumulate):\n new_dst = dst.clone(memory_format=torch.contiguous_format).view(-1)\n new_idx = idx.contiguous().view(-1)\n new_src = src.contiguous().view(-1)\n method = new_dst.index_add_ if accumulate else new_dst.index_copy_\n return method(0, new_idx, new_src).view_as(dst)\n\n for dst_contig, src_contig, idx_contig, idx_reshape, accumulate in product([True, False], repeat=5):\n for dst_size in ((5,), (4, 5)):\n dst = make_arg(dst_size, noncontiguous=not dst_contig)\n src = make_arg(src_size, noncontiguous=not src_contig)\n\n # If accumulate=True, `put_` should be deterministic regardless of the inputs on CPU\n # On CUDA it may not be, but the test has enough tolerance to account for this\n if accumulate:\n idx = make_idx(src_size, high=dst.numel())\n else:\n idx = torch.randperm(dst.numel(), dtype=torch.int64, device=device)[:src_size[0]]\n if not idx_contig:\n idx = torch.repeat_interleave(idx, 2, dim=-1)[..., ::2]\n if idx_reshape:\n idx = idx.reshape(2, 2)\n out = torch.put(dst, idx, src, accumulate)\n # out-place\n reference = ref_put(dst, idx, src, accumulate)\n self.assertEqual(out, reference)\n\n # in-place\n dst.put_(idx, src, accumulate)\n self.assertEqual(dst, reference)\n\n\n # Create the 8 possible combinations of scalar sizes for target / index / source\n scalars = ((make_arg(size_t),\n make_idx(size_i, high=1),\n make_arg(size_s))\n for size_t, size_i, size_s in product([(), (1,)], repeat=3))\n for (dest, idx, source), accumulate in product(scalars, [True, False]):\n dest_init = dest.clone()\n # out-place\n out = torch.put(dest, idx, source, accumulate=accumulate)\n # in-place\n dest1 = dest.clone()\n dest1.put_(idx, source, accumulate=accumulate)\n for d in [out, dest1]:\n if accumulate:\n self.assertEqual(d.item(), (dest_init + source).item())\n else:\n self.assertEqual(d.item(), source.item())\n\n # Empty case\n dest = make_arg((3, 2))\n reference = dest.clone()\n idx = make_idx((0,), high=1)\n source = make_arg((0,))\n for accumulate in [True, False]:\n out = torch.put(dest, idx, source, accumulate=accumulate)\n self.assertEqual(out, reference)\n dest.put_(idx, source, accumulate=accumulate)\n self.assertEqual(dest, reference)\n\n # FIXME: find a test suite for the put operator\n # The bool instance does not work on GPU. See\n # https://github.com/pytorch/pytorch/issues/54317\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_put_accumulate(self, device, dtype):\n # Test for parallel adds with accumulate == True\n low_precision = dtype == torch.half or dtype == torch.bfloat16\n # Less numbers to avoid overflow with low_precision\n # Grainsize is 3000 for the for_loop to be parallized on CPU\n sizes = ((100,)) if low_precision else ((200,), (3002,))\n # Bfloat16 has a particularly bad performance here\n # This operation is nondeterministic on GPU, so we are generous with the rtol\n rtol, atol = (1e-1, 1e-2) if low_precision else (1e-3, 1e-4)\n\n make_arg = partial(make_tensor, low=-2, high=3, device=device, dtype=dtype)\n # Dump everything into the 0-th position\n make_idx = partial(torch.zeros, device=device, dtype=torch.int64)\n args = ((make_idx(size), make_arg(size)) for size in sizes)\n\n for idx, source in args:\n orig = make_arg((1,))\n out = orig.put(idx, source, accumulate=True)\n self.assertEqual(out, orig + source.sum(), rtol=rtol, atol=atol)\n\n # FIXME: find a test suite for the take operator\n def test_take_empty(self, device):\n for input_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]:\n for indices_shape in [(0,), (0, 1, 2, 0)]:\n input = torch.empty(input_shape, device=device)\n indices = torch.empty(indices_shape, dtype=torch.int64, device=device)\n self.assertEqual(indices, torch.take(input, indices), exact_dtype=False)\n\n # FIXME: find a test suite for the put operator\n def test_put_empty(self, device):\n for dst_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]:\n for indices_shape in [(0,), (0, 1, 2, 0)]:\n for accumulate in [False, True]:\n dst = torch.randn(dst_shape, device=device)\n indices = torch.empty(indices_shape, dtype=torch.int64, device=device)\n src = torch.randn(indices_shape, device=device)\n self.assertEqual(dst, dst.put_(indices, src, accumulate=accumulate))\n\n # FIXME: port to test_scatter_gather_ops.py\n def scatter_allow_reduce(self, device, dtype, reduceop):\n device_type = torch.device(device).type\n return device_type != 'cuda' or (reduceop == 'multiply' and dtype.is_floating_point)\n\n @dtypes(*floating_and_complex_types())\n @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_scatter_reduce_operations_to_large_input(self, device, dtype):\n index = torch.tensor([[1], [2]], device=device, dtype=torch.long)\n test_data = [\n (torch.zeros(4, 4, device=device, dtype=dtype),\n torch.ones(2, 2, device=device, dtype=dtype),\n torch.tensor([[0, 0, 0, 0],\n [1, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 0]],\n device=device, dtype=dtype), \"add\"),\n (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4),\n torch.tensor([6], device=device, dtype=dtype).repeat(2, 2),\n torch.tensor([[2, 2, 2, 2],\n [12, 2, 2, 2],\n [12, 2, 2, 2],\n [2, 2, 2, 2]], device=device, dtype=dtype), \"multiply\"),\n ]\n\n for input, src, result, operation in test_data:\n if not self.scatter_allow_reduce(device, dtype, operation):\n continue\n input.scatter_(0, index, src, reduce=operation)\n self.assertEqual(input, result)\n\n @dtypes(*floating_and_complex_types())\n @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_scatter_reduce_scalar(self, device, dtype):\n index = torch.tensor([[1], [2]], device=device, dtype=torch.long)\n test_data = [\n (torch.zeros(4, 4, device=device, dtype=dtype), 1,\n torch.tensor([[0, 0, 0, 0],\n [1, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 0]],\n device=device, dtype=dtype), \"add\"),\n (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), 2,\n torch.tensor([[2, 2, 2, 2],\n [4, 2, 2, 2],\n [4, 2, 2, 2],\n [2, 2, 2, 2]], device=device, dtype=dtype), \"multiply\"),\n ]\n\n for input, src, result, operation in test_data:\n if not self.scatter_allow_reduce(device, dtype, operation):\n continue\n input.scatter_(0, index, src, reduce=operation)\n self.assertEqual(input, result)\n\n # FIXME: port to test_scatter_gather_ops.py\n # TODO: remove this after scatter_add_ is deprecated.\n def test_scatter_add_non_unique_index(self, device):\n height = 2\n width = 65536\n input = torch.ones(height, width, device=device)\n index = torch.zeros(height, width, dtype=torch.long, device=device)\n src = torch.ones(height, width, device=device)\n input.scatter_add_(0, index, src)\n\n self.assertEqual(input,\n torch.tensor([[3], [1]], device=device,\n dtype=torch.float32).repeat(1, width))\n\n @dtypes(*floating_and_complex_types())\n @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_scatter_reduce_non_unique_index(self, device, dtype):\n height = 2\n width = 2\n index = torch.zeros(height, width, dtype=torch.long, device=device)\n test_data = [\n (torch.ones(height, width, device=device, dtype=dtype),\n torch.ones(height, width, device=device, dtype=dtype),\n torch.tensor([[3], [1]], device=device, dtype=dtype).repeat(1, width), \"add\"),\n (torch.tensor([2], device=device, dtype=dtype).repeat(height, width),\n torch.tensor([2], device=device, dtype=dtype).repeat(height, width),\n torch.tensor([[8], [2]], device=device,\n dtype=dtype).repeat(1, width), \"multiply\"),\n ]\n\n for input, src, result, operation in test_data:\n if not self.scatter_allow_reduce(device, dtype, operation):\n continue\n input.scatter_(0, index, src, reduce=operation)\n self.assertEqual(input, result, msg=f\"result: {result} input: {input} method: {str(operation)}\")\n\n @onlyCUDA\n @dtypes(*integral_types(), *complex_types())\n def test_scatter_reduce_multiply_unsupported_dtypes(self, device, dtype):\n height = 2\n width = 2\n index = torch.zeros(height, width, dtype=torch.long, device=device)\n input = torch.ones(height, width, device=device, dtype=dtype)\n src = torch.ones(height, width, device=device, dtype=dtype)\n with self.assertRaises(RuntimeError):\n input.scatter_(0, index, src, reduce=\"multiply\")\n\n # FIXME: port to test_scatter_gather_ops.py\n def test_scatter_to_large_input(self, device):\n input = torch.zeros(4, 4, device=device)\n src = torch.ones(2, 2, device=device)\n index = torch.tensor([[1], [2]], device=device, dtype=torch.long)\n input.scatter_(0, index, src)\n self.assertEqual(input, torch.tensor([[0, 0, 0, 0],\n [1, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 0]], device=device, dtype=torch.float32))\n\n # FIXME: port to test_scatter_gather_ops.py\n def test_scatter_add_to_large_input(self, device):\n input = torch.zeros(4, 4, device=device)\n src = torch.ones(2, 2, device=device)\n index = torch.tensor([[1], [2]], device=device, dtype=torch.long)\n input.scatter_add_(0, index, src)\n self.assertEqual(input, torch.tensor([[0, 0, 0, 0],\n [1, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 0]], device=device, dtype=torch.float32))\n\n # FIXME: port to test_scatter_gather_ops.py\n def test_scatter_bool(self, device):\n x = torch.tensor([[True, True, True], [True, True, True]], device=device)\n res = torch.zeros(3, 3, dtype=torch.bool, device=device)\n res = res.scatter_(0, torch.tensor([[0, 1, 2], [0, 1, 2]], device=device), x)\n self.assertEqual(res, torch.tensor([[True, False, False],\n [False, True, False],\n [False, False, True]], device=device))\n\n # FIXME: port to test_scatter_gather_ops.py\n def test_scatter_add_bool(self, device):\n x = torch.tensor([[True, True, True, True, True], [True, True, True, True, True]], device=device)\n res = torch.zeros(3, 5, dtype=torch.bool, device=device)\n res = res.scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]], device=device), x)\n self.assertEqual(res, torch.tensor([[True, True, True, True, True],\n [False, True, False, True, False],\n [True, False, True, False, True]], device=device))\n\n # FIXME: find a test suite for the masked scatter operator\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_masked_scatter(self, device, dtype):\n dt = dtype\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n for maskType in [torch.uint8, torch.bool]:\n num_copy, num_dest = 3, 10\n dest = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dt, device=device)\n dest2 = dest.clone()\n dest_ones = dest.clone()\n dest_ones_expected = dest.clone()\n src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dt, device=device)\n src_ones = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=dt, device=device)\n mask = torch.tensor((0, 0, 0, 0, 1, 0, 1, 0, 1, 0), dtype=maskType, device=device)\n\n if dt == torch.bool:\n # torch.bool is a special case and is being tested\n # in a separate test\n return\n\n dest.masked_scatter_(mask, src)\n j = 0\n for i in range(num_dest):\n if mask[i]:\n dest2[i] = src[j]\n dest_ones_expected[i] = src_ones[j]\n j += 1\n self.assertEqual(dest, dest2, atol=0, rtol=0)\n\n dest_ones.masked_scatter_(mask, src_ones)\n self.assertEqual(dest_ones, dest_ones_expected, atol=0, rtol=0)\n\n # Bound checking in CUDA is done inside a kernel\n # in order to avoid synchronization, but this means\n # we can not clear the failures. So there is no way\n # to test it then recover.\n if self.device_type != 'cuda':\n # make src smaller. this should fail\n src = torch.zeros(num_copy - 1, dtype=dt, device=device)\n with self.assertRaises(RuntimeError):\n dest.masked_scatter_(mask, src)\n\n # empty tensor\n dest = torch.empty((5, 0, 5), dtype=dt, device=device)\n mask = torch.ones_like(dest, dtype=maskType, device=device)\n src = torch.empty((0,), dtype=dt, device=device)\n dest.masked_scatter_(mask, src)\n\n dest = torch.empty((5, 0, 5), dtype=dt, device=device)\n mask = torch.ones((5, 1, 5), dtype=maskType, device=device)\n src = torch.empty((0,), dtype=dt, device=device)\n dest.masked_scatter_(mask, src)\n\n if self.device_type != 'cuda':\n self.assertEqual(len(w), 5)\n else:\n self.assertEqual(len(w), 4)\n\n warn = 'masked_scatter_ received a mask with dtype torch.uint8,'\n for wi in w:\n self.assertEqual(str(wi.message)[0:55], str(warn))\n\n # FIXME: find a test suite for the masked scatter operator\n def test_masked_scatter_bool_tensor(self, device):\n src = torch.tensor([True, True, True], device=device)\n dst = torch.tensor([False, False, False], device=device)\n mask = torch.tensor([False, True, False], device=device)\n\n dst.masked_scatter_(mask, src)\n self.assertEqual(dst, torch.tensor([False, True, False], device=device))\n\n mask = torch.tensor([True, False, True], device=device)\n dst = dst.masked_scatter(mask, src)\n self.assertEqual(dst, torch.tensor([True, True, True], device=device))\n\n # FIXME: find a test suite for the masked scatter operator\n # test_scatter_gather_ops or test_masked_ops?\n @onlyCUDA\n @largeTensorTest('30GB')\n def test_masked_scatter_large_tensor(self, device):\n t_cpu = torch.empty(2**31 + 1, dtype=torch.bool).random_()\n t = t_cpu.to(device)\n result_cpu = t_cpu.masked_scatter(t_cpu, t_cpu)\n result = t.masked_scatter(t, t)\n self.assertEqual(result, result_cpu)\n\n # FIXME: find a test suite for the masked select operator\n @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))\n def test_masked_select(self, device, dtype):\n if device == 'cpu':\n warn = 'masked_select received a mask with dtype torch.uint8,'\n else:\n warn = 'indexing with dtype torch.uint8 is now deprecated, pl'\n for maskType in [torch.uint8, torch.bool]:\n num_src = 10\n src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dtype, device=device)\n mask = torch.randint(2, (num_src,), device=device, dtype=maskType)\n\n with warnings.catch_warnings(record=True) as w:\n dst = src.masked_select(mask)\n if maskType is torch.uint8:\n self.assertEqual(len(w), 1)\n self.assertEqual(str(w[0].message)[0:53], str(warn))\n dst2 = []\n for i in range(num_src):\n if mask[i]:\n dst2 += [src[i]]\n self.assertEqual(dst, torch.tensor(dst2), atol=0, rtol=0)\n\n dst3 = torch.empty(0, device=device, dtype=dtype)\n torch.masked_select(src, mask, out=dst3)\n self.assertEqual(dst3, torch.tensor(dst2, dtype=dst3.dtype), atol=0, rtol=0)\n\n # Since half on CPU is not supported, need to skip the remaining test cases\n if dtype == torch.half and torch.device(device).type == 'cpu':\n return\n\n # Ensure that masks are expanded to match tensor properly\n a = torch.rand(100, 100, device=device).mul(100).to(dtype)\n mask_first_el_each_row = torch.zeros(100, device=device, dtype=torch.bool)\n mask_first_el_each_row[0] = True\n a_masked = a.masked_select(mask_first_el_each_row)\n self.assertEqual(a_masked, a[:, 0])\n\n mask_first_row = torch.zeros(100, 1, device=device, dtype=torch.bool)\n mask_first_row[0][0] = True\n a_masked = a.masked_select(mask_first_row)\n self.assertEqual(a_masked, a[0, :])\n\n # Ensure that tensor is expanded to match mask properly\n a = torch.rand(100, device=device).mul(100).to(dtype)\n mask_copy_3_times = torch.tensor([[True], [True], [False], [True]], device=device)\n a_masked = a.masked_select(mask_copy_3_times)\n self.assertEqual(a_masked, a.unsqueeze(0).expand(3, 100).flatten())\n\n # FIXME: find a test suite for the masked select operator\n def test_masked_select_discontiguous(self, device):\n for size in (10, 200):\n vals = torch.rand(size, size, device=device)\n mask = torch.full((size, size), False, dtype=torch.bool, device=device)\n mask[:, ::2] = True\n vals_list = (vals, vals.t())\n mask_list = (mask, mask.t())\n out_dc = torch.empty(size * size, device=device)[::2]\n for v, m in product(vals_list, mask_list):\n if m.is_contiguous():\n expected = v[:, ::2].clone().reshape((-1, ))\n else:\n expected = v[::2].clone().reshape((-1, ))\n out = torch.masked_select(v, m)\n self.assertEqual(out, expected, atol=0, rtol=0)\n torch.masked_select(v, m, out=out_dc)\n self.assertEqual(out_dc, expected, atol=0, rtol=0)\n\n # FIXME: find a test suite for the masked fill operator\n @dtypes(*product(all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16), (torch.uint8, torch.bool)))\n def test_masked_fill(self, device, dtypes):\n dtype = dtypes[0]\n mask_dtype = dtypes[1]\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n\n num_dest = 10\n dst = torch.zeros(num_dest, dtype=dtype)\n mask = torch.randint(2, (num_dest,), dtype=mask_dtype)\n val = random.random()\n dst2 = dst.clone()\n\n dst.masked_fill_(mask, val)\n for i in range(num_dest):\n if mask[i]:\n dst2[i] = val\n self.assertEqual(dst, dst2, atol=0, rtol=0)\n\n # test non-contiguous case\n dst = ((torch.randn(num_dest, num_dest, num_dest) * 10).to(dtype)).permute((2, 0, 1))\n dst2 = dst.contiguous()\n if dtype.is_complex:\n mask = dst.abs() > 0\n else:\n mask = dst > 0\n self.assertTrue(not dst.is_contiguous())\n self.assertTrue(dst2.is_contiguous())\n dst.masked_fill_(mask.to(mask_dtype), val)\n dst2.masked_fill_(mask.to(mask_dtype), val)\n self.assertEqual(dst, dst2, atol=0, rtol=0)\n\n if mask_dtype == torch.uint8:\n self.assertEqual(len(w), 3)\n\n warn = 'masked_fill_ received a mask with dtype torch.uint8,'\n for wi in w:\n self.assertEqual(str(wi.message)[0:52], str(warn))\n else:\n self.assertEqual(len(w), 0)\n\n # FIXME: find a test suite for the masked fill operator\n def test_masked_fill_bool_tensor(self, device):\n dst = torch.tensor([True, False, True], device=device)\n mask = torch.tensor([False, True, False], device=device)\n\n dst.masked_fill_(mask, True)\n self.assertEqual(dst, torch.tensor([True, True, True], device=device))\n\n dst = dst.masked_fill(mask, False)\n self.assertEqual(dst, torch.tensor([True, False, True], device=device))\n\n def test_tensor_shape_empty(self, device):\n x = torch.randn((0, 1, 3, 0), device=device)\n # flatten\n self.assertEqual((0,), torch.flatten(x, 0, 3).shape)\n self.assertEqual((0, 0), torch.flatten(x, 0, 2).shape)\n self.assertEqual((0, 3, 0), torch.flatten(x, 1, 2).shape)\n\n # squeeze, unsqueeze\n self.assertEqual((0, 1, 1, 3, 0), torch.unsqueeze(x, 1).shape)\n self.assertEqual((0, 3, 0), torch.squeeze(x, 1).shape)\n self.assertEqual((0, 3, 0), torch.squeeze(x).shape)\n\n # transpose, t\n self.assertEqual((0, 0, 3, 1), torch.transpose(x, 1, 3).shape)\n y = torch.randn((5, 0), device=device)\n self.assertEqual((0, 5), y.t().shape)\n\n # select\n self.assertEqual((0, 1, 0), torch.select(x, 2, 2).shape)\n\n # repeat, permute\n self.assertEqual((9, 0, 5, 6, 0), x.repeat(9, 7, 5, 2, 3).shape)\n self.assertEqual((3, 0, 0, 1), x.permute(2, 3, 0, 1).shape)\n\n # diagonal, diagflat\n self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device)).shape)\n self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device)).shape)\n # off the end offsets are valid\n self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device), offset=1).shape)\n self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device), offset=1).shape)\n # check non-zero sized offsets off the end\n self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=45252).shape)\n self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=-45252).shape)\n\n self.assertEqual((0, 0), torch.diagflat(torch.tensor([], device=device)).shape)\n self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([], device=device), offset=1))\n self.assertEqual((0, 0), torch.diagflat(torch.tensor([[]], device=device)).shape)\n self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([[]], device=device), offset=1))\n\n # stack, split, chunk\n self.assertEqual((4, 0, 1, 3, 0), torch.stack((x, x, x, x)).shape)\n self.assertEqual([(0, 1, 3, 0)],\n [z.shape for z in torch.chunk(x, 1, dim=0)])\n\n self.assertEqual([(0, 1, 3, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=0)])\n self.assertEqual([(0, 1, 1, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=2)])\n\n # NOTE: split_with_sizes behaves differently than NumPy in that it\n # takes sizes rather than offsets\n self.assertEqual([(0, 1, 0, 0), (0, 1, 1, 0), (0, 1, 2, 0)],\n [z.shape for z in torch.split(x, (0, 1, 2), dim=2)])\n\n self.assertRaises(RuntimeError, lambda: torch.split(x, 0, dim=1))\n # This is strange because the split size is larger than the dim size, but consistent with\n # how split handles that case generally (when no 0s are involved).\n self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 1, dim=0)])\n self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 0, dim=0)])\n\n # functions that operate over a dimension but don't reduce.\n def test_dim_function_empty(self, device):\n shape = (0, 1, 2, 0)\n x = torch.randn(shape, device=device)\n\n # size stride\n self.assertEqual(0, x.size(3))\n self.assertEqual(2, x.size(2))\n self.assertEqual(2, x.stride(0))\n self.assertEqual(1, x.stride(2))\n\n self.assertEqual(x, torch.nn.functional.glu(x, 0))\n self.assertEqual((0, 1, 1, 0), torch.nn.functional.glu(x, 2).shape)\n\n # softmax, logsoftmax\n self.assertEqual(x, torch.nn.functional.softmax(x, 0))\n self.assertEqual(x, torch.nn.functional.softmax(x, 2))\n self.assertEqual(x, torch.nn.functional.softmax(x, 3))\n\n self.assertEqual(x, torch.nn.functional.log_softmax(x, 0))\n self.assertEqual(x, torch.nn.functional.log_softmax(x, 2))\n self.assertEqual(x, torch.nn.functional.log_softmax(x, 3))\n\n # cumsum, cumprod, cummax, cummin\n self.assertEqual(shape, torch.cumsum(x, 0).shape)\n self.assertEqual(shape, torch.cumsum(x, 2).shape)\n self.assertEqual(shape, torch.cumprod(x, 0).shape)\n self.assertEqual(shape, torch.cumprod(x, 2).shape)\n self.assertEqual(shape, torch.cummax(x, 0)[0].shape)\n self.assertEqual(shape, torch.cummax(x, 2)[0].shape)\n self.assertEqual(shape, torch.cummin(x, 0)[0].shape)\n self.assertEqual(shape, torch.cummin(x, 2)[0].shape)\n self.assertEqual(shape, torch.logcumsumexp(x, 0).shape)\n self.assertEqual(shape, torch.logcumsumexp(x, 2).shape)\n\n # flip\n self.assertEqual(x, x.flip(0))\n self.assertEqual(x, x.flip(2))\n\n # roll\n self.assertEqual(x, x.roll(0, 1).roll(0, -1))\n self.assertEqual(x, x.roll(1, x.size(1)))\n self.assertEqual(x, x.roll(1))\n self.assertEqual(x, x.roll((1, 1), (3, 1)))\n\n # unbind\n self.assertEqual((), x.unbind(0))\n self.assertEqual((torch.empty((0, 1, 0), device=device), torch.empty((0, 1, 0), device=device)),\n x.unbind(2))\n\n # cross\n y = torch.randn((0, 1, 3, 0), device=device)\n self.assertEqual(y.shape, torch.cross(y, y).shape)\n\n # renorm\n self.assertEqual(shape, torch.renorm(x, 1, 0, 5).shape)\n self.assertEqual(shape, torch.renorm(x, 1, 2, 5).shape)\n\n # sort\n self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=0)])\n self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=2)])\n\n # topk\n self.assertEqual([shape, shape], [z.shape for z in torch.topk(x, 0, dim=0)])\n self.assertEqual([(0, 1, 1, 0), (0, 1, 1, 0)], [z.shape for z in torch.topk(x, 1, dim=2)])\n\n y = torch.randn((2, 3, 4), device=device)\n self.assertEqual([(2, 3, 0), (2, 3, 0)], [z.shape for z in torch.topk(y, 0)])\n\n # gather\n self.assertEqual(shape, torch.gather(x, 0, torch.empty(shape, dtype=torch.int64, device=device)).shape)\n self.assertEqual(shape, torch.gather(x, 2, torch.empty(shape, dtype=torch.int64, device=device)).shape)\n larger_shape = torch.empty((0, 1, 3, 0), dtype=torch.int64, device=device)\n self.assertEqual(larger_shape.shape, torch.gather(x, 2, larger_shape).shape)\n smaller_shape = torch.empty((0, 1, 0, 0), dtype=torch.int64, device=device)\n self.assertEqual(smaller_shape.shape, torch.gather(x, 2, smaller_shape).shape)\n y = torch.randn((2, 3, 4), device=device)\n self.assertEqual((0, 3, 4),\n torch.gather(y, 0, torch.empty((0, 3, 4), dtype=torch.int64, device=device)).shape)\n\n # scatter, scatter_add\n for dim in [0, 2]:\n y = torch.randn(shape, device=device)\n y_src = torch.randn(shape, device=device)\n ind = torch.empty(shape, dtype=torch.int64, device=device)\n self.assertEqual(shape, y.scatter_(dim, ind, y_src).shape)\n self.assertEqual(shape, y.scatter_add_(dim, ind, y_src).shape)\n\n z = torch.randn((2, 3, 4), device=device)\n z_src = torch.randn((2, 3, 4), device=device)\n self.assertEqual(z, z.scatter_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src))\n self.assertEqual(z, z.scatter_add_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src))\n\n # index_fill, index_copy, index_add\n c = x.clone()\n c_clone = c.clone()\n ind_empty = torch.tensor([], dtype=torch.int64, device=device)\n ind_01 = torch.tensor([0, 1], dtype=torch.int64, device=device)\n self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1))\n self.assertEqual(c_clone, c.index_fill_(2, ind_empty, -1))\n self.assertEqual(c_clone, c.index_fill_(2, torch.tensor([0, 1], dtype=torch.int64, device=device), -1))\n self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device)))\n self.assertEqual(c_clone, c.index_copy_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device)))\n self.assertEqual(c_clone, c.index_copy_(2, ind_01, torch.empty((0, 1, 2, 0), device=device)))\n self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device)))\n self.assertEqual(c_clone, c.index_add_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device)))\n self.assertEqual(c_clone, c.index_add_(2, ind_01, torch.empty((0, 1, 2, 0), device=device)))\n\n c = torch.randn((0, 1, 2), device=device)\n c_clone = c.clone()\n self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1))\n self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device)))\n self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device)))\n self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1))\n self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device)))\n self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device)))\n\n # index fill/copy/add non-empty\n z = torch.randn((2, 3, 4), device=device)\n self.assertEqual(z, z.index_fill_(0, ind_empty, -1))\n z = torch.randn((2, 3, 4), device=device)\n self.assertEqual(z, z.index_copy_(0, ind_empty, torch.empty((0, 3, 4), device=device)))\n z = torch.randn((2, 3, 4), device=device)\n self.assertEqual(z, z.index_add_(0, ind_empty, torch.empty((0, 3, 4), device=device)))\n\n # index_select\n self.assertEqual(x, x.index_select(0, ind_empty))\n self.assertEqual((0, 1, 0, 0), x.index_select(2, ind_empty).shape)\n self.assertEqual(x, x.index_select(2, ind_01))\n z = torch.randn((2, 3, 4), device=device) # non-empty\n self.assertEqual((0, 3, 4), z.index_select(0, ind_empty).shape)\n c = torch.randn((0, 1, 2), device=device)\n self.assertEqual(c, c.index_select(0, ind_empty))\n c = torch.randn((0, 1, 2), device=device)\n self.assertEqual(c, c.index_select(0, ind_empty))\n\n # FIXME: find a test suite for the pdist operator\n def _brute_pdist(self, inp, p=2):\n \"\"\"Computes the same as torch.pdist using primitives\"\"\"\n n = inp.shape[-2]\n k = n * (n - 1) // 2\n if k == 0:\n # torch complains about empty indices\n return torch.empty(inp.shape[:-2] + (0,), dtype=inp.dtype, device=inp.device)\n square = torch.norm(inp[..., None, :] - inp[..., None, :, :], p=p, dim=-1)\n unroll = square.view(square.shape[:-2] + (n * n,))\n inds = torch.ones(k, dtype=torch.int)\n inds[torch.arange(n - 1, 1, -1, dtype=torch.int).cumsum(0)] += torch.arange(2, n, dtype=torch.int)\n return unroll[..., inds.cumsum(0)]\n\n # FIXME: find a test suite for the pdist operator\n def _pdist_single(self, shape, device, p, dtype, trans, grad_check=False):\n x = torch.randn(shape, dtype=dtype, device=device)\n if trans:\n x.transpose_(-2, -1)\n if grad_check:\n x.requires_grad_()\n y = x.detach().clone().requires_grad_()\n else:\n y = x\n actual = torch.pdist(x, p=p)\n expected = self._brute_pdist(y, p=p)\n self.assertEqual(expected.shape, actual.shape)\n self.assertEqual(expected, actual)\n if grad_check and expected.size() != torch.Size([0]):\n g0 = torch.rand_like(actual)\n actual.backward(g0)\n expected.backward(g0)\n self.assertEqual(x.grad, y.grad)\n\n # FIXME: find a test suite for the pdist operator\n @slowTest\n def test_pdist_norm_forward(self, device):\n for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]:\n for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]:\n for trans in [False, True]:\n for dtype in [torch.float32, torch.float64]:\n self._pdist_single(shape, device, p, dtype, trans, grad_check=False)\n\n # do a simplified comparison with big inputs, see:\n # https://github.com/pytorch/pytorch/issues/15511\n for dtype in [torch.float32, torch.float64]:\n self._pdist_single((1000, 2), device, 2, dtype, trans=False, grad_check=False)\n\n # FIXME: find a test suite for the pdist operator\n @slowTest\n def test_pdist_norm_backward(self, device):\n for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]:\n for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]:\n for trans in [False, True]:\n self._pdist_single(shape, device, p, torch.float64, trans, grad_check=True)\n\n # FIXME: find a test suite for the pdist operator\n @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, \"sandcastle OOM with current tpx gpu/re configuration\")\n @skipIfRocm\n @onlyCUDA\n @largeTensorTest('10GB', device='cpu')\n @largeTensorTest('5GB', device='cuda')\n def test_pdist_norm_large(self, device):\n # use dim0>=46342 for forward, see:\n # https://github.com/pytorch/pytorch/issues/30583\n # Compare output using GPU with the CPU implementation, as brute_pdist uses too much memory\n x = torch.randn(50000, 1, dtype=torch.float32) # 50k * 4 bytes = 200 KB\n # Will require 1249975000 float32s\n expected_cpu = torch.pdist(x, p=2) # ~1250M * 4 bytes = 5 GB on CPU\n actual_gpu = torch.pdist(x.to(device), p=2) # 5 GB on GPU\n self.assertEqual(expected_cpu, actual_gpu.cpu()) # Another 5 GB on CPU\n\n # FIXME: move to elementwise ternary test suite\n @onlyNativeDeviceTypes\n @dtypesIfCUDA(*set(get_all_math_dtypes('cuda')))\n @dtypes(*set(get_all_math_dtypes('cpu')))\n def test_addcdiv(self, device, dtype):\n # Returns floating or integral scalar corresponding to dtype\n def _number(floating, integer, dtype):\n if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]:\n return floating\n elif dtype in [torch.cfloat, torch.cdouble]:\n return floating * (1 + 1j)\n else:\n return integer\n\n def non_zero_rand(size, dtype, device):\n if dtype.is_floating_point or dtype.is_complex:\n a = torch.rand(size=size, dtype=dtype, device=device)\n elif dtype == torch.uint8:\n a = torch.randint(1, 5, size=size, dtype=dtype, device=device)\n else:\n a = torch.randint(-5, 5, size=size, dtype=dtype, device=device)\n return a + (a == 0).to(dtype)\n\n def _test_addcdiv():\n a = non_zero_rand((2, 2), dtype=dtype, device=device)\n b = non_zero_rand((2, 2), dtype=dtype, device=device)\n c = non_zero_rand((2, 2), dtype=dtype, device=device)\n alpha = _number(0.5, 3, dtype)\n\n expected = a + (alpha * b) / c\n actual = torch.addcdiv(a, b, c, value=alpha)\n self.assertEqual(expected, actual)\n\n with self.assertWarnsOnceRegex(\n UserWarning, \"This overload of addcdiv is deprecated\"):\n self.assertEqual(actual, torch.addcdiv(a, alpha, b, c))\n\n if not (dtype.is_floating_point or dtype.is_complex):\n # Integer division with addcdiv is prohibited\n with self.assertRaises(RuntimeError):\n _test_addcdiv()\n else:\n _test_addcdiv()\n\n if self.device_type == 'cuda' and dtype == torch.half:\n a = torch.tensor([60000.0], device=device, dtype=dtype)\n b = torch.tensor([60000.0], device=device, dtype=dtype)\n c = torch.tensor([1.0], device=device, dtype=dtype)\n out = torch.addcmul(a, b, c, value=-2)\n self.assertTrue(not (out.isnan() or out.isinf()))\n\n def test_nullary_op_mem_overlap(self, device):\n ops = (\n (\"random_\", ()),\n (\"uniform_\", ()),\n (\"cauchy_\", ()),\n (\"log_normal_\", ()),\n (\"exponential_\", ()),\n (\"geometric_\", (0.5,)),\n (\"normal_\", ()),\n )\n\n x = torch.rand((1, 3)).expand((3, 3))\n for op, args in ops:\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n getattr(x, op)(*args)\n\n # FIXME: move to an elementwise ternary test suite and make this an OpInfo test\n @dtypes(torch.double)\n def test_ternary_op_mem_overlap(self, device, dtype):\n ops = [\n (\"addcmul\", True, True, 'cpu'),\n (\"addcmul\", True, True, 'cuda'),\n (\"addcdiv\", True, True, 'cpu'),\n (\"addcdiv\", True, True, 'cuda'),\n (\"lerp\", True, True, 'cpu'),\n (\"lerp\", True, True, 'cuda')\n ]\n\n for (fn, has_input_output_mem_overlap_check,\n has_internal_mem_overlap_check, dev) in ops:\n if dev != device:\n continue\n out_op = getattr(torch, fn)\n inplace_op = getattr(torch.Tensor, fn + '_')\n self.check_internal_mem_overlap(\n inplace_op, 3, dtype, device,\n expected_failure=not has_internal_mem_overlap_check)\n self.ternary_check_input_output_mem_overlap(out_op, dev,\n expected_failure=not has_input_output_mem_overlap_check)\n\n @expectedFailureMeta # RuntimeError not raised\n @dtypes(torch.double)\n @onlyNativeDeviceTypes\n def test_copy_mem_overlap(self, device, dtype):\n self.check_internal_mem_overlap(\n torch.Tensor.copy_, num_inputs=2, dtype=dtype, device=device)\n sz = 9\n doubles = torch.randn(2 * sz, dtype=dtype, device=device)\n self.unary_check_input_output_mem_overlap(\n doubles, sz, lambda input, out: out.copy_(input))\n\n # FIXME: convert to ErrorInputs\n @onlyNativeDeviceTypes\n def test_index_add_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n y = torch.rand((6,), device=device)\n ind = torch.tensor([2, 1, 0], device=device)\n value = torch.rand((3,), device=device)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.index_add_(0, ind, value)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n y.index_add_(0, ind, y[:3])\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_add_(0, ind, ind.clone())\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_add_(0, ind.clone(), ind)\n\n # FIXME: convert to ErrorInputs\n @onlyNativeDeviceTypes\n def test_index_copy_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n y = torch.rand((6,), device=device)\n ind = torch.tensor([2, 1, 0], device=device)\n value = torch.rand((3,), device=device)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.index_copy_(0, ind, value)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n y.index_copy_(0, ind, y[:3])\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_copy_(0, ind, ind.clone())\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_copy_(0, ind.clone(), ind)\n\n # FIXME: convert to ErrorInputs\n @expectedFailureMeta # Warning not triggered\n @onlyNativeDeviceTypes\n def test_index_fill_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n y = torch.rand((6,), device=device)\n ind = torch.tensor([2, 1, 0], device=device)\n value = torch.rand((3,), device=device)\n\n with self.assertWarnsRegex(UserWarning, \"index_fill_ on expanded tensors\"):\n x.index_fill_(0, ind, 1.0)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_fill_(0, ind, 0)\n\n # FIXME: convert to ErrorInputs\n @expectedFailureMeta # RuntimeError not raised\n @onlyNativeDeviceTypes\n def test_shift_mem_overlap(self, device):\n x = torch.rand(3, device=device)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x[:-1] <<= x[1:]\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x[:-1] >>= x[1:]\n\n # FIXME: convert to ErrorInputs\n @expectedFailureMeta # RuntimeError not raised\n @onlyNativeDeviceTypes\n def test_bernoulli_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.bernoulli_()\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.bernoulli_(p=0.1)\n p = torch.rand(6, device=device)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.bernoulli_(p=p)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n torch.bernoulli(torch.rand_like(x), out=x)\n\n # FIXME: convert to ErrorInputs\n @expectedFailureMeta # RuntimeError not raised\n @onlyNativeDeviceTypes\n def test_put_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n y = torch.rand((6,), device=device)\n ind = torch.tensor([2, 1, 0], device=device)\n value = torch.rand((3,), device=device)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.put_(ind, value)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n y.put_(ind[0], y[0])\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.put_(ind, ind)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n y.put_(ind, y[:3])\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.put_(ind, ind.clone())\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.put_(ind.clone(), ind)\n\n # FIXME: convert to ErrorInputs\n @expectedFailureMeta # UserWarning not triggered\n @onlyNativeDeviceTypes\n def test_index_put_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n y = torch.rand((6,), device=device)\n ind = torch.tensor([2, 1, 0], device=device)\n value = torch.rand((3,), device=device)\n with self.assertWarnsRegex(UserWarning, 'expanded tensors'):\n x.index_put_((ind,), value)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n y.index_put_((ind,), y[0])\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_put_((ind,), ind)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n y.index_put_((ind,), y[:3])\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_put_((ind,), ind.clone())\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.index_put_((ind.clone(),), ind)\n\n # FIXME: convert to ErrorInputs\n @expectedFailureMeta # UserWarning not triggered\n @onlyNativeDeviceTypes\n def test_masked_fill_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n mask = torch.tensor([True, False, True, True, False, False], device=device)\n with self.assertWarnsRegex(UserWarning, 'expanded tensors'):\n x.masked_fill_(mask, 0.)\n\n fill_val = torch.tensor(0., device=device)\n with self.assertWarnsRegex(UserWarning, 'expanded tensors'):\n x.masked_fill_(mask, fill_val)\n\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n mask[1:].masked_fill_(mask[:-1], False)\n\n # FIXME: convert to ErrorInputs\n @expectedFailureMeta # RuntimeError not raised\n @onlyNativeDeviceTypes\n def test_masked_scatter_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n src = torch.rand((3,), device=device)\n mask = torch.tensor([True, False, True, True, False, False], device=device)\n\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.masked_scatter_(mask, src)\n\n # FIXME: convert to ErrorInputs\n @onlyNativeDeviceTypes\n def test_scatter_mem_overlap(self, device):\n x = torch.rand((1,), device=device).expand((6,))\n src = torch.rand((3,), device=device)\n ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64)\n\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n x.scatter_(0, ind, src)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n src.scatter_(0, ind, src)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n ind.scatter_(0, ind, ind.clone())\n\n # FIXME: move to test distributions\n @onlyCUDA\n def test_multinomial_device_constrain(self, device):\n x = torch.empty(0, device=\"cpu\")\n y = torch.empty(0, device=device)\n self.assertRaisesRegex(\n RuntimeError, \"Expected all tensors to be on the same device\",\n lambda: torch.multinomial(x, 2, out=y))\n\n # FIXME: move to test distributions\n @deviceCountAtLeast(2)\n @onlyCUDA\n def test_multinomial_gpu_device_constrain(self, devices):\n x = torch.empty(0, device=devices[0])\n y = torch.empty(0, device=devices[1])\n self.assertRaisesRegex(\n RuntimeError, \"Expected all tensors to be on the same device\",\n lambda: torch.multinomial(x, 2, out=y))\n\n # FIXME: convert this to an automated OpInfo test\n @deviceCountAtLeast(2)\n @onlyCUDA\n def test_device_guard(self, devices):\n # verify that all operators with `device_guard: False` behave properly with multiple devices.\n # TODO: if we had operator introspection we could figure out this set of operators automatically...\n x = torch.randn((1, 2, 3), device=devices[1])\n y = torch.zeros((1, 3, 2), device=devices[1])\n scalar = torch.tensor(5, device=devices[1])\n\n # property ops\n torch.cudnn_is_acceptable(x)\n x.is_distributed()\n x.is_floating_point()\n x.is_complex()\n x.is_same_size(y)\n x.is_signed()\n x.size(0)\n x.stride(0)\n x.numel()\n x.is_set_to(y)\n x.data_ptr()\n scalar.is_nonzero()\n\n # sparse property ops\n y[0][1] = 5\n y_sparse = y.to_sparse()\n y_sparse.sparse_dim()\n y_sparse._dimI()\n y_sparse.dense_dim()\n y_sparse._dimV()\n y_sparse._nnz()\n y_sparse.is_coalesced()\n y_sparse._indices()\n y_sparse._values()\n y_sparse.indices()\n y_sparse.values()\n\n # in-place ops\n def inplace():\n return torch.randn((1, 2, 3), device=devices[1])\n inplace().as_strided_(y.size(), y.stride())\n inplace().resize_(y.size())\n inplace().squeeze_()\n inplace().squeeze_(0)\n inplace().unsqueeze_(2)\n inplace().transpose_(1, 2)\n inplace().squeeze_().t_()\n inplace().set_(x.storage())\n inplace().set_(x.storage(), x.storage_offset(), x.size(), x.stride())\n inplace().set_(x)\n inplace().set_()\n y_sparse._coalesced_(True)\n\n # shape modification\n x.as_strided(y.size(), y.stride())\n x.expand((5, 2, 3))\n x.expand_as(x)\n x.sum_to_size((1,))\n torch.broadcast_tensors(x , x)\n x.reshape((1, 3, 2))\n x.reshape_as(y)\n x.squeeze()\n x.squeeze(0)\n x.squeeze().t()\n x.transpose(1, 2)\n x.unsqueeze(2)\n x.view((1, 3, 2))\n x.view_as(y)\n\n # chunk, split, etc.\n x.chunk(2, dim=1)\n x.split(1, dim=2)\n x.split_with_sizes([1, 2], dim=2)\n x.unfold(dimension=2, size=1, step=1)\n\n x.narrow(1, 1, 1)\n x.select(1, 1)\n torch.isnan(x)\n\n torch.empty((1, 3, 2), out=y)\n torch.empty_like(x)\n torch.empty_like(x, dtype=torch.int64)\n\n # to\n x.to(x)\n x.to(y)\n x.to(x, copy=True)\n\n def test_is_signed(self, device):\n self.assertEqual(torch.IntTensor(5).to(device).is_signed(), True)\n self.assertEqual(torch.ByteTensor(5).to(device).is_signed(), False)\n self.assertEqual(torch.CharTensor(5).to(device).is_signed(), True)\n self.assertEqual(torch.FloatTensor(5).to(device).is_signed(), True)\n self.assertEqual(torch.HalfTensor(10).to(device).is_signed(), True)\n\n # Note - reports a leak of 512 bytes on CUDA device 1\n @deviceCountAtLeast(2)\n @skipCUDAMemoryLeakCheckIf(True)\n @onlyCUDA\n def test_tensor_set_errors_multigpu(self, devices):\n f_cuda0 = torch.randn((2, 3), dtype=torch.float32, device=devices[0])\n f_cuda1 = torch.randn((2, 3), dtype=torch.float32, device=devices[1])\n\n self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage()))\n self.assertRaises(RuntimeError,\n lambda: f_cuda0.set_(f_cuda1.storage(), 0, f_cuda1.size(), f_cuda1.stride()))\n self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1))\n\n # FIXME: move to test_serialization\n @onlyCUDA\n @deviceCountAtLeast(1) # Note: Tests works with one but prefers more devices\n def test_serialization(self, devices):\n def _test_serialization(filecontext_lambda):\n t0 = torch.cuda.FloatTensor(5).fill_(1)\n with torch.cuda.device(devices[-1]):\n tn = torch.cuda.FloatTensor(3).fill_(2)\n torch.cuda.set_device(devices[0])\n b = (t0, tn)\n with filecontext_lambda() as f:\n torch.save(b, f)\n f.seek(0)\n c = torch.load(f)\n self.assertEqual(b, c, atol=0, rtol=0)\n u0, un = c\n self.assertEqual(str(u0.device), devices[0])\n self.assertEqual(str(un.device), devices[-1])\n\n _test_serialization(tempfile.NamedTemporaryFile)\n _test_serialization(BytesIOContext)\n\n # FIXME: move memory format tests to their own test class/suite\n def test_memory_format_preserved_after_permute(self, device):\n x = torch.randn(4, 3, 8, 8, device=device)\n nhwc = x.contiguous(memory_format=torch.channels_last)\n y = nhwc.permute(0, 1, 3, 2).permute(0, 1, 3, 2)\n self.assertTrue(y.is_contiguous(memory_format=torch.channels_last))\n\n x = torch.randn(4, 3, 8, 8, 8, device=device)\n ndhwc = x.contiguous(memory_format=torch.channels_last_3d)\n y = ndhwc.permute(0, 1, 4, 3, 2).permute(0, 1, 4, 3, 2)\n self.assertTrue(y.is_contiguous(memory_format=torch.channels_last_3d))\n\n def test_memory_format_propagation_rules(self, device):\n\n contiguous = torch.rand(10, 3, 5, 5, device=device)\n cl = torch.rand(10, 3, 5, 5, device=device).contiguous(memory_format=torch.channels_last)\n ambiguous = torch.rand(10, 3, 1, 1, device=device).contiguous(memory_format=torch.channels_last)\n self.assertTrue(ambiguous.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ambiguous.is_contiguous(memory_format=torch.contiguous_format))\n bias = torch.rand(1, 1, 1, 1, device=device).contiguous(memory_format=torch.channels_last)\n\n def _test_propagation_rules(self, contiguous, cl, ambiguous, bias):\n options = ((ambiguous, contiguous, torch.contiguous_format),\n (ambiguous, cl, torch.channels_last),\n (contiguous, ambiguous, torch.contiguous_format),\n (contiguous, cl, torch.contiguous_format),\n (cl, ambiguous, torch.channels_last),\n (cl, contiguous, torch.channels_last),\n (bias, cl, torch.channels_last),\n (cl, bias, torch.channels_last),)\n\n for a, b, mf in options:\n result = a + b\n self.assertTrue(result.is_contiguous(memory_format=mf))\n\n _test_propagation_rules(self, contiguous, cl, ambiguous, bias)\n\n cl = cl.to(memory_format=torch.channels_last)\n ambiguous = ambiguous.to(memory_format=torch.channels_last)\n bias = bias.to(memory_format=torch.channels_last)\n\n _test_propagation_rules(self, contiguous, cl, ambiguous, bias)\n\n # test cases when strides matter in ambiguous tensors\n for mf in (torch.channels_last, torch.contiguous_format):\n ambiguous = torch.rand(10, 3, 1, 1, device=device).to(memory_format=mf)\n bias = torch.rand(3, 1, 1, device=device)\n result = ambiguous + bias\n self.assertEqual(ambiguous.stride(), result.stride())\n result = bias + ambiguous\n self.assertEqual(ambiguous.stride(), result.stride())\n result = ambiguous * 5\n self.assertEqual(ambiguous.stride(), result.stride())\n\n def test_memory_format_empty_like(self, device):\n def test_helper(x, memory_format):\n xc = x.contiguous(memory_format=memory_format)\n\n like = torch.empty_like(xc, memory_format=torch.preserve_format)\n self.assertFalse(like.is_contiguous())\n self.assertTrue(like.is_contiguous(memory_format=memory_format))\n\n like_x = torch.empty_like(x, memory_format=torch.preserve_format)\n self.assertTrue(like_x.is_contiguous())\n self.assertFalse(like_x.is_contiguous(memory_format=memory_format))\n\n like = torch.empty_like(x, memory_format=memory_format)\n self.assertFalse(like.is_contiguous())\n self.assertTrue(like.is_contiguous(memory_format=memory_format))\n\n like = torch.empty_like(xc, memory_format=torch.contiguous_format)\n self.assertTrue(like.is_contiguous())\n self.assertFalse(like.is_contiguous(memory_format=memory_format))\n\n like = torch.empty_like(xc)\n self.assertFalse(like.is_contiguous())\n self.assertTrue(like.is_contiguous(memory_format=memory_format))\n\n sparse = x.to_sparse()\n with self.assertRaises(RuntimeError):\n z = torch.empty_like(sparse, memory_format=torch.preserve_format)\n\n test_helper(torch.randn(4, 3, 8, 8, device=device), torch.channels_last)\n test_helper(torch.randn(4, 3, 8, 8, 8, device=device), torch.channels_last_3d)\n\n def test_memory_format_consistency(self, device):\n x = torch.randn(10, 3, 1, 1, device=device)\n x_rep = x.as_strided(x.size(), x.stride())\n self.assertEqual(x.size(), x_rep.size())\n self.assertEqual(x.stride(), x_rep.stride())\n self.assertEqual(x.is_contiguous(), x_rep.is_contiguous())\n self.assertEqual(x.is_contiguous(memory_format=torch.channels_last), x_rep.is_contiguous(memory_format=torch.channels_last))\n self.assertEqual(\n x.is_contiguous(memory_format=torch.channels_last_3d), x_rep.is_contiguous(memory_format=torch.channels_last_3d))\n\n # FIXME: make this a elementwise unary and elementwise binary OpInfo test\n def test_memory_format_operators(self, device):\n def _chunk_op(x, y):\n x1, x2 = x.chunk(2, dim=1)\n return x1 + x2\n\n def _unsqueeze_op_add(x, y):\n return x[0].unsqueeze(0) + 3\n\n def _unsqueeze_op_clone(x, y):\n return x[0].unsqueeze(0).clone()\n\n def _test_helper(x, y, bias, memory_format):\n return_contig_fns = [\n lambda x, y: y + x,\n lambda x, y: y * x,\n lambda x, y: y.addcdiv(x, y, value=2),\n lambda x, y: y.addcmul(x, y, value=2),\n ]\n bias_fns = [\n lambda x, b: x + b,\n lambda x, b: b + x,\n ]\n fns = [\n lambda x, y: x.clone(),\n lambda x, y: x + 3,\n lambda x, y: 3 * x,\n lambda x, y: x + y,\n lambda x, y: x * y,\n lambda x, y: abs(x),\n lambda x, y: x.abs(),\n lambda x, y: x.abs_(),\n lambda x, y: x.acos(),\n lambda x, y: x.acos_(),\n lambda x, y: x.add(y, alpha=3),\n lambda x, y: x.add_(y, alpha=3),\n lambda x, y: x.addcdiv(y, y, value=2),\n lambda x, y: x.addcdiv_(y, y, value=2),\n lambda x, y: x.addcmul(y, y, value=2),\n lambda x, y: x.addcmul_(y, y, value=2),\n lambda x, y: x.acosh(),\n lambda x, y: x.acosh_(),\n lambda x, y: x.asinh(),\n lambda x, y: x.asinh_(),\n lambda x, y: x.atanh(),\n lambda x, y: x.atanh_(),\n lambda x, y: x.asin(),\n lambda x, y: x.asin_(),\n lambda x, y: x.atan(),\n lambda x, y: x.atan2(y),\n lambda x, y: x.atan2_(y),\n lambda x, y: x.ceil(),\n lambda x, y: x.ceil_(),\n lambda x, y: x.clamp(-1, 1),\n lambda x, y: x.cos(),\n lambda x, y: x.cosh(),\n lambda x, y: x.div(0.5),\n lambda x, y: x.div_(0.5),\n lambda x, y: x.div(y),\n lambda x, y: x.div_(y),\n lambda x, y: x.digamma(),\n lambda x, y: x.digamma_(),\n lambda x, y: x.erf(),\n lambda x, y: x.erfc(),\n lambda x, y: x.erfinv(),\n lambda x, y: x.erfinv_(),\n lambda x, y: x.exp(),\n lambda x, y: x.expm1(),\n lambda x, y: x.expm1_(),\n lambda x, y: x.floor(),\n lambda x, y: x.floor_(),\n lambda x, y: x.fmod(2),\n lambda x, y: x.frac(),\n lambda x, y: x.hypot(y),\n lambda x, y: x.hypot_(y),\n lambda x, y: x.i0(),\n lambda x, y: x.i0_(),\n lambda x, y: x.lerp(y, 0.5),\n lambda x, y: x.log(),\n lambda x, y: x.log_(),\n lambda x, y: x.log10(),\n lambda x, y: x.log10_(),\n lambda x, y: x.log1p(),\n lambda x, y: x.log1p_(),\n lambda x, y: x.log2(),\n lambda x, y: x.log2_(),\n lambda x, y: x.mul(3),\n lambda x, y: x.mul_(3),\n lambda x, y: x.neg(),\n lambda x, y: x.neg_(),\n lambda x, y: x.pow(3),\n lambda x, y: x.pow_(3),\n lambda x, y: x.pow(0.0),\n lambda x, y: x.pow(1.0),\n lambda x, y: x.reciprocal(),\n lambda x, y: x.remainder(2),\n lambda x, y: x.round(),\n lambda x, y: x.round_(),\n lambda x, y: x.rsqrt(),\n lambda x, y: x.rsqrt_(),\n lambda x, y: x.sigmoid(),\n lambda x, y: x.sigmoid_(),\n lambda x, y: x.logit(),\n lambda x, y: x.logit_(),\n lambda x, y: x.logit(1e-6),\n lambda x, y: x.logit_(1e-6),\n lambda x, y: x.sign(),\n lambda x, y: x.sign_(),\n lambda x, y: x.sgn(),\n lambda x, y: x.sgn_(),\n lambda x, y: x.sin(),\n lambda x, y: x.sin_(),\n lambda x, y: x.sinh(),\n lambda x, y: x.sinh_(),\n lambda x, y: x.sqrt(),\n lambda x, y: x.sqrt_(),\n lambda x, y: x.tan(),\n lambda x, y: x.tanh(),\n lambda x, y: x.trunc(),\n lambda x, y: x.trunc_(),\n _chunk_op,\n _unsqueeze_op_add,\n _unsqueeze_op_clone,\n ]\n for fn in fns:\n x_c = x.contiguous()\n y_c = y.contiguous()\n result_c = fn(x_c, y_c)\n result = fn(x, y)\n self.assertEqual(result, result_c)\n self.assertTrue(\n result.is_contiguous(memory_format=memory_format),\n \"result of the '{}' is not in '{}' format\".format(inspect.getsource(fn).strip(), memory_format))\n\n for fn in bias_fns:\n x_c = x.contiguous()\n b_c = bias.contiguous()\n result_c = fn(x_c, b_c)\n result = fn(x, bias)\n self.assertEqual(result, result_c)\n self.assertTrue(\n result.is_contiguous(memory_format=memory_format),\n \"result of the '{}' is not in '{}' format\".format(inspect.getsource(fn).strip(), memory_format))\n\n for fn in return_contig_fns:\n x_c = x.contiguous()\n y_c = y.contiguous()\n result_c = fn(x_c, y_c)\n result = fn(x, y)\n self.assertEqual(result, result_c)\n self.assertTrue(\n result.is_contiguous(memory_format=torch.contiguous_format),\n \"result of the '{}' is not in '{}' format\".format(inspect.getsource(fn).strip(), torch.contiguous_format))\n\n _test_helper(\n torch.randn((4, 3, 8, 8), device=device).contiguous(memory_format=torch.channels_last),\n abs(torch.randn((4, 3, 8, 8), device=device)) + 1,\n torch.randn((1, 3, 1, 1), device=device).contiguous(memory_format=torch.channels_last),\n torch.channels_last)\n _test_helper(\n torch.randn((4, 3, 8, 8, 8), device=device).contiguous(memory_format=torch.channels_last_3d),\n abs(torch.randn((4, 3, 8, 8, 8), device=device)) + 1,\n torch.randn((1, 3, 1, 1, 1), device=device).contiguous(memory_format=torch.channels_last_3d),\n torch.channels_last_3d)\n\n # FIXME: make this a elementwise unary and elementwise binary OpInfo test\n def test_strides_propagation(self, device):\n def _test_helper(x, op, unary=False):\n def compare_strides(s1, s2, div):\n sdiv = [s // div for s in s1]\n self.assertEqual(sdiv, s2)\n\n dim = x.dim()\n # we produce memory dense outputs, so when input is strided on the last dimension\n # we need to divide by that dimension stride to compare input and result strides\n div = x.stride(-1)\n for p in permutations(range(dim)):\n xp = x.permute(p)\n if not unary:\n y = torch.randn(xp.size(-1), device=x.device, dtype=x.dtype)\n for inputs in ((xp, xp), (xp, y), (y, xp)):\n res = op(*inputs)\n compare_strides(xp.stride(), res.stride(), div)\n self.assertEqual(xp.size(), res.size())\n out = torch.empty(0, device=xp.device, dtype=res.dtype)\n res = op(*inputs, out=out)\n compare_strides(xp.stride(), res.stride(), div)\n self.assertEqual(xp.size(), res.size())\n else:\n res = op(xp)\n compare_strides(xp.stride(), res.stride(), div)\n self.assertEqual(xp.size(), res.size())\n out = torch.empty(0, device=xp.device, dtype=res.dtype)\n res = op(xp, out=out)\n compare_strides(xp.stride(), res.stride(), div)\n self.assertEqual(xp.size(), res.size())\n\n # torch.eq by default calls TensorIterator with defined output, torch.add with undefined\n binary_ops = (torch.eq, torch.add)\n unary_ops = (torch.exp,)\n # memory dense, sliced and ambiguous sliced (ambiguous dense loses permutation information)\n xs = (torch.randn(2, 3, 4, device=device), torch.randn(2, 3, 8, device=device)[:, :, ::2],\n torch.randn(1, 1, 4, 12, device=device)[:, :, :, ::2])\n for op in binary_ops:\n for x in xs:\n _test_helper(x, op)\n for op in unary_ops:\n for x in xs:\n _test_helper(x, op, unary=True)\n\n # FIXME: move dlpack tests to their own test class/suite\n @skipMeta\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_dlpack_capsule_conversion(self, device, dtype):\n # DLpack does not explicitly support bool (xref dmlc/dlpack#75)\n x = make_tensor((5,), dtype=dtype, device=device)\n z = from_dlpack(to_dlpack(x))\n self.assertEqual(z, x)\n\n @skipMeta\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_dlpack_protocol_conversion(self, device, dtype):\n x = make_tensor((5,), dtype=dtype, device=device)\n z = from_dlpack(x)\n self.assertEqual(z, x)\n\n @skipMeta\n @onlyNativeDeviceTypes\n def test_dlpack_shared_storage(self, device):\n x = make_tensor((5,), dtype=torch.float64, device=device)\n z = from_dlpack(to_dlpack(x))\n z[0] = z[0] + 20.0\n self.assertEqual(z, x)\n\n @skipMeta\n @onlyCUDA\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_dlpack_conversion_with_streams(self, device, dtype):\n # Create a stream where the tensor will reside\n stream = torch.cuda.Stream()\n with torch.cuda.stream(stream):\n # Do an operation in the actual stream\n x = make_tensor((5,), dtype=dtype, device=device) + 1\n # DLPack protocol helps establish a correct stream order\n # (hence data dependency) at the exchange boundary.\n # DLPack manages this synchronization for us, so we don't need to\n # explicitly wait until x is populated\n stream = torch.cuda.Stream()\n with torch.cuda.stream(stream):\n z = from_dlpack(x)\n stream.synchronize()\n self.assertEqual(z, x)\n\n @skipMeta\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_from_dlpack(self, device, dtype):\n x = make_tensor((5,), dtype=dtype, device=device)\n y = torch.from_dlpack(x)\n self.assertEqual(x, y)\n\n @skipMeta\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_from_dlpack_noncontinguous(self, device, dtype):\n x = make_tensor((25,), dtype=dtype, device=device).reshape(5, 5)\n\n y1 = x[0]\n y1_dl = torch.from_dlpack(y1)\n self.assertEqual(y1, y1_dl)\n\n y2 = x[:, 0]\n y2_dl = torch.from_dlpack(y2)\n self.assertEqual(y2, y2_dl)\n\n y3 = x[1, :]\n y3_dl = torch.from_dlpack(y3)\n self.assertEqual(y3, y3_dl)\n\n y4 = x[1]\n y4_dl = torch.from_dlpack(y4)\n self.assertEqual(y4, y4_dl)\n\n y5 = x.t()\n y5_dl = torch.from_dlpack(y5)\n self.assertEqual(y5, y5_dl)\n\n @skipMeta\n @onlyCUDA\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_dlpack_conversion_with_diff_streams(self, device, dtype):\n stream_a = torch.cuda.Stream()\n stream_b = torch.cuda.Stream()\n # DLPack protocol helps establish a correct stream order\n # (hence data dependency) at the exchange boundary.\n # the `tensor.__dlpack__` method will insert a synchronization event\n # in the current stream to make sure that it was correctly populated.\n with torch.cuda.stream(stream_a):\n x = make_tensor((5,), dtype=dtype, device=device) + 1\n z = torch.from_dlpack(x.__dlpack__(stream_b.cuda_stream))\n stream_a.synchronize()\n stream_b.synchronize()\n self.assertEqual(z, x)\n\n @skipMeta\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_from_dlpack_dtype(self, device, dtype):\n x = make_tensor((5,), dtype=dtype, device=device)\n y = torch.from_dlpack(x)\n assert x.dtype == y.dtype\n\n @skipMeta\n @onlyCUDA\n def test_dlpack_default_stream(self, device):\n class DLPackTensor:\n def __init__(self, tensor):\n self.tensor = tensor\n\n def __dlpack_device__(self):\n return self.tensor.__dlpack_device__()\n\n def __dlpack__(self, stream=None):\n if torch.version.hip is None:\n assert stream == 1\n else:\n assert stream == 0\n capsule = self.tensor.__dlpack__(stream)\n converted = True\n return capsule\n\n # CUDA-based tests runs on non-default streams\n with torch.cuda.stream(torch.cuda.default_stream()):\n x = DLPackTensor(make_tensor((5,), dtype=torch.float32, device=device))\n from_dlpack(x)\n\n @skipMeta\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_dlpack_tensor_invalid_stream(self, device, dtype):\n with self.assertRaises(TypeError):\n x = make_tensor((5,), dtype=dtype, device=device)\n x.__dlpack__(stream=object())\n\n @skipMeta\n def test_dlpack_error_on_bool_tensor(self):\n x = torch.tensor([True], dtype=torch.bool)\n with self.assertRaises(RuntimeError):\n to_dlpack(x)\n\n # TODO: increase tests once NumPy supports the `__dlpack__` protocol\n @skipMeta\n def test_dlpack_export_requires_grad(self):\n x = torch.zeros(10, dtype=torch.float32, requires_grad=True)\n with self.assertRaisesRegex(RuntimeError, r\"require gradient\"):\n x.__dlpack__()\n\n @skipMeta\n def test_dlpack_export_is_conj(self):\n x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])\n y = torch.conj(x)\n with self.assertRaisesRegex(RuntimeError, r\"conjugate bit\"):\n y.__dlpack__()\n\n @skipMeta\n def test_dlpack_export_non_strided(self):\n x = torch.sparse_coo_tensor([[0]], [1], size=(1,))\n y = torch.conj(x)\n with self.assertRaisesRegex(RuntimeError, r\"strided\"):\n y.__dlpack__()\n\n @onlyCUDA\n @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, \"is_pinned uses failure to detect pointer property\")\n def test_pin_memory_from_constructor(self, device):\n def _get_like(t, **kwargs):\n return [\n torch.rand_like(t, **kwargs),\n torch.randn_like(t, **kwargs),\n torch.empty_like(t, **kwargs),\n torch.full_like(t, 4, **kwargs),\n torch.zeros_like(t, **kwargs),\n torch.ones_like(t, **kwargs),\n ]\n\n def _get_tensors(**kwargs):\n return [\n torch.tensor([10, 11], **kwargs),\n torch.randn(3, 5, **kwargs),\n torch.rand(3, **kwargs),\n # torch.randint(3, 5, **kwargs), // unsupported\n torch.zeros(3, **kwargs),\n torch.randperm(3, **kwargs),\n torch.empty(6, **kwargs),\n torch.ones(6, **kwargs),\n torch.eye(6, **kwargs),\n torch.arange(3, 5, **kwargs)]\n\n pinned_tensors = _get_tensors(pin_memory=True) + _get_like(torch.empty(5, dtype=torch.float64), pin_memory=True)\n for x in pinned_tensors:\n self.assertTrue(x.is_pinned())\n\n tensors = _get_tensors() + _get_like(torch.empty(5, dtype=torch.float64, pin_memory=True))\n for x in tensors:\n self.assertFalse(x.is_pinned())\n\n @deviceCountAtLeast(1)\n @onlyCUDA\n def test_storage_all_devices(self, devices):\n for device in devices:\n t = torch.tensor((), device=device)\n self.assertEqual(t.dtype, t.storage().dtype)\n\n # FIXME: move to test distributions\n @dtypesIfCUDA(torch.float, torch.double, torch.half)\n @dtypes(torch.float, torch.double)\n def test_multinomial(self, device, dtype):\n def make_prob_dist(shape, is_contiguous):\n if is_contiguous:\n if dtype == torch.half:\n return torch.zeros(shape, device=device).uniform_().to(dtype=torch.half)\n return torch.zeros(shape, device=device, dtype=dtype).uniform_()\n elif len(shape) == 1:\n if dtype == torch.half:\n return torch.zeros((shape + [5]), device=device).uniform_().to(dtype=torch.half)[:, 2]\n return torch.zeros((shape + [5]), device=device, dtype=dtype).uniform_()[:, 2]\n else:\n # num dim = 2\n new_shape = [2, shape[1], 7, 1, shape[0], 1, 10]\n if dtype == torch.half:\n prob_dist = torch.zeros(new_shape, device=device).uniform_().to(dtype=torch.half)\n else:\n prob_dist = torch.zeros(new_shape, device=device, dtype=dtype).uniform_()\n prob_dist = prob_dist.transpose(1, 4)\n prob_dist = prob_dist[1, :, 5, 0, :, 0, 4]\n assert not prob_dist.is_contiguous() # sanity check\n return prob_dist\n\n for is_contiguous in (True, False):\n # with replacement\n n_row = 3\n for n_col in range(4, 5 + 1):\n prob_dist = make_prob_dist([n_row, n_col], is_contiguous)\n # indices that shouldn't be sampled (<0 means none)\n zero_prob_indices = torch.LongTensor(n_row).random_(-2, n_col).tolist()\n for i, j in enumerate(zero_prob_indices):\n if j >= 0:\n prob_dist[i, j] = 0\n n_sample = n_col * 3\n sample_indices = torch.multinomial(prob_dist, n_sample, True)\n self.assertEqual(prob_dist.dim(), 2)\n self.assertEqual(sample_indices.size(1), n_sample)\n for i in range(n_row):\n zero_prob_idx = zero_prob_indices[i]\n if zero_prob_idx < 0:\n continue\n for j in range(n_sample):\n self.assertNotEqual(sample_indices[i, j], zero_prob_idx,\n msg=\"sampled an index with zero probability\")\n\n # without replacement\n n_row = 3\n for n_col in range(2, 10 + 1, 2):\n prob_dist = make_prob_dist([n_row, n_col], is_contiguous)\n # indices that shouldn't be sampled (<0 means none)\n zero_prob_indices = torch.LongTensor(n_row).random_(-1, n_col).tolist()\n for i, j in enumerate(zero_prob_indices):\n if j >= 0:\n prob_dist[i, j] = 0\n n_sample = max(1, n_col - 2)\n sample_indices = torch.multinomial(prob_dist, n_sample, False)\n self.assertEqual(prob_dist.dim(), 2)\n self.assertEqual(sample_indices.size(1), n_sample)\n for i in range(n_row):\n row_samples = {}\n zero_prob_idx = zero_prob_indices[i]\n for j in range(n_sample):\n sample_idx = sample_indices[i, j]\n if zero_prob_idx >= 0:\n self.assertNotEqual(sample_idx, zero_prob_idx,\n msg=\"sampled an index with zero probability\")\n self.assertNotIn(sample_idx, row_samples, \"sampled an index twice\")\n row_samples[sample_idx] = True\n\n # vector\n n_col = 4\n prob_dist = make_prob_dist([n_col], is_contiguous).fill_(1)\n zero_prob_idx = 1 # index that shouldn't be sampled\n prob_dist[zero_prob_idx] = 0\n n_sample = 20\n sample_indices = torch.multinomial(prob_dist, n_sample, True)\n for sample_index in sample_indices:\n self.assertNotEqual(sample_index, zero_prob_idx, msg=\"sampled an index with zero probability\")\n s_dim = sample_indices.dim()\n self.assertEqual(sample_indices.dim(), 1, msg=\"wrong number of dimensions\")\n self.assertEqual(prob_dist.dim(), 1, msg=\"wrong number of prob_dist dimensions\")\n self.assertEqual(sample_indices.size(0), n_sample, msg=\"wrong number of samples\")\n\n # CUDA misalignment issue (#46702)\n n_row, n_col = 2, 3\n prob_dist = make_prob_dist([n_row, n_col], True)\n n_sample = 1\n sample_indices = torch.multinomial(prob_dist, n_sample, True)\n self.assertEqual(sample_indices.dim(), 2, msg=\"wrong number of dimensions\")\n self.assertEqual(sample_indices.size(1), n_sample, msg=\"wrong number of samples\")\n\n # FIXME: move to test distributions\n @onlyCUDA\n @dtypes(torch.float, torch.double, torch.half)\n def test_multinomial_deterministic(self, device, dtype):\n gen = torch.Generator(device=device)\n\n trials = 5\n seed = 0\n prob_dist = torch.rand(10000, 1000, device=device, dtype=dtype)\n n_sample = 1\n\n for i in range(trials):\n gen.manual_seed(seed)\n samples_1 = torch.multinomial(prob_dist, n_sample, True, generator=gen)\n\n gen.manual_seed(seed)\n samples_2 = torch.multinomial(prob_dist, n_sample, True, generator=gen)\n\n self.assertEqual(samples_1, samples_2)\n self.assertEqual(samples_1.dim(), 2, msg=\"wrong number of dimensions\")\n self.assertEqual(samples_1.size(1), n_sample, msg=\"wrong number of samples\")\n\n # FIXME: move to test distributions\n @slowTest\n @dtypes(torch.float)\n def test_multinomial_rng_state_advance(self, device, dtype):\n corpus_size = 100000\n freqs = torch.ones(corpus_size, dtype=torch.float, device=device)\n n_sample = 100\n samples1 = torch.multinomial(freqs, n_sample, replacement=True)\n samples2 = torch.multinomial(freqs, n_sample, replacement=True)\n samples = torch.cat([samples1, samples2])\n # expect no more than 1 repeating elements generated in 2 attempts\n # the probability of at least element being repeated is surprisingly large, 18%\n self.assertLessEqual(2 * n_sample - samples.unique().size(0), 2)\n samples1 = torch.multinomial(freqs, n_sample, replacement=False)\n samples2 = torch.multinomial(freqs, n_sample, replacement=False)\n samples = torch.cat([samples1, samples2])\n # expect no more than 1 repeating elements generated in 2 attempts\n self.assertLessEqual(2 * n_sample - samples.unique().size(0), 1)\n\n def _test_memory_format_transformations(self, device, input_generator_fn, transformation_fn,\n memory_format, compare_data=True, default_is_preserve=False):\n\n assert(memory_format == torch.channels_last or memory_format == torch.channels_last_3d)\n\n # xc is a channels last tensor\n xc = input_generator_fn(device)\n # xc is not memory dense, but looks like channels last\n if memory_format == torch.channels_last:\n xc = xc[..., ::2, ::2]\n else:\n xc = xc[..., ::2, ::2, ::2]\n\n clone = transformation_fn(xc, memory_format=torch.preserve_format)\n self.assertFalse(clone.is_contiguous())\n self.assertTrue(clone.is_contiguous(memory_format=memory_format))\n self.assertFalse(xc.is_contiguous())\n self.assertFalse(xc.is_contiguous(memory_format=memory_format))\n if compare_data:\n self.assertEqual(xc, clone.to(xc))\n\n xc = input_generator_fn(device)\n clone = transformation_fn(xc, memory_format=torch.contiguous_format)\n self.assertTrue(clone.is_contiguous())\n self.assertFalse(clone.is_contiguous(memory_format=memory_format))\n if compare_data:\n self.assertEqual(xc, clone.to(xc))\n\n xc = input_generator_fn(device)\n clone = transformation_fn(xc)\n\n if default_is_preserve:\n self.assertFalse(clone.is_contiguous())\n self.assertTrue(clone.is_contiguous(memory_format=memory_format))\n else:\n self.assertTrue(clone.is_contiguous())\n self.assertFalse(clone.is_contiguous(memory_format=memory_format))\n if compare_data:\n self.assertEqual(xc, clone.to(xc))\n\n x = torch.randn((3, 4, 5, 6, 7, 8, 9), device=device)\n for _ in range(10):\n permutation = list(range(len(x.shape)))\n random.shuffle(permutation)\n x = x.permute(permutation)\n self.assertEqual(x.stride(), transformation_fn(x, memory_format=torch.preserve_format).stride())\n\n def test_memory_format_to(self, device):\n def get_generator(memory_format, shape):\n def input_generator_fn(device):\n return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format)\n return input_generator_fn\n\n def transformation_fn(tensor, **kwargs):\n return tensor.to(dtype=torch.float64, **kwargs)\n\n formats_shapes = (\n (torch.channels_last, (4, 3, 8, 8)),\n (torch.channels_last_3d, (4, 3, 8, 8, 8)))\n\n for mf, shape in formats_shapes:\n self._test_memory_format_transformations(\n device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True)\n\n def test_memory_format_type(self, device):\n def get_generator(memory_format, shape):\n def input_generator_fn(device):\n return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format)\n return input_generator_fn\n\n def transformation_fn(tensor, **kwargs):\n return tensor.to(torch.float64, **kwargs)\n\n formats_shapes = (\n (torch.channels_last, (4, 3, 8, 8)),\n (torch.channels_last_3d, (4, 3, 8, 8, 8)))\n\n for mf, shape in formats_shapes:\n self._test_memory_format_transformations(\n device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True)\n\n def test_memory_format_clone(self, device):\n def get_generator(memory_format, shape):\n def input_generator_fn(device):\n return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format)\n return input_generator_fn\n\n def transformation_fn(tensor, **kwargs):\n return tensor.clone(**kwargs)\n\n formats_shapes = (\n (torch.channels_last, (4, 3, 8, 8)),\n (torch.channels_last_3d, (4, 3, 8, 8, 8)))\n\n for mf, shape in formats_shapes:\n self._test_memory_format_transformations(\n device, get_generator(mf, shape), transformation_fn, mf, True, default_is_preserve=True)\n\n def test_memory_format_factory_like_functions_preserve(self, device):\n def get_generator(memory_format, shape):\n def input_generator_fn(device):\n return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format)\n return input_generator_fn\n\n transformation_fns = [\n lambda t, **kwargs: torch.zeros_like(t, **kwargs),\n lambda t, **kwargs: torch.ones_like(t, **kwargs),\n lambda t, **kwargs: torch.randint_like(t, 10, 100, **kwargs),\n lambda t, **kwargs: torch.randint_like(t, 100, **kwargs),\n lambda t, **kwargs: torch.randn_like(t, **kwargs),\n lambda t, **kwargs: torch.rand_like(t, **kwargs),\n lambda t, **kwargs: torch.full_like(t, 7, **kwargs),\n lambda t, **kwargs: torch.empty_like(t, **kwargs)]\n\n formats_shapes = (\n (torch.channels_last, (4, 3, 8, 8)),\n (torch.channels_last_3d, (4, 3, 8, 8, 8)))\n\n for mf, shape, in formats_shapes:\n for transformation_fn in transformation_fns:\n self._test_memory_format_transformations(\n device, get_generator(mf, shape), transformation_fn, mf, compare_data=False, default_is_preserve=True)\n\n def test_memory_format_type_shortcuts(self, device):\n def get_generator(memory_format, shape, dtype):\n def input_generator_fn(device):\n return torch.randn(shape, device=device, dtype=dtype).clamp(0, 1) \\\n .round().contiguous(memory_format=memory_format)\n return input_generator_fn\n\n\n def get_fn(fn_name):\n def transformation_fn(tensor, **kwargs):\n fn = getattr(tensor, fn_name)\n return fn(**kwargs)\n return transformation_fn\n\n shortcuts = ['byte', 'char', 'double', 'bool', 'half', 'int', 'long', 'short']\n if device == 'cpu':\n shortcuts += ['bfloat16']\n\n formats_shapes = (\n (torch.channels_last, (4, 3, 8, 8)),\n (torch.channels_last_3d, (4, 3, 8, 8, 8)))\n\n for mf, shape in formats_shapes:\n for fn_name in shortcuts:\n self._test_memory_format_transformations(\n device, get_generator(mf, shape, torch.float32), get_fn(fn_name), mf, default_is_preserve=True)\n\n # Test 'float' separately to avoid float->float no-op.\n for mf, shape in formats_shapes:\n self._test_memory_format_transformations(\n device, get_generator(mf, shape, torch.float64), get_fn('float'), mf, default_is_preserve=True)\n\n @onlyCUDA\n def test_memory_format_cpu_and_cuda_ops(self, device):\n def get_generator(memory_format, shape):\n def input_generator_fn(device):\n return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format)\n return input_generator_fn\n\n def transformation_cpu_fn(tensor, **kwargs):\n return tensor.cpu(**kwargs)\n\n def transformation_cuda_fn(tensor, **kwargs):\n return tensor.cuda(**kwargs)\n\n formats_shapes = (\n (torch.channels_last, (4, 3, 8, 8)),\n (torch.channels_last_3d, (4, 3, 8, 8, 8)))\n\n for mf, shape in formats_shapes:\n self._test_memory_format_transformations(\n 'cuda', get_generator(mf, shape), transformation_cpu_fn, mf, default_is_preserve=True)\n self._test_memory_format_transformations(\n 'cpu', get_generator(mf, shape), transformation_cuda_fn, mf, default_is_preserve=True)\n\n # FIXME: move to test_serialization\n def test_pickle_gradscaler(self, device):\n # This test is not in test_cuda.py because it should pass in 3 cases:\n # 1. cuda is not available.\n # 2. cuda is available but device is not cuda.\n # 3. cuda is available and device is cuda.\n # In case 1, a and b disable themselves on construction and shouldn't try to pickle workhorse attributes.\n # In case 2, a and b are enabled. Workhorse attributes participate in pickling, but none are lazy-inited\n # to cuda Tensors, because I don't want to do cuda things if device is not cuda.\n # In case 3, a and b are enabled and we may also try lazy-initing _scale to a cuda tensor.\n device = torch.device(device)\n try_lazy_inits = (True, False) if device.type == \"cuda\" else (False,)\n for lazy_init_scale in try_lazy_inits:\n a = torch.cuda.amp.GradScaler(init_scale=3., growth_factor=4., backoff_factor=.5, growth_interval=2)\n self.assertTrue(not a.is_enabled() if torch.cuda.amp.common.amp_definitely_not_available() else a.is_enabled())\n if lazy_init_scale:\n # Dummy a.scale() call lazy-inits a._scale Tensor.\n a.scale(torch.tensor([4.0], dtype=torch.float32, device=device))\n self.assertTrue(isinstance(a._scale, torch.cuda.FloatTensor))\n # The following three lines should work whether or not cuda is available.\n serialized = pickle.dumps(a)\n b = pickle.loads(serialized)\n self.assertEqual(b.is_enabled(), a.is_enabled())\n if a.is_enabled():\n self.assertEqual(b.get_scale(), 3.)\n self.assertEqual(b.get_growth_factor(), 4.)\n self.assertEqual(b.get_backoff_factor(), .5)\n self.assertEqual(b.get_growth_interval(), 2)\n self.assertEqual(b._init_growth_tracker, 0)\n # supplies a dummy key to test the defaultdict's default_factory\n self.assertEqual(b._per_optimizer_states[\"fdsa\"],\n torch.cuda.amp.grad_scaler._refresh_per_optimizer_state())\n if lazy_init_scale:\n self.assertEqual(b.scale(torch.tensor([4.0], dtype=torch.float32, device=device)), 12.0)\n\n # FIXME: convert to ErrorInputs\n def test_multinomial_invalid(self, device):\n def test(probs):\n with self.assertRaisesRegex(RuntimeError,\n 'probability tensor contains either `inf`, `nan` or element < 0'):\n torch.multinomial(probs.to(device), 2)\n torch.cuda.synchronize()\n\n test(torch.tensor([1., -1., 1.]))\n test(torch.tensor([1., inf, 1.]))\n test(torch.tensor([1., -inf, 1.]))\n test(torch.tensor([1., 1., nan]))\n\n # FIXME: convert to ErrorInputs\n def test_multinomial_invalid_distribution(self, device):\n def test(probs, replacement):\n with self.assertRaisesRegex(RuntimeError,\n r\"invalid multinomial distribution \\(sum of probabilities <= 0\\)\"):\n torch.multinomial(probs, 2, replacement)\n torch.cuda.synchronize()\n\n x = torch.zeros(3, device=device)\n y = torch.zeros(3, 3, device=device)\n z = torch.zeros(3, 3, device=device)\n z[1, :] = 1\n\n test(x, False)\n test(y, False)\n test(z, False)\n\n # Verify only for CPU as replacement=True\n # throws device side assert triggered.\n if self.device_type == 'cpu':\n test(x, True)\n test(y, True)\n test(z, True)\n\n # FIXME: move to test distributions\n def _test_multinomial_empty(self, device, replacement, num_samples):\n probs = torch.ones(0, 3, device=device)\n expected = torch.empty(0, num_samples, dtype=torch.int64)\n out = torch.multinomial(probs, num_samples=num_samples, replacement=replacement)\n self.assertEqual(out, expected)\n\n # FIXME: move to test distributions\n def test_multinomial_empty_w_replacement(self, device):\n self._test_multinomial_empty(device, True, 1)\n self._test_multinomial_empty(device, True, 2)\n\n # FIXME: move to test distributions\n def test_multinomial_empty_wo_replacement(self, device):\n self._test_multinomial_empty(device, False, 1)\n self._test_multinomial_empty(device, False, 2)\n\n # FIXME: move to elementwise ternary test suite\n def _test_where_scalar_template(self, device, dtype, exec_fn):\n for ndims in range(0, 4):\n shape = self._rand_shape(ndims, min_size=5, max_size=10)\n for n in range(ndims + 1):\n for c in combinations(list(range(ndims)), n):\n for scalar_type in [int, float, complex]:\n if dtype.is_complex:\n condition = make_tensor(shape, dtype=dtype, device=device).abs() > 0.5\n else:\n condition = make_tensor(shape, dtype=dtype, device=device) > 0.5\n\n x = make_tensor(shape, dtype=dtype, device=device)\n\n if not dtype.is_complex and scalar_type == complex:\n continue\n\n scalar_1 = scalar_type(random.random())\n\n exec_fn(scalar_type, dtype, condition, x, scalar_1)\n\n # FIXME: move to elementwise ternary test suite\n # For current implementation,\n # below are the valid `TensorDtype` and `ScalarType` combinations.\n def _where_valid_scalar_tensor_combination(self, scalar_type, dtype):\n if (scalar_type == int and dtype == torch.long):\n return True\n elif (scalar_type == float and dtype == torch.double):\n return True\n elif (scalar_type == complex and dtype == torch.complex128):\n return True\n return False\n\n # FIXME: move to elementwise ternary test suite\n @onlyNativeDeviceTypes\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_where_scalar_invalid_combination_raises(self, device, dtype):\n\n def checkRaises(scalar_type, dtype, condition, x, scalar_1):\n if not self._where_valid_scalar_tensor_combination(scalar_type, dtype):\n # Note: This should fail once `where` supports type promotion.\n with self.assertRaisesRegex(RuntimeError, \"expected scalar type\"):\n torch.where(condition, x, scalar_1)\n\n self._test_where_scalar_template(device, dtype, checkRaises)\n\n # FIXME: move to elementwise ternary test suite\n @skipCUDAVersionIn([(11, 2)]) # test fails for 11.2, see https://github.com/pytorch/pytorch/issues/51980\n @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16))\n def test_where_scalar_valid_combination(self, device, dtype):\n\n def checkResult(scalar_type, dtype, condition, x, scalar_1):\n if self._where_valid_scalar_tensor_combination(scalar_type, dtype):\n def x_like(scalar, without_dtype=False):\n return torch.tensor(scalar, dtype=dtype, device=device).expand_as(x)\n\n # X = Tensor, Y = Scalar\n scalar_out = torch.where(condition, x, scalar_1)\n tensor_out = torch.where(condition, x, x_like(scalar_1))\n self.assertEqual(scalar_out, tensor_out)\n\n # X = Scalar, Y = Tensor\n scalar_out = torch.where(condition, scalar_1, x)\n tensor_out = torch.where(condition, x_like(scalar_1), x)\n self.assertEqual(scalar_out, tensor_out)\n\n self._test_where_scalar_template(device, dtype, checkResult)\n\n # FIXME: move to elementwise ternary test suite\n # As the test fails with Runtime Error not raised on XLA\n @onlyNativeDeviceTypes\n def test_where_scalar_scalar(self, device):\n # Scalar-Scalar Version\n height = 5\n width = 5\n default_dtype = torch.get_default_dtype()\n for test_default_dtype in [torch.float, torch.double]:\n torch.set_default_dtype(test_default_dtype)\n for scalar_type_1 in [int, float, complex]:\n for scalar_type_2 in [int, float, complex]:\n x1 = scalar_type_1(random.random() * random.randint(10, 20))\n x2 = scalar_type_2(random.random() * random.randint(20, 30))\n condition = torch.randn(height, width, device=device) > 0.5\n if scalar_type_1 != scalar_type_2:\n self.assertRaisesRegex(RuntimeError, \"expected scalar type\", lambda: torch.where(condition, x1, x2))\n else:\n def get_dtype(scalar_type):\n complex_dtype = torch.complex64 if torch.float == torch.get_default_dtype() else torch.complex128\n type_map = {int: torch.long, float: torch.get_default_dtype(), complex: complex_dtype}\n return type_map[scalar_type]\n expected = torch.zeros((height, width), dtype=get_dtype(scalar_type_1))\n expected[condition] = x1\n expected[~condition] = x2\n result = torch.where(condition, x1, x2)\n self.assertEqual(expected, result)\n\n # Reset the original dtype\n torch.set_default_dtype(default_dtype)\n\n def test_hook_remove(self, device):\n # Reference: https://github.com/pytorch/pytorch/issues/58354\n def _test_helper(remove_hook):\n def install_hook(tensor):\n handle = None\n\n def hook(tensor):\n if remove_hook:\n handle.remove()\n return torch.zeros_like(tensor)\n handle = tensor.register_hook(hook)\n\n t = torch.ones((1, 5), device=device, requires_grad=True)\n install_hook(t)\n\n # First call to backward\n t.mean().backward()\n self.assertEqual(t.grad, torch.zeros_like(t))\n\n # Second call to backward\n t.mean().backward()\n if remove_hook:\n # After removing the hook, make sure the usual gradient is returned\n self.assertEqual(t.grad, 0.2 * torch.ones_like(t))\n else:\n self.assertEqual(t.grad, torch.zeros_like(t))\n\n _test_helper(remove_hook=True)\n _test_helper(remove_hook=False)\n\n # FIXME: get PyTorch/XLA to run test_testing\n # This test should ideally be in test_testing.py,\n # but since pytorch/xla runs tests from test_torch.py, we have it here.\n @skipXLA\n def test_skip_xla(self, device):\n if self.device_type == 'xla':\n # Should not reach here!\n self.assertTrue(False)\n\n # FIXME: get PyTorch/XLA to run test_testing\n # This test should ideally be in test_testing.py,\n # but since pytorch/xla runs tests from test_torch.py, we have it here.\n @expectedFailureXLA\n def test_expected_failure_xla(self, device):\n if self.device_type == 'xla':\n self.assertTrue(False)\n\n # FIXME: get PyTorch/XLA to run test_testing\n # This test should ideally be in test_testing.py,\n # but since pytorch/xla runs tests from test_torch.py, we have it here.\n def test_assertRaisesRegex_ignore_msg_non_native_device(self, device):\n # Verify that self.assertRaisesRegex only checks the Error and ignores\n # message for non-native devices.\n x = torch.randn((10, 3), device=device)\n t = torch.empty(10, dtype=torch.int64, device=device).random_(0, 3)\n invalid_weight = torch.randn(4, device=device)\n msg = \"weight tensor should be defined either for all 3 classes or no classes\"\n\n # XLA raises RuntimeError with a different message.\n with self.assertRaisesRegex(RuntimeError, msg):\n torch.nn.functional.nll_loss(x, t, weight=invalid_weight)\n\n @dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32))\n def test_copy_(self, device, dtype):\n def can_cast(src_dtype, dst_dtype):\n # torch.can_cast(torch.int16, torch.uint8) returns True\n # which isn't actually safe-cast.\n # This function returns False in this case.\n def is_unsigned_int(dtype):\n return dtype is torch.uint8\n\n if is_unsigned_int(dst_dtype):\n return is_unsigned_int(src_dtype)\n return torch.can_cast(src_dtype, dst_dtype)\n\n def make_tensor_wrapper(shape, dtype):\n if dtype is not torch.complex32:\n # Make tensor does not support generating\n # complex32 tensor\n return make_tensor(shape, device=device, dtype=dtype)\n return torch.randn(shape, device=device, dtype=dtype)\n\n t = make_tensor_wrapper((50,), dtype)\n src_dtypes = all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32)\n for src_dtype in src_dtypes:\n src = make_tensor_wrapper((50,), dtype=src_dtype)\n t.copy_(src)\n dst = make_tensor_wrapper((50, ), dtype=src_dtype)\n if can_cast(src_dtype, dtype):\n rtol = None\n atol = None\n if dtype in (torch.half, torch.complex32):\n rtol = 1e-3\n atol = 1e-3\n if dtype in (torch.bfloat16,):\n rtol = 1e-2\n atol = 1e-2\n self.assertEqual(src, dst.copy_(t), rtol=rtol, atol=atol)\n\n @dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32))\n def test_item(self, device, dtype):\n t = torch.ones((), device=device, dtype=dtype)\n self.assertEqual(1, t.item())\n\n\n# Tests that compare a device's computation with the (gold-standard) CPU's.\nclass TestDevicePrecision(TestCase):\n exact_dtype = True\n\n # FIXME: move to indexing test suite\n @onlyCUDA\n def test_index_add_bfloat16(self, device):\n inp_tensor = torch.randn(5, 3, device='cpu').bfloat16()\n t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.bfloat16, device='cpu')\n index = torch.tensor([0, 4, 2], device='cpu')\n out_cpu = inp_tensor.index_add(0, index, t)\n\n inp_tensor = inp_tensor.to(device=device)\n t = t.to(device=device)\n index = index.to(device=device)\n out_gpu = inp_tensor.index_add(0, index, t)\n\n self.assertEqual(out_cpu, out_gpu, atol=1e-2, rtol=0)\n\n # FIXME: move to serialization test suite\n def test_device_serialization(self, device):\n x = torch.randn(4, 4, device=device)\n\n with tempfile.NamedTemporaryFile() as f:\n torch.save(x, f)\n f.seek(0)\n x_copy = torch.load(f)\n\n self.assertEqual(x_copy, x)\n self.assertIs(type(x_copy), type(x))\n self.assertEqual(x_copy.device, x.device)\n\n # FIXME: move to serialization test suite\n @deviceCountAtLeast(2)\n def test_multidevice_serialization(self, devices):\n x = [torch.randn(4, 4, device=devices[0]),\n torch.randn(4, 4, device=devices[1])]\n\n with tempfile.NamedTemporaryFile() as f:\n torch.save(x, f)\n f.seek(0)\n x_copy = torch.load(f)\n\n for original, cp in zip(x, x_copy):\n self.assertEqual(cp, original)\n self.assertIs(type(cp), type(original))\n self.assertEqual(cp.device, original.device)\n\n # FIXME: move to data movement test suite\n @deviceCountAtLeast(1)\n def test_copy_noncontig(self, devices):\n def do_test(d0, d1):\n x = torch.tensor([1.5, 2.5, 3.5, 4.5, 5.5, 6.5], device=d0)\n y = torch.tensor([0, 0, 0, 0, 0, 0], device=d1)\n self.assertNotEqual(x.dtype, y.dtype)\n\n y[::2].copy_(x[::2])\n self.assertEqual(y, [1, 0, 3, 0, 5, 0])\n\n do_test('cpu', devices[0])\n do_test(devices[0], 'cpu')\n\n if len(devices) > 1:\n do_test(devices[0], devices[1])\n\n @deviceCountAtLeast(2)\n def test_type_conversions_same_device(self, devices):\n x = torch.randn(5, 5, device=devices[1])\n self.assertEqual(x.int().device, torch.device(devices[1]))\n self.assertEqual(x.type(torch.int).device, torch.device(devices[1]))\n self.assertEqual(x.to(torch.int).device, torch.device(devices[1]))\n\n @dtypesIfCUDA(torch.half, torch.float, torch.double,\n torch.int8, torch.short, torch.int, torch.long,\n torch.uint8)\n @dtypes(torch.float, torch.double,\n torch.int8, torch.short, torch.int, torch.long,\n torch.uint8)\n def test_from_sequence(self, device, dtype):\n seq = [list(range(i * 4, i * 4 + 4)) for i in range(5)]\n reference = torch.arange(0, 20).resize_(5, 4)\n self.assertEqual(torch.tensor(seq, dtype=dtype, device=device), reference, exact_dtype=False)\n\n # FIXME: moved to indexing test suite\n @deviceCountAtLeast(1)\n def test_advancedindex_mixed_cpu_devices(self, devices) -> None:\n def test(x: torch.Tensor, ia: torch.Tensor, ib: torch.Tensor) -> None:\n # test getitem\n self.assertEqual(x[:, ia, None, ib, 0].cpu(),\n x.cpu()[:, ia.cpu(), None, ib.cpu(), 0])\n self.assertEqual(x[ia], x.cpu()[ia.cpu()])\n # test setitem\n x_clone1 = x.clone()\n x_clone2 = x.clone()\n first_shape = x[:, ia, None, ib, 0].shape\n second_shape = x[ia].shape\n x_clone1[:, ia, None, ib, 0] = torch.randn(first_shape).to(x_clone1)\n x_clone2[ia] = torch.randn(second_shape).to(x_clone2)\n\n cpu = torch.device('cpu')\n for device in devices:\n # Index cpu tensor with device tensor\n x = torch.randn(3, 4, 4, 4, 3)\n ia = torch.tensor([0, 2, 1]).to(device)\n ib = torch.tensor([0, 2, 1]).to(device)\n test(x, ia, ib)\n\n # Index device tensor with cpu tensor\n x = x.to(device)\n ia = ia.to(cpu)\n ib = ib.to(cpu)\n test(x, ia, ib)\n\n # Index cpu tensor with mixed cpu, device tensors\n x = x.to(cpu)\n ia = ia.to(cpu)\n ib = ib.to(device)\n test(x, ia, ib)\n\n # Index device tensor with mixed cpu, device tensors\n x = x.to(device)\n ia = ia.to(cpu)\n ib = ib.to(device)\n test(x, ia, ib)\n\n if len(devices) > 1:\n other_device = devices[0]\n if device == devices[0]:\n other_device = devices[1]\n # Index device tensor with mixed cpu, device tensors on different devices\n x = x.to(device)\n ia = ia.to(cpu)\n ib = ib.to(other_device)\n test(x, ia, ib)\n\n # FIXME: move to data movement test suite\n def test_copy_broadcast(self, device) -> None:\n x = torch.randn(10, 5)\n y = torch.randn(5, device=device)\n x.copy_(y)\n self.assertEqual(x[3], y)\n\n x = torch.randn(10, 5, device=device)\n y = torch.randn(5)\n x.copy_(y)\n self.assertEqual(x[3], y)\n\n # FIXME: move to an elementwise ternary test suite\n @dtypes(torch.int64, torch.float32, torch.float64)\n def test_clamp(self, device, dtype):\n test_args = [\n *product(\n [(100, 50), (10, 64), (97,)], # shape\n (True, False), # non-contiguous\n )\n ]\n\n for shape, noncontig in test_args:\n x = make_tensor(shape, device=device, dtype=dtype,\n noncontiguous=noncontig)\n ub = make_tensor(shape, device=device, dtype=dtype,\n noncontiguous=noncontig)\n lb = make_tensor(shape, device=device, dtype=dtype,\n noncontiguous=noncontig)\n\n expect = x.max(lb).min(ub)\n actual = x.clamp(lb, ub)\n self.assertEqual(expect, actual)\n\n expect = np.clip(x.cpu().numpy(), lb.cpu().numpy(), ub.cpu().numpy())\n self.assertEqual(expect, actual)\n\n expect = x.max(lb)\n actual = x.clamp(min=lb)\n self.assertEqual(expect, actual)\n\n expect = x.min(ub)\n actual = x.clamp(max=ub)\n self.assertEqual(expect, actual)\n\n # Test broadcasting min & max\n expect = x.max(lb[0]).min(ub[..., :1])\n actual = x.clamp(lb[0], ub[..., :1])\n self.assertEqual(expect, actual)\n\n # Test broadcasting x\n expect = x[..., :1].max(lb).min(ub)\n actual = x[..., :1].clamp(lb, ub)\n self.assertEqual(expect, actual)\n\n def test_cuda_device_idx(self, device):\n x = torch.zeros(3, device=device)\n y = torch._efficientzerotensor(3, device=device)\n self.assertEqual(x.device, y.device)\n\n# we implemented custom deallocation for subclasses, so it behooves\n# us to make sure all of these bits work. We'll use __del__ to\n# track if objects die or not\nclass Tracker:\n def __init__(self, marker):\n self.marker = marker\n\n @staticmethod\n def make():\n marker = [False]\n return marker, Tracker(marker)\n\n def __del__(self):\n self.marker[0] = True\n\[email protected]\ndef disable_gc():\n if gc.isenabled():\n try:\n gc.disable()\n yield\n finally:\n gc.enable()\n else:\n yield\n\nclass TestTorch(TestCase):\n exact_dtype = True\n\n def test_dir(self):\n dir(torch)\n\n def test_wildcard_import(self):\n exec('from torch import *')\n\n def test_newaxis_numpy_comparison(self):\n def run_test(tensor, *idx):\n npt = tensor.numpy()\n self.assertEqual(tensor[idx], npt[idx])\n\n # 1D Tensor Tests\n x = torch.arange(0, 10)\n cases = [\n [None],\n [None, None],\n [Ellipsis, None],\n [None, Ellipsis],\n [2, None],\n [None, 2],\n [Ellipsis, None, 2],\n [Ellipsis, 2, None],\n [2, Ellipsis, None],\n [2, None, Ellipsis],\n [None, 2, Ellipsis],\n [None, Ellipsis, 2],\n ]\n\n for case in cases:\n run_test(x, *case)\n\n # 2D Tensor Tests\n x = torch.arange(0, 12).view(3, 4)\n cases = [\n [None],\n [None, None],\n [None, None, None],\n [Ellipsis, None],\n [Ellipsis, None, None],\n [None, Ellipsis],\n [None, Ellipsis, None],\n [None, None, Ellipsis],\n [2, None],\n [2, None, Ellipsis],\n [2, Ellipsis, None],\n [None, 2, Ellipsis],\n [Ellipsis, 2, None],\n [Ellipsis, None, 2],\n [None, Ellipsis, 2],\n [1, 2, None],\n [1, 2, Ellipsis, None],\n [1, Ellipsis, 2, None],\n [Ellipsis, 1, None, 2],\n [Ellipsis, 1, 2, None],\n [1, None, 2, Ellipsis],\n [None, 1, Ellipsis, 2],\n [None, 1, 2, Ellipsis],\n ]\n\n for case in cases:\n run_test(x, *case)\n\n def _consecutive(self, size, start=1):\n sequence = torch.ones(torch.tensor(size).prod(0)).cumsum(0)\n sequence.add_(start - 1)\n return sequence.resize_(*size)\n\n def test_newindex(self):\n reference = self._consecutive((3, 3, 3))\n # This relies on __index__() being correct - but we have separate tests for that\n\n def checkPartialAssign(index):\n reference = torch.zeros(3, 3, 3)\n reference[index] = self._consecutive((3, 3, 3))[index]\n self.assertEqual(reference[index], self._consecutive((3, 3, 3))[index], atol=0, rtol=0)\n reference[index] = 0\n self.assertEqual(reference, torch.zeros(3, 3, 3), atol=0, rtol=0)\n\n checkPartialAssign(0)\n checkPartialAssign(1)\n checkPartialAssign(2)\n checkPartialAssign((0, 1))\n checkPartialAssign((1, 2))\n checkPartialAssign((0, 2))\n checkPartialAssign(torch.LongTensor((0, 2)))\n\n with self.assertRaises(IndexError):\n reference[1, 1, 1, 1] = 1\n with self.assertRaises(IndexError):\n reference[1, 1, 1, (1, 1)] = 1\n with self.assertRaises(IndexError):\n reference[3, 3, 3, 3, 3, 3, 3, 3] = 1\n with self.assertRaises(IndexError):\n reference[0.0] = 1\n with self.assertRaises(TypeError):\n reference[0.0:2.0] = 1\n with self.assertRaises(IndexError):\n reference[0.0, 0.0:2.0] = 1\n with self.assertRaises(IndexError):\n reference[0.0, :, 0.0:2.0] = 1\n with self.assertRaises(IndexError):\n reference[0.0, ..., 0.0:2.0] = 1\n with self.assertRaises(IndexError):\n reference[0.0, :, 0.0] = 1\n\n # FIXME: move to indexing test suite\n def test_index_add(self):\n for device in get_all_device_types():\n for dest_contig, src_contig, index_contig in product([True, False], repeat=3):\n for other_sizes in ((), (4, 5)):\n for dtype in [torch.int, torch.long]:\n num_copy, num_dest = 3, 3\n dest = torch.randn(num_dest, *other_sizes, device=device)\n if not dest_contig:\n dest = make_tensor(dest.shape, device=device, dtype=dest.dtype, noncontiguous=True)\n src = torch.randn(num_copy, *other_sizes, device=device)\n if not src_contig:\n src = torch.testing.make_non_contiguous(src)\n idx = torch.randperm(num_dest, dtype=dtype, device=device).narrow(0, 0, num_copy)\n if not index_contig:\n idx = torch.testing.make_non_contiguous(idx)\n # index_add_ without alpha argument\n dest2 = dest.clone()\n dest.index_add_(0, idx, src)\n for i in range(idx.size(0)):\n dest2[idx[i]] += src[i]\n self.assertEqual(dest, dest2)\n # index_add_ with alpha argument\n dest2 = dest.clone()\n dest.index_add_(0, idx, src, alpha=2)\n for i in range(idx.size(0)):\n dest2[idx[i]] += src[i] * 2\n self.assertEqual(dest, dest2)\n\n # FIXME: resolve comment below and move this to indexing test suite\n # add coverage for issue with atomic add that appeared only for\n # specific dtypes on cuda:\n # https://github.com/pytorch/pytorch/issues/29153\n def test_index_add_all_dtypes(self):\n for device in get_all_device_types():\n for dtype in get_all_math_dtypes(device):\n for idx_dtype in [torch.int, torch.long]:\n size = [5, 5]\n if dtype.is_floating_point or dtype.is_complex:\n tensor = torch.rand(size, dtype=dtype, device=device)\n elif dtype.is_signed:\n tensor = torch.randint(-5, 15, size, dtype=dtype, device=device)\n else:\n tensor = torch.randint(0, 10, size, dtype=dtype, device=device)\n\n # index_add calls atomicAdd on cuda.\n zeros = torch.zeros(size, dtype=dtype, device=device)\n\n added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor)\n self.assertEqual(added, tensor)\n\n added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor, alpha=-1)\n self.assertEqual(added, -tensor)\n\n # FIXME: move to shape ops test suite\n def test_unflatten(self):\n # test args: tensor, int, sizes\n self.assertEqual(torch.tensor([]).unflatten(0, (0, 1)), torch.empty(0, 1))\n self.assertEqual(torch.tensor([1]).unflatten(0, (1, 1)), torch.tensor([[1]]))\n self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (2, 2)), torch.tensor([[1, 2], [3, 4]]))\n self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, [2, 2]), torch.tensor([[1, 2], [3, 4]]))\n self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, torch.Size([2, 2])), torch.tensor([[1, 2], [3, 4]]))\n self.assertEqual(torch.ones(2, 10).unflatten(1, (5, 2)), torch.ones(2, 5, 2))\n self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (-1, 2)),\n torch.tensor([[1, 2], [3, 4]]))\n self.assertEqual(torch.ones(2, 10).unflatten(1, (5, -1)),\n torch.ones(2, 5, 2))\n self.assertEqual(torch.ones(2, 10).unflatten(1, (-1,)),\n torch.ones(2, 10))\n self.assertEqual(torch.ones(2, 3 * 4 * 5 * 6).unflatten(1, (3, 4, -1, 6)),\n torch.ones(2, 3, 4, 5, 6))\n self.assertEqual(torch.ones(2, 0, 2).unflatten(1, (3, -1, 4, 5)),\n torch.ones(2, 3, 0, 4, 5, 2))\n\n # test invalid args: tensor, str, sizes\n with self.assertRaisesRegex(TypeError, r\"received an invalid combination of arguments\"):\n torch.tensor([1]).unflatten('A', (1, 1))\n\n # test invalid args: tensor, str, namedshape\n with self.assertRaisesRegex(RuntimeError, r\"Name 'A' not found in Tensor\\[None\\].\"):\n torch.ones(4).unflatten('A', (('A', 2), ('B', 2)))\n\n # test other invalid arguments\n with self.assertRaisesRegex(RuntimeError, r\"sizes must be non-empty\"):\n torch.tensor([1]).unflatten(0, [])\n with self.assertRaisesRegex(RuntimeError, r\"Provided sizes \\[2, 2\\] don't multiply up to the size of dim 0 \\(1\\)\"):\n torch.tensor([1]).unflatten(0, [2, 2])\n with self.assertRaisesRegex(IndexError, r\"dimension specified as 0 but tensor has no dimensions\"):\n torch.tensor(1).unflatten(0, [0])\n with self.assertRaisesRegex(RuntimeError, r\"only one dimension can be inferred\"):\n torch.randn(5, 10).unflatten(1, (-1, -1))\n with self.assertRaisesRegex(RuntimeError,\n r\"Provided sizes \\[-1, 4\\] don't multiply up to the size of dim 1 \\(10\\)\"):\n torch.randn(5, 10).unflatten(1, (-1, 4))\n with self.assertRaisesRegex(RuntimeError,\n r\"the unspecified dimension size -1 can be any value and is ambiguous\"):\n torch.randn(2, 0).unflatten(1, (2, -1, 0))\n\n def test_structseq_repr(self):\n a = torch.arange(250).reshape(5, 5, 10)\n expected = \"\"\"\n torch.return_types.max(\n values=tensor([[ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49],\n [ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99],\n [140, 141, 142, 143, 144, 145, 146, 147, 148, 149],\n [190, 191, 192, 193, 194, 195, 196, 197, 198, 199],\n [240, 241, 242, 243, 244, 245, 246, 247, 248, 249]]),\n indices=tensor([[4, 4, 4, 4, 4, 4, 4, 4, 4, 4],\n [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],\n [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],\n [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],\n [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]]))\"\"\"\n self.assertEqual(repr(a.max(1)), textwrap.dedent(expected).strip())\n\n def test_is_same_size(self):\n t1 = torch.empty(3, 4, 9, 10)\n t2 = torch.empty(3, 4)\n t3 = torch.empty(1, 9, 3, 3)\n t4 = torch.empty(3, 4, 9, 10)\n\n self.assertFalse(t1.is_same_size(t2))\n self.assertFalse(t1.is_same_size(t3))\n self.assertTrue(t1.is_same_size(t4))\n\n def test_tensor_set(self):\n t1 = torch.tensor([])\n t2 = torch.empty(3, 4, 9, 10).uniform_()\n t1.set_(t2)\n self.assertEqual(t1.storage()._cdata, t2.storage()._cdata)\n size = torch.Size([9, 3, 4, 10])\n t1.set_(t2.storage(), 0, size)\n self.assertEqual(t1.size(), size)\n t1.set_(t2.storage(), 0, tuple(size))\n self.assertEqual(t1.size(), size)\n self.assertEqual(t1.stride(), (120, 40, 10, 1))\n stride = (10, 360, 90, 1)\n t1.set_(t2.storage(), 0, size, stride)\n self.assertEqual(t1.stride(), stride)\n t1.set_(t2.storage(), 0, size=size, stride=stride)\n self.assertEqual(t1.size(), size)\n self.assertEqual(t1.stride(), stride)\n\n # test argument names\n t1 = torch.tensor([])\n # 1. case when source is tensor\n t1.set_(source=t2)\n self.assertEqual(t1.storage()._cdata, t2.storage()._cdata)\n # 2. case when source is storage\n t1.set_(source=t2.storage())\n self.assertEqual(t1.storage()._cdata, t2.storage()._cdata)\n # 3. case when source is storage, and other args also specified\n t1.set_(source=t2.storage(), storage_offset=0, size=size, stride=stride)\n self.assertEqual(t1.size(), size)\n self.assertEqual(t1.stride(), stride)\n\n t1 = torch.tensor([True, True], dtype=torch.bool)\n t2 = torch.tensor([False, False], dtype=torch.bool)\n t1.set_(t2)\n self.assertEqual(t1.storage()._cdata, t2.storage()._cdata)\n\n def test_tensor_set_errors(self):\n f_cpu = torch.randn((2, 3), dtype=torch.float32)\n d_cpu = torch.randn((2, 3), dtype=torch.float64)\n\n # change dtype\n self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage()))\n self.assertRaises(RuntimeError,\n lambda: f_cpu.set_(d_cpu.storage(), 0, d_cpu.size(), d_cpu.stride()))\n self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu))\n\n # change device\n if torch.cuda.is_available():\n f_cuda = torch.randn((2, 3), dtype=torch.float32, device='cuda')\n\n # cpu -> cuda\n self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage()))\n self.assertRaises(RuntimeError,\n lambda: f_cpu.set_(f_cuda.storage(), 0, f_cuda.size(), f_cuda.stride()))\n self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda))\n\n # cuda -> cpu\n self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage()))\n self.assertRaises(RuntimeError,\n lambda: f_cuda.set_(f_cpu.storage(), 0, f_cpu.size(), f_cpu.stride()))\n self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu))\n\n # FIXME: move this test test_testing.py (along with allclose testing)\n # NOTE: test_equal will be deprecated in favor of torch.testing.assert_close\n # once torch.testing is out of beta\n def test_equal(self):\n # Contiguous, 1D\n t1 = torch.tensor((3., 4., 9., 10.))\n t2 = t1.contiguous()\n t3 = torch.tensor((1., 9., 3., 10.))\n t4 = torch.tensor((3., 4., 9.))\n t5 = torch.tensor([])\n self.assertTrue(t1.equal(t2))\n self.assertFalse(t1.equal(t3))\n self.assertFalse(t1.equal(t4))\n self.assertFalse(t1.equal(t5))\n self.assertTrue(torch.equal(t1, t2))\n self.assertFalse(torch.equal(t1, t3))\n self.assertFalse(torch.equal(t1, t4))\n self.assertFalse(torch.equal(t1, t5))\n\n # Non contiguous, 2D\n s = torch.tensor(((1, 2, 3, 4), (5, 6, 7, 8)))\n s1 = s[:, 1:3]\n s2 = s1.clone()\n s3 = torch.tensor(((2, 3), (6, 7)))\n s4 = torch.tensor(((0, 0), (0, 0)))\n\n self.assertFalse(s1.is_contiguous())\n self.assertTrue(s1.equal(s2))\n self.assertTrue(s1.equal(s3))\n self.assertFalse(s1.equal(s4))\n self.assertTrue(torch.equal(s1, s2))\n self.assertTrue(torch.equal(s1, s3))\n self.assertFalse(torch.equal(s1, s4))\n\n def test_element_size(self):\n byte = torch.ByteStorage().element_size()\n char = torch.CharStorage().element_size()\n short = torch.ShortStorage().element_size()\n int = torch.IntStorage().element_size()\n long = torch.LongStorage().element_size()\n float = torch.FloatStorage().element_size()\n double = torch.DoubleStorage().element_size()\n bool = torch.BoolStorage().element_size()\n bfloat16 = torch.BFloat16Storage().element_size()\n complexfloat = torch.ComplexFloatStorage().element_size()\n complexdouble = torch.ComplexDoubleStorage().element_size()\n\n self.assertEqual(byte, torch.ByteTensor().element_size())\n self.assertEqual(char, torch.CharTensor().element_size())\n self.assertEqual(short, torch.ShortTensor().element_size())\n self.assertEqual(int, torch.IntTensor().element_size())\n self.assertEqual(long, torch.LongTensor().element_size())\n self.assertEqual(float, torch.FloatTensor().element_size())\n self.assertEqual(double, torch.DoubleTensor().element_size())\n self.assertEqual(bool, torch.BoolTensor().element_size())\n self.assertEqual(bfloat16, torch.tensor([], dtype=torch.bfloat16).element_size())\n self.assertEqual(complexfloat, torch.tensor([], dtype=torch.complex64).element_size())\n self.assertEqual(complexdouble, torch.tensor([], dtype=torch.complex128).element_size())\n\n self.assertGreater(byte, 0)\n self.assertGreater(char, 0)\n self.assertGreater(short, 0)\n self.assertGreater(int, 0)\n self.assertGreater(long, 0)\n self.assertGreater(float, 0)\n self.assertGreater(double, 0)\n self.assertGreater(bool, 0)\n self.assertGreater(bfloat16, 0)\n self.assertGreater(complexfloat, 0)\n self.assertGreater(complexdouble, 0)\n\n # These tests are portable, not necessarily strict for your system.\n self.assertEqual(byte, 1)\n self.assertEqual(char, 1)\n self.assertEqual(bool, 1)\n self.assertGreaterEqual(short, 2)\n self.assertGreaterEqual(int, 2)\n self.assertGreaterEqual(int, short)\n self.assertGreaterEqual(long, 4)\n self.assertGreaterEqual(long, int)\n self.assertGreaterEqual(double, float)\n\n def test_permute(self):\n orig = [1, 2, 3, 4, 5, 6, 7]\n perm = torch.randperm(7).tolist()\n x = torch.empty(*orig).fill_(0)\n new = [i - 1 for i in x.permute(*perm).size()]\n self.assertEqual(perm, new)\n self.assertEqual(x.size(), orig)\n\n def test_reversed(self):\n val = torch.arange(0, 10)\n self.assertEqual(reversed(val), torch.arange(9, -1, -1))\n\n val = torch.arange(1, 10).view(3, 3)\n self.assertEqual(reversed(val), torch.tensor([[7, 8, 9], [4, 5, 6], [1, 2, 3]]))\n\n val = torch.tensor(42)\n self.assertEqual(reversed(val), torch.tensor(42))\n\n def test_contains(self):\n x = torch.arange(0, 10)\n self.assertEqual(4 in x, True)\n self.assertEqual(12 in x, False)\n\n x = torch.arange(1, 10).view(3, 3)\n val = torch.arange(1, 4)\n self.assertEqual(val in x, True)\n val += 10\n self.assertEqual(val in x, False)\n\n self.assertRaisesRegex(\n RuntimeError,\n \"Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.\".format(type(\"foo\")),\n lambda: \"foo\" in x)\n self.assertRaisesRegex(\n RuntimeError,\n \"Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.\".format(type([1, 2])),\n lambda: [1, 2] in x)\n\n def test_deepcopy_parameter(self):\n from copy import deepcopy\n l = torch.nn.Linear(10, 1)\n s = l.state_dict(keep_vars=True)\n self.assertEqual(torch.nn.Parameter, type(s['weight']))\n self.assertEqual(torch.nn.Parameter, type(s['bias']))\n\n s2 = deepcopy(s)\n self.assertEqual(torch.nn.Parameter, type(s2['weight']))\n self.assertEqual(torch.nn.Parameter, type(s2['bias']))\n\n def test_pickle(self):\n import pickle\n a = torch.randn(5, 5)\n serialized = pickle.dumps(a)\n b = pickle.loads(serialized)\n self.assertEqual(a, b)\n\n def test_pickle_parameter(self):\n import pickle\n a = torch.nn.Parameter(torch.randn(5, 5))\n serialized = pickle.dumps(a)\n b = pickle.loads(serialized)\n self.assertTrue(isinstance(b, torch.nn.Parameter))\n self.assertEqual(a.requires_grad, b.requires_grad)\n self.assertEqual(a, b)\n\n def test_pickle_parameter_no_requires_grad(self):\n import pickle\n a = torch.nn.Parameter(torch.randn(5, 5), requires_grad=False)\n serialized = pickle.dumps(a)\n b = pickle.loads(serialized)\n self.assertTrue(isinstance(b, torch.nn.Parameter))\n self.assertEqual(a.requires_grad, b.requires_grad)\n self.assertEqual(a, b)\n\n def test_pickle_dtype(self):\n t = torch.float32\n serialized = pickle.dumps(t)\n b = pickle.loads(serialized)\n self.assertTrue(isinstance(b, torch.dtype))\n self.assertEqual(id(b), id(t))\n\n def test_pickle_size(self):\n a = torch.rand(10).size()\n serialized = pickle.dumps(a)\n b = pickle.loads(serialized)\n self.assertTrue(isinstance(b, torch.Size))\n self.assertEqual(a, b)\n\n def test_pickle_function(self):\n # https://github.com/pytorch/pytorch/issues/37703\n a = torch.tanh\n serialized = pickle.dumps(a)\n b = pickle.loads(serialized)\n self.assertEqual(a, b)\n\n def test_generator_cpu(self):\n # test default generators are equal\n self.assertEqual(torch.default_generator, torch.default_generator)\n\n # tests Generator API\n # manual_seed, seed, initial_seed, get_state, set_state\n g1 = torch.Generator()\n g2 = torch.Generator()\n g1.manual_seed(12345)\n g2.manual_seed(12345)\n self.assertEqual(g1.initial_seed(), g2.initial_seed())\n\n g1.seed()\n g2.seed()\n self.assertNotEqual(g1.initial_seed(), g2.initial_seed())\n\n g1 = torch.Generator()\n g2_state = g2.get_state()\n g2_randn = torch.randn(1, generator=g2)\n g1.set_state(g2_state)\n g1_randn = torch.randn(1, generator=g1)\n self.assertEqual(g1_randn, g2_randn)\n\n default_state = torch.default_generator.get_state()\n q = torch.empty(100)\n g1_normal = q.normal_()\n g2 = torch.Generator()\n g2.set_state(default_state)\n g2_normal = q.normal_(generator=g2)\n self.assertEqual(g1_normal, g2_normal)\n\n def test_invalid_generator_raises(self):\n self.assertRaises(RuntimeError, lambda: torch.Generator('opengl'))\n\n def _sobol_reference_samples(self, scramble: bool) -> torch.Tensor:\n if not scramble:\n # theoretical values from Joe Kuo 2010\n return torch.tensor(\n [\n [0., 0.],\n [0.5, 0.5],\n [0.75, 0.25],\n [0.25, 0.75],\n [0.375, 0.375],\n [0.875, 0.875],\n [0.625, 0.125],\n [0.125, 0.625],\n ],\n )\n else:\n # theoretical values unknown: convergence properties checked\n return torch.tensor(\n [\n [0.50860737, 0.29320504],\n [0.07116939, 0.89594537],\n [0.49354145, 0.11524881],\n [0.93097717, 0.70244044],\n [0.87266153, 0.23887917],\n [0.31021884, 0.57600391],\n [0.13687253, 0.42054182],\n [0.69931293, 0.77336788],\n ],\n )\n\n def test_sobolengine_bounds(self, scramble: bool = False):\n engine = torch.quasirandom.SobolEngine(100, scramble=scramble, seed=123456)\n sample = engine.draw(512)\n self.assertTrue(torch.all(sample >= 0))\n self.assertTrue(torch.all(sample <= 1))\n\n def test_sobolengine_bounds_scrambled(self):\n self.test_sobolengine_bounds(scramble=True)\n\n def test_sobolengine_draw(self, scramble: bool = False):\n ref_sample = self._sobol_reference_samples(scramble=scramble)\n engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456)\n sample = engine.draw(n=len(ref_sample))\n self.assertEqual(sample, ref_sample)\n self.assertEqual(engine.num_generated, len(ref_sample))\n\n def test_sobolengine_draw_scrambled(self):\n self.test_sobolengine_draw(scramble=True)\n\n def test_sobolengine_first_point(self):\n for dtype in (torch.float, torch.double):\n engine = torch.quasirandom.SobolEngine(2, scramble=False)\n sample = engine.draw(1, dtype=dtype)\n self.assertTrue(torch.all(sample == 0))\n self.assertEqual(sample.dtype, dtype)\n for dtype in (torch.float, torch.double):\n engine = torch.quasirandom.SobolEngine(2, scramble=True, seed=123456)\n sample = engine.draw(1, dtype=dtype)\n self.assertTrue(torch.all(sample != 0))\n self.assertEqual(sample.dtype, dtype)\n\n def test_sobolengine_continuing(self, scramble: bool = False):\n ref_sample = self._sobol_reference_samples(scramble=scramble)\n engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456)\n n_half = len(ref_sample) // 2\n _ = engine.draw(n=n_half)\n sample = engine.draw(n=n_half)\n torch.testing.assert_close(sample, ref_sample[n_half:])\n\n def test_sobolengine_continuing_scrambled(self):\n self.test_sobolengine_continuing(scramble=True)\n\n def test_sobolengine_reset(self, scramble: bool = False):\n ref_sample = self._sobol_reference_samples(scramble=scramble)\n engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456)\n _ = engine.draw(n=len(ref_sample) // 2)\n engine.reset()\n self.assertEqual(engine.num_generated, 0)\n sample = engine.draw(n=len(ref_sample))\n torch.testing.assert_close(sample, ref_sample)\n\n def test_sobolengine_reset_scrambled(self):\n self.test_sobolengine_reset(scramble=True)\n\n def test_sobolengine_fast_forward(self, scramble: bool = False):\n ref_sample = self._sobol_reference_samples(scramble=scramble)\n engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456)\n engine.fast_forward(4)\n sample = engine.draw(n=4)\n torch.testing.assert_close(sample, ref_sample[4:])\n # alternate fast forwarding with sampling\n engine.reset()\n even_draws = []\n for i in range(8):\n if i % 2 == 0:\n even_draws.append(engine.draw())\n else:\n engine.fast_forward(1)\n torch.testing.assert_close(\n ref_sample[[i for i in range(8) if i % 2 == 0]],\n torch.from_numpy(np.concatenate(even_draws)),\n )\n\n def test_sobolengine_fast_forward_scrambled(self):\n self.test_sobolengine_fast_forward(scramble=True)\n\n def test_sobolengine_distribution(self, scramble=False):\n d = 50\n engine = torch.quasirandom.SobolEngine(d, scramble=scramble, seed=123456)\n sample = engine.draw(1024)\n torch.testing.assert_close(\n torch.mean(sample, dim=0), torch.full((d,), 0.5), atol=2, rtol=2\n )\n torch.testing.assert_close(\n np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=2, rtol=2\n )\n torch.testing.assert_close(\n np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=2, rtol=2\n )\n\n def test_sobolengine_distribution_scrambled(self):\n self.test_sobolengine_distribution(scramble=True)\n\n def test_sobolengine_draw_base2(self, scramble=False):\n ref_sample = self._sobol_reference_samples(scramble=scramble)\n engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456)\n sample = engine.draw_base2(2)\n self.assertEqual(ref_sample[:4], sample)\n # resampling still having N=2**n\n sample = engine.draw_base2(2)\n self.assertEqual(ref_sample[4:8], sample)\n\n def test_sobolengine_draw_base2_scrambled(self):\n self.test_sobolengine_draw_base2(scramble=True)\n\n def test_sobolengine_raise(self):\n maxdim = torch.quasirandom.SobolEngine.MAXDIM\n with self.assertRaises(ValueError):\n torch.quasirandom.SobolEngine(maxdim + 1)\n\n def test_sobolengine_high_dim(self):\n engine = torch.quasirandom.SobolEngine(1111, scramble=False, seed=123456)\n samples1 = engine.draw()\n vals1, counts1 = torch.unique(samples1, return_counts=True)\n samples2 = engine.draw()\n vals2, counts2 = torch.unique(samples2, return_counts=True)\n self.assertEqual(vals1.item(), 0.0)\n self.assertEqual(counts1.item(), 1111)\n self.assertEqual(vals2.item(), 0.5)\n self.assertEqual(counts1.item(), 1111)\n\n def test_parsing_int64(self):\n # accepts integer arguments\n x = torch.cumsum(torch.ones(5, 5), 0)\n self.assertEqual(x, torch.cumsum(torch.ones(5, 5), torch.tensor(0)))\n # doesn't accept floating point variables\n self.assertRaises(TypeError, lambda: torch.cumsum(torch.ones(5, 5), torch.tensor(0.)))\n\n def test_parsing_double(self):\n # accepts floating point and integer arguments\n x = torch.randn(2, 3)\n torch.isclose(x, x, 1, 1)\n self.assertTrue(torch.isclose(x, x, 1, 1).all())\n self.assertTrue(torch.isclose(x, x, 1.5, 1.).all())\n # accepts floating point and integer tensors\n self.assertTrue(torch.isclose(x, x, torch.tensor(1), torch.tensor(1)).all())\n self.assertTrue(torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1.)).all())\n # doesn't accept variables with requires_grad\n self.assertRaises(TypeError,\n lambda: torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1., requires_grad=True)).all())\n\n def test_parsing_intlist(self):\n # parse with integer variables\n self.assertEqual(torch.Size([3, 4]), torch.ones((torch.tensor(3), torch.tensor(4))).shape)\n self.assertEqual(torch.Size([3, 4]), torch.ones(torch.tensor(3), torch.tensor(4)).shape)\n # parse with numpy integers\n self.assertEqual(torch.Size([3, 4]), torch.ones((np.array(3), np.int64(4))).shape)\n self.assertEqual(torch.Size([3, 4]), torch.ones(np.array(3), np.int64(4)).shape)\n self.assertEqual(torch.Size([3, 4]), torch.ones((np.int64(3), np.array(4))).shape)\n self.assertEqual(torch.Size([3, 4]), torch.ones(np.int64(3), np.array(4)).shape)\n\n # fail parse with float variables\n self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3.), torch.tensor(4))))\n # fail parse with numpy floats\n self.assertRaises(TypeError, lambda: torch.ones((np.float(3.), torch.tensor(4))))\n self.assertRaises(TypeError, lambda: torch.ones((np.array(3.), torch.tensor(4))))\n\n # fail parse with > 1 element variables\n self.assertRaises(TypeError, lambda: torch.ones(torch.tensor(3, 3)))\n self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3, 3))))\n self.assertRaises(TypeError, lambda: torch.ones(np.array(3, 3)))\n self.assertRaises(TypeError, lambda: torch.ones((np.array(3, 3))))\n\n # fail parse with additional positional args after intlist arg\n self.assertRaisesRegex(TypeError,\n \"received an invalid combination of arguments\",\n lambda: torch.LongTensor((6, 0), 1, 1, 0))\n self.assertRaisesRegex(TypeError,\n \"missing 1 required positional arguments\",\n lambda: torch.tensor().new_zeros((5, 5), 0))\n\n def test_from_buffer(self):\n a = bytearray([1, 2, 3, 4])\n self.assertEqual(torch.ByteStorage.from_buffer(a).tolist(), [1, 2, 3, 4])\n shorts = torch.ShortStorage.from_buffer(a, 'big')\n self.assertEqual(shorts.size(), 2)\n self.assertEqual(shorts.tolist(), [258, 772])\n ints = torch.IntStorage.from_buffer(a, 'little')\n self.assertEqual(ints.size(), 1)\n self.assertEqual(ints[0], 67305985)\n f = bytearray([0x40, 0x10, 0x00, 0x00])\n floats = torch.FloatStorage.from_buffer(f, 'big')\n self.assertEqual(floats.size(), 1)\n self.assertEqual(floats[0], 2.25)\n\n f = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x40])\n bools = torch.BoolStorage.from_buffer(f, 'big')\n self.assertEqual(bools.size(), 8)\n self.assertEqual(bools.tolist(), [False, True, True, True, True, True, True, True])\n self.assertEqual(bools.type(), 'torch.BoolStorage')\n self.assertTrue(isinstance(bools, torch.BoolStorage))\n\n f = bytearray(b'\\x80\\x02\\x8a\\nl\\xfc\\x9cF\\xf9 j\\xa8P\\x19.\\x80\\x02M\\xe9')\n bools = torch.BoolStorage.from_buffer(f, 'big')\n self.assertEqual(bools.size(), 19)\n\n f = bytearray(b'\\0x4A')\n bools = torch.BoolStorage.from_buffer(f, 'big')\n self.assertEqual(bools.size(), 4)\n self.assertEqual(bools.tolist(), [False, True, True, True])\n bytes = torch.ByteStorage.from_buffer(a)\n self.assertEqual(bytes.nbytes(), 4)\n self.assertEqual(bytes.tolist(), [1, 2, 3, 4])\n self.assertTrue(isinstance(bytes, torch.ByteStorage))\n\n def test_storage_error(self):\n quantized_storages = [\n torch.QInt32Storage,\n torch.QInt8Storage,\n torch.QUInt2x4Storage,\n torch.QUInt4x2Storage,\n torch.QUInt8Storage,\n ]\n\n with self.assertRaisesRegex(RuntimeError, r\"Only child classes of _LegacyStorage can be instantiated\"):\n torch.storage._LegacyStorage()\n\n for storage_class in torch._storage_classes:\n if storage_class in [torch._UntypedStorage, torch.cuda._UntypedStorage, torch._TypedStorage]:\n continue\n\n device = 'cuda' if storage_class.__module__ == 'torch.cuda' else 'cpu'\n dtype = storage_class.dtype\n\n if device == 'cuda' and not torch.cuda.is_available():\n continue\n\n # Legacy <type>Storage constructor errors\n with self.assertRaisesRegex(RuntimeError, r\"'device' cannot be specified\"):\n storage_class(device='cpu')\n\n with self.assertRaisesRegex(RuntimeError, r\"'dtype' cannot be specified\"):\n storage_class(dtype=torch.float)\n\n with self.assertRaisesRegex(TypeError, r\"got an unexpected keyword\"):\n storage_class(sdlkjf=torch.float)\n\n with self.assertRaisesRegex(RuntimeError, r\"Too many positional arguments\"):\n storage_class(0, 0)\n\n with self.assertRaisesRegex(TypeError, r\"invalid data type\"):\n storage_class('string')\n\n with self.assertRaisesRegex(TypeError, r\"Argument type not recognized\"):\n storage_class(torch.tensor([]))\n\n s = storage_class()\n\n with self.assertRaisesRegex(RuntimeError, r\"No positional arguments\"):\n storage_class(0, wrap_storage=s._untyped())\n\n with self.assertRaisesRegex(TypeError, r\"must be _UntypedStorage\"):\n storage_class(wrap_storage=s)\n\n if torch.cuda.is_available():\n if storage_class in quantized_storages:\n with self.assertRaisesRegex(RuntimeError, r\"Cannot create CUDA storage with quantized dtype\"):\n s.cuda()\n\n else:\n\n if s.is_cuda:\n s_other_device = s.cpu()\n else:\n s_other_device = s.cuda()\n\n with self.assertRaisesRegex(RuntimeError, r\"Device of 'wrap_storage' must be\"):\n storage_class(wrap_storage=s_other_device._untyped())\n\n # _TypedStorage constructor errors\n with self.assertRaisesRegex(RuntimeError, r\"No positional arguments\"):\n torch._TypedStorage(0, wrap_storage=s._untyped(), dtype=dtype)\n\n with self.assertRaisesRegex(RuntimeError, r\"Argument 'dtype' must be specified\"):\n torch._TypedStorage(wrap_storage=s._untyped())\n\n with self.assertRaisesRegex(TypeError, r\"Argument 'dtype' must be torch.dtype\"):\n torch._TypedStorage(wrap_storage=s._untyped(), dtype=0)\n\n with self.assertRaisesRegex(RuntimeError, r\"Argument 'device' should not be specified\"):\n torch._TypedStorage(wrap_storage=s._untyped(), dtype=dtype, device=device)\n\n with self.assertRaisesRegex(TypeError, r\"Argument 'wrap_storage' must be _UntypedStorage\"):\n torch._TypedStorage(wrap_storage=s, dtype=dtype)\n\n with self.assertRaisesRegex(RuntimeError, r\"Storage device not recognized\"):\n torch._TypedStorage(dtype=dtype, device='xla')\n\n if torch.cuda.is_available():\n if storage_class in quantized_storages:\n with self.assertRaisesRegex(RuntimeError, r\"Cannot create CUDA storage with quantized dtype\"):\n torch._TypedStorage(dtype=dtype, device='cuda')\n\n with self.assertRaisesRegex(TypeError, r\"Argument type not recognized\"):\n torch._TypedStorage(torch.tensor([]), dtype=dtype, device=device)\n\n with self.assertRaisesRegex(RuntimeError, r\"Too many positional arguments\"):\n torch._TypedStorage(0, 0, dtype=dtype, device=device)\n\n def test_storage_error_no_attribute(self):\n storage_classes = [\n torch.cuda.ByteStorage,\n torch.cuda.FloatStorage,\n torch.cuda._UntypedStorage,\n ]\n for storage_class in storage_classes:\n with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'):\n storage_class.from_buffer()\n\n if storage_class == torch.cuda._UntypedStorage:\n with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'):\n storage_class._new_with_weak_ptr()\n\n else:\n with self.assertRaisesRegex(AttributeError, r'has no attribute'):\n storage_class._new_with_weak_ptr()\n\n with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'):\n storage_class._new_shared_filename(0, 0, 0)\n\n def test_storage_casts(self):\n storage = torch.IntStorage([-1, 0, 1, 2, 3, 4])\n self.assertEqual(storage.size(), 6)\n self.assertEqual(storage.tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertEqual(storage.type(), 'torch.IntStorage')\n self.assertIs(storage.dtype, torch.int32)\n\n floatStorage = storage.float()\n self.assertEqual(floatStorage.size(), 6)\n self.assertEqual(floatStorage.tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertEqual(floatStorage.type(), 'torch.FloatStorage')\n self.assertEqual(floatStorage.int().tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertIs(floatStorage.dtype, torch.float32)\n\n halfStorage = storage.half()\n self.assertEqual(halfStorage.size(), 6)\n self.assertEqual(halfStorage.tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertEqual(halfStorage.type(), 'torch.HalfStorage')\n self.assertEqual(halfStorage.int().tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertIs(halfStorage.dtype, torch.float16)\n\n bfloat16Storage = storage.bfloat16()\n self.assertEqual(bfloat16Storage.size(), 6)\n self.assertEqual(bfloat16Storage.tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertEqual(bfloat16Storage.type(), 'torch.BFloat16Storage')\n self.assertEqual(bfloat16Storage.int().tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertIs(bfloat16Storage.dtype, torch.bfloat16)\n\n longStorage = storage.long()\n self.assertEqual(longStorage.size(), 6)\n self.assertEqual(longStorage.tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertEqual(longStorage.type(), 'torch.LongStorage')\n self.assertEqual(longStorage.int().tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertIs(longStorage.dtype, torch.int64)\n\n shortStorage = storage.short()\n self.assertEqual(shortStorage.size(), 6)\n self.assertEqual(shortStorage.tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertEqual(shortStorage.type(), 'torch.ShortStorage')\n self.assertEqual(shortStorage.int().tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertIs(shortStorage.dtype, torch.int16)\n\n doubleStorage = storage.double()\n self.assertEqual(doubleStorage.size(), 6)\n self.assertEqual(doubleStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])\n self.assertEqual(doubleStorage.type(), 'torch.DoubleStorage')\n self.assertEqual(doubleStorage.int().tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertIs(doubleStorage.dtype, torch.float64)\n\n charStorage = storage.char()\n self.assertEqual(charStorage.size(), 6)\n self.assertEqual(charStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])\n self.assertEqual(charStorage.type(), 'torch.CharStorage')\n self.assertEqual(charStorage.int().tolist(), [-1, 0, 1, 2, 3, 4])\n self.assertIs(charStorage.dtype, torch.int8)\n\n byteStorage = storage.byte()\n self.assertEqual(byteStorage.size(), 6)\n self.assertEqual(byteStorage.tolist(), [255, 0, 1, 2, 3, 4])\n self.assertEqual(byteStorage.type(), 'torch.ByteStorage')\n self.assertEqual(byteStorage.int().tolist(), [255, 0, 1, 2, 3, 4])\n self.assertIs(byteStorage.dtype, torch.uint8)\n\n boolStorage = storage.bool()\n self.assertEqual(boolStorage.size(), 6)\n self.assertEqual(boolStorage.tolist(), [True, False, True, True, True, True])\n self.assertEqual(boolStorage.type(), 'torch.BoolStorage')\n self.assertEqual(boolStorage.int().tolist(), [1, 0, 1, 1, 1, 1])\n self.assertIs(boolStorage.dtype, torch.bool)\n\n complexfloat_storage = torch.ComplexFloatStorage([-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j])\n self.assertEqual(complexfloat_storage.size(), 6)\n self.assertEqual(complexfloat_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j])\n self.assertEqual(complexfloat_storage.type(), 'torch.ComplexFloatStorage')\n self.assertIs(complexfloat_storage.dtype, torch.complex64)\n\n complexdouble_storage = complexfloat_storage.complex_double()\n self.assertEqual(complexdouble_storage.size(), 6)\n self.assertEqual(complexdouble_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j])\n self.assertEqual(complexdouble_storage.type(), 'torch.ComplexDoubleStorage')\n self.assertIs(complexdouble_storage.dtype, torch.complex128)\n\n def test_from_file(self):\n def assert_with_filename(filename):\n size = 10000\n s1 = torch.FloatStorage.from_file(filename, True, size)\n t1 = torch.FloatTensor(s1).copy_(torch.randn(size))\n self.assertEqual(s1.data_ptr(), torch.FloatTensor(s1).data_ptr())\n\n # check mapping\n s2 = torch.FloatStorage.from_file(filename, True, size)\n t2 = torch.FloatTensor(s2)\n self.assertEqual(t1, t2, atol=0, rtol=0)\n\n # check changes to t1 from t2\n rnum = random.uniform(-1, 1)\n t1.fill_(rnum)\n self.assertEqual(t1, t2, atol=0, rtol=0)\n\n # check changes to t2 from t1\n rnum = random.uniform(-1, 1)\n t2.fill_(rnum)\n self.assertEqual(t1, t2, atol=0, rtol=0)\n\n # release the tensors\n del s1, t1, s2, t2\n\n with TemporaryFileName() as fname:\n assert_with_filename(fname)\n\n if IS_FILESYSTEM_UTF8_ENCODING:\n with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname:\n assert_with_filename(fname)\n\n def test_torch_from_file(self):\n def assert_with_filename(filename):\n size = 10000\n s1 = torch.from_file(filename, True, size, dtype=torch.float)\n t1 = torch.FloatTensor(s1).copy_(torch.randn(size))\n\n # check mapping\n s2 = torch.from_file(filename, True, size, dtype=torch.float)\n t2 = torch.FloatTensor(s2)\n self.assertEqual(t1, t2, atol=0, rtol=0)\n\n # check changes to t1 from t2\n rnum = random.uniform(-1, 1)\n t1.fill_(rnum)\n self.assertEqual(t1, t2, atol=0, rtol=0)\n\n # check changes to t2 from t1\n rnum = random.uniform(-1, 1)\n t2.fill_(rnum)\n self.assertEqual(t1, t2, atol=0, rtol=0)\n\n # release the tensors\n del s1, t1, s2, t2\n\n with TemporaryFileName() as fname:\n assert_with_filename(fname)\n\n if IS_FILESYSTEM_UTF8_ENCODING:\n with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname:\n assert_with_filename(fname)\n\n def test_print(self):\n default_type = torch.tensor([]).type()\n for t in torch._tensor_classes:\n if t == torch.HalfTensor:\n continue # HalfTensor does not support fill\n if t.is_sparse:\n continue\n if t.is_cuda and not torch.cuda.is_available():\n continue\n obj = t(100, 100).fill_(1)\n obj.__repr__()\n str(obj)\n # test half tensor\n obj = torch.rand(100, 100, device='cpu').half()\n obj.__repr__()\n str(obj)\n for t in torch._storage_classes:\n if t == torch.BFloat16Storage:\n continue # Fix once fill is enabled for bfloat16\n if t.is_cuda and not torch.cuda.is_available():\n continue\n if t == torch.BoolStorage or t == torch.cuda.BoolStorage:\n obj = t(100).fill_(True)\n else:\n obj = t(100).fill_(1)\n obj.__repr__()\n str(obj)\n\n # test complex tensor\n # complex tensor print uses two formatters, one for real values\n # and the other for imag values. this is consistent with numpy\n x = torch.tensor([2.3 + 4j, 7 + 6j])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([2.3000+4.j, 7.0000+6.j])''')\n\n # test scientific notation for complex tensors\n x = torch.tensor([1e28 + 2j , -1e-28j])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1.0000e+28+2.0000e+00j, -0.0000e+00-1.0000e-28j])''')\n\n # test big integer\n x = torch.tensor(2341234123412341)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor(2341234123412341)''')\n\n # test scientific notation\n x = torch.tensor([1e28, 1e-28])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1.0000e+28, 1.0000e-28])''')\n\n # test scientific notation using set_printoptions\n x = torch.tensor([1e2, 1e-2])\n torch.set_printoptions(sci_mode=True)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1.0000e+02, 1.0000e-02])''')\n torch.set_printoptions(sci_mode=False)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([ 100.0000, 0.0100])''')\n torch.set_printoptions(sci_mode=None) # reset to the default value\n\n # test no leading space if all elements positive\n x = torch.tensor([1, 2])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1, 2])''')\n\n # test for leading space if there are negative elements\n x = torch.tensor([1, -2])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([ 1, -2])''')\n\n # test inf and nan\n x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([4.0000, inf, 1.5000, -inf, 0.0000, nan, 1.0000])''')\n\n y = torch.tensor([4, inf, complex(1.5, inf), complex(-inf, 4), 0, complex(nan, inf), complex(3, nan)])\n self.assertEqual(y.__repr__(), str(y))\n expected_str = '''\\\ntensor([4.0000+0.j, inf+0.j, 1.5000+infj, -inf+4.j, 0.0000+0.j, nan+infj,\n 3.0000+nanj])'''\n self.assertExpectedInline(str(y), expected_str)\n\n # test dtype\n torch.set_default_dtype(torch.float)\n x = torch.tensor([1e-324, 1e-323, 1e-322, 1e307, 1e308, 1e309], dtype=torch.float64)\n self.assertEqual(x.__repr__(), str(x))\n expected_str = '''\\\ntensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308,\n inf], dtype=torch.float64)'''\n self.assertExpectedInline(str(x), expected_str)\n\n # test changing default dtype\n torch.set_default_dtype(torch.float64)\n self.assertEqual(x.__repr__(), str(x))\n expected_str = '''\\\ntensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308,\n inf])'''\n self.assertExpectedInline(str(x), expected_str)\n\n # test summary\n x = torch.zeros(10000)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([0., 0., 0., ..., 0., 0., 0.])''')\n\n # test internal summary function\n x = torch.rand(1, 20, 5, 30)\n summary = torch._tensor_str.get_summarized_data(x)\n self.assertEqual(summary.shape, (1, 6, 5, 6))\n first_and_last = [0, 1, 2, -3, -2, -1]\n self.assertEqual(summary, x[:, first_and_last][..., first_and_last])\n\n # test device\n if torch.cuda.is_available():\n x = torch.tensor([123], device='cuda:0')\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''')\n\n # test changing default to cuda\n torch.set_default_tensor_type(torch.cuda.FloatTensor)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([123])''')\n\n # test printing a tensor on a different gpu than current one.\n if torch.cuda.device_count() >= 2:\n with torch.cuda.device(1):\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''')\n\n # test printing cpu tensor when default device is cuda\n y = torch.tensor([123], device='cpu')\n self.assertEqual(y.__repr__(), str(y))\n self.assertExpectedInline(str(y), '''tensor([123], device='cpu')''')\n torch.set_default_tensor_type(default_type)\n\n\n # test integral floats and requires_grad\n x = torch.tensor([123.], requires_grad=True)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([123.], requires_grad=True)''')\n\n # test non-contiguous print\n # sliced tensor should have > PRINT_OPTS.threshold elements\n x = torch.ones(100, 2, 2, 10)\n y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1))\n self.assertEqual(str(y), y.__repr__())\n expected_str = '''\\\ntensor([[[1., 1., 1., ..., 1., 1., 1.],\n [1., 1., 1., ..., 1., 1., 1.]],\n\n [[1., 1., 1., ..., 1., 1., 1.],\n [1., 1., 1., ..., 1., 1., 1.]],\n\n [[1., 1., 1., ..., 1., 1., 1.],\n [1., 1., 1., ..., 1., 1., 1.]],\n\n ...,\n\n [[1., 1., 1., ..., 1., 1., 1.],\n [1., 1., 1., ..., 1., 1., 1.]],\n\n [[1., 1., 1., ..., 1., 1., 1.],\n [1., 1., 1., ..., 1., 1., 1.]],\n\n [[1., 1., 1., ..., 1., 1., 1.],\n [1., 1., 1., ..., 1., 1., 1.]]])\\\n'''\n\n self.assertExpectedInline(str(y), expected_str)\n\n x = torch.ones(100, 2, 2, 10) * (1 + 1j)\n y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1))\n self.assertEqual(str(y), y.__repr__())\n expected_str = '''\\\ntensor([[[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j],\n [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]],\n\n [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j],\n [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]],\n\n [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j],\n [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]],\n\n ...,\n\n [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j],\n [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]],\n\n [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j],\n [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]],\n\n [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j],\n [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]]])\\\n'''\n self.assertExpectedInline(str(y), expected_str)\n\n # test print 0-dim tensor: there's no 0-dim in Numpy, we match arrayprint style\n x = torch.tensor(0.00002)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor(2.0000e-05)''')\n\n # test print boolean tensor\n x = torch.tensor([True])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([True])''')\n\n x = torch.tensor(True)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor(True)''')\n\n # [Numpy] test print float in sci_mode when min < 0.0001.\n x = torch.tensor([0.00002])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([2.0000e-05])''')\n\n # [Numpy] test print complex in sci_mode when real_min < 0.0001 and (or) imag_min < 0.0001.\n x = torch.tensor([0.00002]) * (1 + 1j)\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([2.0000e-05+2.0000e-05j])''')\n\n # [Numpy] test print float in sci_mode when max > 1e8.\n # TODO: Pytorch uses fixed precision to print, while Numpy uses dragon4_scientific\n # to do automatic trimming and padding.\n x = torch.tensor([123456789.])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1.2346e+08])''')\n\n # [Numpy] test print float in sci_mode when max / min > 1000.\n x = torch.tensor([0.01, 11])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1.0000e-02, 1.1000e+01])''')\n\n # [Numpy] test print int max / min > 1000, no sci_mode\n x = torch.tensor([1, 1010])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([ 1, 1010])''')\n\n # [Numpy] test print int > 1e8, no sci_mode\n x = torch.tensor([1000000000]) # 1e9\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1000000000])''')\n\n # [Numpy] test printing float in int_mode\n x = torch.tensor([1., 1000.])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([ 1., 1000.])''')\n\n # [Numpy] test printing float in int_mode in sci format when max / min > 1000.\n x = torch.tensor([1., 1010.])\n self.assertEqual(x.__repr__(), str(x))\n self.assertExpectedInline(str(x), '''tensor([1.0000e+00, 1.0100e+03])''')\n\n def test_sizeof(self) -> None:\n sizeof_empty = torch.randn(0).storage().__sizeof__()\n sizeof_10 = torch.randn(10).storage().__sizeof__()\n sizeof_100 = torch.randn(100).storage().__sizeof__()\n self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10)\n self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0)\n\n sizeof_empty = torch.randn(0).to(torch.uint8).storage().__sizeof__()\n sizeof_10 = torch.randn(10).to(torch.uint8).storage().__sizeof__()\n sizeof_100 = torch.randn(100).to(torch.uint8).storage().__sizeof__()\n self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10)\n self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0)\n\n def test_iter(self) -> None:\n x = torch.randn(5, 5)\n for i, sub in enumerate(x):\n self.assertEqual(sub, x[i])\n\n x = torch.tensor([])\n self.assertEqual(list(x), [])\n\n def test_new(self) -> None:\n x = torch.autograd.Variable(torch.tensor([]))\n y = torch.autograd.Variable(torch.randn(4, 4))\n z = torch.autograd.Variable(torch.IntTensor([1, 2, 3]))\n self.assertEqual(x.new().shape, [0])\n self.assertEqual(x.new(), x)\n self.assertEqual(x.new(1, 2).shape, [1, 2])\n self.assertEqual(x.new(torch.Size([3, 4])).shape, [3, 4])\n self.assertEqual(x.new([3, 4]).shape, [2])\n self.assertEqual(x.new([3, 4]).tolist(), [3, 4])\n self.assertEqual(x.new((3, 4)).tolist(), [3, 4])\n self.assertEqual(x.new([np.int32(3), np.float64(4)]).tolist(), [3, 4])\n self.assertEqual(x.new(np.array((3, 4))).tolist(), [3, 4])\n self.assertEqual(x.new([z[2], z[0] + 3]).tolist(), [3, 4])\n self.assertEqual(x.new(size=(3, 4)).shape, [3, 4])\n self.assertEqual(x.new(()).shape, [0])\n self.assertEqual(x.new(y.storage()).data_ptr(), y.data_ptr())\n self.assertEqual(x.new(y).data_ptr(), y.data_ptr())\n self.assertIsNot(x.new(y), y)\n\n self.assertRaises(TypeError, lambda: x.new(z))\n # TypeError would be better\n self.assertRaises(RuntimeError, lambda: x.new(z.storage()))\n\n @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, \"is_pinned uses failure to detect pointer property\")\n def test_pin_memory(self):\n x = torch.randn(3, 5)\n self.assertFalse(x.is_pinned())\n if not torch.cuda.is_available():\n self.assertRaises(RuntimeError, lambda: x.pin_memory())\n else:\n pinned = x.pin_memory()\n self.assertTrue(pinned.is_pinned())\n self.assertEqual(pinned, x)\n self.assertNotEqual(pinned.data_ptr(), x.data_ptr())\n # test that pin_memory on already pinned tensor has no effect\n self.assertIs(pinned, pinned.pin_memory())\n self.assertEqual(pinned.data_ptr(), pinned.pin_memory().data_ptr())\n\n def test_error_msg_type_translation(self):\n with self.assertRaisesRegex(\n RuntimeError,\n # message includes both Double and Long\n '(?=.*Double)(?=.*Long)'):\n\n # Calls model with a LongTensor input but DoubleTensor weights\n input = torch.zeros(1, 1, 1, 6, dtype=torch.long)\n weight = torch.nn.Parameter(torch.zeros(1, 1, 1, 3, dtype=torch.double))\n model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False)\n model.weight = weight\n out = model(input)\n\n def test_apply(self):\n x = torch.arange(1, 6)\n res = x.clone().apply_(lambda k: k + k)\n self.assertEqual(res, x * 2)\n self.assertRaises(TypeError, lambda: x.apply_(lambda k: \"str\"))\n\n def test_map(self):\n x = torch.autograd.Variable(torch.randn(3, 3))\n y = torch.autograd.Variable(torch.randn(3))\n res = x.clone()\n res.map_(y, lambda a, b: a + b)\n self.assertEqual(res, x + y)\n self.assertRaisesRegex(TypeError, \"not callable\", lambda: res.map_(y, \"str\"))\n\n def test_map2(self):\n x = torch.autograd.Variable(torch.randn(3, 3))\n y = torch.autograd.Variable(torch.randn(3))\n z = torch.autograd.Variable(torch.randn(1, 3))\n res = x.clone()\n res.map2_(y, z, lambda a, b, c: a + b * c)\n self.assertEqual(res, x + y * z)\n z.requires_grad = True\n self.assertRaisesRegex(\n RuntimeError, \"requires grad\",\n lambda: res.map2_(y, z, lambda a, b, c: a + b * c))\n\n def test_Size(self):\n x = torch.Size([1, 2, 3])\n self.assertIsInstance(x, tuple)\n self.assertEqual(x[0], 1)\n self.assertEqual(x[1], 2)\n self.assertEqual(x[2], 3)\n self.assertEqual(len(x), 3)\n self.assertRaises(TypeError, lambda: torch.Size(torch.ones(3)))\n\n self.assertIsInstance(x * 2, torch.Size)\n self.assertIsInstance(x[:-1], torch.Size)\n self.assertIsInstance(x + x, torch.Size)\n\n def test_Size_scalar(self):\n three = torch.tensor(3)\n two = torch.tensor(2)\n x = torch.Size([0, 1, two, three, 4])\n for i in range(1, 5):\n self.assertEqual(x[i], i)\n\n def test_Size_iter(self):\n for sizes in [iter([1, 2, 3, 4, 5]), range(1, 6)]:\n x = torch.Size(sizes)\n for i in range(0, 5):\n self.assertEqual(x[i], i + 1)\n\n def test_t_not_2d_error(self):\n self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t())\n self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t_())\n\n # skip this test for now as it affects all tests\n @unittest.skipIf(True, \"flush_denormal not supported\")\n def test_set_flush_denormal(self):\n tiny_float = 1e-42\n tiny_double = 1e-320\n float_tensor = torch.FloatTensor([1.0, tiny_float])\n double_tensor = torch.DoubleTensor([1.0, tiny_float, tiny_double])\n\n self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0)\n self.assertEqual(float_tensor[1], tiny_float, atol=tiny_float / 16, rtol=0)\n self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0)\n self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0)\n self.assertEqual(double_tensor[2], tiny_double, atol=0.0, rtol=0)\n\n torch.set_flush_denormal(True)\n self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0)\n self.assertEqual(float_tensor[1], 0.0, atol=0.0, rtol=0) # tiny_float to zero\n self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0)\n # tiny_float is not converted to zero in double type\n self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0)\n self.assertEqual(double_tensor[2], 0.0, atol=0.0, rtol=0) # tiny_double to zero\n torch.set_flush_denormal(False)\n\n def test_show_config(self):\n # We can't usefully test the output; just make sure this doesn't crash\n torch.__config__.show()\n\n @unittest.skipIf(IS_FBCODE, \"CXX_FLAGS is only for OSS build.\")\n def test_cxx_flags(self):\n torch.__config__._cxx_flags()\n\n def test_parallel_info(self):\n torch.__config__.parallel_info()\n\n @slowTest\n def test_slow_test(self):\n # Just a smoketest to make sure our slowTest decorator works.\n pass\n\n def test_is_nonzero(self):\n with self.assertRaisesRegex(RuntimeError, \"Boolean value of Tensor with no values is ambiguous\"):\n torch.tensor([]).is_nonzero()\n with self.assertRaisesRegex(RuntimeError, \"Boolean value of Tensor with more than one value is ambiguous\"):\n torch.tensor([0, 0]).is_nonzero()\n self.assertFalse(torch.tensor(0).is_nonzero())\n self.assertTrue(torch.tensor(1).is_nonzero())\n self.assertFalse(torch.tensor([0]).is_nonzero())\n self.assertTrue(torch.tensor([1]).is_nonzero())\n self.assertFalse(torch.tensor([[0]]).is_nonzero())\n self.assertTrue(torch.tensor([[1]]).is_nonzero())\n self.assertTrue(torch.tensor(0.1).is_nonzero())\n self.assertTrue(torch.tensor(-0.1).is_nonzero())\n self.assertFalse(torch.tensor(0.0).is_nonzero())\n self.assertTrue(torch.tensor(True).is_nonzero())\n self.assertFalse(torch.tensor(False).is_nonzero())\n self.assertFalse(torch.tensor(0 + 0j).is_nonzero())\n self.assertTrue(torch.tensor(0 + 0.1j).is_nonzero())\n\n def test_assert_async(self):\n with self.assertRaisesRegex(RuntimeError, \"Boolean value of Tensor with no values is ambiguous\"):\n torch._assert_async(torch.tensor([]))\n with self.assertRaisesRegex(RuntimeError, \"Boolean value of Tensor with more than one value is ambiguous\"):\n torch._assert_async(torch.tensor([0, 0]))\n with self.assertRaisesRegex(RuntimeError, \"Expected Tensor with single nonzero value, but got zero\"):\n torch._assert_async(torch.tensor(0))\n torch._assert_async(torch.tensor(1))\n torch._assert_async(torch.tensor(0.1))\n torch._assert_async(torch.tensor(-0.1))\n with self.assertRaisesRegex(RuntimeError, \"Expected Tensor with single nonzero value, but got zero\"):\n torch._assert_async(torch.tensor(0.0))\n torch._assert_async(torch.tensor(True))\n with self.assertRaisesRegex(RuntimeError, \"Expected Tensor with single nonzero value, but got zero\"):\n torch._assert_async(torch.tensor(False))\n torch._assert_async(torch.tensor(0 + 0.1j))\n with self.assertRaisesRegex(RuntimeError, \"Expected Tensor with single nonzero value, but got zero\"):\n torch._assert_async(torch.tensor(0 + 0j))\n\n # NB: we must not be built with CUDA; if we are built with CUDA but no CUDA\n # is available, we get a different error.\n @unittest.skipIf(torch.backends.cuda.is_built() or IS_SANDCASTLE, \"CUDA is built, can't test CUDA not built error\")\n def test_cuda_not_built(self):\n msg = \"Torch not compiled with CUDA enabled\"\n self.assertRaisesRegex(AssertionError, msg, lambda: torch.cuda.current_device())\n self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1], device=\"cuda\"))\n self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).cuda())\n self.assertRaisesRegex(TypeError, msg, lambda: torch.cuda.FloatTensor())\n self.assertRaisesRegex(TypeError, msg, lambda: torch.set_default_tensor_type(torch.cuda.FloatTensor))\n self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).to(device=\"cuda\"))\n\n def test_has_internal_overlap(self):\n OVERLAP_NO = 0\n OVERLAP_YES = 1\n OVERLAP_TOO_HARD = 2\n\n # Check for contiguous tensors\n a = torch.randn(3, 3)\n self.assertEqual(torch._debug_has_internal_overlap(a), OVERLAP_NO)\n\n # Checks for zero strides\n b = torch.randn(1, 3)\n b_expanded = b.expand(4, 3)\n self.assertEqual(torch._debug_has_internal_overlap(b_expanded), OVERLAP_YES)\n\n # Check for zero strided, size 1 axis, in non-contiguous storage (gh-33812)\n c = torch.randn(10).as_strided([2, 1, 5], [1, 0, 2])\n self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_NO)\n c = torch.randn(2, 1, 10)[::2].as_strided((2, 1, 5), (10, 0, 2))\n self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_TOO_HARD)\n\n def test_allow_tensor_metadata_change(self):\n def do_test(t):\n with self.assertRaisesRegex(\n RuntimeError,\n \"set_sizes_contiguous is not allowed on a Tensor created from .data or .detach()\"):\n t.resize_((2, 1))\n with self.assertRaisesRegex(\n RuntimeError,\n \"set_storage is not allowed on a Tensor created from .data or .detach()\"):\n t.set_()\n with self.assertRaisesRegex(\n RuntimeError,\n \"set_storage_offset is not allowed on a Tensor created from .data or .detach()\"):\n t.set_(t.storage(), 0, t.size(), list(t.stride()))\n\n do_test(torch.tensor([[1, 2]]).data)\n do_test(torch.tensor([[1, 2]]).detach())\n\n @skipIfNotRegistered(\"LayerNorm\", \"Skipping as LayerNorm is not registered\")\n def test_c10_layer_norm(self):\n # test that we can call c10 ops and they return a reasonable result\n X = torch.rand(5, 5, dtype=torch.float)\n weight = torch.rand(*X.size()[1:], dtype=torch.float)\n bias = torch.rand(*X.size()[1:], dtype=torch.float)\n epsilon = 1e-4\n\n expected_norm = torch.nn.functional.layer_norm(\n X, X.size()[1:], weight=weight, bias=bias, eps=epsilon)\n actual_norm, actual_mean, actual_stdev = \\\n torch.ops._caffe2.LayerNorm(torch.tensor(X), torch.tensor(\n weight), torch.tensor(bias), 1, epsilon, True)\n torch.testing.assert_close(expected_norm, actual_norm)\n\n def test_memory_format(self):\n def test_helper(x, memory_format):\n y = x.contiguous(memory_format=memory_format)\n self.assertFalse(y.is_contiguous())\n self.assertTrue(y.is_contiguous(memory_format=memory_format))\n self.assertEqual(y, x)\n\n test_helper(torch.randn(4, 3, 8, 8), torch.channels_last)\n test_helper(torch.randn(4, 3, 8, 8, 8), torch.channels_last_3d)\n\n def test_memory_format_contiguous_returns_same_tensor_if_already_satisfies(self):\n def test_helper(x, memory_format):\n alias = x.contiguous(memory_format=memory_format)\n alias.fill_(7)\n self.assertEqual(x, alias)\n\n test_helper(torch.randn(4, 8, 8, 3).permute(0, 3, 1, 2), torch.channels_last)\n test_helper(torch.randn(4, 8, 8, 8, 3).permute(0, 4, 1, 2, 3), torch.channels_last_3d)\n\n def test_memory_format_empty(self):\n def test_helper(dim1, dim2, memory_format):\n with self.assertRaises(RuntimeError):\n x = torch.empty(dim1, memory_format=memory_format)\n x = torch.empty(dim2, memory_format=memory_format)\n self.assertTrue(x.is_contiguous(memory_format=memory_format))\n\n test_helper((3, 3), (3, 3, 3, 3), torch.channels_last)\n test_helper((3, 3, 3), (3, 3, 3, 3, 3), torch.channels_last_3d)\n\n def test_subclass_tensors(self):\n # raise an error when trying to subclass FloatTensor\n with self.assertRaisesRegex(TypeError, \"type 'torch.FloatTensor' is not an acceptable base type\"):\n class Foo1(torch.FloatTensor):\n pass\n\n # but allow subclassing Tensor:\n class Foo2(torch.Tensor):\n def foo(self):\n return 5\n f = Foo2()\n self.assertEqual(f.foo(), 5)\n\n def test_ndim(self):\n a = torch.randn(1, 2, 3)\n self.assertEqual(3, a.ndim)\n b = torch.randn(())\n self.assertEqual(0, b.ndim)\n c = torch.randn(1, 0)\n self.assertEqual(2, c.ndim)\n\n def test_fill_diagonal(self):\n a1 = torch.randn(7, 3)\n a2 = a1.clone()\n v = 1\n for i in range(3):\n a2[i][i] = v\n a1.fill_diagonal_(v)\n self.assertEqual(a1, a2)\n\n b1 = torch.randn(7, 3)\n b2 = b1.clone()\n for i in range(3):\n b2[i][i] = v\n b2[i + 4][i] = v\n b1.fill_diagonal_(v, wrap=True)\n self.assertEqual(b1, b2)\n\n c1 = torch.rand(3, 3, 3)\n c2 = c1.clone()\n for i in range(3):\n c2[i][i][i] = v\n c1.fill_diagonal_(v)\n self.assertEqual(c1, c2)\n\n # non-contiguous tensor\n d1 = torch.rand(3, 3, 3)[:, 1, ...]\n d2 = d1.clone()\n for i in range(3):\n d2[i][i] = v\n d1.fill_diagonal_(v)\n self.assertEqual(d1, d2)\n\n e1 = torch.rand(7, 3, 3)[:, 1, ...]\n e2 = e1.clone()\n for i in range(3):\n e2[i][i] = v\n e2[i + 4][i] = v\n e1.fill_diagonal_(v, wrap=True)\n self.assertEqual(e1, e2)\n\n def test_setting_real_imag_to_a_number(self):\n x = torch.randn(4, dtype=torch.cfloat)\n x.real = 0\n x.imag = 0\n zeros = torch.zeros(4)\n self.assertEqual(x.real, zeros)\n self.assertEqual(x.imag, zeros)\n\n def test_batch_norm_cpu_inference(self):\n # input nchw in (2,1,1,1), (2,2,2,2)\n inputs = [\n torch.tensor([[[[-0.5000]]], [[[0.5000]]]]),\n torch.tensor([\n [\n [[-0.5000, 0.5000], [-1.0000, 1.0000]],\n [[-0.2500, -0.5000], [0.2500, 0.5000]]\n ],\n [\n [[0.1000, 1.0000], [1.0000, 0.1000]],\n [[1.0000, 0.5000], [1.5000, -1.5000]]\n ]])]\n # output nchw in (2,1,1,1), (2,2,2,2)\n outputs = [\n torch.tensor([\n [[[-0.499997496604919433593750000]]],\n [[[0.499997496604919433593750000]]]]),\n torch.tensor([\n [[[-0.499997496604919433593750000, 0.499997496604919433593750000],\n [-0.999994993209838867187500000, 0.999994993209838867187500000]],\n [[-0.249998748302459716796875000, -0.499997496604919433593750000],\n [0.249998748302459716796875000, 0.499997496604919433593750000]]],\n [[[0.099999502301216125488281250, 0.999994993209838867187500000],\n [0.999994993209838867187500000, 0.099999502301216125488281250]],\n [[0.999994993209838867187500000, 0.499997496604919433593750000],\n [1.499992489814758300781250000, -1.499992489814758300781250000]]]])]\n\n\n for i in range(len(inputs)):\n for affine in [False, True]:\n m = torch.nn.BatchNorm2d(inputs[i].size()[1], 1e-05, 0.1, affine=affine)\n m.eval()\n # contiguous case\n input1 = inputs[i].contiguous()\n output1 = m(input1)\n # non-contiguous case\n input2 = input1.permute(0, 1, 3, 2)\n output2 = m(input2).permute(0, 1, 3, 2)\n # channels last case\n input3 = input1.contiguous(memory_format=torch.channels_last)\n output3 = m(input3)\n self.assertEqual(output3, outputs[i])\n self.assertEqual(output3, output1)\n self.assertEqual(output3, output2)\n\n # FIXME: move these meta tests to their own test suite/class or\n # distribute them among the appropriate test suites for their ops\n @noarchTest\n def test_empty_meta(self):\n x = torch.empty(2 ** 20, 2 ** 20, device='meta')\n y = torch.empty(2 ** 20, device='meta')\n z = x + y\n self.assertEqual(z.size(), (2 ** 20, 2 ** 20))\n self.assertRaises(RuntimeError, lambda: z[0][0].item())\n\n @noarchTest\n def test_format_scalar_meta(self):\n x = torch.empty((), device='meta')\n self.assertEqual(format(x), repr(x))\n\n @noarchTest\n def test_upsample_nearest1d_meta(self):\n # TODO: this test should be triggered by test_nn.py but right\n # now meta is not enabled (and even if it was, we are probably\n # missing too many meta functions to get through the test unmolested)\n\n # NB: Can't make the exponent too big, or it will overflow\n # signed 64-bit integer\n x = torch.empty(2 * 10 ** 8, 3, 2 * 10 ** 8, device='meta')\n z = torch.nn.functional.interpolate(x, scale_factor=2)\n self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8))\n self.assertRaises(RuntimeError, lambda: z[0][0][0].item())\n\n # TODO: the out tests cannot be triggered by test_nn.py because\n # we don't actually do out= arguments for nn functions, so there\n # is no public API by which to get the out version\n\n # interpolate doesn't seem to support out=\n # (not sure why passing None here doesn't work? How strange...)\n z = torch.empty(0, device='meta')\n torch._C._nn.upsample_nearest1d(x, (4 * 10 ** 8,), 2, out=z)\n self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8))\n self.assertRaises(RuntimeError, lambda: z[0][0][0].item())\n\n @noarchTest\n def test_upsample_nearest2d_meta(self):\n # TODO: the out tests cannot be triggered by test_nn.py because\n # we don't actually do out= arguments for nn functions, so there\n # is no public API by which to get the out version\n\n # Make sure we don't clobber strides of out tensor. NB: this\n # test must be done on 2d/3d, because 1d doesn't have any meaningful\n # layout support\n x = torch.empty(4, 3, 8, 8, device='meta')\n out = torch.empty(4, 3, 16, 16, device='meta', memory_format=torch.channels_last)\n torch._C._nn.upsample_nearest2d(x, (16, 16), out=out)\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n\n x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last)\n out = torch.empty(4, 3, 16, 16, device='meta')\n torch._C._nn.upsample_nearest2d(x, (16, 16), out=out)\n self.assertTrue(out.is_contiguous())\n\n # But if resize occurs, do clobber\n x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last)\n out = torch.empty(0, device='meta')\n torch._C._nn.upsample_nearest2d(x, (16, 16), out=out)\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n\n # Complain if out dtype mismatch\n x = torch.empty(4, 3, 8, 8, device='meta', dtype=torch.float)\n out = torch.empty(4, 3, 16, 16, device='meta', dtype=torch.double)\n self.assertExpectedRaisesInline(\n RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out),\n \"\"\"Expected out tensor to have dtype float, but got double instead\"\"\"\n )\n\n # Complain if out device mismatch\n x = torch.empty(0, 3, 8, 8, device='meta')\n out = torch.empty(0, 3, 16, 16, device='cpu')\n self.assertExpectedRaisesInline(\n RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out),\n \"\"\"Expected out tensor to have device meta, but got cpu instead\"\"\"\n )\n\n @noarchTest\n def test_detach_meta(self):\n x = torch.empty(2, device='meta')\n # This used to segfault\n self.assertRaises(RuntimeError, lambda: x.detach().storage())\n\n @noarchTest\n def test_add_meta_scalar(self):\n # From https://github.com/pytorch/pytorch/issues/53815\n x = torch.empty(2, device='meta')\n y = x + 2\n self.assertEqual(y.size(), x.size())\n\n def test_normal_shape(self):\n warned = False\n for device in get_all_device_types():\n tensor1 = torch.rand(1, device=device)\n tensor4 = torch.rand(4, device=device)\n tensor120 = torch.rand(120, device=device)\n tensor2145 = torch.rand(2, 1, 4, 5, device=device)\n tensor2345 = torch.rand(2, 3, 4, 5, device=device)\n tensor2345_non_contiguous = torch.rand(2, 4, 3, 5, device=device).permute(0, 2, 1, 3)\n tensor2345_channels_last = tensor2345.contiguous(memory_format=torch.channels_last)\n output2345 = torch.zeros(2, 3, 4, 5, device=device)\n output345 = torch.zeros(3, 4, 5, device=device)\n\n # inputs have same size\n self.assertEqual(torch.normal(tensor2345, tensor2345).size(), (2, 3, 4, 5))\n self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345).size(), (2, 3, 4, 5))\n self.assertEqual(torch.normal(tensor2345, tensor2345_channels_last).size(), (2, 3, 4, 5))\n self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345_channels_last).size(), (2, 3, 4, 5))\n\n # scalar case\n self.assertEqual(torch.normal(tensor2345, 2).size(), (2, 3, 4, 5))\n self.assertEqual(torch.normal(2, tensor2345).size(), (2, 3, 4, 5))\n\n # inputs are expandable tensors\n self.assertEqual(torch.normal(tensor2345, tensor1).size(), (2, 3, 4, 5))\n self.assertEqual(torch.normal(tensor2145, tensor2345).size(), (2, 3, 4, 5))\n\n # inputs are non-expandable tensors, but they have same number of elements\n with self.assertRaisesRegex(\n RuntimeError,\n r\"The size of tensor a \\(120\\) must match the size of \"\n r\"tensor b \\(5\\) at non-singleton dimension 3\"):\n self.assertEqual(torch.normal(tensor120, tensor2345).size(), (120,))\n with self.assertRaisesRegex(\n RuntimeError,\n r\"The size of tensor a \\(5\\) must match the size of \"\n r\"tensor b \\(120\\) at non-singleton dimension 3\"):\n self.assertEqual(torch.normal(tensor2345, tensor120).size(), (2, 3, 4, 5))\n\n # inputs are non-expandable tensors and they don't have same number of elements\n with self.assertRaisesRegex(\n RuntimeError,\n r\"The size of tensor a \\(5\\) must match the size of \"\n r\"tensor b \\(4\\) at non-singleton dimension 3\"):\n torch.normal(tensor2345, tensor4)\n\n # output and inputs are size compatible\n self.assertEqual(torch.normal(tensor2345, tensor2345, out=output2345).size(), (2, 3, 4, 5))\n\n # output and inputs are not size compatible\n with self.assertWarnsRegex(\n UserWarning,\n \"This behavior is deprecated, and in a future PyTorch \"\n \"release outputs will not be resized unless they have \"\n \"zero elements\"):\n self.assertEqual(torch.normal(tensor2345, tensor2145, out=output345).size(), (2, 3, 4, 5))\n with self.assertRaisesRegex(\n RuntimeError,\n r\"The size of tensor a \\(5\\) must match the size of \"\n r\"tensor b \\(120\\) at non-singleton dimension 3\"):\n # inputs are not expandable, output size is not the same as mean\n torch.normal(tensor2345, tensor120, out=output345)\n\n def test_tensoriterator_output_setup(self):\n # Test whether the output's memory layout is correct\n def test_memory_layout(x, y, scale, zero_point, out):\n self.assertEqual(x.dim(), 4)\n self.assertEqual(x.size(), y.size())\n self.assertEqual(y.size(), out.size())\n\n shape = x.size()\n for n in range(shape[0]):\n for c in range(shape[1]):\n for h in range(shape[2]):\n for w in range(shape[3]):\n if scale is not None and zero_point is not None:\n self.assertEqual(\n out[n][c][h][w],\n torch.ops.quantized.add(x[n][c][h][w], y[n][c][h][w], scale, zero_point))\n else:\n self.assertEqual(out[n][c][h][w], x[n][c][h][w] + y[n][c][h][w])\n\n xraw = torch.rand(2, 3, 4, 4)\n yraw = torch.rand(2, 3, 4, 4)\n qxraw = torch.quantize_per_tensor(xraw, 0.1, 5, torch.quint8)\n qyraw = torch.quantize_per_tensor(yraw, 0.1, 5, torch.quint8)\n\n # contiguous case fast setup\n test_memory_layout(xraw, yraw, None, None, xraw + yraw)\n test_memory_layout(qxraw, qyraw, 0.1, 5, torch.ops.quantized.add(qxraw, qyraw, 0.1, 5))\n\n # channels last case fast setup\n x = xraw.contiguous(memory_format=torch.channels_last)\n y = yraw.contiguous(memory_format=torch.channels_last)\n test_memory_layout(x, y, None, None, x + y)\n qx = qxraw.contiguous(memory_format=torch.channels_last)\n qy = qyraw.contiguous(memory_format=torch.channels_last)\n test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5))\n\n # non contiguous case fast setup (dense, non-overlapping, same shape and strides)\n x = xraw.permute(0, 2, 3, 1)\n y = yraw.permute(0, 2, 3, 1)\n test_memory_layout(x, y, None, None, x + y)\n qx = qxraw.permute(0, 2, 3, 1)\n qy = qyraw.permute(0, 2, 3, 1)\n test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5))\n\n # non contiguous case fast setup (dense, non-overlapping)\n # input tensors have same shape and strides\n # output tensor have same shape as input tensors but different stride\n # output tensor should preserve its strides in this case\n x = xraw.permute(0, 2, 3, 1)\n y = yraw.permute(0, 2, 3, 1)\n out = torch.empty_like(xraw)\n out = out.permute(0, 3, 2, 1)\n expected_stride = out.stride()\n test_memory_layout(x, y, None, None, torch.add(x, y, out=out))\n self.assertEqual(expected_stride, out.stride())\n\n # non contiguous case non fast setup\n x = xraw.permute(0, 2, 3, 1)\n y = yraw.permute(0, 3, 2, 1)\n test_memory_layout(x, y, None, None, x + y)\n qx = qxraw.permute(0, 2, 3, 1)\n qy = qyraw.permute(0, 3, 2, 1)\n test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5))\n\n # Tests to make sure we still handle .data properly until it is removed\n def test_dot_data_use(self):\n # .data allows to change the Tensors types inplace, check that we still\n # raise a nice error.\n with self.assertRaisesRegex(\n RuntimeError,\n # message includes both Double and Long\n '(?=.*Double)(?=.*Long)'):\n\n # Calls model with a LongTensor input but DoubleTensor weights\n input = torch.randn(1, 1, 1, 6, dtype=torch.double)\n weight = torch.zeros(1, 1, 1, 3, dtype=torch.long)\n model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False)\n model.weight.data = weight\n out = model(input)\n\n def test_empty_storage_view(self):\n # we should be able to \"modify\" slices of a 0-element\n # array without an error being raised due to\n # trying to resize its storage\n t = torch.from_numpy(np.empty((0, 4)))\n t[:, 1::2] *= 1\n\n def test_has_storage(self):\n self.assertIsNotNone(torch.tensor([]).storage())\n self.assertIsNotNone(torch.empty(0).storage())\n self.assertIsNotNone(torch.tensor([]).clone().storage())\n self.assertIsNotNone(torch.tensor([0, 0, 0]).nonzero().storage())\n self.assertIsNotNone(torch.tensor([]).new().storage())\n\n # FIXME: Extend this test and put in a TensorProperties test class\n def test_numel(self):\n b = torch.ByteTensor(3, 100, 100)\n self.assertEqual(b.nelement(), 3 * 100 * 100)\n self.assertEqual(b.numel(), 3 * 100 * 100)\n\n # Verifies that (deep)copies of dtypes are the same objects\n def test_copy_dtypes(self):\n for dtype in all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool):\n copied_dtype = copy.deepcopy(dtype)\n self.assertIs(dtype, copied_dtype)\n\n def test_dtype_is_signed(self):\n for dtype in all_types_and_complex_and(torch.half, torch.bfloat16, torch.half):\n self.assertEqual(dtype.is_signed, torch.is_signed(torch.tensor(0, dtype=dtype)))\n\n self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.quint8.is_signed)\n self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint8.is_signed)\n self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint32.is_signed)\n\n # FIXME: Put the following random tests into their own test class or test suite\n def test_RNGState(self):\n state = torch.get_rng_state()\n stateCloned = state.clone()\n before = torch.rand(1000)\n\n self.assertEqual(state.ne(stateCloned).long().sum(), 0, atol=0, rtol=0)\n\n torch.set_rng_state(state)\n after = torch.rand(1000)\n self.assertEqual(before, after, atol=0, rtol=0)\n\n def test_RNGStateAliasing(self):\n # Fork the random number stream at this point\n gen = torch.Generator()\n gen.set_state(torch.get_rng_state())\n self.assertEqual(gen.get_state(), torch.get_rng_state())\n\n target_value = torch.rand(1000)\n # Dramatically alter the internal state of the main generator\n _ = torch.rand(100000)\n forked_value = torch.rand(1000, generator=gen)\n self.assertEqual(target_value, forked_value, atol=0, rtol=0, msg=\"RNG has not forked correctly.\")\n\n def test_RNG_after_pickle(self):\n torch.random.manual_seed(100)\n before = torch.rand(10)\n\n torch.random.manual_seed(100)\n buf = io.BytesIO()\n tensor = torch.tensor([1, 2, 3])\n ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(tensor)\n after = torch.rand(10)\n\n self.assertEqual(before, after, atol=0, rtol=0)\n\n def test_boxMullerState(self):\n torch.manual_seed(123)\n odd_number = 101\n seeded = torch.randn(odd_number)\n state = torch.get_rng_state()\n midstream = torch.randn(odd_number)\n torch.set_rng_state(state)\n repeat_midstream = torch.randn(odd_number)\n torch.manual_seed(123)\n reseeded = torch.randn(odd_number)\n self.assertEqual(midstream, repeat_midstream, atol=0, rtol=0,\n msg='get_rng_state/set_rng_state not generating same sequence of normally distributed numbers')\n self.assertEqual(seeded, reseeded, atol=0, rtol=0,\n msg='repeated calls to manual_seed not generating same sequence of normally distributed numbers')\n\n def test_manual_seed(self):\n rng_state = torch.get_rng_state()\n torch.manual_seed(2)\n x = torch.randn(100)\n self.assertEqual(torch.initial_seed(), 2)\n torch.manual_seed(2)\n y = torch.randn(100)\n self.assertEqual(x, y)\n\n max_int64 = 0x7fff_ffff_ffff_ffff\n min_int64 = -max_int64 - 1\n max_uint64 = 0xffff_ffff_ffff_ffff\n # Check all boundary cases of valid seed value inputs\n test_cases = [\n # (seed, expected_initial_seed)\n # Positive seeds should be unchanged\n (max_int64, max_int64),\n (max_int64 + 1, max_int64 + 1),\n (max_uint64, max_uint64),\n (0, 0),\n # Negative seeds wrap around starting from the largest seed value\n (-1, max_uint64),\n (min_int64, max_int64 + 1)\n ]\n for seed, expected_initial_seed in test_cases:\n torch.manual_seed(seed)\n actual_initial_seed = torch.initial_seed()\n msg = \"expected initial_seed() = %x after calling manual_seed(%x), but got %x instead\" % (\n expected_initial_seed, seed, actual_initial_seed)\n self.assertEqual(expected_initial_seed, actual_initial_seed, msg=msg)\n for invalid_seed in [min_int64 - 1, max_uint64 + 1]:\n with self.assertRaisesRegex(RuntimeError, r'Overflow when unpacking long'):\n torch.manual_seed(invalid_seed)\n\n torch.set_rng_state(rng_state)\n\n # FIXME: Describe this test and port to the generic device framework in a more\n # appropriate test suite for the copy operation\n def test_copy_transpose(self):\n x = torch.arange(100 * 100, dtype=torch.float).reshape(100, 100).t()\n y = torch.empty(100, 100, dtype=torch.float)\n y.copy_(x)\n self.assertEqual(y[:, 0], range(100))\n self.assertEqual(y[:, 40], range(4000, 4100))\n\n y = torch.empty(100, 100, dtype=torch.double)\n y.copy_(x)\n self.assertEqual(y[:, 0], range(100))\n self.assertEqual(y[:, 40], range(4000, 4100))\n\n # Validates regression reported in https://github.com/pytorch/pytorch/issues/45269\n x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.cfloat).t()\n y = torch.empty(100, 100, dtype=torch.cfloat)\n y.copy_(x)\n self.assertEqual(y[:, 0], range(100))\n self.assertEqual(y[:, 40], range(4000, 4100))\n\n x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.complex32).t()\n y = torch.empty(100, 100, dtype=torch.complex32)\n y.copy_(x)\n self.assertEqual(y[:, 0], range(100))\n self.assertEqual(y[:, 40], range(4000, 4100))\n\n # FIXME: Port to a more appropriate test suite\n def test_copy_broadcast(self):\n torch.zeros(5, 6).copy_(torch.zeros(6))\n self.assertRaises(RuntimeError, lambda: torch.zeros(5, 6).copy_(torch.zeros(30)))\n\n # FIXME: Port to a more appropriate test suite\n def test_copy_many_to_one(self):\n # Testing in-place copy where it attempt to write from many memory\n # storage to a single storage would cause RuntimeError to be thrown\n self.assertRaises(RuntimeError, lambda: torch.zeros(1, 6).expand(5, 6).copy_(torch.zeros(5, 6)))\n\n # FIXME: Port to a more appropriate test suite\n def test_to(self):\n def test_copy_behavior(t, non_blocking=False):\n self.assertIs(t, t.to(t, non_blocking=non_blocking))\n self.assertIs(t, t.to(t.dtype, non_blocking=non_blocking))\n self.assertIs(t, t.to(torch.empty_like(t), non_blocking=non_blocking))\n self.assertIsNot(t, t.to(t, non_blocking=non_blocking, copy=True))\n self.assertIsNot(t, t.to(t.dtype, non_blocking=non_blocking, copy=True))\n self.assertIsNot(t, t.to(torch.empty_like(t), non_blocking=non_blocking, copy=True))\n\n devices = [t.device]\n if t.device.type == 'cuda':\n if t.device.index == -1:\n devices.append('cuda:{}'.format(torch.cuda.current_device()))\n elif t.device.index == torch.cuda.current_device():\n devices.append('cuda')\n for device in devices:\n self.assertIs(t, t.to(device, non_blocking=non_blocking))\n self.assertIs(t, t.to(device, t.dtype, non_blocking=non_blocking))\n self.assertIsNot(t, t.to(device, non_blocking=non_blocking, copy=True))\n self.assertIsNot(t, t.to(device, t.dtype, non_blocking=non_blocking, copy=True))\n\n a = torch.tensor(5)\n test_copy_behavior(a)\n self.assertEqual(a.device, a.to('cpu').device)\n self.assertEqual(a.device, a.to('cpu', dtype=torch.float32).device)\n self.assertIs(torch.float32, a.to('cpu', dtype=torch.float32).dtype)\n self.assertEqual(a.device, a.to(torch.float32).device)\n self.assertIs(torch.float32, a.to(dtype=torch.float32).dtype)\n self.assertEqual(a.data_ptr(), a.to('cpu').data_ptr())\n self.assertEqual(a.data_ptr(), a.to(dtype=a.dtype, device=a.device, copy=False).data_ptr())\n self.assertEqual(a.data_ptr(), a.to('cpu', copy=False).data_ptr())\n self.assertNotEqual(a.data_ptr(), a.to('cpu', copy=True).data_ptr())\n\n if torch.cuda.is_available():\n for non_blocking in [True, False]:\n for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:\n b = torch.tensor(5., device=cuda)\n test_copy_behavior(b, non_blocking)\n self.assertEqual(b.device, b.to(cuda, non_blocking=non_blocking).device)\n self.assertEqual(a.device, b.to('cpu', non_blocking=non_blocking).device)\n self.assertEqual(b.device, a.to(cuda, non_blocking=non_blocking).device)\n self.assertIs(torch.int32, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).dtype)\n self.assertEqual(a.device, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).device)\n self.assertIs(torch.int32, b.to(dtype=torch.int32).dtype)\n self.assertEqual(b.device, b.to(dtype=torch.int32).device)\n\n # FIXME: describe this test\n def test_as_subclass(self):\n class SubTensor(torch.Tensor):\n member_var = object()\n\n t0 = torch.tensor(0)\n t1 = torch.tensor([1, 2])\n t2 = torch.tensor([[3, 4], [5, 6]])\n\n s0 = t0.as_subclass(SubTensor)\n s1 = t1.as_subclass(SubTensor)\n s2 = t2.as_subclass(SubTensor)\n\n # Check that the correct type is returned.\n self.assertTrue(type(s0) is SubTensor)\n self.assertTrue(type(s1) is SubTensor)\n self.assertTrue(type(s2) is SubTensor)\n\n # Check that the data is equal.\n self.assertEqual(t0, s0)\n self.assertEqual(t1, s1)\n self.assertEqual(t2, s2)\n\n t0[()] = 1\n t1[1] = 3\n t2[1, 1] = 7\n\n # Check that the data is equal even after modification.\n self.assertEqual(t0, s0)\n self.assertEqual(t1, s1)\n self.assertEqual(t2, s2)\n\n # Check that member variables are passed through.\n self.assertTrue(s0.member_var is SubTensor.member_var)\n self.assertTrue(s1.member_var is SubTensor.member_var)\n self.assertTrue(s2.member_var is SubTensor.member_var)\n\n # Test that autograd is propagated.\n t = torch.tensor(5, dtype=torch.float32, requires_grad=True)\n\n # Run a calculation on the tensor.\n exp_t = torch.exp(t)\n\n # Cast exp_t to a subclass.\n exp_s = exp_t.as_subclass(SubTensor)\n\n # Make sure that t.grad was initially None\n self.assertTrue(t.grad is None)\n\n # Run the autograd calculation.\n exp_s.backward()\n\n # Make sure autograd was propagated to the original tensor\n # declared with requires_grad.\n self.assertTrue(t.grad is not None)\n\n # Make sure invalid subclasses raise nice errors\n class BadSubTensor():\n member_var = object()\n\n err_msg = \"Creating a Tensor subclass from a class that does not inherit from Tensor\"\n with self.assertRaisesRegex(RuntimeError, err_msg):\n s0 = t0.as_subclass(BadSubTensor)\n\n # FIXME: Port to a test suite that better fits slicing\n def test_slice(self):\n empty = torch.empty(0, 4)\n x = torch.arange(0., 16).view(4, 4)\n self.assertEqual(x[:], x)\n self.assertEqual(x[:4], x)\n # start and stop are clamped to the size of dim\n self.assertEqual(x[:5], x)\n # if start >= stop then the result is empty\n self.assertEqual(x[2:1], empty)\n self.assertEqual(x[2:2], empty)\n # out of bounds is also empty\n self.assertEqual(x[10:12], empty)\n # additional correctness checks\n self.assertEqual(x[:1].tolist(), [[0, 1, 2, 3]])\n self.assertEqual(x[:-3].tolist(), [[0, 1, 2, 3]])\n self.assertEqual(x[:, -2:3].tolist(), [[2], [6], [10], [14]])\n self.assertEqual(x[0:-1:2].tolist(), [[0, 1, 2, 3], [8, 9, 10, 11]])\n\n def test_type(self):\n x = torch.randn(3, 3).double()\n self.assertEqual(x.type('torch.FloatTensor').dtype, torch.float32)\n self.assertEqual(x.type(torch.FloatTensor).dtype, torch.float32)\n self.assertEqual(x.int().type(torch.Tensor).dtype, torch.get_default_dtype())\n self.assertEqual(x.type(torch.int32).dtype, torch.int32)\n\n # FIXME: port to a quantization test suite\n def test_qengine(self):\n qengines = torch.backends.quantized.supported_engines\n original_qe = torch.backends.quantized.engine\n for qe in qengines:\n torch.backends.quantized.engine = qe\n assert torch.backends.quantized.engine == qe, 'qengine not set successfully'\n torch.backends.quantized.engine = original_qe\n\n # FIXME: port to a distributed test suite -- also... how could this be OOMing on Windows CUDA?\n @slowTest\n @unittest.skipIf(NO_MULTIPROCESSING_SPAWN, \"Disabled for environments that \\\n don't support multiprocessing with spawn start method\")\n @unittest.skipIf(IS_WINDOWS, 'FIXME: CUDA OOM error on Windows')\n def test_multinomial_invalid_probs(self):\n def _spawn_method(self, method, arg):\n try:\n mp.set_start_method('spawn')\n except RuntimeError:\n pass\n with mp.Pool(1) as pool:\n out: list = pool.map(method, [arg])\n self.assertTrue(out[0])\n\n def _test_multinomial_invalid_probs(probs):\n try:\n # n_sample = 1 is a special case, test n_sample=2 which is more general\n torch.multinomial(probs.to('cpu'), 2)\n return False # Should not be reached\n except RuntimeError as e:\n return 'probability tensor contains either `inf`, `nan` or element < 0' in str(e)\n\n _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., -1., 1.]))\n _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., inf, 1.]))\n _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., -inf, 1.]))\n _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., 1., nan]))\n\n # FIXME: port to more appropriate test suite\n def test_to_with_tensor(self):\n a = torch.tensor(5)\n self.assertEqual(a.device, a.to(a).device)\n\n if torch.cuda.is_available():\n for non_blocking in [True, False]:\n for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:\n b = torch.tensor(5., device=cuda)\n self.assertEqual(b.device, b.to(b, non_blocking=non_blocking).device)\n self.assertEqual(a.device, b.to(a, non_blocking=non_blocking).device)\n self.assertEqual(b.device, a.to(b, non_blocking=non_blocking).device)\n\n def test_device(self):\n cpu = torch.device('cpu')\n self.assertEqual('cpu', str(cpu))\n self.assertEqual('cpu', cpu.type)\n self.assertEqual(None, cpu.index)\n\n cpu0 = torch.device('cpu:0')\n self.assertEqual('cpu:0', str(cpu0))\n self.assertEqual('cpu', cpu0.type)\n self.assertEqual(0, cpu0.index)\n\n cpu0 = torch.device('cpu', 0)\n self.assertEqual('cpu:0', str(cpu0))\n self.assertEqual('cpu', cpu0.type)\n self.assertEqual(0, cpu0.index)\n\n cuda = torch.device('cuda')\n self.assertEqual('cuda', str(cuda))\n self.assertEqual('cuda', cuda.type)\n self.assertEqual(None, cuda.index)\n\n cuda1 = torch.device('cuda:1')\n self.assertEqual('cuda:1', str(cuda1))\n self.assertEqual('cuda', cuda1.type)\n self.assertEqual(1, cuda1.index)\n\n cuda1 = torch.device('cuda', 1)\n self.assertEqual('cuda:1', str(cuda1))\n self.assertEqual('cuda', cuda1.type)\n self.assertEqual(1, cuda1.index)\n\n cuda90 = torch.device('cuda', 90)\n self.assertEqual('cuda:90', str(cuda90))\n self.assertEqual('cuda', cuda90.type)\n self.assertEqual(90, cuda90.index)\n\n self.assertRaises(RuntimeError, lambda: torch.device('cpu:-1'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:-1'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 '))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda: 2'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 2'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2?'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:?2'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.232'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 cuda:3'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2+cuda:3'))\n self.assertRaises(RuntimeError, lambda: torch.device('cuda:2cuda:3'))\n self.assertRaises(RuntimeError, lambda: torch.device(-1))\n\n self.assertRaises(RuntimeError, lambda: torch.device('other'))\n self.assertRaises(RuntimeError, lambda: torch.device('other:0'))\n\n device_set = {'cpu', 'cpu:0', 'cuda', 'cuda:0', 'cuda:1', 'cuda:10', 'cuda:100'}\n device_hash_set = set()\n for device in list(device_set):\n device_hash_set.add(hash(torch.device(device)))\n self.assertEqual(len(device_set), len(device_hash_set))\n\n def get_expected_device_repr(device):\n if device.index is not None:\n return \"device(type='{type}', index={index})\".format(\n type=device.type, index=device.index)\n\n return \"device(type='{type}')\".format(type=device.type)\n\n for device in device_set:\n dev = torch.device(device)\n self.assertEqual(repr(dev), get_expected_device_repr(dev))\n\n # Tests that the use_deterministic_flag can be set as expected\n @wrapDeterministicFlagAPITest\n def test_deterministic_flag(self):\n for deterministic, warn_only in product([True, False], [True, False]):\n torch.use_deterministic_algorithms(deterministic, warn_only=warn_only)\n self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled())\n self.assertEqual(warn_only, torch.is_deterministic_algorithms_warn_only_enabled())\n\n if deterministic:\n if warn_only:\n debug_mode = 1\n else:\n debug_mode = 2\n else:\n debug_mode = 0\n\n self.assertEqual(debug_mode, torch.get_deterministic_debug_mode())\n\n for debug_mode in [0, 1, 2]:\n torch.set_deterministic_debug_mode(debug_mode)\n self.assertEqual(debug_mode, torch.get_deterministic_debug_mode())\n deterministic = debug_mode in [1, 2]\n warn_only = debug_mode == 1\n\n self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled())\n self.assertEqual(warn_only, torch.is_deterministic_algorithms_warn_only_enabled())\n\n for debug_mode, debug_mode_str in [(0, 'default'), (1, 'warn'), (2, 'error')]:\n torch.set_deterministic_debug_mode(debug_mode_str)\n self.assertEqual(debug_mode, torch.get_deterministic_debug_mode())\n\n with self.assertRaisesRegex(\n TypeError,\n r\"_set_deterministic_algorithms\\(\\): argument 'mode' \\(position 1\\) must be bool, not int\"):\n torch.use_deterministic_algorithms(1)\n\n with self.assertRaisesRegex(\n TypeError,\n r\"_set_deterministic_algorithms\\(\\): argument 'warn_only' must be bool, not int\"):\n torch.use_deterministic_algorithms(False, warn_only=1)\n\n def test_type_conversion_via_dtype_name(self):\n x = torch.tensor([1])\n self.assertEqual(x.byte().dtype, torch.uint8)\n self.assertEqual(x.bool().dtype, torch.bool)\n self.assertEqual(x.char().dtype, torch.int8)\n self.assertEqual(x.double().dtype, torch.float64)\n self.assertEqual(x.float().dtype, torch.float32)\n self.assertEqual(x.half().dtype, torch.float16)\n self.assertEqual(x.int().dtype, torch.int32)\n self.assertEqual(x.bfloat16().dtype, torch.bfloat16)\n cfloat = x.cfloat()\n self.assertEqual(cfloat.dtype, torch.complex64)\n self.assertEqual(cfloat.real, x.float())\n self.assertEqual(cfloat.imag, torch.zeros_like(cfloat.imag))\n cdouble = x.cdouble()\n self.assertEqual(cdouble.dtype, torch.complex128)\n self.assertEqual(cdouble.real, x.double())\n self.assertEqual(cdouble.imag, torch.zeros_like(cdouble.imag))\n\n # FIXME: Describe this test\n def test_doc_template(self) -> None:\n from torch._torch_docs import __file__ as doc_file\n from torch._torch_docs import multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args\n\n with open(doc_file, \"r\", encoding=\"utf-8\") as f:\n doc_strs = f.read()\n\n for doc_str in re.findall(r'add_docstr\\((.*?),.*?(\"\"\"|\\'\\'\\')(.*?)(\"\"\"|\\'\\'\\')\\)', doc_strs, re.MULTILINE | re.DOTALL):\n for common_args in [multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args]:\n for k, v in common_args.items():\n self.assertNotIn(v, doc_str[2], 'The argument description \"{}\" in {} can be '\n 'replaced by {{{}}}'.format(v, doc_str[0], k))\n\n def test_doc(self):\n checked_types = (types.MethodType, types.FunctionType,\n types.BuiltinFunctionType, types.BuiltinMethodType)\n\n def _test_namespace(ns, *skips):\n if isinstance(ns, object):\n ns_name = ns.__class__.__name__\n else:\n ns_name = ns.__name__\n skip_regexes = []\n for r in skips:\n if isinstance(r, string_classes):\n skip_regexes.append(re.compile('^{}$'.format(re.escape(r))))\n else:\n skip_regexes.append(r)\n\n for name in dir(ns):\n if name.startswith('_'):\n continue\n if name in ['real', 'imag']:\n y = torch.randn(1, dtype=torch.cfloat)\n var = getattr(y, name)\n elif name in [\"H\", \"mT\", \"mH\"]:\n y = torch.randn(1, 1)\n var = getattr(y, name)\n else:\n var = getattr(ns, name)\n if not isinstance(var, checked_types):\n continue\n doc = var.__doc__\n has_doc = doc is not None and len(doc.strip()) > 0\n full_name = ns_name + '.' + name\n if any(r.match(name) for r in skip_regexes):\n self.assertFalse(has_doc,\n 'New docs have been added for {}, please remove '\n 'it from the skipped list in TestTorch.test_doc'.format(full_name))\n else:\n self.assertTrue(has_doc, '{} is missing documentation'.format(full_name))\n\n # FIXME: All of the following should be marked as expected failures\n # so that it is easier to tell when missing has been added.\n # FIXME: fix all the skipped ones below!\n test_namespace(torch.randn(1),\n 'as_strided_',\n re.compile('^clamp_(min|max)_?$'),\n 'is_distributed',\n 'is_nonzero',\n 'is_same_size',\n 'log_softmax',\n 'map2_',\n 'new',\n 'reinforce',\n 'relu',\n 'relu_',\n 'prelu',\n 'resize',\n 'resize_as',\n 'softmax',\n 'split_with_sizes',\n 'unsafe_split_with_sizes',\n '_autocast_to_fp16',\n '_autocast_to_fp32',\n )\n\n test_namespace(torch.nn)\n test_namespace(torch.nn.functional, 'assert_int_or_pair')\n # TODO: add torch.* tests when we have proper namespacing on ATen functions\n # test_namespace(torch)\n\n # FIXME: deprecate torch.Tensor constructor\n def test_tensor_ctor_scalar(self):\n x = torch.Tensor(torch.tensor(1.0))\n self.assertEqual(x, torch.tensor(1.0))\n\n def test_deepcopy_gradient(self):\n from copy import deepcopy\n a = torch.zeros(10)\n a.grad = torch.ones(10)\n self.assertEqual(a.grad, deepcopy(a).grad)\n s = torch.zeros(10).to_sparse()\n s.grad = torch.ones(10).to_sparse()\n self.assertEqual(s.grad, deepcopy(s).grad)\n\n # ensure sharing is not broken\n c = deepcopy([a, a.grad])\n self.assertTrue(c[0].grad is c[1])\n\n def test_tensor_base_init(self):\n # Direct construction not OK\n self.assertRaises(RuntimeError, lambda: torch._C._TensorBase())\n\n # But construction of subclass is OK\n class T(torch._C._TensorBase):\n pass\n\n T()\n\n def test_tensor_base_new(self):\n\n # OK to call super().__new__, see\n # https://github.com/pytorch/pytorch/issues/57421\n class TestTensor(torch._C._TensorBase):\n @staticmethod\n def __new__(cls, x, *args, **kwargs):\n return super().__new__(cls, x, *args, **kwargs)\n\n x = torch.ones(5)\n test_tensor = TestTensor(x)\n\n def test_pyobj_preserved(self):\n x = torch.empty(2)\n x.foo = 2 # put something on __dict__\n y = torch.empty(2)\n y.grad = x\n del x # x is dead in Python\n self.assertEqual(y.grad.foo, 2)\n z = y.grad # it's live\n del z # it's dead again\n self.assertEqual(y.grad.foo, 2)\n\n def test_subclass_preserved(self):\n class MyTensor(torch.Tensor):\n pass\n\n x = MyTensor(torch.empty(2))\n y = torch.empty(2)\n y.grad = x\n del x # x is dead in Python\n self.assertEqual(type(y.grad), MyTensor)\n z = y.grad # it's live\n del z # it's dead again\n self.assertEqual(type(y.grad), MyTensor)\n\n def test_tensor_slot_dealloc(self):\n\n class SlotTensor1(torch._C._TensorBase):\n __slots__ = ['slot1']\n\n class SlotTensor2(SlotTensor1):\n __slots__ = ['slot2']\n\n m1, t1 = Tracker.make()\n m2, t2 = Tracker.make()\n slot_tensor = SlotTensor2(torch.empty(2))\n slot_tensor.slot1 = t1\n slot_tensor.slot2 = t2\n del t1\n del t2\n self.assertFalse(m1[0])\n self.assertFalse(m2[0])\n del slot_tensor\n self.assertTrue(m1[0])\n self.assertTrue(m2[0])\n\n def test_tensor_dict_dealloc(self):\n m, t = Tracker.make()\n x = torch.empty(2)\n x.arf = t\n del t\n self.assertFalse(m[0])\n del x\n self.assertTrue(m[0])\n\n def test_tensor_finalizer_dealloc(self):\n m = [False]\n\n class FinalizerTensor(torch._C._TensorBase):\n def __del__(self):\n m[0] = True\n\n fin_tensor = FinalizerTensor(torch.empty(2))\n self.assertFalse(m[0])\n del fin_tensor\n self.assertTrue(m[0])\n\n def test_tensor_weakref_dealloc(self):\n\n x = torch.empty(2)\n m = [False]\n\n def cb(r):\n m[0] = True\n\n wref = weakref.ref(x, cb)\n del x\n self.assertTrue(m[0])\n self.assertEqual(wref(), None)\n\n def test_tensor_cycle_via_dict(self):\n m1, t1 = Tracker.make()\n x = torch.empty(2)\n x._tracker = t1\n del t1\n\n m2, t2 = Tracker.make()\n y = torch.empty(2)\n y._tracker = t2\n del t2\n\n x._loop = y\n y._loop = x\n\n # C++ reference should keep the cycle live!\n # This exercise THPVariable_subtype_traverse\n # NB: Because z.grad is a reference done entirely in C++, cycles\n # involving it directly are NOT broken by Python GC; you've\n # set up a good old C++ reference cycle which we cannot safely\n # break (because C++ references are allowed to be accessed\n # multithreaded-ly) (TODO: except maybe if you can prove that\n # only Python has access to the C++ object, in which case you can\n # also prove that no multithreaded access occurs)\n z = torch.empty(2)\n z.grad = x\n\n del x\n del y\n\n gc.collect()\n self.assertFalse(m1[0])\n self.assertFalse(m2[0])\n\n with disable_gc():\n del z\n self.assertFalse(m1[0])\n self.assertFalse(m2[0])\n\n gc.collect()\n self.assertTrue(m1[0])\n self.assertTrue(m2[0])\n\n def test_tensor_cycle_via_slots(self):\n m1 = [False]\n m2 = [False]\n\n class SlotTensor1(torch._C._TensorBase):\n __slots__ = ['slot1']\n\n def __del__(self):\n m1[0] = True\n\n class SlotTensor2(SlotTensor1):\n __slots__ = ['slot2']\n\n def __del__(self):\n m2[0] = True\n\n x = SlotTensor1(torch.empty(2))\n y = SlotTensor2(torch.empty(2))\n\n x.slot1 = y\n y.slot2 = x\n\n del x\n with disable_gc():\n del y\n self.assertFalse(m1[0])\n self.assertFalse(m2[0])\n\n gc.collect()\n self.assertTrue(m1[0])\n self.assertTrue(m2[0])\n\n # FIXME: move to test_autograd?\n def test_backward_hooks_traverse(self):\n m1, t1 = Tracker.make()\n m2, t2 = Tracker.make()\n x = torch.empty(2, requires_grad=True)\n x._tracker = t1\n y = torch.empty(2, requires_grad=True)\n y._tracker = t2\n del t1\n del t2\n\n # this hits a special setter, it's not just a __dict__ entry\n x._backward_hooks = y\n y._backward_hooks = x\n\n del x\n with disable_gc():\n del y\n self.assertFalse(m1[0])\n self.assertFalse(m2[0])\n\n gc.collect()\n\n self.assertTrue(m1[0])\n self.assertTrue(m2[0])\n\n def test_dead_weak_ref(self):\n x = torch.empty(2)\n w_x = weakref.ref(x)\n y = torch.empty(2)\n y.grad = x\n del x\n\n x = w_x()\n # Ideally, x would keep the tensor live. But CPython doesn't\n # provide enough hooks to do this. So it will go dead and x\n # will transmute into an undefined tensor. Not great, but the\n # best we can do.\n del y\n\n self.assertRaises(RuntimeError, lambda: x.sigmoid())\n\n def test_resurrected_weak_ref(self):\n x = torch.empty(2)\n w_x = weakref.ref(x)\n y = torch.empty(2)\n y.grad = x\n del x\n\n x = w_x()\n # Use this to manually fix weak references after dereferencing them\n x._fix_weakref()\n del y\n x.sigmoid()\n\n # FIXME: move to test_linalg\n @torch.inference_mode()\n def test_bmm_multithreaded(self):\n device = 'cpu'\n num_threads = torch.get_num_threads()\n\n torch.set_num_threads(4)\n batch_sizes = [1, 10]\n M, N, O = 23, 8, 12\n dtype = torch.float32\n numpy_dtype = dtype\n\n def invert_perm(p):\n d = {x: i for i, x in enumerate(p)}\n return (d[0], d[1], d[2])\n\n def generate_inputs(num_batches):\n # transposed tensors\n for perm1, perm2 in itertools.product(itertools.permutations((0, 1, 2)), repeat=2):\n b1 = make_tensor((num_batches, M, N), dtype=dtype, device=device, low=-1, high=1)\n b2 = make_tensor((num_batches, N, O), dtype=dtype, device=device, low=-1, high=1)\n b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1))\n b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2))\n yield b1, b2\n # broadcasting tensors\n for b1, b2, b3, b4, b5, b6 in itertools.product((True, False), repeat=6):\n shape1 = (num_batches if b1 else 1, M if b2 else 1, N if b3 else 1)\n shape2 = (num_batches if b4 else 1, N if b5 else 1, O if b6 else 1)\n b1 = make_tensor(shape1, dtype=dtype, device=device, low=-1, high=1).expand(num_batches, M, N)\n b2 = make_tensor(shape2, dtype=dtype, device=device, low=-1, high=1).expand(num_batches, N, O)\n yield b1, b2\n # zero-sized tensors\n for z1, z2, z3, z4 in itertools.product((True, False), repeat=4):\n shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0)\n shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0)\n b1 = torch.randn(shape1, dtype=dtype, device=device)\n b2 = torch.randn(shape2, dtype=dtype, device=device)\n yield b1, b2\n\n try:\n for num_batches in batch_sizes:\n for (b1, b2), perm3 in itertools.product(generate_inputs(num_batches), itertools.permutations((0, 1, 2))):\n res1 = torch.bmm(b1, b2)\n res2 = torch.full((num_batches, M, O), math.nan, dtype=dtype, device=device) \\\n .permute(perm3).contiguous().permute(invert_perm(perm3))\n torch.bmm(b1, b2, out=res2)\n expect = torch.from_numpy(\n b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype)\n self.assertEqual(expect, res1)\n self.assertEqual(expect, res2)\n finally:\n torch.set_num_threads(num_threads)\n\n def test_conj_neg_tolist(self):\n x = torch.randn(2, dtype=torch.cfloat)\n y1 = x.conj()\n y1_expect = x.conj_physical()\n y2 = y1.imag\n self.assertEqual(y1, y1_expect.tolist())\n self.assertEqual(y2, y1_expect.imag.tolist())\n\n# The following block extends TestTorch with negative dim wrapping tests\n# FIXME: replace these with OpInfo sample inputs or systemic OpInfo tests\n# Functions to test negative dimension wrapping\nMETHOD = 1\nINPLACE_METHOD = 2\nFUNCTIONAL = 4\nDIM_ARG = None\n\ndef make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim=0):\n def neg_dim_test(self):\n if isinstance(tensor_arg, list):\n assert METHOD not in types and INPLACE_METHOD not in types\n x = [torch.randn(arg) for arg in tensor_arg]\n ndim = len(tensor_arg[-1])\n else:\n x = torch.randn(*tensor_arg)\n ndim = len(tensor_arg)\n ndim += extra_dim\n\n n_dim_to_test = sum(e is DIM_ARG for e in arg_constr())\n\n for dims_val in combinations(range(ndim), n_dim_to_test):\n arg = arg_constr()\n arg_neg = copy.deepcopy(arg)\n idx = 0\n for i, v in enumerate(arg):\n if v is DIM_ARG:\n arg[i] = dims_val[idx]\n arg_neg[i] = dims_val[idx] - ndim\n idx += 1\n\n if METHOD in types:\n a = getattr(x, name)(*arg)\n b = getattr(x, name)(*arg_neg)\n self.assertEqual(a, b)\n\n if INPLACE_METHOD in types:\n a = x.clone()\n getattr(a, name + '_')(*arg)\n b = x.clone()\n getattr(b, name + '_')(*arg_neg)\n self.assertEqual(a, b)\n\n if FUNCTIONAL in types:\n a = getattr(torch, name)(x, *arg)\n b = getattr(torch, name)(x, *arg_neg)\n self.assertEqual(a, b)\n\n return neg_dim_test\n\ndef idx_tensor(size, max_val):\n return torch.LongTensor(*size).random_(0, max_val - 1)\n\ndef add_neg_dim_tests():\n neg_dim_tests = [\n ('narrow', (10, 20, 30), lambda: [DIM_ARG, 0, 5], [METHOD]),\n ('transpose', (10, 20, 30), lambda: [DIM_ARG, DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]),\n ('size', (10, 20, 30), lambda: [DIM_ARG], [METHOD]),\n ('cat', [(2, 3, 4), (2, 3, 4)], lambda: [DIM_ARG], [FUNCTIONAL]),\n ('chunk', (10, 20, 30), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]),\n ('gather', (10, 20), lambda: [DIM_ARG, idx_tensor((10, 20), 10)], [METHOD, FUNCTIONAL]),\n ('index_select', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10)], [METHOD, FUNCTIONAL]),\n ('split', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]),\n ('squeeze', (10, 1, 20, 1), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]),\n ('unbind', (2, 3, 4), lambda: [DIM_ARG], [FUNCTIONAL]),\n ('unsqueeze', (10, 20), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL], 1),\n ('logcumsumexp', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('cumprod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('cumsum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('cummax', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('cummin', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('mean', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('median', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('nanmedian', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('mode', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('norm', (10, 20), lambda: [2, DIM_ARG], [METHOD, FUNCTIONAL]),\n ('prod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('std', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('sum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('var', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('kthvalue', (10, 20), lambda: [3, DIM_ARG], [METHOD, FUNCTIONAL]),\n ('max', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('min', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('sort', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]),\n ('topk', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]),\n ('renorm', (10, 20), lambda: [2, DIM_ARG, 1], [METHOD, INPLACE_METHOD, FUNCTIONAL]),\n ('index_add', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]),\n ('index_copy', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]),\n ('index_fill', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), 12], [INPLACE_METHOD]),\n ('scatter', (10, 10), lambda: [DIM_ARG, idx_tensor((10, 10), 10), torch.randn(10, 10)], [INPLACE_METHOD]),\n ('select', (10, 20), lambda: [DIM_ARG, 3], [METHOD]),\n ('unfold', (10, 20), lambda: [DIM_ARG, 5, 2], [METHOD]),\n ]\n\n for decl in neg_dim_tests:\n if len(decl) == 4:\n name, tensor_arg, arg_constr, types = decl\n extra_dim = 0\n elif len(decl) == 5:\n name, tensor_arg, arg_constr, types, extra_dim = decl\n\n test_name = 'test_' + name + '_neg_dim'\n\n assert not hasattr(TestTorch, test_name), \"Duplicated test name: \" + test_name\n setattr(TestTorch, test_name, make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim))\n\n# TODO: these empy classes are temporarily instantiated for XLA compatibility\n# once XLA updates their test suite it should be removed\nclass TestViewOps(TestCase):\n pass\n\nclass TestTensorDeviceOps(TestCase):\n pass\n\n# Generates tests\n# Note: test generation must be done at file scope, not within main, or\n# pytest will fail.\nadd_neg_dim_tests()\ninstantiate_device_type_tests(TestViewOps, globals())\ninstantiate_device_type_tests(TestVitalSignsCuda, globals())\ninstantiate_device_type_tests(TestTensorDeviceOps, globals())\ninstantiate_device_type_tests(TestTorchDeviceType, globals())\ninstantiate_device_type_tests(TestDevicePrecision, globals(), except_for='cpu')\n\nif __name__ == '__main__':\n run_tests()\n"
] | [
[
"torch.all",
"torch.set_default_tensor_type",
"torch.fmod",
"torch.BoolTensor",
"torch.randint",
"torch.max",
"torch.zeros",
"torch.set_vital",
"torch.multinomial",
"torch.cumprod",
"torch.IntStorage",
"torch.device",
"torch.__config__._cxx_flags",
"torch.get_num_threads",
"torch.conj",
"torch.put",
"torch.cuda.stream",
"torch.isclose",
"torch.testing._internal.common_utils.skipIfNotRegistered",
"torch._C._TensorBase",
"torch.Generator",
"torch.multiprocessing.set_start_method",
"torch.cuda.amp.grad_scaler._refresh_per_optimizer_state",
"torch.randn",
"torch.median",
"torch.equal",
"torch.storage._LegacyStorage",
"torch.quantize_per_tensor",
"numpy.diff",
"torch.testing._internal.common_device_type.get_all_device_types",
"torch.bmm",
"torch.masked_select",
"torch.ones_like",
"torch.kthvalue",
"torch.squeeze",
"torch.normal",
"torch.empty_like",
"torch.full",
"torch.cuda.current_device",
"torch.cudnn_is_acceptable",
"torch.nn.ReplicationPad1d",
"torch.min",
"torch.nn.Conv2d",
"torch.nn.ReflectionPad3d",
"torch.nn.Linear",
"torch.exp",
"torch.bernoulli",
"torch.multiprocessing.Pool",
"torch.amin",
"torch.read_vitals",
"numpy.array",
"torch.testing._internal.common_utils.run_tests",
"torch.cross",
"torch.FloatStorage",
"torch.take",
"torch.nn.ReflectionPad2d",
"torch.pdist",
"torch.tan",
"torch.nn.functional.log_softmax",
"numpy.gradient",
"torch.asinh",
"torch.nn.ConvTranspose3d",
"torch.testing._internal.common_device_type.expectedAlertNondeterministic",
"torch.acosh",
"torch.where",
"torch.nn.functional.grid_sample",
"torch.broadcast_tensors",
"torch.gather",
"torch.cuda.device",
"torch.grid_sampler_3d",
"torch.testing.make_tensor",
"torch.testing._internal.common_utils.TemporaryFileName",
"torch.select",
"torch.__config__.show",
"torch.transpose",
"torch.nn.functional.glu",
"torch.cudnn_grid_sampler",
"torch.randperm",
"torch.vitals_enabled",
"torch.sum",
"numpy.nan_to_num",
"torch.ShortStorage",
"torch.testing._internal.common_dtype.floating_types_and",
"torch.repeat_interleave",
"numpy.concatenate",
"torch.FloatTensor",
"torch.nn.CTCLoss",
"torch.cuda.is_available",
"torch.set_num_threads",
"torch.split",
"torch.testing._internal.common_utils.TemporaryDirectoryName",
"torch.LongStorage",
"torch.nn.ReplicationPad2d",
"torch.gradient",
"torch.testing._internal.common_cuda.tf32_is_not_fp32",
"torch.norm",
"torch.utils.data.TensorDataset",
"torch.tensor",
"torch.testing._internal.common_device_type.deviceCountAtLeast",
"torch.rand",
"torch.reciprocal",
"torch.sort",
"torch.atan",
"torch.testing.assert_close",
"torch.LongTensor",
"torch.from_file",
"torch.testing._internal.common_utils.skipCUDAMemoryLeakCheckIf",
"torch.zeros_like",
"torch.is_tensor",
"torch.testing._internal.common_device_type.dtypes",
"torch.get_rng_state",
"torch.storage._dtype_to_storage_type_map",
"torch.cuda.FloatTensor",
"numpy.int64",
"torch.ByteStorage",
"torch.stack",
"torch.cuda.device_count",
"torch.nn.ReflectionPad1d",
"torch.testing._internal.common_dtype.complex_types",
"torch.corrcoef",
"torch.pairwise_distance",
"torch.manual_seed",
"torch.nan_to_num",
"torch.from_dlpack",
"torch.FloatStorage.from_file",
"torch.IntTensor",
"torch.CharTensor",
"torch.testing._internal.common_utils.parametrize",
"torch._C._nn.upsample_nearest1d",
"numpy.empty",
"torch.set_rng_state",
"torch.randn_like",
"torch.__config__.parallel_info",
"torch.renorm",
"numpy.take",
"torch.cat",
"torch.set_default_dtype",
"torch.testing._internal.common_utils.DeterministicGuard",
"torch.load",
"torch.topk",
"torch.testing._internal.common_device_type.largeTensorTest",
"torch.default_generator.get_state",
"torch.addcdiv",
"torch.testing._internal.common_cuda.tf32_on_and_off",
"torch.get_deterministic_debug_mode",
"torch.ShortTensor",
"torch.unique",
"torch.nn.functional.interpolate",
"torch._tensor_str.get_summarized_data",
"torch.full_like",
"torch.cummax",
"torch.cuda.amp.common.amp_definitely_not_available",
"torch.quasirandom.SobolEngine",
"torch.ByteStorage.from_buffer",
"torch.nn.AvgPool3d",
"torch.save",
"torch.nn.AdaptiveMaxPool2d",
"torch._neg_view",
"torch.ones",
"torch.addcmul",
"torch.add",
"torch.initial_seed",
"torch._utils._element_size",
"torch.ShortStorage.from_buffer",
"torch.cuda.synchronize",
"torch.cummin",
"torch.from_numpy",
"torch._debug_has_internal_overlap",
"torch.nn.FractionalMaxPool2d",
"torch.isfinite",
"torch.utils.dlpack.from_dlpack",
"torch.arange",
"numpy.repeat",
"torch.DoubleTensor",
"torch.index_select",
"torch.testing._internal.common_device_type.skipCUDAVersionIn",
"torch.cos",
"torch.testing._internal.common_utils.CudaSyncGuard",
"torch.utils.dlpack.to_dlpack",
"torch.set_printoptions",
"torch.BoolStorage.from_buffer",
"torch.nn.functional.conv2d",
"torch.BFloat16Storage",
"torch.unsqueeze",
"torch.cuda.amp.GradScaler",
"numpy.cov",
"torch.testing.make_non_contiguous",
"torch.ComplexFloatStorage",
"torch.atanh",
"torch.cosh",
"torch.ne",
"torch.ByteTensor",
"torch.backends.cuda.is_built",
"torch.BoolStorage",
"torch.cuda.set_device",
"torch.mode",
"torch.set_deterministic_debug_mode",
"torch.nn.functional.multilabel_margin_loss",
"numpy.percentile",
"torch.nn.AdaptiveAvgPool3d",
"torch.testing._internal.common_dtype.all_types_and",
"torch.cov",
"scipy.stats.chisquare",
"torch.chunk",
"torch.dist",
"torch.cumsum",
"torch.cuda.Stream",
"scipy.stats.geom",
"torch.mean",
"torch.nn.functional.softmax",
"torch.set_flush_denormal",
"torch.erfc",
"torch.nn.FractionalMaxPool3d",
"torch.nn.ReplicationPad3d",
"torch.rand_like",
"torch.nn.functional.nll_loss",
"torch.use_deterministic_algorithms",
"torch.remainder",
"torch.utils.data.DataLoader",
"torch.nn.functional.one_hot",
"torch.index_copy",
"torch.sparse_coo_tensor",
"torch.tanh",
"torch.grid_sampler",
"torch.cdist",
"torch._TypedStorage",
"numpy.random.randn",
"torch.HalfTensor",
"torch.flatten",
"torch.are_deterministic_algorithms_enabled",
"torch.IntStorage.from_buffer",
"torch.cuda.default_stream",
"torch.jit.script",
"torch._efficientzerotensor",
"torch.Size",
"torch._grid_sampler_2d_cpu_fallback",
"torch.amax",
"numpy.arange",
"torch.testing._internal.common_utils.bytes_to_scalar",
"torch.ComplexDoubleStorage",
"torch.eye",
"torch.inference_mode",
"torch.testing._internal.common_dtype.get_all_math_dtypes",
"torch.FloatStorage.from_buffer",
"torch.get_default_dtype",
"torch.is_deterministic_algorithms_warn_only_enabled",
"torch.nn.NLLLoss",
"torch.empty",
"torch.testing._internal.common_dtype.integral_types",
"torch.nn.functional.multi_margin_loss",
"torch.randint_like",
"torch._C._nn.upsample_nearest2d",
"torch.logcumsumexp",
"torch.diff",
"torch.testing._internal.common_dtype.floating_and_complex_types",
"torch.CharStorage",
"torch.isnan",
"torch.testing._internal.common_dtype.floating_types",
"torch.DoubleStorage",
"torch.random.manual_seed",
"numpy.int32",
"torch.index_add",
"torch.can_cast",
"torch.nn.LayerNorm",
"torch.nn.MaxPool3d",
"torch.nn.AdaptiveAvgPool2d",
"torch.version.cuda.split",
"torch.testing._internal.common_device_type.dtypesIfCUDA",
"torch.erf",
"torch.grid_sampler_2d",
"torch.nn.ConvTranspose1d",
"torch.clamp",
"numpy.float64",
"torch.ops.quantized.add",
"numpy.float",
"torch.testing._internal.common_dtype.all_types_and_complex_and"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amarack/dqn_zoo | [
"465aedaee48a6e13cb141808abf23876a1b21e4e"
] | [
"dqn_zoo/prioritized/run_atari.py"
] | [
"# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"A Prioritized DQN agent training on Atari.\n\nFrom the paper \"Prioritized Experience Replay\" http://arxiv.org/abs/1511.05952.\n\nThis is Double DQN with:\n\n* Proportional prioritized sampling and importance sampling correction.\n* Smaller learning rate, but with the same effective maximum learning rate\n (controlled by the optimizer epsilon parameter).\n\"\"\"\n\n# pylint: disable=g-bad-import-order\n\nimport collections\nimport itertools\nimport sys\nimport typing\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport dm_env\nimport haiku as hk\nimport jax\nfrom jax.config import config\nimport numpy as np\nimport optax\n\nfrom dqn_zoo import atari_data\nfrom dqn_zoo import gym_atari\nfrom dqn_zoo import networks\nfrom dqn_zoo import parts\nfrom dqn_zoo import processors\nfrom dqn_zoo import replay as replay_lib\nfrom dqn_zoo.prioritized import agent\n\n# Relevant flag values are expressed in terms of environment frames.\nFLAGS = flags.FLAGS\nflags.DEFINE_string('environment_name', 'pong', '')\nflags.DEFINE_integer('environment_height', 84, '')\nflags.DEFINE_integer('environment_width', 84, '')\nflags.DEFINE_bool('use_gym', False, '')\nflags.DEFINE_integer('replay_capacity', int(1e6), '')\nflags.DEFINE_bool('compress_state', True, '')\nflags.DEFINE_float('min_replay_capacity_fraction', 0.05, '')\nflags.DEFINE_integer('batch_size', 32, '')\nflags.DEFINE_integer('max_frames_per_episode', 108000, '') # 30 mins.\nflags.DEFINE_integer('num_action_repeats', 4, '')\nflags.DEFINE_integer('num_stacked_frames', 4, '')\nflags.DEFINE_float('exploration_epsilon_begin_value', 1., '')\nflags.DEFINE_float('exploration_epsilon_end_value', 0.01, '')\nflags.DEFINE_float('exploration_epsilon_decay_frame_fraction', 0.02, '')\nflags.DEFINE_float('eval_exploration_epsilon', 0.01, '')\nflags.DEFINE_integer('target_network_update_period', int(1.2e5), '')\nflags.DEFINE_float('grad_error_bound', 1. / 32, '')\nflags.DEFINE_float('learning_rate', 0.00025 / 4, '')\nflags.DEFINE_float('optimizer_epsilon', (0.01 / 32**2) * (1. / 4)**2, '')\nflags.DEFINE_float('additional_discount', 0.99, '')\nflags.DEFINE_float('max_abs_reward', 1., '')\nflags.DEFINE_integer('seed', 1, '') # GPU may introduce nondeterminism.\nflags.DEFINE_integer('num_iterations', 200, '')\nflags.DEFINE_integer('num_train_frames', int(1e6), '') # Per iteration.\nflags.DEFINE_integer('num_eval_frames', int(5e5), '') # Per iteration.\nflags.DEFINE_integer('learn_period', 16, '')\nflags.DEFINE_string('results_csv_path', '/tmp/results.csv', '')\n\nflags.DEFINE_float('priority_exponent', 0.6, '')\nflags.DEFINE_float('importance_sampling_exponent_begin_value', 0.4, '')\nflags.DEFINE_float('importance_sampling_exponent_end_value', 1., '')\nflags.DEFINE_float('uniform_sample_probability', 1e-3, '')\nflags.DEFINE_bool('normalize_weights', True, '')\n\n\ndef main(argv):\n \"\"\"Trains Prioritized DQN agent on Atari.\"\"\"\n del argv\n logging.info('Prioritized DQN on Atari on %s.',\n jax.lib.xla_bridge.get_backend().platform)\n random_state = np.random.RandomState(FLAGS.seed)\n rng_key = jax.random.PRNGKey(\n random_state.randint(-sys.maxsize - 1, sys.maxsize + 1))\n\n if FLAGS.results_csv_path:\n writer = parts.CsvWriter(FLAGS.results_csv_path)\n else:\n writer = parts.NullWriter()\n\n def environment_builder():\n \"\"\"Creates Atari environment.\"\"\"\n env = gym_atari.GymAtari(\n FLAGS.environment_name, seed=random_state.randint(1, 2**32))\n return gym_atari.RandomNoopsEnvironmentWrapper(\n env,\n min_noop_steps=1,\n max_noop_steps=30,\n seed=random_state.randint(1, 2**32),\n )\n\n env = environment_builder()\n\n logging.info('Environment: %s', FLAGS.environment_name)\n logging.info('Action spec: %s', env.action_spec())\n logging.info('Observation spec: %s', env.observation_spec())\n num_actions = env.action_spec().num_values\n network_fn = networks.double_dqn_atari_network(num_actions)\n network = hk.transform(network_fn)\n\n def preprocessor_builder():\n return processors.atari(\n additional_discount=FLAGS.additional_discount,\n max_abs_reward=FLAGS.max_abs_reward,\n resize_shape=(FLAGS.environment_height, FLAGS.environment_width),\n num_action_repeats=FLAGS.num_action_repeats,\n num_pooled_frames=2,\n zero_discount_on_life_loss=True,\n num_stacked_frames=FLAGS.num_stacked_frames,\n grayscaling=True,\n )\n\n # Create sample network input from sample preprocessor output.\n sample_processed_timestep = preprocessor_builder()(env.reset())\n sample_processed_timestep = typing.cast(dm_env.TimeStep,\n sample_processed_timestep)\n sample_network_input = sample_processed_timestep.observation\n assert sample_network_input.shape == (FLAGS.environment_height,\n FLAGS.environment_width,\n FLAGS.num_stacked_frames)\n\n exploration_epsilon_schedule = parts.LinearSchedule(\n begin_t=int(FLAGS.min_replay_capacity_fraction * FLAGS.replay_capacity *\n FLAGS.num_action_repeats),\n decay_steps=int(FLAGS.exploration_epsilon_decay_frame_fraction *\n FLAGS.num_iterations * FLAGS.num_train_frames),\n begin_value=FLAGS.exploration_epsilon_begin_value,\n end_value=FLAGS.exploration_epsilon_end_value)\n\n # Note the t in the replay is not exactly aligned with the agent t.\n importance_sampling_exponent_schedule = parts.LinearSchedule(\n begin_t=int(FLAGS.min_replay_capacity_fraction * FLAGS.replay_capacity),\n end_t=(FLAGS.num_iterations *\n int(FLAGS.num_train_frames / FLAGS.num_action_repeats)),\n begin_value=FLAGS.importance_sampling_exponent_begin_value,\n end_value=FLAGS.importance_sampling_exponent_end_value)\n\n if FLAGS.compress_state:\n\n def encoder(transition):\n return transition._replace(\n s_tm1=replay_lib.compress_array(transition.s_tm1),\n s_t=replay_lib.compress_array(transition.s_t))\n\n def decoder(transition):\n return transition._replace(\n s_tm1=replay_lib.uncompress_array(transition.s_tm1),\n s_t=replay_lib.uncompress_array(transition.s_t))\n else:\n encoder = None\n decoder = None\n\n replay_structure = replay_lib.Transition(\n s_tm1=None,\n a_tm1=None,\n r_t=None,\n discount_t=None,\n s_t=None,\n )\n\n replay = replay_lib.PrioritizedTransitionReplay(\n FLAGS.replay_capacity, replay_structure, FLAGS.priority_exponent,\n importance_sampling_exponent_schedule, FLAGS.uniform_sample_probability,\n FLAGS.normalize_weights, random_state, encoder, decoder)\n\n optimizer = optax.rmsprop(\n learning_rate=FLAGS.learning_rate,\n decay=0.95,\n eps=FLAGS.optimizer_epsilon,\n centered=True,\n )\n\n train_rng_key, eval_rng_key = jax.random.split(rng_key)\n\n train_agent = agent.PrioritizedDqn(\n preprocessor=preprocessor_builder(),\n sample_network_input=sample_network_input,\n network=network,\n optimizer=optimizer,\n transition_accumulator=replay_lib.TransitionAccumulator(),\n replay=replay,\n batch_size=FLAGS.batch_size,\n exploration_epsilon=exploration_epsilon_schedule,\n min_replay_capacity_fraction=FLAGS.min_replay_capacity_fraction,\n learn_period=FLAGS.learn_period,\n target_network_update_period=FLAGS.target_network_update_period,\n grad_error_bound=FLAGS.grad_error_bound,\n rng_key=train_rng_key,\n )\n eval_agent = parts.EpsilonGreedyActor(\n preprocessor=preprocessor_builder(),\n network=network,\n exploration_epsilon=FLAGS.eval_exploration_epsilon,\n rng_key=eval_rng_key,\n )\n\n # Set up checkpointing.\n checkpoint = parts.NullCheckpoint()\n\n state = checkpoint.state\n state.iteration = 0\n state.train_agent = train_agent\n state.eval_agent = eval_agent\n state.random_state = random_state\n state.writer = writer\n if checkpoint.can_be_restored():\n checkpoint.restore()\n\n while state.iteration <= FLAGS.num_iterations:\n # New environment for each iteration to allow for determinism if preempted.\n env = environment_builder()\n\n logging.info('Training iteration %d.', state.iteration)\n train_seq = parts.run_loop(train_agent, env, FLAGS.max_frames_per_episode)\n num_train_frames = 0 if state.iteration == 0 else FLAGS.num_train_frames\n train_seq_truncated = itertools.islice(train_seq, num_train_frames)\n train_stats = parts.generate_statistics(train_seq_truncated)\n\n logging.info('Evaluation iteration %d.', state.iteration)\n eval_agent.network_params = train_agent.online_params\n eval_seq = parts.run_loop(eval_agent, env, FLAGS.max_frames_per_episode)\n eval_seq_truncated = itertools.islice(eval_seq, FLAGS.num_eval_frames)\n eval_stats = parts.generate_statistics(eval_seq_truncated)\n\n # Logging and checkpointing.\n human_normalized_score = atari_data.get_human_normalized_score(\n FLAGS.environment_name, eval_stats['episode_return'])\n capped_human_normalized_score = np.amin([1., human_normalized_score])\n log_output = [\n ('iteration', state.iteration, '%3d'),\n ('frame', state.iteration * FLAGS.num_train_frames, '%5d'),\n ('eval_episode_return', eval_stats['episode_return'], '% 2.2f'),\n ('train_episode_return', train_stats['episode_return'], '% 2.2f'),\n ('eval_num_episodes', eval_stats['num_episodes'], '%3d'),\n ('train_num_episodes', train_stats['num_episodes'], '%3d'),\n ('eval_frame_rate', eval_stats['step_rate'], '%4.0f'),\n ('train_frame_rate', train_stats['step_rate'], '%4.0f'),\n ('train_exploration_epsilon', train_agent.exploration_epsilon, '%.3f'),\n ('importance_sampling_exponent',\n train_agent.importance_sampling_exponent, '%.3f'),\n ('max_seen_priority', train_agent.max_seen_priority, '%.3f'),\n ('normalized_return', human_normalized_score, '%.3f'),\n ('capped_normalized_return', capped_human_normalized_score, '%.3f'),\n ('human_gap', 1. - capped_human_normalized_score, '%.3f'),\n ]\n log_output_str = ', '.join(('%s: ' + f) % (n, v) for n, v, f in log_output)\n logging.info(log_output_str)\n writer.write(collections.OrderedDict((n, v) for n, v, _ in log_output))\n state.iteration += 1\n checkpoint.save()\n\n writer.close()\n\n\nif __name__ == '__main__':\n config.update('jax_platform_name', 'gpu') # Default to GPU.\n config.update('jax_numpy_rank_promotion', 'raise')\n config.config_with_absl()\n app.run(main)\n"
] | [
[
"numpy.amin",
"numpy.random.RandomState"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NV-jpt/cucim | [
"4d861fe38bfa5f2fcaedcc029d51c93fd33456a2"
] | [
"python/cucim/src/cucim/core/operations/intensity/tests/test_zoom.py"
] | [
"import os\n\nimport cupy\nimport numpy as np\nimport pytest\nimport skimage.data\nfrom PIL import Image\n\nimport cucim.core.operations.intensity as its\n\n\ndef get_input_arr():\n img = skimage.data.astronaut()\n arr = np.asarray(img)\n arr = np.transpose(arr)\n return arr\n\n\ndef get_zoomed_data():\n dirname = os.path.dirname(__file__)\n img1 = Image.open(os.path.join(os.path.abspath(dirname), \"zoomed.png\"))\n arr_o = np.asarray(img1)\n arr_o = np.transpose(arr_o)\n return arr_o\n\n\ndef test_zoom_param():\n arr = get_input_arr()\n with pytest.raises(ValueError):\n arr1 = arr.flatten()\n its.zoom(arr1, [1.1, 1.1])\n with pytest.raises(TypeError):\n img = Image.fromarray(arr.T, 'RGB')\n its.zoom(img, [1.1, 1.1])\n\n\ndef test_zoom_numpy_input():\n arr = get_input_arr()\n zoomed_arr = get_zoomed_data()\n output = its.zoom(arr, [1.1, 1.1])\n assert np.allclose(output, zoomed_arr)\n\n\ndef test_zoom_cupy_input():\n arr = get_input_arr()\n zoomed_arr = get_zoomed_data()\n cupy_arr = cupy.asarray(arr)\n cupy_output = its.zoom(cupy_arr, [1.1, 1.1])\n np_output = cupy.asnumpy(cupy_output)\n assert np.allclose(np_output, zoomed_arr)\n\n\ndef test_zoom_batchinput():\n arr = get_input_arr()\n zoomed_arr = get_zoomed_data()\n arr_batch = np.stack((arr,) * 8, axis=0)\n np_output = its.zoom(arr_batch, [1.1, 1.1])\n assert np_output.shape[0] == 8\n\n for i in range(np_output.shape[0]):\n assert np.allclose(np_output[i], zoomed_arr)\n"
] | [
[
"numpy.asarray",
"numpy.allclose",
"numpy.stack",
"numpy.transpose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
OskarLiew/modAL | [
"c95fb1d3be63176bb1c226ac6de5cb4ddce87dd6"
] | [
"tests/core_tests.py"
] | [
"import random\nimport unittest\nimport numpy as np\n\nimport mock\nimport modAL.models.base\nimport modAL.models.learners\nimport modAL.utils.selection\nimport modAL.utils.validation\nimport modAL.utils.combination\nimport modAL.acquisition\nimport modAL.batch\nimport modAL.density\nimport modAL.disagreement\nimport modAL.expected_error\nimport modAL.multilabel\nimport modAL.uncertainty\n\nfrom copy import deepcopy\nfrom itertools import chain, product\nfrom collections import namedtuple\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.svm import SVC\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom scipy.stats import entropy, norm\nfrom scipy.special import ndtr\nfrom scipy import sparse as sp\n\n\nTest = namedtuple('Test', ['input', 'output'])\n\n\ndef random_array(shape, n_arrays):\n for _ in range(n_arrays):\n yield np.random.rand(*shape)\n\n\nclass TestUtils(unittest.TestCase):\n\n def test_check_class_labels(self):\n for n_labels in range(1, 10):\n for n_learners in range(1, 10):\n # 1. test fitted estimators\n labels = np.random.randint(10, size=n_labels)\n different_labels = np.random.randint(10, 20, size=np.random.randint(1, 10))\n learner_list_1 = [mock.MockEstimator(classes_=labels) for _ in range(n_learners)]\n learner_list_2 = [mock.MockEstimator(classes_=different_labels) for _ in range(np.random.randint(1, 5))]\n shuffled_learners = random.sample(learner_list_1 + learner_list_2, len(learner_list_1 + learner_list_2))\n self.assertTrue(modAL.utils.validation.check_class_labels(*learner_list_1))\n self.assertFalse(modAL.utils.validation.check_class_labels(*shuffled_learners))\n\n # 2. test unfitted estimators\n unfitted_learner_list = [mock.MockEstimator(classes_=labels) for _ in range(n_learners)]\n idx = np.random.randint(0, n_learners)\n unfitted_learner_list.insert(idx, mock.MockEstimator(fitted=False))\n self.assertRaises(NotFittedError, modAL.utils.validation.check_class_labels, *unfitted_learner_list)\n\n def test_check_class_proba(self):\n for n_labels in range(2, 20):\n # when all classes are known:\n proba = np.random.rand(100, n_labels)\n class_labels = list(range(n_labels))\n np.testing.assert_almost_equal(\n modAL.utils.check_class_proba(proba, known_labels=class_labels, all_labels=class_labels),\n proba\n )\n for unknown_idx in range(n_labels):\n all_labels = list(range(n_labels))\n known_labels = deepcopy(all_labels)\n known_labels.remove(unknown_idx)\n aug_proba = np.insert(proba[:, known_labels], unknown_idx, np.zeros(len(proba)), axis=1)\n np.testing.assert_almost_equal(\n modAL.utils.check_class_proba(proba[:, known_labels], known_labels=known_labels, all_labels=all_labels),\n aug_proba\n )\n\n def test_linear_combination(self):\n\n def dummy_function(X_in):\n return np.ones(shape=(len(X_in), 1))\n\n for n_samples in range(2, 10):\n for n_features in range(1, 10):\n for n_functions in range(2, 10):\n functions = [dummy_function for _ in range(n_functions)]\n linear_combination = modAL.utils.combination.make_linear_combination(*functions)\n\n X_in = np.random.rand(n_samples, n_features)\n if n_samples == 1:\n true_result = float(n_functions)\n else:\n true_result = n_functions*np.ones(shape=(n_samples, 1))\n\n try:\n np.testing.assert_almost_equal(linear_combination(X_in), true_result)\n except:\n linear_combination(X_in)\n\n def test_product(self):\n for n_dim in range(1, 5):\n shape = tuple([10] + [2 for _ in range(n_dim-1)])\n X_in = 2*np.ones(shape=shape)\n for n_functions in range(1, 10):\n functions = [(lambda x: x) for _ in range(n_functions)]\n # linear combination without weights\n product = modAL.utils.combination.make_product(*functions)\n np.testing.assert_almost_equal(\n product(X_in),\n X_in**n_functions\n )\n\n # linear combination with weights\n exponents = np.random.rand(n_functions)\n exp_product = modAL.utils.combination.make_product(*functions, exponents=exponents)\n np.testing.assert_almost_equal(\n exp_product(X_in),\n np.prod([X_in**exponent for exponent in exponents], axis=0)\n )\n\n def test_make_query_strategy(self):\n query_strategy = modAL.utils.combination.make_query_strategy(\n utility_measure=modAL.uncertainty.classifier_uncertainty,\n selector=modAL.utils.selection.multi_argmax\n )\n\n for n_samples in range(1, 10):\n for n_classes in range(1, 10):\n proba = np.random.rand(n_samples, n_classes)\n proba = proba/np.sum(proba, axis=1).reshape(n_samples, 1)\n X = np.random.rand(n_samples, 3)\n\n learner = modAL.models.learners.ActiveLearner(\n estimator=mock.MockEstimator(predict_proba_return=proba)\n )\n\n query_1 = query_strategy(learner, X)\n query_2 = modAL.uncertainty.uncertainty_sampling(learner, X)\n\n np.testing.assert_equal(query_1[0], query_2[0])\n np.testing.assert_almost_equal(query_1[1], query_2[1])\n\n def test_data_vstack(self):\n for n_samples, n_features in product(range(1, 10), range(1, 10)):\n # numpy arrays\n a, b = np.random.rand(n_samples, n_features), np.random.rand(n_samples, n_features)\n np.testing.assert_almost_equal(\n modAL.utils.data.data_vstack((a, b)),\n np.concatenate((a, b))\n )\n\n # sparse matrices\n for format in ['lil', 'csc', 'csr']:\n a, b = sp.random(n_samples, n_features, format=format), sp.random(n_samples, n_features, format=format)\n self.assertEqual((modAL.utils.data.data_vstack((a, b)) != sp.vstack((a, b))).sum(), 0)\n\n # not supported formats\n self.assertRaises(TypeError, modAL.utils.data.data_vstack, (1, 1))\n\n # functions from modAL.utils.selection\n\n def test_multi_argmax(self):\n for n_pool in range(2, 100):\n for n_instances in range(1, n_pool+1):\n utility = np.zeros(n_pool)\n max_idx = np.random.choice(range(n_pool), size=n_instances, replace=False)\n utility[max_idx] = 1e-10 + np.random.rand(n_instances, )\n np.testing.assert_equal(\n np.sort(modAL.utils.selection.multi_argmax(utility, n_instances)),\n np.sort(max_idx)\n )\n\n def test_shuffled_argmax(self):\n for n_pool in range(1, 100):\n for n_instances in range(1, n_pool+1):\n values = np.random.permutation(n_pool)\n true_query_idx = np.argsort(values)[len(values)-n_instances:]\n \n np.testing.assert_equal(\n true_query_idx,\n modAL.utils.selection.shuffled_argmax(values, n_instances)\n )\n\n def test_weighted_random(self):\n for n_pool in range(2, 100):\n for n_instances in range(1, n_pool):\n utility = np.ones(n_pool)\n query_idx = modAL.utils.selection.weighted_random(utility, n_instances)\n # testing for correct number of returned indices\n np.testing.assert_equal(len(query_idx), n_instances)\n # testing for uniqueness of each query index\n np.testing.assert_equal(len(query_idx), len(np.unique(query_idx)))\n\n\nclass TestAcquisitionFunctions(unittest.TestCase):\n def test_acquisition_functions(self):\n for n_samples in range(1, 100):\n mean, std = np.random.rand(100, 1), np.random.rand(100, 1)\n modAL.acquisition.PI(mean, std, 0, 0)\n modAL.acquisition.EI(mean, std, 0, 0)\n modAL.acquisition.UCB(mean, std, 0)\n\n mean, std = np.random.rand(100, ), np.random.rand(100, )\n modAL.acquisition.PI(mean, std, 0, 0)\n modAL.acquisition.EI(mean, std, 0, 0)\n modAL.acquisition.UCB(mean, std, 0)\n\n def test_optimizer_PI(self):\n for n_samples in range(1, 100):\n mean = np.random.rand(n_samples, )\n std = np.random.rand(n_samples, )\n tradeoff = np.random.rand()\n max_val = np.random.rand()\n\n # 1. fitted estimator\n mock_estimator = mock.MockEstimator(predict_return=(mean, std))\n optimizer = modAL.models.learners.BayesianOptimizer(estimator=mock_estimator)\n optimizer._set_max([0], [max_val])\n true_PI = ndtr((mean - max_val - tradeoff)/std)\n\n np.testing.assert_almost_equal(\n true_PI,\n modAL.acquisition.optimizer_PI(optimizer, np.random.rand(n_samples, 2), tradeoff)\n )\n\n # 2. unfitted estimator\n mock_estimator = mock.MockEstimator(fitted=False)\n optimizer = modAL.models.learners.BayesianOptimizer(estimator=mock_estimator)\n optimizer._set_max([0], [max_val])\n true_PI = ndtr((np.zeros(shape=(len(mean), 1)) - max_val - tradeoff) / np.ones(shape=(len(mean), 1)))\n\n np.testing.assert_almost_equal(\n true_PI,\n modAL.acquisition.optimizer_PI(optimizer, np.random.rand(n_samples, 2), tradeoff)\n )\n\n def test_optimizer_EI(self):\n for n_samples in range(1, 100):\n mean = np.random.rand(n_samples, )\n std = np.random.rand(n_samples, )\n tradeoff = np.random.rand()\n max_val = np.random.rand()\n\n # 1. fitted estimator\n mock_estimator = mock.MockEstimator(\n predict_return=(mean, std)\n )\n optimizer = modAL.models.learners.BayesianOptimizer(estimator=mock_estimator)\n optimizer._set_max([0], [max_val])\n true_EI = (mean - optimizer.y_max - tradeoff) * ndtr((mean - optimizer.y_max - tradeoff) / std) \\\n + std * norm.pdf((mean - optimizer.y_max - tradeoff) / std)\n\n np.testing.assert_almost_equal(\n true_EI,\n modAL.acquisition.optimizer_EI(optimizer, np.random.rand(n_samples, 2), tradeoff)\n )\n\n # 2. unfitted estimator\n mock_estimator = mock.MockEstimator(fitted=False)\n optimizer = modAL.models.learners.BayesianOptimizer(estimator=mock_estimator)\n optimizer._set_max([0], [max_val])\n true_EI = (np.zeros(shape=(len(mean), 1)) - optimizer.y_max - tradeoff) * ndtr((np.zeros(shape=(len(mean), 1)) - optimizer.y_max - tradeoff) / np.ones(shape=(len(mean), 1))) \\\n + np.ones(shape=(len(mean), 1)) * norm.pdf((np.zeros(shape=(len(mean), 1)) - optimizer.y_max - tradeoff) / np.ones(shape=(len(mean), 1)))\n\n np.testing.assert_almost_equal(\n true_EI,\n modAL.acquisition.optimizer_EI(optimizer, np.random.rand(n_samples, 2), tradeoff)\n )\n\n def test_optimizer_UCB(self):\n for n_samples in range(1, 100):\n mean = np.random.rand(n_samples, )\n std = np.random.rand(n_samples, )\n beta = np.random.rand()\n\n # 1. fitted estimator\n mock_estimator = mock.MockEstimator(\n predict_return=(mean, std)\n )\n optimizer = modAL.models.learners.BayesianOptimizer(estimator=mock_estimator)\n true_UCB = mean + beta*std\n\n np.testing.assert_almost_equal(\n true_UCB,\n modAL.acquisition.optimizer_UCB(optimizer, np.random.rand(n_samples, 2), beta)\n )\n\n # 2. unfitted estimator\n mock_estimator = mock.MockEstimator(fitted=False)\n optimizer = modAL.models.learners.BayesianOptimizer(estimator=mock_estimator)\n true_UCB = np.zeros(shape=(len(mean), 1)) + beta * np.ones(shape=(len(mean), 1))\n\n np.testing.assert_almost_equal(\n true_UCB,\n modAL.acquisition.optimizer_UCB(optimizer, np.random.rand(n_samples, 2), beta)\n )\n\n def test_selection(self):\n for n_samples in range(1, 100):\n for n_instances in range(1, n_samples):\n X = np.random.rand(n_samples, 3)\n mean = np.random.rand(n_samples, )\n std = np.random.rand(n_samples, )\n max_val = np.random.rand()\n\n mock_estimator = mock.MockEstimator(\n predict_return=(mean, std)\n )\n\n optimizer = modAL.models.learners.BayesianOptimizer(estimator=mock_estimator)\n optimizer._set_max([0], [max_val])\n\n modAL.acquisition.max_PI(optimizer, X, tradeoff=np.random.rand(), n_instances=n_instances)\n modAL.acquisition.max_EI(optimizer, X, tradeoff=np.random.rand(), n_instances=n_instances)\n modAL.acquisition.max_UCB(optimizer, X, beta=np.random.rand(), n_instances=n_instances)\n\n\nclass TestDensity(unittest.TestCase):\n\n def test_similarize_distance(self):\n from scipy.spatial.distance import cosine\n sim = modAL.density.similarize_distance(cosine)\n for _ in range(100):\n for n_dim in range(1, 10):\n X_1, X_2 = np.random.rand(n_dim), np.random.rand(n_dim)\n np.testing.assert_almost_equal(\n sim(X_1, X_2),\n 1/(1 + cosine(X_1, X_2))\n )\n\n def test_information_density(self):\n for n_samples in range(1, 10):\n for n_dim in range(1, 10):\n X_pool = np.random.rand(n_samples, n_dim)\n similarities = modAL.density.information_density(X_pool)\n np.testing.assert_equal(len(similarities), n_samples)\n\n\nclass TestDisagreements(unittest.TestCase):\n\n def test_vote_entropy(self):\n for n_samples in range(1, 10):\n for n_classes in range(1, 10):\n for true_query_idx in range(n_samples):\n # 1. fitted committee\n vote_return = np.zeros(shape=(n_samples, n_classes), dtype=np.int16)\n vote_return[true_query_idx] = np.asarray(range(n_classes), dtype=np.int16)\n committee = mock.MockCommittee(classes_=np.asarray(range(n_classes)), vote_return=vote_return)\n vote_entr = modAL.disagreement.vote_entropy(\n committee, np.random.rand(n_samples, n_classes)\n )\n true_entropy = np.zeros(shape=(n_samples, ))\n true_entropy[true_query_idx] = entropy(np.ones(n_classes)/n_classes)\n np.testing.assert_array_almost_equal(vote_entr, true_entropy)\n\n # 2. unfitted committee\n committee = mock.MockCommittee(fitted=False)\n true_entropy = np.zeros(shape=(n_samples,))\n vote_entr = modAL.disagreement.vote_entropy(\n committee, np.random.rand(n_samples, n_classes)\n )\n np.testing.assert_almost_equal(vote_entr, true_entropy)\n\n def test_consensus_entropy(self):\n for n_samples in range(1, 10):\n for n_classes in range(2, 10):\n for true_query_idx in range(n_samples):\n # 1. fitted committee\n proba = np.zeros(shape=(n_samples, n_classes))\n proba[:, 0] = 1.0\n proba[true_query_idx] = np.ones(n_classes)/n_classes\n committee = mock.MockCommittee(predict_proba_return=proba)\n consensus_entropy = modAL.disagreement.consensus_entropy(\n committee, np.random.rand(n_samples, n_classes)\n )\n true_entropy = np.zeros(shape=(n_samples,))\n true_entropy[true_query_idx] = entropy(np.ones(n_classes) / n_classes)\n np.testing.assert_array_almost_equal(consensus_entropy, true_entropy)\n\n # 2. unfitted committee\n committee = mock.MockCommittee(fitted=False)\n true_entropy = np.zeros(shape=(n_samples,))\n consensus_entropy = modAL.disagreement.consensus_entropy(\n committee, np.random.rand(n_samples, n_classes)\n )\n np.testing.assert_almost_equal(consensus_entropy, true_entropy)\n\n def test_KL_max_disagreement(self):\n for n_samples in range(1, 10):\n for n_classes in range(2, 10):\n for n_learners in range (2, 10):\n # 1. fitted committee\n vote_proba = np.zeros(shape=(n_samples, n_learners, n_classes))\n vote_proba[:, :, 0] = 1.0\n committee = mock.MockCommittee(\n n_learners=n_learners, classes_=range(n_classes),\n vote_proba_return=vote_proba\n )\n\n true_KL_disagreement = np.zeros(shape=(n_samples, ))\n\n try:\n np.testing.assert_array_almost_equal(\n true_KL_disagreement,\n modAL.disagreement.KL_max_disagreement(committee, np.random.rand(n_samples, 1))\n )\n except:\n modAL.disagreement.KL_max_disagreement(committee, np.random.rand(n_samples, 1))\n\n # 2. unfitted committee\n committee = mock.MockCommittee(fitted=False)\n true_KL_disagreement = np.zeros(shape=(n_samples,))\n returned_KL_disagreement = modAL.disagreement.KL_max_disagreement(\n committee, np.random.rand(n_samples, n_classes)\n )\n np.testing.assert_almost_equal(returned_KL_disagreement, true_KL_disagreement)\n\n def test_vote_entropy_sampling(self):\n for n_samples, n_features, n_classes in product(range(1, 10), range(1, 10), range(1, 10)):\n committee = mock.MockCommittee(classes_=np.asarray(range(n_classes)),\n vote_return=np.zeros(shape=(n_samples, n_classes), dtype=np.int16))\n modAL.disagreement.vote_entropy_sampling(committee, np.random.rand(n_samples, n_features))\n modAL.disagreement.vote_entropy_sampling(committee, np.random.rand(n_samples, n_features),\n random_tie_break=True)\n\n def test_consensus_entropy_sampling(self):\n for n_samples, n_features, n_classes in product(range(1, 10), range(1, 10), range(1, 10)):\n committee = mock.MockCommittee(predict_proba_return=np.random.rand(n_samples, n_classes))\n modAL.disagreement.consensus_entropy_sampling(committee, np.random.rand(n_samples, n_features))\n modAL.disagreement.consensus_entropy_sampling(committee, np.random.rand(n_samples, n_features),\n random_tie_break=True)\n\n def test_max_disagreement_sampling(self):\n for n_samples, n_features, n_classes, n_learners in product(range(1, 10), range(1, 10), range(1, 10), range(2, 5)):\n committee = mock.MockCommittee(\n n_learners=n_learners, classes_=range(n_classes),\n vote_proba_return=np.zeros(shape=(n_samples, n_learners, n_classes))\n )\n modAL.disagreement.max_disagreement_sampling(committee, np.random.rand(n_samples, n_features))\n modAL.disagreement.max_disagreement_sampling(committee, np.random.rand(n_samples, n_features),\n random_tie_break=True)\n\n def test_max_std_sampling(self):\n for n_samples, n_features in product(range(1, 10), range(1, 10)):\n regressor = GaussianProcessRegressor()\n regressor.fit(np.random.rand(n_samples, n_features), np.random.rand(n_samples))\n modAL.disagreement.max_std_sampling(regressor, np.random.rand(n_samples, n_features))\n modAL.disagreement.max_std_sampling(regressor, np.random.rand(n_samples, n_features),\n random_tie_break=True)\n\n\nclass TestEER(unittest.TestCase):\n def test_eer(self):\n for n_pool, n_features, n_classes in product(range(5, 10), range(1, 5), range(2, 5)):\n X_training, y_training = np.random.rand(10, n_features), np.random.randint(0, n_classes, size=10)\n X_pool, y_pool = np.random.rand(n_pool, n_features), np.random.randint(0, n_classes+1, size=n_pool)\n\n learner = modAL.models.ActiveLearner(RandomForestClassifier(n_estimators=2),\n X_training=X_training, y_training=y_training)\n\n modAL.expected_error.expected_error_reduction(learner, X_pool)\n modAL.expected_error.expected_error_reduction(learner, X_pool, random_tie_break=True)\n modAL.expected_error.expected_error_reduction(learner, X_pool, p_subsample=0.1)\n modAL.expected_error.expected_error_reduction(learner, X_pool, loss='binary')\n modAL.expected_error.expected_error_reduction(learner, X_pool, p_subsample=0.1, loss='log')\n self.assertRaises(AssertionError, modAL.expected_error.expected_error_reduction,\n learner, X_pool, p_subsample=1.5)\n self.assertRaises(AssertionError, modAL.expected_error.expected_error_reduction,\n learner, X_pool, loss=42)\n\n\nclass TestUncertainties(unittest.TestCase):\n\n def test_classifier_uncertainty(self):\n test_cases = (Test(p * np.ones(shape=(k, l)), (1 - p) * np.ones(shape=(k, )))\n for k in range(1, 100) for l in range(1, 10) for p in np.linspace(0, 1, 11))\n for case in test_cases:\n # testing _proba_uncertainty\n np.testing.assert_almost_equal(\n modAL.uncertainty._proba_uncertainty(case.input),\n case.output\n )\n\n # fitted estimator\n fitted_estimator = mock.MockEstimator(predict_proba_return=case.input)\n np.testing.assert_almost_equal(\n modAL.uncertainty.classifier_uncertainty(fitted_estimator, np.random.rand(10)),\n case.output\n )\n\n # not fitted estimator\n not_fitted_estimator = mock.MockEstimator(fitted=False)\n np.testing.assert_almost_equal(\n modAL.uncertainty.classifier_uncertainty(not_fitted_estimator, case.input),\n np.ones(shape=(len(case.output)))\n )\n\n def test_classifier_margin(self):\n test_cases_1 = (Test(p * np.ones(shape=(k, l)), np.zeros(shape=(k,)))\n for k in range(1, 100) for l in range(1, 10) for p in np.linspace(0, 1, 11))\n test_cases_2 = (Test(p * np.tile(np.asarray(range(k))+1.0, l).reshape(l, k),\n p * np.ones(shape=(l, ))*int(k!=1))\n for k in range(1, 10) for l in range(1, 100) for p in np.linspace(0, 1, 11))\n for case in chain(test_cases_1, test_cases_2):\n # _proba_margin\n np.testing.assert_almost_equal(\n modAL.uncertainty._proba_margin(case.input),\n case.output\n )\n\n # fitted estimator\n fitted_estimator = mock.MockEstimator(predict_proba_return=case.input)\n np.testing.assert_almost_equal(\n modAL.uncertainty.classifier_margin(fitted_estimator, np.random.rand(10)),\n case.output\n )\n\n # not fitted estimator\n not_fitted_estimator = mock.MockEstimator(fitted=False)\n np.testing.assert_almost_equal(\n modAL.uncertainty.classifier_margin(not_fitted_estimator, case.input),\n np.zeros(shape=(len(case.output)))\n )\n\n def test_classifier_entropy(self):\n for n_samples in range(1, 100):\n for n_classes in range(1, 20):\n proba = np.zeros(shape=(n_samples, n_classes))\n for sample_idx in range(n_samples):\n proba[sample_idx, np.random.choice(range(n_classes))] = 1.0\n\n # _proba_entropy\n np.testing.assert_almost_equal(\n modAL.uncertainty._proba_entropy(proba),\n np.zeros(shape=(n_samples,))\n )\n\n # fitted estimator\n fitted_estimator = mock.MockEstimator(predict_proba_return=proba)\n np.testing.assert_equal(\n modAL.uncertainty.classifier_entropy(fitted_estimator, np.random.rand(n_samples, 1)),\n np.zeros(shape=(n_samples, ))\n )\n\n # not fitted estimator\n not_fitted_estimator = mock.MockEstimator(fitted=False)\n np.testing.assert_almost_equal(\n modAL.uncertainty.classifier_entropy(not_fitted_estimator, np.random.rand(n_samples, 1)),\n np.zeros(shape=(n_samples, ))\n )\n\n def test_uncertainty_sampling(self):\n for n_samples in range(1, 10):\n for n_classes in range(1, 10):\n max_proba = np.zeros(n_classes)\n for true_query_idx in range(n_samples):\n predict_proba = np.random.rand(n_samples, n_classes)\n predict_proba[true_query_idx] = max_proba\n classifier = mock.MockEstimator(predict_proba_return=predict_proba)\n query_idx, query_instance = modAL.uncertainty.uncertainty_sampling(\n classifier, np.random.rand(n_samples, n_classes)\n )\n shuffled_query_idx, shuffled_query_instance = modAL.uncertainty.uncertainty_sampling(\n classifier, np.random.rand(n_samples, n_classes),\n random_tie_break=True\n )\n np.testing.assert_array_equal(query_idx, true_query_idx)\n\n def test_margin_sampling(self):\n for n_samples in range(1, 10):\n for n_classes in range(2, 10):\n for true_query_idx in range(n_samples):\n predict_proba = np.zeros(shape=(n_samples, n_classes))\n predict_proba[:, 0] = 1.0\n predict_proba[true_query_idx, 0] = 0.0\n classifier = mock.MockEstimator(predict_proba_return=predict_proba)\n query_idx, query_instance = modAL.uncertainty.margin_sampling(\n classifier, np.random.rand(n_samples, n_classes)\n )\n shuffled_query_idx, shuffled_query_instance = modAL.uncertainty.margin_sampling(\n classifier, np.random.rand(n_samples, n_classes),\n random_tie_break=True\n )\n np.testing.assert_array_equal(query_idx, true_query_idx)\n\n def test_entropy_sampling(self):\n for n_samples in range(1, 10):\n for n_classes in range(2, 10):\n max_proba = np.ones(n_classes)/n_classes\n for true_query_idx in range(n_samples):\n predict_proba = np.zeros(shape=(n_samples, n_classes))\n predict_proba[:, 0] = 1.0\n predict_proba[true_query_idx] = max_proba\n classifier = mock.MockEstimator(predict_proba_return=predict_proba)\n query_idx, query_instance = modAL.uncertainty.entropy_sampling(\n classifier, np.random.rand(n_samples, n_classes)\n )\n shuffled_query_idx, shuffled_query_instance = modAL.uncertainty.entropy_sampling(\n classifier, np.random.rand(n_samples, n_classes),\n random_tie_break=True\n )\n np.testing.assert_array_equal(query_idx, true_query_idx)\n\n\nclass TestActiveLearner(unittest.TestCase):\n\n def test_add_training_data(self):\n for n_samples in range(1, 10):\n for n_features in range(1, 10):\n for n_new_samples in range(1, 10):\n # testing for valid cases\n # 1. integer class labels\n X_initial = np.random.rand(n_samples, n_features)\n y_initial = np.random.randint(0, 2, size=(n_samples,))\n X_new = np.random.rand(n_new_samples, n_features)\n y_new = np.random.randint(0, 2, size=(n_new_samples,))\n learner = modAL.models.learners.ActiveLearner(\n estimator=mock.MockEstimator(),\n X_training=X_initial, y_training=y_initial\n )\n learner._add_training_data(X_new, y_new)\n np.testing.assert_almost_equal(\n learner.X_training,\n np.vstack((X_initial, X_new))\n )\n np.testing.assert_equal(\n learner.y_training,\n np.concatenate((y_initial, y_new))\n )\n # 2. vector class labels\n y_initial = np.random.randint(0, 2, size=(n_samples, n_features+1))\n y_new = np.random.randint(0, 2, size=(n_new_samples, n_features+1))\n learner = modAL.models.learners.ActiveLearner(\n estimator=mock.MockEstimator(),\n X_training=X_initial, y_training=y_initial\n )\n learner._add_training_data(X_new, y_new)\n np.testing.assert_equal(\n learner.y_training,\n np.concatenate((y_initial, y_new))\n )\n # 3. data with shape (n, )\n X_initial = np.random.rand(n_samples, )\n y_initial = np.random.randint(0, 2, size=(n_samples,))\n learner = modAL.models.learners.ActiveLearner(\n estimator=mock.MockEstimator(),\n X_training=X_initial, y_training=y_initial\n )\n X_new = np.random.rand(n_new_samples,)\n y_new = np.random.randint(0, 2, size=(n_new_samples,))\n learner._add_training_data(X_new, y_new)\n\n\n\n # testing for invalid cases\n # 1. len(X_new) != len(y_new)\n X_new = np.random.rand(n_new_samples, n_features)\n y_new = np.random.randint(0, 2, size=(2*n_new_samples,))\n self.assertRaises(ValueError, learner._add_training_data, X_new, y_new)\n # 2. X_new has wrong dimensions\n X_new = np.random.rand(n_new_samples, 2*n_features)\n y_new = np.random.randint(0, 2, size=(n_new_samples,))\n self.assertRaises(ValueError, learner._add_training_data, X_new, y_new)\n\n def test_predict(self):\n for n_samples in range(1, 100):\n for n_features in range(1, 10):\n X = np.random.rand(n_samples, n_features)\n predict_return = np.random.randint(0, 2, size=(n_samples, ))\n mock_classifier = mock.MockEstimator(predict_return=predict_return)\n learner = modAL.models.learners.ActiveLearner(\n estimator=mock_classifier\n )\n np.testing.assert_equal(\n learner.predict(X),\n predict_return\n )\n\n def test_predict_proba(self):\n for n_samples in range(1, 100):\n for n_features in range(1, 10):\n X = np.random.rand(n_samples, n_features)\n predict_proba_return = np.random.randint(0, 2, size=(n_samples,))\n mock_classifier = mock.MockEstimator(predict_proba_return=predict_proba_return)\n learner = modAL.models.learners.ActiveLearner(\n estimator=mock_classifier\n )\n np.testing.assert_equal(\n learner.predict_proba(X),\n predict_proba_return\n )\n\n def test_query(self):\n for n_samples in range(1, 100):\n for n_features in range(1, 10):\n X = np.random.rand(n_samples, n_features)\n query_idx = np.random.randint(0, n_samples)\n mock_query = mock.MockFunction(return_val=(query_idx, X[query_idx]))\n learner = modAL.models.learners.ActiveLearner(\n estimator=None,\n query_strategy=mock_query\n )\n np.testing.assert_equal(\n learner.query(X),\n (query_idx, X[query_idx])\n )\n\n def test_score(self):\n test_cases = (np.random.rand() for _ in range(10))\n for score_return in test_cases:\n mock_classifier = mock.MockEstimator(score_return=score_return)\n learner = modAL.models.learners.ActiveLearner(mock_classifier, mock.MockFunction(None))\n np.testing.assert_almost_equal(\n learner.score(np.random.rand(5, 2), np.random.rand(5, )),\n score_return\n )\n\n def test_teach(self):\n X_training = np.random.rand(10, 2)\n y_training = np.random.randint(0, 2, size=10)\n\n for bootstrap, only_new in product([True, False], [True, False]):\n for n_samples in range(1, 10):\n X = np.random.rand(n_samples, 2)\n y = np.random.randint(0, 2, size=n_samples)\n\n learner = modAL.models.learners.ActiveLearner(\n X_training=X_training, y_training=y_training,\n estimator=mock.MockEstimator()\n )\n\n learner.teach(X, y, bootstrap=bootstrap, only_new=only_new)\n\n def test_nan(self):\n X_training_nan = np.ones(shape=(10, 2)) * np.nan\n X_training_inf = np.ones(shape=(10, 2)) * np.inf\n y_training = np.random.randint(0, 2, size=10)\n\n learner = modAL.models.learners.ActiveLearner(\n X_training=X_training_nan, y_training=y_training,\n estimator=mock.MockEstimator(),\n force_all_finite=False\n )\n learner.teach(X_training_nan, y_training)\n\n learner = modAL.models.learners.ActiveLearner(\n X_training=X_training_inf, y_training=y_training,\n estimator=mock.MockEstimator(),\n force_all_finite=False\n )\n learner.teach(X_training_inf, y_training)\n\n def test_keras(self):\n pass\n\n def test_sklearn(self):\n learner = modAL.models.learners.ActiveLearner(\n estimator=RandomForestClassifier(n_estimators=10),\n X_training=np.random.rand(10, 10),\n y_training=np.random.randint(0, 2, size=(10,))\n )\n learner.fit(np.random.rand(10, 10), np.random.randint(0, 2, size=(10,)))\n pred = learner.predict(np.random.rand(10, 10))\n learner.predict_proba(np.random.rand(10, 10))\n confusion_matrix(pred, np.random.randint(0, 2, size=(10,)))\n\n def test_sparse_matrices(self):\n query_strategies = [\n modAL.uncertainty.uncertainty_sampling,\n modAL.uncertainty.entropy_sampling,\n modAL.uncertainty.margin_sampling\n ]\n formats = ['lil', 'csc', 'csr']\n sample_count = range(10, 20)\n feature_count = range(1, 5)\n\n for query_strategy, format, n_samples, n_features in product(query_strategies, formats, sample_count, feature_count):\n X_pool = sp.random(n_samples, n_features, format=format)\n y_pool = np.random.randint(0, 2, size=(n_samples, ))\n initial_idx = np.random.choice(range(n_samples), size=5, replace=False)\n\n learner = modAL.models.learners.ActiveLearner(\n estimator=RandomForestClassifier(n_estimators=10), query_strategy=query_strategy,\n X_training=X_pool[initial_idx], y_training=y_pool[initial_idx]\n )\n query_idx, query_inst = learner.query(X_pool)\n learner.teach(X_pool[query_idx], y_pool[query_idx])\n\n\nclass TestBayesianOptimizer(unittest.TestCase):\n def test_set_max(self):\n # case 1: the estimator is not fitted yet\n regressor = mock.MockEstimator()\n learner = modAL.models.learners.BayesianOptimizer(estimator=regressor)\n self.assertEqual(-np.inf, learner.y_max)\n\n # case 2: the estimator is fitted already\n for n_samples in range(1, 100):\n X = np.random.rand(n_samples, 2)\n y = np.random.rand(n_samples, )\n max_val = np.max(y)\n\n regressor = mock.MockEstimator()\n learner = modAL.models.learners.BayesianOptimizer(\n estimator=regressor,\n X_training=X, y_training=y\n )\n np.testing.assert_almost_equal(max_val, learner.y_max)\n\n def test_set_new_max(self):\n for n_reps in range(100):\n # case 1: the learner is not fitted yet\n for n_samples in range(1, 10):\n X = np.random.rand(n_samples, 3)\n y = np.random.rand(n_samples)\n max_idx = np.argmax(y)\n regressor = mock.MockEstimator()\n learner = modAL.models.learners.BayesianOptimizer(estimator=regressor)\n learner._set_max(X, y)\n np.testing.assert_equal(learner.X_max, X[max_idx])\n np.testing.assert_equal(learner.y_max, y[max_idx])\n\n # case 2: new value is not a maximum\n for n_samples in range(1, 10):\n X = np.random.rand(n_samples, 2)\n y = np.random.rand(n_samples)\n\n regressor = mock.MockEstimator()\n learner = modAL.models.learners.BayesianOptimizer(\n estimator=regressor,\n X_training=X, y_training=y\n )\n\n X_new = np.random.rand()\n y_new = y - np.random.rand()\n X_old_max = learner.X_max\n y_old_max = learner.y_max\n learner._set_max(X_new, y_new)\n np.testing.assert_equal(X_old_max, learner.X_max)\n np.testing.assert_equal(y_old_max, learner.y_max)\n\n # case 3: new value is a maximum\n for n_samples in range(1, 10):\n X = np.random.rand(n_samples, 2)\n y = np.random.rand(n_samples)\n\n regressor = mock.MockEstimator()\n learner = modAL.models.learners.BayesianOptimizer(\n estimator=regressor,\n X_training=X, y_training=y\n )\n\n X_new = np.random.rand(n_samples, 2)\n y_new = y + np.random.rand()\n max_idx = np.argmax(y_new)\n learner._set_max(X_new, y_new)\n np.testing.assert_equal(X_new[max_idx], learner.X_max)\n np.testing.assert_equal(y_new[max_idx], learner.y_max)\n\n def test_get_max(self):\n for n_samples in range(1, 100):\n for max_idx in range(0, n_samples):\n X = np.random.rand(n_samples, 3)\n y = np.random.rand(n_samples)\n y[max_idx] = 10\n\n regressor = mock.MockEstimator()\n optimizer = modAL.models.learners.BayesianOptimizer(regressor, X_training=X, y_training=y)\n X_max, y_max = optimizer.get_max()\n np.testing.assert_equal(X_max, X[max_idx])\n np.testing.assert_equal(y_max, y[max_idx])\n\n def test_teach(self):\n for bootstrap, only_new in product([True, False], [True, False]):\n # case 1. optimizer is uninitialized\n for n_samples in range(1, 100):\n for n_features in range(1, 100):\n regressor = mock.MockEstimator()\n learner = modAL.models.learners.BayesianOptimizer(estimator=regressor)\n\n X = np.random.rand(n_samples, 2)\n y = np.random.rand(n_samples)\n learner.teach(X, y, bootstrap=bootstrap, only_new=only_new)\n\n # case 2. optimizer is initialized\n for n_samples in range(1, 100):\n for n_features in range(1, 100):\n X = np.random.rand(n_samples, 2)\n y = np.random.rand(n_samples)\n\n regressor = mock.MockEstimator()\n learner = modAL.models.learners.BayesianOptimizer(\n estimator=regressor,\n X_training=X, y_training=y\n )\n learner.teach(X, y, bootstrap=bootstrap, only_new=only_new)\n\n\nclass TestCommittee(unittest.TestCase):\n\n def test_set_classes(self):\n # 1. test unfitted learners\n for n_learners in range(1, 10):\n learner_list = [modAL.models.learners.ActiveLearner(estimator=mock.MockEstimator(fitted=False))\n for idx in range(n_learners)]\n committee = modAL.models.learners.Committee(learner_list=learner_list)\n self.assertEqual(committee.classes_, None)\n self.assertEqual(committee.n_classes_, 0)\n\n # 2. test fitted learners\n for n_classes in range(1, 10):\n learner_list = [modAL.models.learners.ActiveLearner(estimator=mock.MockEstimator(classes_=np.asarray([idx])))\n for idx in range(n_classes)]\n committee = modAL.models.learners.Committee(learner_list=learner_list)\n np.testing.assert_equal(\n committee.classes_,\n np.unique(range(n_classes))\n )\n\n def test_predict(self):\n for n_learners in range(1, 10):\n for n_instances in range(1, 10):\n prediction = np.random.randint(10, size=(n_instances, n_learners))\n committee = modAL.models.learners.Committee(\n learner_list=[mock.MockActiveLearner(\n mock.MockEstimator(classes_=np.asarray([0])),\n predict_return=prediction[:, learner_idx]\n )\n for learner_idx in range(n_learners)]\n )\n np.testing.assert_equal(\n committee.vote(np.random.rand(n_instances, 5)),\n prediction\n )\n\n def test_predict_proba(self):\n for n_samples in range(1, 100):\n for n_learners in range(1, 10):\n for n_classes in range(1, 10):\n vote_proba_output = np.random.rand(n_samples, n_learners, n_classes)\n # assembling the mock learners\n learner_list = [mock.MockActiveLearner(\n predict_proba_return=vote_proba_output[:, learner_idx, :],\n predictor=mock.MockEstimator(classes_=list(range(n_classes)))\n ) for learner_idx in range(n_learners)]\n committee = modAL.models.learners.Committee(learner_list=learner_list)\n np.testing.assert_almost_equal(\n committee.predict_proba(np.random.rand(n_samples, 1)),\n np.mean(vote_proba_output, axis=1)\n )\n\n def test_vote(self):\n for n_members in range(1, 10):\n for n_instances in range(1, 100):\n vote_output = np.random.randint(0, 2, size=(n_instances, n_members))\n # assembling the Committee\n learner_list = [mock.MockActiveLearner(\n predict_return=vote_output[:, member_idx],\n predictor=mock.MockEstimator(classes_=[0])\n )\n for member_idx in range(n_members)]\n committee = modAL.models.learners.Committee(learner_list=learner_list)\n np.testing.assert_array_almost_equal(\n committee.vote(np.random.rand(n_instances).reshape(-1, 1)),\n vote_output\n )\n\n def test_vote_proba(self):\n for n_samples in range(1, 100):\n for n_learners in range(1, 10):\n for n_classes in range(1, 10):\n vote_proba_output = np.random.rand(n_samples, n_learners, n_classes)\n # assembling the mock learners\n learner_list = [mock.MockActiveLearner(\n predict_proba_return=vote_proba_output[:, learner_idx, :],\n predictor=mock.MockEstimator(classes_=list(range(n_classes)))\n ) for learner_idx in range(n_learners)]\n committee = modAL.models.learners.Committee(learner_list=learner_list)\n np.testing.assert_almost_equal(\n committee.vote_proba(np.random.rand(n_samples, 1)),\n vote_proba_output\n )\n\n def test_teach(self):\n X_training = np.random.rand(10, 2)\n y_training = np.random.randint(0, 2, size=10)\n\n for bootstrap, only_new in product([True, False], [True, False]):\n for n_samples in range(1, 10):\n X = np.random.rand(n_samples, 2)\n y = np.random.randint(0, 2, size=n_samples)\n\n learner_1 = modAL.models.learners.ActiveLearner(\n X_training=X_training, y_training=y_training,\n estimator=mock.MockEstimator(classes_=[0, 1])\n )\n learner_2 = modAL.models.learners.ActiveLearner(\n X_training=X_training, y_training=y_training,\n estimator=mock.MockEstimator(classes_=[0, 1])\n )\n\n committee = modAL.models.learners.Committee(\n learner_list=[learner_1, learner_2]\n )\n\n committee.teach(X, y, bootstrap=bootstrap, only_new=only_new)\n\n\nclass TestCommitteeRegressor(unittest.TestCase):\n\n def test_predict(self):\n for n_members in range(1, 10):\n for n_instances in range(1, 100):\n vote = np.random.rand(n_instances, n_members)\n # assembling the Committee\n learner_list = [mock.MockActiveLearner(predict_return=vote[:, member_idx])\n for member_idx in range(n_members)]\n committee = modAL.models.learners.CommitteeRegressor(learner_list=learner_list)\n np.testing.assert_array_almost_equal(\n committee.predict(np.random.rand(n_instances).reshape(-1, 1), return_std=False),\n np.mean(vote, axis=1)\n )\n np.testing.assert_array_almost_equal(\n committee.predict(np.random.rand(n_instances).reshape(-1, 1), return_std=True),\n (np.mean(vote, axis=1), np.std(vote, axis=1))\n )\n\n def test_vote(self):\n for n_members in range(1, 10):\n for n_instances in range(1, 100):\n vote_output = np.random.rand(n_instances, n_members)\n # assembling the Committee\n learner_list = [mock.MockActiveLearner(predict_return=vote_output[:, member_idx])\n for member_idx in range(n_members)]\n committee = modAL.models.learners.CommitteeRegressor(learner_list=learner_list)\n np.testing.assert_array_almost_equal(\n committee.vote(np.random.rand(n_instances).reshape(-1, 1)),\n vote_output\n )\n\n\nclass TestMultilabel(unittest.TestCase):\n def test_SVM_loss(self):\n for n_classes in range(2, 10):\n for n_instances in range(1, 10):\n X_training = np.random.rand(n_instances, 5)\n y_training = np.random.randint(0, 2, size=(n_instances, n_classes))\n X_pool = np.random.rand(n_instances, 5)\n y_pool = np.random.randint(0, 2, size=(n_instances, n_classes))\n classifier = OneVsRestClassifier(SVC(probability=True, gamma='auto'))\n classifier.fit(X_training, y_training)\n avg_loss = modAL.multilabel._SVM_loss(classifier, X_pool)\n mcc_loss = modAL.multilabel._SVM_loss(classifier, X_pool,\n most_certain_classes=np.random.randint(0, n_classes, size=(n_instances)))\n self.assertEqual(avg_loss.shape, (len(X_pool), ))\n self.assertEqual(mcc_loss.shape, (len(X_pool),))\n\n def test_strategies(self):\n for n_classes in range(3, 10):\n for n_pool_instances in range(1, 10):\n for n_query_instances in range(1, min(n_pool_instances, 3)):\n X_training = np.random.rand(n_pool_instances, 5)\n y_training = np.random.randint(0, 2, size=(n_pool_instances, n_classes))\n X_pool = np.random.rand(n_pool_instances, 5)\n classifier = OneVsRestClassifier(SVC(probability=True, gamma='auto'))\n classifier.fit(X_training, y_training)\n\n active_learner = modAL.models.ActiveLearner(classifier)\n # no random tie break\n modAL.multilabel.SVM_binary_minimum(active_learner, X_pool)\n modAL.multilabel.mean_max_loss(classifier, X_pool, n_query_instances)\n modAL.multilabel.max_loss(classifier, X_pool, n_query_instances)\n modAL.multilabel.min_confidence(classifier, X_pool, n_query_instances)\n modAL.multilabel.avg_confidence(classifier, X_pool, n_query_instances)\n modAL.multilabel.max_score(classifier, X_pool, n_query_instances)\n modAL.multilabel.avg_score(classifier, X_pool, n_query_instances)\n # random tie break\n modAL.multilabel.SVM_binary_minimum(active_learner, X_pool, random_tie_break=True)\n modAL.multilabel.mean_max_loss(classifier, X_pool, n_query_instances, random_tie_break=True)\n modAL.multilabel.max_loss(classifier, X_pool, n_query_instances, random_tie_break=True)\n modAL.multilabel.min_confidence(classifier, X_pool, n_query_instances, random_tie_break=True)\n modAL.multilabel.avg_confidence(classifier, X_pool, n_query_instances, random_tie_break=True)\n modAL.multilabel.max_score(classifier, X_pool, n_query_instances, random_tie_break=True)\n modAL.multilabel.avg_score(classifier, X_pool, n_query_instances, random_tie_break=True)\n\n\nclass TestExamples(unittest.TestCase):\n\n def test_examples(self):\n import example_tests.multidimensional_data\n import example_tests.active_regression\n import example_tests.bagging\n import example_tests.ensemble\n import example_tests.ensemble_regression\n import example_tests.pool_based_sampling\n import example_tests.query_by_committee\n import example_tests.shape_learning\n import example_tests.stream_based_sampling\n import example_tests.custom_query_strategies\n import example_tests.information_density\n import example_tests.bayesian_optimization\n import example_tests.ranked_batch_mode\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n0"
] | [
[
"numpy.linspace",
"numpy.asarray",
"numpy.concatenate",
"scipy.sparse.random",
"numpy.max",
"numpy.mean",
"scipy.sparse.vstack",
"numpy.random.randint",
"numpy.testing.assert_equal",
"scipy.special.ndtr",
"sklearn.ensemble.RandomForestClassifier",
"numpy.unique",
"numpy.testing.assert_almost_equal",
"numpy.std",
"numpy.argmax",
"numpy.zeros",
"numpy.testing.assert_array_almost_equal",
"numpy.random.rand",
"sklearn.svm.SVC",
"numpy.argsort",
"numpy.sum",
"scipy.stats.norm.pdf",
"scipy.spatial.distance.cosine",
"numpy.sort",
"numpy.ones",
"numpy.testing.assert_array_equal",
"numpy.random.permutation",
"sklearn.gaussian_process.GaussianProcessRegressor",
"numpy.prod",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
tsalo/neuropower-core | [
"5f3534063263ac2cb99c71b58ad2a482aa382f03"
] | [
"neuropower/tests/test_cluster.py"
] | [
"from unittest import TestCase\nfrom neuropower import cluster\nimport numpy as np\n\nclass TestCluster(TestCase):\n def test_cluster_output(self):\n np.random.seed(seed=100)\n testSPM = np.random.rand(4,4,4)\n mask = np.zeros((4,4,4))+1\n tab = cluster.cluster(testSPM,0.5,mask)\n self.assertEqual(np.around(tab.peak[1],decimals=2),0.98)\n self.assertEqual(len(tab),6)\n"
] | [
[
"numpy.around",
"numpy.zeros",
"numpy.random.rand",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
henry-li-06/march-madness-bracket | [
"17b4eb83128153a8406893547c70198114f82636"
] | [
"bracket/bracket.py"
] | [
"from model import model, all_games_19\r\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\r\nfrom sklearn.decomposition import PCA\r\nimport pandas as pd\r\n\r\n\r\nclass Node:\r\n '''\r\n Data should be \"N/A\" if the winner hasn't been predicted yet\r\n '''\r\n # vertical separation between nodes\r\n VERTICAL_SEPARATION = [0, 0, 150, 65, 30, 15, 8]\r\n # horizontal separation between nodes\r\n HORIZONTAL_SEPARATION = 80\r\n\r\n data = pd.read_csv('bracket/data/all_games_19_data.csv', index_col=0).drop(\r\n columns=['Away Team', 'Home Team', 'Winner', 'Away Win'])\r\n scaler = MinMaxScaler()\r\n pca = PCA(n_components=8)\r\n pca.fit(scaler.fit_transform(data))\r\n\r\n seeds = [1, 8, 5, 4, 6, 3, 7, 2]\r\n regions = ['East', 'South', 'West', 'Midwest']\r\n\r\n i = 0 # iterator for adding teams\r\n\r\n @classmethod\r\n def init_data(cls, year):\r\n cls.team_data = pd.read_csv('bracket/data/cbb{}.csv'.format(year))\r\n cls.features = list(\r\n cls.team_data.drop(\r\n columns=['TEAM', 'CONF', 'G', 'W', 'POSTSEASON', 'SEED', 'REGION'\r\n ]).columns)\r\n cls.first_round_games = []\r\n for region in cls.regions:\r\n for seed in cls.seeds:\r\n game = []\r\n team1 = cls.team_data.loc[(cls.team_data['SEED'] == seed) &\r\n (cls.team_data['REGION'] == region),\r\n 'TEAM'].reset_index()['TEAM'][0]\r\n team2 = cls.team_data.loc[(cls.team_data['SEED'] == 17 - seed) & (\r\n cls.team_data['REGION'] == region)].reset_index()['TEAM'][0]\r\n game.append(team1)\r\n game.append(team2)\r\n cls.first_round_games.append(game)\r\n\r\n def __init__(self, data, d, x, y):\r\n self.data = data\r\n self.left = None\r\n self.right = None\r\n self.depth = d\r\n self.x = x\r\n self.y = y\r\n\r\n def __str__(self):\r\n return self.data\r\n\r\n def insert(self, data):\r\n if (self.left is None):\r\n self.left = Node(data, self.depth + 1)\r\n elif (self.right is None):\r\n self.right = Node(data, self.depth + 1)\r\n else:\r\n return \"Cannot insert node.\"\r\n\r\n def print_tree(self):\r\n if (not self.left is None):\r\n self.left.print_tree()\r\n # print(self.data)\r\n if (not self.right is None):\r\n self.right.print_tree()\r\n\r\n def create_tree(self):\r\n self.left = Node('N/A', self.depth + 1,\r\n self.x - Node.HORIZONTAL_SEPARATION, self.y)\r\n self.right = Node('N/A', self.depth + 1,\r\n self.x + Node.HORIZONTAL_SEPARATION, self.y)\r\n self.left.create_tree_left()\r\n self.right.create_tree_right()\r\n\r\n def create_tree_left(self):\r\n if (self.depth < 5):\r\n self.left = Node('N/A', self.depth + 1,\r\n self.x - Node.HORIZONTAL_SEPARATION,\r\n self.y + Node.VERTICAL_SEPARATION[self.depth + 1])\r\n self.right = Node(\r\n 'N/A', self.depth + 1, self.x - Node.HORIZONTAL_SEPARATION,\r\n self.y - Node.VERTICAL_SEPARATION[self.depth + 1])\r\n self.left.create_tree_left()\r\n self.right.create_tree_left()\r\n\r\n def create_tree_right(self):\r\n if (self.depth < 5):\r\n self.left = Node('N/A', self.depth + 1,\r\n self.x + Node.HORIZONTAL_SEPARATION,\r\n self.y - Node.VERTICAL_SEPARATION[self.depth + 1])\r\n self.right = Node(\r\n 'N/A', self.depth + 1, self.x + Node.HORIZONTAL_SEPARATION,\r\n self.y + Node.VERTICAL_SEPARATION[self.depth + 1])\r\n self.left.create_tree_right()\r\n self.right.create_tree_right()\r\n\r\n def add_teams(self):\r\n self.left.add_teams_left()\r\n self.right.add_teams_right()\r\n\r\n def add_teams_left(self):\r\n if (self.depth == 5):\r\n self.left = Node(self.first_round_games[Node.i][0], self.depth + 1,\r\n self.x - Node.HORIZONTAL_SEPARATION,\r\n self.y + Node.VERTICAL_SEPARATION[self.depth + 1])\r\n self.right = Node(\r\n self.first_round_games[Node.i][1], self.depth + 1,\r\n self.x - Node.HORIZONTAL_SEPARATION,\r\n self.y - Node.VERTICAL_SEPARATION[self.depth + 1])\r\n Node.i += 1\r\n else:\r\n self.left.add_teams_left()\r\n self.right.add_teams_left()\r\n\r\n def add_teams_right(self):\r\n if (self.depth == 5):\r\n self.left = Node(self.first_round_games[Node.i][0], self.depth + 1,\r\n self.x + Node.HORIZONTAL_SEPARATION,\r\n self.y - Node.VERTICAL_SEPARATION[self.depth + 1])\r\n self.right = Node(\r\n self.first_round_games[Node.i][1], self.depth + 1,\r\n self.x + Node.HORIZONTAL_SEPARATION,\r\n self.y + Node.VERTICAL_SEPARATION[self.depth + 1])\r\n Node.i += 1\r\n else:\r\n self.left.add_teams_right()\r\n self.right.add_teams_right()\r\n\r\n def build_tree(self):\r\n self.create_tree()\r\n self.add_teams()\r\n\r\n def check_tree(self):\r\n if (self.depth == 5):\r\n print(self)\r\n else:\r\n self.left.check_tree()\r\n self.right.check_tree()\r\n\r\n def make_prediction(self):\r\n if (self.left.data != 'N/A'):\r\n self.data = Node.make_game_prediction(self.left.data,\r\n self.right.data)\r\n else:\r\n self.left.make_predictions()\r\n self.right.make_predictions()\r\n\r\n def make_predictions(self):\r\n while (self.data == 'N/A'):\r\n self.make_prediction()\r\n\r\n @classmethod\r\n def make_game_prediction(cls, away_team, home_team):\r\n inputs = []\r\n for feature in cls.features:\r\n away_team_val = cls.team_data.loc[\r\n cls.team_data['TEAM'] == away_team,\r\n [feature]].reset_index()[feature][0]\r\n home_team_val = cls.team_data.loc[\r\n cls.team_data['TEAM'] == home_team,\r\n [feature]].reset_index()[feature][0]\r\n inputs.append(away_team_val - home_team_val)\r\n\r\n scaled_features = cls.scaler.transform([inputs])\r\n pca_projection = cls.pca.transform(scaled_features)\r\n prediction = model.predict(pca_projection)\r\n return away_team if prediction[0] == 'Y' else home_team\r\n"
] | [
[
"pandas.read_csv",
"sklearn.decomposition.PCA",
"sklearn.preprocessing.MinMaxScaler"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
r-kapoor/dig-network | [
"1e17132140d28cc1e302d4749833700c86927c9b"
] | [
"sampling_experiments.py"
] | [
"import json\nimport codecs\nimport tldextract\nimport pickle\nimport random\nimport copy\nimport matplotlib.pyplot as plt\n\n# One of 'city', 'name', 'phone'\nVARIABLE = 'phone'\n\nwith open('backpage.com/nebraska.json', \"rb\") as fp:\n urls = pickle.load(fp)\n\ncount = 0\n\ndef preprocess(urls):\n ad_to_extraction = dict()\n extraction_to_ad = dict()\n ad_extraction_pairs = list()\n ad_extraction_pairs_true = set()\n\n ad_id = 0\n\n for key, value in urls.items():\n if VARIABLE in value['ground_truth']:\n set_t = value['ground_truth'][VARIABLE]\n\n if VARIABLE in value['high_precision']:\n set_hr = value['high_precision'][VARIABLE]\n else:\n continue\n\n if len(set_hr) == 0:\n continue\n\n ad_to_extraction[ad_id] = set_hr\n\n for extraction in set_hr:\n if extraction in extraction_to_ad:\n extraction_to_ad[extraction].append(ad_id)\n else:\n extraction_to_ad[extraction] = [ad_id]\n\n ad_extraction_pairs.append((ad_id, extraction))\n\n for extraction in set_t:\n ad_extraction_pairs_true.add((ad_id, extraction))\n\n ad_id += 1\n\n return ad_to_extraction, extraction_to_ad, ad_extraction_pairs, ad_extraction_pairs_true\n\ndef sample_edges_directly(ad_extraction_pairs, num):\n return random.sample(ad_extraction_pairs, num)\n\ndef check_if_zero(dictionary):\n for key, values in dictionary.items():\n if len(values) == 0:\n print(key,\":\",values,\" EMPTY\")\n exit()\n\ndef sample_edges_from_ads(ad_to_extraction, num):\n sampled_edges = list()\n ads_list = list(ad_to_extraction)\n if(num < len(ad_to_extraction)):\n # Need to sample just num ads and then 1 from each\n sampled_ads = random.sample(ads_list, num)\n for sampled_ad in sampled_ads:\n samples_extraction = random.choice(list(ad_to_extraction[sampled_ad]))\n sampled_edges.append((sampled_ad, samples_extraction))\n else:\n print(\"Num Out of Bounds Ads:\", num)\n dict_copy = copy.deepcopy(ad_to_extraction)\n # check_if_zero(dict_copy)\n removal_list = list()\n # Sample 1 from each extraction without replacement\n for sampled_ad, extractions in dict_copy.items():\n # if len(dict_copy[sampled_ad]) == 0:\n # print(sampled_ad)\n sampled_extraction = random.choice(list(dict_copy[sampled_ad]))\n sampled_edges.append((sampled_ad, sampled_extraction))\n dict_copy[sampled_ad].remove(sampled_extraction)\n if len(dict_copy[sampled_ad]) == 0:\n removal_list.append(sampled_ad)\n\n for value in removal_list:\n del dict_copy[value]\n\n # check_if_zero(dict_copy)\n\n # Repeatedly sample\n while len(sampled_edges) < num:\n sampled_ad = random.choice(list(dict_copy))\n # if len(dict_copy[sampled_ad]) == 0:\n # print(sampled_ad)\n sampled_extraction = random.choice(list(dict_copy[sampled_ad]))\n sampled_edges.append((sampled_ad, sampled_extraction))\n dict_copy[sampled_ad].remove(sampled_extraction)\n if len(dict_copy[sampled_ad]) == 0:\n del dict_copy[sampled_ad]\n return sampled_edges\n\ndef sample_edges_from_extractions(extraction_to_ad, num):\n sampled_edges = list()\n extractions_list = list(extraction_to_ad)\n if num < len(extraction_to_ad):\n sampled_extractions = random.sample(extractions_list, num)\n for sampled_extraction in sampled_extractions:\n sampled_ad = random.choice(list(extraction_to_ad[sampled_extraction]))\n sampled_edges.append((sampled_ad, sampled_extraction))\n else:\n print(\"Num Out of Bounds Extrac:\", num)\n dict_copy = copy.deepcopy(extraction_to_ad)\n removal_list = list()\n # Sample 1 from each extraction without replacement\n for sampled_extraction, ads in dict_copy.items():\n sampled_ad = random.choice(list(dict_copy[sampled_extraction]))\n sampled_edges.append((sampled_ad, sampled_extraction))\n dict_copy[sampled_extraction].remove(sampled_ad)\n if len(dict_copy[sampled_extraction]) == 0:\n removal_list.append(sampled_extraction)\n\n for value in removal_list:\n del dict_copy[value]\n\n # Repeatedly sample \n while len(sampled_edges) < num:\n sampled_extraction = random.choice(list(dict_copy))\n sampled_ad = random.choice(list(dict_copy[sampled_extraction]))\n sampled_edges.append((sampled_ad, sampled_extraction))\n dict_copy[sampled_extraction].remove(sampled_ad)\n if len(dict_copy[sampled_extraction]) == 0:\n del dict_copy[sampled_extraction]\n\n return sampled_edges\n\ndef get_accuracy(ad_extraction_pairs_true, sampled_edges):\n correct_count = 0\n incorrect_count = 0\n for sampled_edge in sampled_edges:\n if sampled_edge in ad_extraction_pairs_true:\n correct_count += 1\n else:\n incorrect_count += 1\n\n return correct_count/(correct_count+incorrect_count)\n\nad_to_extraction, extraction_to_ad, ad_extraction_pairs, ad_extraction_pairs_true = preprocess(urls)\n\nprint(\"Num Ads:\", len(ad_to_extraction))\nprint(\"Num Extr:\", len(extraction_to_ad))\nprint(\"Number of True Ad Extraction pairs:\", len(ad_extraction_pairs_true))\nprint(\"Number of HR Ad Extraction pairs:\", len(ad_extraction_pairs))\n\nSAMPLING_RATES = [0.01, 0.02, 0.05, 0.08, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\ndirectly_accuracy = list()\nextractions_accuracy = list()\nad_accuracy = list()\n\ntotal_values = len(ad_extraction_pairs)\nfor rate in SAMPLING_RATES:\n num_to_sample = (int)(rate*total_values)\n print(\"Sampling \", num_to_sample, \"at \", rate, \" rate\")\n directly_accuracy_samples = list()\n extractions_accuracy_samples = list()\n ad_accuracy_samples = list()\n\n for iteration in range(5):\n print(\"Iteration:\", iteration)\n directly_sampled_edges = sample_edges_directly(ad_extraction_pairs, num_to_sample)\n extractions_sampled_edges = sample_edges_from_extractions(extraction_to_ad, num_to_sample)\n ad_sampled_edges = sample_edges_from_ads(ad_to_extraction, num_to_sample)\n\n directly_accuracy_samples.append(get_accuracy(ad_extraction_pairs_true, directly_sampled_edges))\n extractions_accuracy_samples.append(get_accuracy(ad_extraction_pairs_true, extractions_sampled_edges))\n ad_accuracy_samples.append(get_accuracy(ad_extraction_pairs_true, ad_sampled_edges))\n\n directly_accuracy.append(sum(directly_accuracy_samples)/len(directly_accuracy_samples))\n extractions_accuracy.append(sum(extractions_accuracy_samples)/len(extractions_accuracy_samples))\n ad_accuracy.append(sum(ad_accuracy_samples)/len(ad_accuracy_samples))\n\nprint(directly_accuracy)\nprint(extractions_accuracy)\nprint(ad_accuracy)\n\ntrue_accuracy = [directly_accuracy[len(directly_accuracy)-1]] * len(directly_accuracy)\nplt.plot(SAMPLING_RATES, directly_accuracy, 'b-', label='Sample Edges Directly')\nplt.plot(SAMPLING_RATES, extractions_accuracy, 'g-', label='Sample Extraction Nodes')\nplt.plot(SAMPLING_RATES, ad_accuracy, 'r-', label='Sample from Ad Nodes')\nplt.plot(SAMPLING_RATES, true_accuracy, 'k-', label='True')\nplt.ylabel('Accuracy')\nplt.xlabel('Sampling Rate')\nplt.legend()\nplt.show()\n\n\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
swemoney/adventofcode2020 | [
"94c3c032e68b182881dc545771a79fd884b7cf93"
] | [
"day/day11part1.py"
] | [
"from functools import cached_property\nfrom puzzle import Puzzle # pylint: disable=import-error\nfrom enum import Enum, auto\nimport numpy as np\n\nclass SeatStatus(Enum):\n occupied = \"#\"\n unoccupied = \"L\"\n floor = \".\"\n \nclass Seat:\n status: SeatStatus\n\n def __init__(self, seat_string):\n self.status = SeatStatus(seat_string)\n\n @property\n def flipped(self):\n if self.status == SeatStatus.unoccupied:\n return SeatStatus.occupied\n if self.status == SeatStatus.occupied:\n return SeatStatus.unoccupied\n return SeatStatus.floor\n\n @property\n def is_floor(self):\n return self.status == SeatStatus.floor\n\n @property\n def is_occupied(self):\n return self.status == SeatStatus.occupied\n\n @property\n def is_unoccupied(self):\n return self.status == SeatStatus.unoccupied\n\n def __eq__(self, other):\n return self.status == other.status\n\nclass SeatMap:\n def __init__(self, seat_map):\n self.seats = []\n for row in seat_map:\n self.seats.append([Seat(col) for col in row])\n\n @property\n def unoccupied_count(self):\n return sum([[seat.status for seat in row].count(SeatStatus.unoccupied) for row in self.seats])\n\n @property\n def occupied_count(self):\n return sum([[seat.status for seat in row].count(SeatStatus.occupied) for row in self.seats])\n\n def simulate_people(self):\n new_seats = []\n for row, row_seats in enumerate(self.seats):\n new_row = []\n for col, seat in enumerate(row_seats):\n new_seat = Seat(seat.flipped.value) if self.should_flip_seat(row,col) else seat\n new_row.append(new_seat)\n new_seats.append(new_row)\n if np.array_equal(self.seats, new_seats):\n return\n self.seats = new_seats\n self.simulate_people()\n\n def should_flip_seat(self, row, col):\n seat = self.seats[row][col]\n neighbors = self.neighbors(row, col)\n if seat.is_floor: return False\n if (seat.is_unoccupied) and (SeatStatus.occupied not in [n.status for n in neighbors]):\n return True\n if (seat.is_occupied) and ([n.status for n in neighbors].count(SeatStatus.occupied) >= 4):\n return True\n return False\n\n def neighbors(self, row, col):\n neighbors = []\n for i in (-1, 0, 1):\n for j in (-1, 0, 1):\n n_row, n_col = (row + i, col + j)\n if i == 0 and j == 0: continue # Starting seat\n if n_row < 0 or n_col < 0: continue # Don't wrap around\n if n_row > len(self.seats)-1: continue # Out of bounds\n if n_col > len(self.seats[i])-1: continue # Out of bounds\n neighbors.append(self.seats[n_row][n_col])\n return neighbors\n\nclass Day11Part1:\n puzzle = None\n\n def run(self):\n seat_map = SeatMap(self.parsed_input)\n seat_map.simulate_people()\n print(seat_map.occupied_count)\n\n @cached_property\n def parsed_input(self):\n return [list(line.strip('\\n')) for line in self.puzzle.input]\n "
] | [
[
"numpy.array_equal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
spencels/mnist_cnn | [
"80ffcae1a453e38c571b62d3e70dd69dc32bfced"
] | [
"process_data.py"
] | [
"#!/usr/bin/env python\n# MNIST data pre-processing script.\nimport gzip\nimport struct\nimport sys\nimport functools\nimport subprocess\nfrom distutils import sysconfig\nimport imp\nimport cProfile as profile\nimport pstats\nimport io\n\nimport cv2\nimport numpy as np\nimport scipy as sp\nfrom scipy import ndimage\nimport matplotlib.pyplot as plt\n\ndef load_cython(lib):\n subprocess.check_call(\n ['cython', '-a', lib + '.pyx'])\n\n headers = sysconfig.get_python_inc()\n subprocess.check_call(\n ['gcc', '-shared', '-pthread', '-fPIC', '-fwrapv', '-O2', '-Wall',\n '-fno-strict-aliasing', '-fopenmp', '-I' + headers, '-o', lib + '.so', lib + '.c'])\n return imp.load_dynamic(lib, lib + '.so')\n\ndistort_images = load_cython('distort_images')\n\n\ndef read_images(file):\n \"\"\"Reads MNIST file into numpy tensor.\"\"\"\n # From https://gist.github.com/tylerneylon/ce60e8a06e7506ac45788443f7269e40\n zero, data_type, dims = struct.unpack('>HBB', file.read(4))\n shape = tuple(struct.unpack('>I', file.read(4))[0] for d in range(dims))\n return np.fromstring(file.read(), dtype=np.uint8).reshape(shape)\n\n\ndef save_images(images, file):\n \"\"\"Save images array to outfile.\"\"\"\n file.write(b'\\x00\\x00\\x08') # Header\n file.write(struct.pack('>B', len(images.shape)))\n for dimension in images.shape:\n file.write(struct.pack('>I', dimension))\n file.write(images.tobytes())\n\n\ndef read_labels(file):\n zero, data_type, dims = struct.unpack('>HBB', file.read(4))\n count = struct.unpack('>I', file.read(4))\n return np.fromstring(file.read(), dtype=np.uint8)\n\n\ndef save_labels(labels, file):\n file.write(b'\\x00\\x00\\x08\\x01')\n file.write(struct.pack('>I', labels.shape[0]))\n file.write(labels.tobytes())\n\n\ndef elastic_distort(images, sigma=4, alpha=34, kernel_size=33):\n \"\"\"Distort elastically.\"\"\"\n # Create distortion vector field.\n shape = images.shape\n randoms = np.random.uniform(\n -1, 1, (shape[0], shape[1], shape[2], 2)) * alpha\n filtered1d = ndimage.filters.gaussian_filter(\n input=randoms,\n sigma=(0, 0, sigma, 0),\n order=0,\n mode='constant',\n cval=0.0)\n filtered2d = ndimage.filters.gaussian_filter(\n input=filtered1d,\n sigma=(0, sigma, 0, 0),\n order=0,\n mode='constant',\n cval=0.0)\n\n # Distort.\n # plt.imshow(np.concatenate((filtered2d[0], np.zeros((28, 28, 1))), axis=2))\n # plt.show()\n return distort_images.distort_images(images, filtered2d.astype(np.float32))\n\n\ndef compare_n_images(input_images, output_images, n):\n for i in range(n):\n figure = plt.figure()\n f1 = figure.add_subplot(1, 2, 1)\n plt.imshow(input_images[i], cmap='gray')\n f2 = figure.add_subplot(1, 2, 2)\n plt.imshow(output_images[i], cmap='gray')\n plt.show()\n\n\ndef process_images(images, distort):\n # Elastic distortions.\n if distort:\n images = elastic_distort(images, sigma=4, alpha=34)\n\n # This originally used ndimage.interpolate.zoom to scale images to 29x29. For\n # some reason this caused accuracy losses. Rather than debug the issues, the\n # resampling was moved to the live model because there was no loss in training\n # speed.\n return images\n\n\ndef augment_dataset(\n input_filename,\n labels_filename,\n output_filename,\n output_labels_filename,\n duplication=1,\n distort=True):\n print('Reading images.')\n with gzip.open(input_filename, 'rb') as infile:\n input_images = read_images(infile)\n\n # Augment.\n print('Processing images.')\n output_images = np.empty((0, 28, 28), dtype=np.uint8)\n for i in range(duplication):\n output_images = np.concatenate(\n (output_images, process_images(input_images, distort)), axis=0)\n\n # compare_n_images(input_images, output_images, 5)\n\n print('Writing images.')\n with open(output_filename, 'wb') as outfile:\n save_images(output_images, outfile)\n\n # Labels.\n print('Processing and writing labels.')\n with gzip.open(labels_filename, 'rb') as infile:\n labels = read_labels(infile)\n labels = np.tile(labels, duplication)\n with open(output_labels_filename, 'wb') as outfile:\n save_labels(labels, outfile)\n\n print('Done.')\n\n\ndef main(argv):\n augment_dataset(\n 'MNIST_data/train-images-idx3-ubyte.gz',\n 'MNIST_data/train-labels-idx1-ubyte.gz',\n 'MNIST_data/train-images-processed',\n 'MNIST_data/train-labels-processed',\n distort=True,\n duplication=8)\n\n augment_dataset(\n 'MNIST_data/t10k-images-idx3-ubyte.gz',\n 'MNIST_data/t10k-labels-idx1-ubyte.gz',\n 'MNIST_data/t10k-images-processed',\n 'MNIST_data/t10k-labels-processed',\n distort=False)\n\nif __name__ == '__main__':\n main(sys.argv)"
] | [
[
"matplotlib.pyplot.imshow",
"numpy.tile",
"scipy.ndimage.filters.gaussian_filter",
"numpy.random.uniform",
"matplotlib.pyplot.show",
"numpy.empty",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"0.16",
"1.0",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"0.10",
"0.17",
"1.3"
],
"tensorflow": []
}
] |
zlazow/cclabel | [
"06510f09decd52a77a20780e0ac8378f3aad6a5c"
] | [
"Miscel/Image Histogram and Check Pixels Script.py"
] | [
"from PIL import Image\nimport numpy as np\nfrom numpy import array\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\n\n\nfilename = raw_input(\"Filename: \")\nimg = Image.open(filename)\narr = array(img)\n\n\n# the histogram of the data\nn, bins, patches = plt.hist(arr, 50, normed=1, facecolor='green', alpha=0.75)\n\nplt.xlabel('Pixel Value')\nplt.ylabel('Frequency')\nplt.title(\"NDVI\")\nplt.axis([80, 160, 0, .06])\nplt.grid(True)\n\nplt.show()\n#count = 0.0\n#size = arr.shape[0] * arr.shape[1]\n#for y in range(arr.shape[1]):\n# for x in range(arr.shape[0]):\n# if np.all(arr[x,y]):\n# count +=1\n#\n#print count/size\n#print count\n#print size \n\n\n\n#filename2 = raw_input(\"Filename2: \")\n#img2 = Image.open(filename2)\n#arr2 = array(img2)\n"
] | [
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
9465565598/ThaparWorkshopANN | [
"e141cd8f3e600f35826516738188e87ac3480fc3"
] | [
"scikit-learn/figures/plot_interactive_tree.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import make_blobs\nfrom sklearn.tree import DecisionTreeClassifier\n\nfrom scipy import ndimage\n\nfrom .tree_plotting import plot_tree as plot_tree_mpl\n\nX, y = make_blobs(centers=[[0, 0], [1, 1]], random_state=61526, n_samples=50)\n\n\ndef plot_tree(max_depth=1):\n fig, ax = plt.subplots(1, 2, figsize=(10, 5))\n h = 0.02\n\n x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\n y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n\n if max_depth != 0:\n tree = DecisionTreeClassifier(max_depth=max_depth, random_state=1)\n tree.fit(X, y)\n Z = tree.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]\n Z = Z.reshape(xx.shape)\n faces = tree.tree_.apply(\n np.c_[xx.ravel(), yy.ravel()].astype(np.float32))\n faces = faces.reshape(xx.shape)\n border = ndimage.laplace(faces) != 0\n ax[0].contourf(xx, yy, Z, alpha=.4, cmap='RdBu_r')\n ax[0].scatter(xx[border], yy[border], marker='.', s=1)\n ax[0].set_title(\"max_depth = %d\" % max_depth)\n plot_tree_mpl(tree, ax=ax[1], impurity=False, filled=True)\n # ax[1].axis(\"off\")\n else:\n ax[0].set_title(\"data set\")\n ax[1].set_visible(False)\n ax[0].scatter(X[:, 0], X[:, 1], c=np.array(['tab:blue', 'tab:red'])[y],\n s=60)\n ax[0].set_xlim(x_min, x_max)\n ax[0].set_ylim(y_min, y_max)\n ax[0].set_xticks(())\n ax[0].set_yticks(())\n\n\ndef plot_tree_interactive():\n from ipywidgets import interactive, IntSlider\n slider = IntSlider(min=0, max=8, step=1, value=0)\n return interactive(plot_tree, max_depth=slider)\n"
] | [
[
"scipy.ndimage.laplace",
"numpy.arange",
"matplotlib.pyplot.subplots",
"sklearn.tree.DecisionTreeClassifier",
"numpy.array",
"sklearn.datasets.make_blobs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.