repo_name
stringlengths
8
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
dom-s/transformers
[ "83446a88d902661fab12bf8c37a1aa2845cdca5f" ]
[ "src/transformers/modeling_albert.py" ]
[ "# coding=utf-8\n# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"PyTorch ALBERT model. \"\"\"\n\nimport logging\nimport math\nimport os\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\n\nfrom transformers.configuration_albert import AlbertConfig\nfrom transformers.modeling_bert import ACT2FN, BertEmbeddings, BertSelfAttention, prune_linear_layer\nfrom transformers.modeling_utils import PreTrainedModel\n\nfrom .file_utils import add_start_docstrings, add_start_docstrings_to_callable\n\n\nlogger = logging.getLogger(__name__)\n\n\nALBERT_PRETRAINED_MODEL_ARCHIVE_MAP = {\n \"albert-base-v1\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-pytorch_model.bin\",\n \"albert-large-v1\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-large-pytorch_model.bin\",\n \"albert-xlarge-v1\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-pytorch_model.bin\",\n \"albert-xxlarge-v1\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-pytorch_model.bin\",\n \"albert-base-v2\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v2-pytorch_model.bin\",\n \"albert-large-v2\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-large-v2-pytorch_model.bin\",\n \"albert-xlarge-v2\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-v2-pytorch_model.bin\",\n \"albert-xxlarge-v2\": \"https://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-v2-pytorch_model.bin\",\n}\n\n\ndef load_tf_weights_in_albert(model, config, tf_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model.\"\"\"\n try:\n import re\n import numpy as np\n import tensorflow as tf\n except ImportError:\n logger.error(\n \"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\"\n )\n raise\n tf_path = os.path.abspath(tf_checkpoint_path)\n logger.info(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n logger.info(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array)\n\n for name, array in zip(names, arrays):\n print(name)\n\n for name, array in zip(names, arrays):\n original_name = name\n\n # If saved from the TF HUB module\n name = name.replace(\"module/\", \"\")\n\n # Renaming and simplifying\n name = name.replace(\"ffn_1\", \"ffn\")\n name = name.replace(\"bert/\", \"albert/\")\n name = name.replace(\"attention_1\", \"attention\")\n name = name.replace(\"transform/\", \"\")\n name = name.replace(\"LayerNorm_1\", \"full_layer_layer_norm\")\n name = name.replace(\"LayerNorm\", \"attention/LayerNorm\")\n name = name.replace(\"transformer/\", \"\")\n\n # The feed forward layer had an 'intermediate' step which has been abstracted away\n name = name.replace(\"intermediate/dense/\", \"\")\n name = name.replace(\"ffn/intermediate/output/dense/\", \"ffn_output/\")\n\n # ALBERT attention was split between self and output which have been abstracted away\n name = name.replace(\"/output/\", \"/\")\n name = name.replace(\"/self/\", \"/\")\n\n # The pooler is a linear layer\n name = name.replace(\"pooler/dense\", \"pooler\")\n\n # The classifier was simplified to predictions from cls/predictions\n name = name.replace(\"cls/predictions\", \"predictions\")\n name = name.replace(\"predictions/attention\", \"predictions\")\n\n # Naming was changed to be more explicit\n name = name.replace(\"embeddings/attention\", \"embeddings\")\n name = name.replace(\"inner_group_\", \"albert_layers/\")\n name = name.replace(\"group_\", \"albert_layer_groups/\")\n\n # Classifier\n if len(name.split(\"/\")) == 1 and (\"output_bias\" in name or \"output_weights\" in name):\n name = \"classifier/\" + name\n\n # No ALBERT model currently handles the next sentence prediction task\n if \"seq_relationship\" in name:\n continue\n\n name = name.split(\"/\")\n\n # Ignore the gradients applied by the LAMB/ADAM optimizers.\n if \"adam_m\" in name or \"adam_v\" in name or \"global_step\" in name:\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n\n pointer = model\n for m_name in name:\n if re.fullmatch(r\"[A-Za-z]+_\\d+\", m_name):\n scope_names = re.split(r\"_(\\d+)\", m_name)\n else:\n scope_names = [m_name]\n\n if scope_names[0] == \"kernel\" or scope_names[0] == \"gamma\":\n pointer = getattr(pointer, \"weight\")\n elif scope_names[0] == \"output_bias\" or scope_names[0] == \"beta\":\n pointer = getattr(pointer, \"bias\")\n elif scope_names[0] == \"output_weights\":\n pointer = getattr(pointer, \"weight\")\n elif scope_names[0] == \"squad\":\n pointer = getattr(pointer, \"classifier\")\n else:\n try:\n pointer = getattr(pointer, scope_names[0])\n except AttributeError:\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n if len(scope_names) >= 2:\n num = int(scope_names[1])\n pointer = pointer[num]\n\n if m_name[-11:] == \"_embeddings\":\n pointer = getattr(pointer, \"weight\")\n elif m_name == \"kernel\":\n array = np.transpose(array)\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n print(\"Initialize PyTorch weight {} from {}\".format(name, original_name))\n pointer.data = torch.from_numpy(array)\n\n return model\n\n\nclass AlbertEmbeddings(BertEmbeddings):\n \"\"\"\n Construct the embeddings from word, position and token_type embeddings.\n \"\"\"\n\n def __init__(self, config):\n super().__init__(config)\n\n self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=0)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)\n self.LayerNorm = torch.nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)\n\n\nclass AlbertAttention(BertSelfAttention):\n def __init__(self, config):\n super().__init__(config)\n\n self.output_attentions = config.output_attentions\n self.num_attention_heads = config.num_attention_heads\n self.hidden_size = config.hidden_size\n self.attention_head_size = config.hidden_size // config.num_attention_heads\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.pruned_heads = set()\n\n def prune_heads(self, heads):\n if len(heads) == 0:\n return\n mask = torch.ones(self.num_attention_heads, self.attention_head_size)\n heads = set(heads) - self.pruned_heads # Convert to set and emove already pruned heads\n for head in heads:\n # Compute how many pruned heads are before the head and move the index accordingly\n head = head - sum(1 if h < head else 0 for h in self.pruned_heads)\n mask[head] = 0\n mask = mask.view(-1).contiguous().eq(1)\n index = torch.arange(len(mask))[mask].long()\n\n # Prune linear layers\n self.query = prune_linear_layer(self.query, index)\n self.key = prune_linear_layer(self.key, index)\n self.value = prune_linear_layer(self.value, index)\n self.dense = prune_linear_layer(self.dense, index, dim=1)\n\n # Update hyper params and store pruned heads\n self.num_attention_heads = self.num_attention_heads - len(heads)\n self.all_head_size = self.attention_head_size * self.num_attention_heads\n self.pruned_heads = self.pruned_heads.union(heads)\n\n def forward(self, input_ids, attention_mask=None, head_mask=None):\n mixed_query_layer = self.query(input_ids)\n mixed_key_layer = self.key(input_ids)\n mixed_value_layer = self.value(input_ids)\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 if attention_mask is not None:\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 # Mask heads if we want to\n if head_mask is not None:\n attention_probs = attention_probs * head_mask\n\n context_layer = torch.matmul(attention_probs, value_layer)\n\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n\n # Should find a better way to do this\n w = (\n self.dense.weight.t()\n .view(self.num_attention_heads, self.attention_head_size, self.hidden_size)\n .to(context_layer.dtype)\n )\n b = self.dense.bias.to(context_layer.dtype)\n\n projected_context_layer = torch.einsum(\"bfnd,ndh->bfh\", context_layer, w) + b\n projected_context_layer_dropout = self.dropout(projected_context_layer)\n layernormed_context_layer = self.LayerNorm(input_ids + projected_context_layer_dropout)\n return (layernormed_context_layer, attention_probs) if self.output_attentions else (layernormed_context_layer,)\n\n\nclass AlbertLayer(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n self.config = config\n self.full_layer_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.attention = AlbertAttention(config)\n self.ffn = nn.Linear(config.hidden_size, config.intermediate_size)\n self.ffn_output = nn.Linear(config.intermediate_size, config.hidden_size)\n self.activation = ACT2FN[config.hidden_act]\n\n def forward(self, hidden_states, attention_mask=None, head_mask=None):\n attention_output = self.attention(hidden_states, attention_mask, head_mask)\n ffn_output = self.ffn(attention_output[0])\n ffn_output = self.activation(ffn_output)\n ffn_output = self.ffn_output(ffn_output)\n hidden_states = self.full_layer_layer_norm(ffn_output + attention_output[0])\n\n return (hidden_states,) + attention_output[1:] # add attentions if we output them\n\n\nclass AlbertLayerGroup(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.albert_layers = nn.ModuleList([AlbertLayer(config) for _ in range(config.inner_group_num)])\n\n def forward(self, hidden_states, attention_mask=None, head_mask=None):\n layer_hidden_states = ()\n layer_attentions = ()\n\n for layer_index, albert_layer in enumerate(self.albert_layers):\n layer_output = albert_layer(hidden_states, attention_mask, head_mask[layer_index])\n hidden_states = layer_output[0]\n\n if self.output_attentions:\n layer_attentions = layer_attentions + (layer_output[1],)\n\n if self.output_hidden_states:\n layer_hidden_states = layer_hidden_states + (hidden_states,)\n\n outputs = (hidden_states,)\n if self.output_hidden_states:\n outputs = outputs + (layer_hidden_states,)\n if self.output_attentions:\n outputs = outputs + (layer_attentions,)\n return outputs # last-layer hidden state, (layer hidden states), (layer attentions)\n\n\nclass AlbertTransformer(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n self.config = config\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.embedding_hidden_mapping_in = nn.Linear(config.embedding_size, config.hidden_size)\n self.albert_layer_groups = nn.ModuleList([AlbertLayerGroup(config) for _ in range(config.num_hidden_groups)])\n\n def forward(self, hidden_states, attention_mask=None, head_mask=None):\n hidden_states = self.embedding_hidden_mapping_in(hidden_states)\n\n all_attentions = ()\n\n if self.output_hidden_states:\n all_hidden_states = (hidden_states,)\n\n for i in range(self.config.num_hidden_layers):\n # Number of layers in a hidden group\n layers_per_group = int(self.config.num_hidden_layers / self.config.num_hidden_groups)\n\n # Index of the hidden group\n group_idx = int(i / (self.config.num_hidden_layers / self.config.num_hidden_groups))\n\n layer_group_output = self.albert_layer_groups[group_idx](\n hidden_states,\n attention_mask,\n head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group],\n )\n hidden_states = layer_group_output[0]\n\n if self.output_attentions:\n all_attentions = all_attentions + layer_group_output[-1]\n\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n outputs = (hidden_states,)\n if self.output_hidden_states:\n outputs = outputs + (all_hidden_states,)\n if self.output_attentions:\n outputs = outputs + (all_attentions,)\n return outputs # last-layer hidden state, (all hidden states), (all attentions)\n\n\nclass AlbertPreTrainedModel(PreTrainedModel):\n \"\"\" An abstract class to handle weights initialization and\n a simple interface for downloading and loading pretrained models.\n \"\"\"\n\n config_class = AlbertConfig\n pretrained_model_archive_map = ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP\n base_model_prefix = \"albert\"\n\n def _init_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if isinstance(module, (nn.Linear)) and module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n\nALBERT_START_DOCSTRING = r\"\"\"\n\n This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class.\n Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general\n usage and behavior.\n\n Args:\n config (:class:`~transformers.AlbertConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the configuration.\n Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.\n\"\"\"\n\nALBERT_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using :class:`transformers.AlbertTokenizer`.\n See :func:`transformers.PreTrainedTokenizer.encode` and\n :func:`transformers.PreTrainedTokenizer.encode_plus` for details.\n\n `What are input IDs? <../glossary.html#input-ids>`__\n attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Segment token indices to indicate first and second portions of the inputs.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n corresponds to a `sentence B` token\n\n `What are token type IDs? <../glossary.html#token-type-ids>`_\n position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Indices of positions of each input sequence tokens in the position embeddings.\n Selected in the range ``[0, config.max_position_embeddings - 1]``.\n\n `What are position IDs? <../glossary.html#position-ids>`_\n head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n :obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.\n input_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):\n Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert `input_ids` indices into associated vectors\n than the model's internal embedding lookup matrix.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare ALBERT Model transformer outputting raw hidden-states without any specific head on top.\",\n ALBERT_START_DOCSTRING,\n)\nclass AlbertModel(AlbertPreTrainedModel):\n\n config_class = AlbertConfig\n pretrained_model_archive_map = ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP\n load_tf_weights = load_tf_weights_in_albert\n base_model_prefix = \"albert\"\n\n def __init__(self, config):\n super().__init__(config)\n\n self.config = config\n self.embeddings = AlbertEmbeddings(config)\n self.encoder = AlbertTransformer(config)\n self.pooler = nn.Linear(config.hidden_size, config.hidden_size)\n self.pooler_activation = nn.Tanh()\n\n self.init_weights()\n\n def get_input_embeddings(self):\n return self.embeddings.word_embeddings\n\n def set_input_embeddings(self, value):\n self.embeddings.word_embeddings = value\n\n def _resize_token_embeddings(self, new_num_tokens):\n old_embeddings = self.embeddings.word_embeddings\n new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)\n self.embeddings.word_embeddings = new_embeddings\n return self.embeddings.word_embeddings\n\n def _prune_heads(self, heads_to_prune):\n \"\"\" Prunes heads of the model.\n heads_to_prune: dict of {layer_num: list of heads to prune in this layer}\n ALBERT has a different architecture in that its layers are shared across groups, which then has inner groups.\n If an ALBERT model has 12 hidden layers and 2 hidden groups, with two inner groups, there\n is a total of 4 different layers.\n\n These layers are flattened: the indices [0,1] correspond to the two inner groups of the first hidden layer,\n while [2,3] correspond to the two inner groups of the second hidden layer.\n\n Any layer with in index other than [0,1,2,3] will result in an error.\n See base class PreTrainedModel for more information about head pruning\n \"\"\"\n for layer, heads in heads_to_prune.items():\n group_idx = int(layer / self.config.inner_group_num)\n inner_group_idx = int(layer - group_idx * self.config.inner_group_num)\n self.encoder.albert_layer_groups[group_idx].albert_layers[inner_group_idx].attention.prune_heads(heads)\n\n @add_start_docstrings_to_callable(ALBERT_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n ):\n r\"\"\"\n Return:\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.AlbertConfig`) and inputs:\n last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the model.\n pooler_output (:obj:`torch.FloatTensor`: of shape :obj:`(batch_size, hidden_size)`):\n Last layer hidden-state of the first token of the sequence (classification token)\n further processed by a Linear layer and a Tanh activation function. The Linear\n layer weights are trained from the next sentence prediction (classification)\n objective during pre-training.\n\n This output is usually *not* a good summary\n of the semantic content of the input, you're often better with averaging or pooling\n the sequence of hidden-states for the whole input sequence.\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Example::\n\n from transformers import AlbertModel, AlbertTokenizer\n import torch\n\n tokenizer = AlbertTokenizer.from_pretrained('albert-base-v2')\n model = AlbertModel.from_pretrained('albert-base-v2')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\", add_special_tokens=True)).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n\n \"\"\"\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n if attention_mask is None:\n attention_mask = torch.ones(input_shape, device=device)\n if token_type_ids is None:\n token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)\n\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 if head_mask is not None:\n if head_mask.dim() == 1:\n head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)\n head_mask = head_mask.expand(self.config.num_hidden_layers, -1, -1, -1, -1)\n elif head_mask.dim() == 2:\n head_mask = (\n head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1)\n ) # We can specify head_mask for each layer\n head_mask = head_mask.to(\n dtype=next(self.parameters()).dtype\n ) # switch to fload if need + fp16 compatibility\n else:\n head_mask = [None] * self.config.num_hidden_layers\n\n embedding_output = self.embeddings(\n input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds\n )\n encoder_outputs = self.encoder(embedding_output, extended_attention_mask, head_mask=head_mask)\n\n sequence_output = encoder_outputs[0]\n\n pooled_output = self.pooler_activation(self.pooler(sequence_output[:, 0]))\n\n outputs = (sequence_output, pooled_output) + encoder_outputs[\n 1:\n ] # add hidden_states and attentions if they are here\n return outputs\n\n\nclass AlbertMLMHead(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n self.LayerNorm = nn.LayerNorm(config.embedding_size)\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n self.dense = nn.Linear(config.hidden_size, config.embedding_size)\n self.decoder = nn.Linear(config.embedding_size, config.vocab_size)\n self.activation = ACT2FN[config.hidden_act]\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.activation(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n hidden_states = self.decoder(hidden_states)\n\n prediction_scores = hidden_states + self.bias\n\n return prediction_scores\n\n\n@add_start_docstrings(\n \"Albert Model with a `language modeling` head on top.\", ALBERT_START_DOCSTRING,\n)\nclass AlbertForMaskedLM(AlbertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.albert = AlbertModel(config)\n self.predictions = AlbertMLMHead(config)\n\n self.init_weights()\n self.tie_weights()\n\n def tie_weights(self):\n self._tie_or_clone_weights(self.predictions.decoder, self.albert.embeddings.word_embeddings)\n\n def get_output_embeddings(self):\n return self.predictions.decoder\n\n @add_start_docstrings_to_callable(ALBERT_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n masked_lm_labels=None,\n ):\n r\"\"\"\n masked_lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Labels for computing the masked language modeling loss.\n Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)\n Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with\n labels in ``[0, ..., config.vocab_size]``\n\n Returns:\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.AlbertConfig`) and inputs:\n loss (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Masked language modeling loss.\n prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Example::\n\n from transformers import AlbertTokenizer, AlbertForMaskedLM\n import torch\n\n tokenizer = AlbertTokenizer.from_pretrained('albert-base-v2')\n model = AlbertForMaskedLM.from_pretrained('albert-base-v2')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\", add_special_tokens=True)).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, masked_lm_labels=input_ids)\n loss, prediction_scores = outputs[:2]\n\n \"\"\"\n outputs = self.albert(\n input_ids=input_ids,\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 )\n sequence_outputs = outputs[0]\n\n prediction_scores = self.predictions(sequence_outputs)\n\n outputs = (prediction_scores,) + outputs[2:] # Add hidden states and attention if they are here\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss()\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n outputs = (masked_lm_loss,) + outputs\n\n return outputs\n\n\n@add_start_docstrings(\n \"\"\"Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. \"\"\",\n ALBERT_START_DOCSTRING,\n)\nclass AlbertForSequenceClassification(AlbertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.albert = AlbertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)\n\n self.init_weights()\n\n @add_start_docstrings_to_callable(ALBERT_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):\n Labels for computing the sequence classification/regression loss.\n Indices should be in ``[0, ..., config.num_labels - 1]``.\n If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss),\n If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy).\n\n Returns:\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.AlbertConfig`) and inputs:\n loss: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification (or regression if config.num_labels==1) loss.\n logits ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``\n Classification (or regression if config.num_labels==1) scores (before SoftMax).\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Examples::\n\n from transformers import AlbertTokenizer, AlbertForSequenceClassification\n import torch\n\n tokenizer = AlbertTokenizer.from_pretrained('albert-base-v2')\n model = AlbertForSequenceClassification.from_pretrained('albert-base-v2')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n labels = torch.tensor([1]).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=labels)\n loss, logits = outputs[:2]\n\n \"\"\"\n\n outputs = self.albert(\n input_ids=input_ids,\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 )\n\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n\n outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here\n\n if labels is not None:\n if self.num_labels == 1:\n # We are doing regression\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), labels.view(-1))\n else:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), logits, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\n \"\"\"Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of\n the hidden-states output to compute `span start logits` and `span end logits`). \"\"\",\n ALBERT_START_DOCSTRING,\n)\nclass AlbertForQuestionAnswering(AlbertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.albert = AlbertModel(config)\n self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n @add_start_docstrings_to_callable(ALBERT_INPUTS_DOCSTRING)\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n start_positions=None,\n end_positions=None,\n ):\n r\"\"\"\n start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`).\n Position outside of the sequence are not taken into account for computing the loss.\n end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`).\n Position outside of the sequence are not taken into account for computing the loss.\n\n Returns:\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.AlbertConfig`) and inputs:\n loss: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.\n start_scores ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``\n Span-start scores (before SoftMax).\n end_scores: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``\n Span-end scores (before SoftMax).\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Examples::\n\n # The checkpoint albert-base-v2 is not fine-tuned for question answering. Please see the\n # examples/run_squad.py example to see how to fine-tune a model to a question answering task.\n\n from transformers import AlbertTokenizer, AlbertForQuestionAnswering\n import torch\n\n tokenizer = AlbertTokenizer.from_pretrained('albert-base-v2')\n model = AlbertForQuestionAnswering.from_pretrained('albert-base-v2')\n question, text = \"Who was Jim Henson?\", \"Jim Henson was a nice puppet\"\n input_dict = tokenizer.encode_plus(question, text, return_tensors='pt')\n start_scores, end_scores = model(**input_dict)\n\n \"\"\"\n\n outputs = self.albert(\n input_ids=input_ids,\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 )\n\n sequence_output = outputs[0]\n\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 outputs = (start_logits, end_logits,) + outputs[2:]\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 = 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 outputs = (total_loss,) + outputs\n\n return outputs # (loss), start_logits, end_logits, (hidden_states), (attentions)\n" ]
[ [ "torch.ones", "torch.nn.Linear", "torch.einsum", "numpy.transpose", "torch.nn.MSELoss", "tensorflow.train.list_variables", "torch.nn.Softmax", "torch.nn.Embedding", "torch.nn.Tanh", "torch.nn.CrossEntropyLoss", "torch.from_numpy", "torch.nn.LayerNorm", "torch.zeros", "tensorflow.train.load_variable", "torch.nn.Dropout", "torch.matmul" ] ]
guyang3532/text
[ "e2fc987ff6a002018040cffac5e0d61c3d0b06c6" ]
[ "benchmark/experimental_vectors.py" ]
[ "import time\n\nimport torch\nfrom torchtext.experimental.datasets import AG_NEWS\nfrom torchtext.experimental.vectors import FastText as FastTextExperimental\nfrom torchtext.vocab import FastText\n\n\ndef benchmark_experimental_vectors():\n def _run_benchmark_lookup(tokens, vector):\n t0 = time.monotonic()\n for token in tokens:\n vector[token]\n print(\"Lookup time:\", time.monotonic() - t0)\n\n train, = AG_NEWS(data_select='train')\n vocab = train.get_vocab()\n tokens = []\n for (label, text) in train:\n for id in text.tolist():\n tokens.append(vocab.itos[id])\n\n # existing FastText construction\n print(\"Existing FastText - Not Jit Mode\")\n t0 = time.monotonic()\n fast_text = FastText()\n print(\"Construction time:\", time.monotonic() - t0)\n _run_benchmark_lookup(tokens, fast_text)\n\n # experimental FastText construction\n print(\"FastText Experimental\")\n t0 = time.monotonic()\n fast_text_experimental = FastTextExperimental(validate_file=False)\n print(\"Construction time:\", time.monotonic() - t0)\n\n # not jit lookup\n print(\"FastText Experimental - Not Jit Mode\")\n _run_benchmark_lookup(tokens, fast_text_experimental)\n\n # jit lookup\n print(\"FastText Experimental - Jit Mode\")\n jit_fast_text_experimental = torch.jit.script(fast_text_experimental)\n _run_benchmark_lookup(tokens, jit_fast_text_experimental)\n\n\nif __name__ == \"__main__\":\n benchmark_experimental_vectors()\n" ]
[ [ "torch.jit.script" ] ]
anonymous-user-commits/perturb-net
[ "66fc7c4a1234fa34b92bcc85751f0a6e23d80a23", "66fc7c4a1234fa34b92bcc85751f0a6e23d80a23" ]
[ "cnns/nnlib/robustness/pni/code/models/nomarlization_layer.py", "cnns/nnlib/robustness/pni/code/models/noise_layer_robust.py" ]
[ "import torch\nimport torch.nn as nn\n\n\nclass Normalize_layer(nn.Module):\n\n def __init__(self, mean, std):\n super(Normalize_layer, self).__init__()\n self.mean = nn.Parameter(torch.Tensor(mean).unsqueeze(1).unsqueeze(1),\n requires_grad=False)\n self.std = nn.Parameter(torch.Tensor(std).unsqueeze(1).unsqueeze(1),\n requires_grad=False)\n\n def forward(self, input):\n return input.sub(self.mean).div(self.std)\n\n\nclass noise_Normalize_layer(nn.Module):\n\n def __init__(self, mean, std, input_noise=False):\n super(noise_Normalize_layer, self).__init__()\n self.mean = nn.Parameter(torch.Tensor(mean).unsqueeze(1).unsqueeze(1),\n requires_grad=False)\n self.std = nn.Parameter(torch.Tensor(std).unsqueeze(1).unsqueeze(1),\n requires_grad=False)\n self.input_noise = input_noise\n self.alpha_i = nn.Parameter(torch.Tensor([0.25]), requires_grad=True)\n\n def forward(self, input):\n output = input.sub(self.mean).div(self.std)\n\n input_std = output.std().item()\n input_noise = output.clone().normal_(0, input_std)\n\n return output + input_noise * self.alpha_i * self.input_noise\n\n\n", "import torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass noise_Conv2d(nn.Conv2d):\n\n def __init__(self, in_channels, out_channels, kernel_size, stride=1,\n padding=0, dilation=1,\n groups=1, bias=True, noise_std=0.1):\n super(noise_Conv2d, self).__init__(in_channels, out_channels,\n kernel_size, stride,\n padding, dilation, groups, bias)\n self.noise_std = noise_std\n\n def forward(self, input):\n noise_i = input.clone().normal_(0, self.noise_std)\n noise_input = input + noise_i\n\n output = F.conv2d(noise_input, self.weight, self.bias, self.stride,\n self.padding, self.dilation,\n self.groups)\n\n return output\n" ]
[ [ "torch.Tensor" ], [ "torch.nn.functional.conv2d" ] ]
yihui-he2020/epipolar-transformers
[ "6824f4345b2998500fbacd0f4e30f67f8e3da7b8" ]
[ "modeling/backbones/resnet.py" ]
[ "import logging\nimport os\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.model_zoo as model_zoo\nfrom modeling.layers.epipolar import Epipolar\nfrom modeling import registry\nfrom core import cfg\nfrom .basic_batch import find_tensor_peak_batch\nfrom utils.logger import setup_logger\nfrom utils.model_serialization import load_state_dict\n\n# logger = logging.getLogger(__name__)\nlogger = setup_logger(\"resnet\", cfg.FOLDER_NAME)\n\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\n 'resnet152']\n\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=None):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=None):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv1x1(inplanes, planes)\n self.bn1 = norm_layer(planes)\n self.conv2 = conv3x3(planes, planes, stride)\n self.bn2 = norm_layer(planes)\n self.conv3 = conv1x1(planes, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, norm_layer=None):\n super(ResNet, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self.inplanes = 64\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = norm_layer(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0], norm_layer=norm_layer)\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2, norm_layer=norm_layer)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2, norm_layer=norm_layer)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2, norm_layer=norm_layer)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.out_channels = 512 * block.expansion\n #self.fc = nn.Linear(self.out_channels, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1, norm_layer=None):\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, norm_layer))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, norm_layer=norm_layer))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n #x = self.fc(x)\n\n return x\n\n\[email protected]('R-18')\ndef resnet18(cfg, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n if cfg.BACKBONE.PRETRAINED:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18']), strict=False)\n return model\n\n\[email protected]('R-34')\ndef resnet34(cfg, **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if cfg.BACKBONE.PRETRAINED:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']), strict=False)\n return model\n\n\[email protected]('R-50')\ndef resnet50(cfg, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if cfg.BACKBONE.PRETRAINED:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']), strict=False)\n return model\n\n\[email protected]('R-101')\ndef resnet101(cfg, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n if cfg.BACKBONE.PRETRAINED:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']), strict=False)\n return model\n\n\[email protected]('R-152')\ndef resnet152(cfg, **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\n if cfg.BACKBONE.PRETRAINED:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152']), strict=False)\n return model\n\n\n# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n# Written by Chunyu Wang ([email protected]), modified by Yihui He\n# ------------------------------------------------------------------------------\n\n\nclass PoseResNet(nn.Module):\n\n def __init__(self, block, layers, cfg, **kwargs):\n if cfg.BACKBONE.BN_MOMENTUM < 0:\n self.BN_MOMENTUM = None\n else:\n self.BN_MOMENTUM = cfg.BACKBONE.BN_MOMENTUM\n\n DECONV_WITH_BIAS = False\n NUM_DECONV_LAYERS = 3\n NUM_DECONV_FILTERS = [256, 256, 256]\n NUM_DECONV_KERNELS = [4, 4, 4]\n FINAL_CONV_KERNEL = 1 #cfg.POSE_RESNET.FINAL_CONV_KERNEL\n self.inplanes = 64\n self.deconv_with_bias = DECONV_WITH_BIAS\n\n super(PoseResNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64, momentum=self.BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n\n # used for deconv layers\n self.deconv_layers = self._make_deconv_layer(\n NUM_DECONV_LAYERS,\n NUM_DECONV_FILTERS,\n NUM_DECONV_KERNELS,\n )\n\n self.final_layer = nn.Conv2d(\n in_channels=NUM_DECONV_FILTERS[-1],\n out_channels=cfg.KEYPOINT.NUM_PTS,\n kernel_size=FINAL_CONV_KERNEL, \n stride=1,\n padding=1 if FINAL_CONV_KERNEL == 3 else 0\n )\n\n if 'epipolarpose' in cfg.BACKBONE.BODY:\n if cfg.EPIPOLAR.MERGE == 'both':\n self.epipolar_sampler1 = Epipolar()\n self.epipolar_sampler = Epipolar()\n else:\n self.epipolar_sampler = None\n self.epipolar_sampler1 = None\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion, momentum=self.BN_MOMENTUM),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def _get_deconv_cfg(self, deconv_kernel, index):\n if deconv_kernel == 4:\n padding = 1\n output_padding = 0\n elif deconv_kernel == 3:\n padding = 1\n output_padding = 1\n elif deconv_kernel == 2:\n padding = 0\n output_padding = 0\n\n return deconv_kernel, padding, output_padding\n\n def _make_deconv_layer(self, num_layers, num_filters, num_kernels):\n assert num_layers == len(num_filters), \\\n 'ERROR: num_deconv_layers is different len(num_deconv_filters)'\n assert num_layers == len(num_kernels), \\\n 'ERROR: num_deconv_layers is different len(num_deconv_filters)'\n\n layers = []\n for i in range(num_layers):\n kernel, padding, output_padding = \\\n self._get_deconv_cfg(num_kernels[i], i)\n\n planes = num_filters[i]\n layers.append(\n nn.ConvTranspose2d(\n in_channels=self.inplanes,\n out_channels=planes,\n kernel_size=kernel,\n stride=2,\n padding=padding,\n output_padding=output_padding,\n bias=self.deconv_with_bias))\n layers.append(nn.BatchNorm2d(planes, momentum=self.BN_MOMENTUM))\n layers.append(nn.ReLU(inplace=True))\n self.inplanes = planes\n\n return nn.Sequential(*layers)\n\n def forward(self, x, other_inputs=[None, None, None, None, None, None, None]):\n batch_size = x.shape[0]\n other_features, other_KRT, other_heatmaps, KRT, camera, other_camera, other_img = other_inputs\n features, heatmaps, batch_locs, batch_scos, corr_poss, depths = [], [], [], [], [], []\n # 3 x 256 x 256\n x = self.conv1(x)\n # 128 x 128\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n x = self.layer1(x)\n # 256 x 64 x 64\n\n def getOtherFeat(feat, sampler=None):\n # skip feature aggregation for last layer\n corr_pos = None\n depth = None\n if other_features is None:\n # normal hourglass\n return feat, None, None, None\n if 'epipolarpose' in cfg.BACKBONE.BODY:\n ret, corr_pos, depth, sample_locs = \\\n sampler(feat, other_features, KRT, other_KRT, \\\n camera=camera, other_camera=other_camera)\n return ret + feat, corr_pos, depth, sample_locs\n \n if cfg.EPIPOLAR.MERGE == 'early':\n feature = x\n x, corr_pos, depth, sample_locs = getOtherFeat(feature, sampler=self.epipolar_sampler)\n depths.append(depth)\n corr_poss.append(corr_pos)\n elif cfg.EPIPOLAR.MERGE == 'both':\n feature = x\n x, _, _, _ = getOtherFeat(feature, sampler=self.epipolar_sampler)\n\n x = self.layer2(x)\n # 512 x 32 × 32\n x = self.layer3(x)\n # 1024 x 16 × 16\n x = self.layer4(x)\n # 2048 x 8 x 8\n\n feature = self.deconv_layers(x)\n #256 x 64 x 64\n \n if cfg.EPIPOLAR.MERGE == 'late':\n x, corr_pos, depth, sample_locs = getOtherFeat(feature, sampler=self.epipolar_sampler)\n depths.append(depth)\n corr_poss.append(corr_pos)\n elif cfg.EPIPOLAR.MERGE == 'both':\n x, corr_pos, depth, sample_locs = getOtherFeat(feature, sampler=self.epipolar_sampler1) \n depths.append(depth)\n corr_poss.append(corr_pos) \n else:\n x = feature\n\n #20 x 64 x 64\n heatmaps.append(self.final_layer(x))\n \n # The location of the current batch\n for ibatch in range(batch_size):\n batch_location, batch_score = find_tensor_peak_batch(heatmaps[-1][ibatch], \n cfg.KEYPOINT.SIGMA, \n cfg.BACKBONE.DOWNSAMPLE)\n batch_locs.append(batch_location)\n batch_scos.append(batch_score)\n batch_locs, batch_scos = torch.stack(batch_locs), torch.stack(batch_scos)\n if other_features is None:\n corr_poss, depths = None, None\n else:\n corr_poss = corr_poss[-1]\n depths = depths[-1]\n\n return feature, heatmaps, batch_locs, batch_scos, corr_poss, depths, sample_locs, None \n\n def init_weights(self, pretrained=None):\n if pretrained is not None:\n if isinstance(pretrained, str) and os.path.isfile(pretrained):\n logger.info('=> loading pretrained model {}'.format(pretrained))\n pretrained_state_dict = torch.load(pretrained)\n else:\n logger.info('=> loading pretrained model from web')\n pretrained_state_dict = pretrained\n\n logger.info('=> init deconv weights from normal distribution')\n for name, m in self.deconv_layers.named_modules():\n if isinstance(m, nn.ConvTranspose2d):\n logger.info('=> init {}.weight as normal(0, 0.001)'.format(name))\n logger.info('=> init {}.bias as 0'.format(name))\n nn.init.normal_(m.weight, std=0.001)\n if self.deconv_with_bias:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n logger.info('=> init {}.weight as 1'.format(name))\n logger.info('=> init {}.bias as 0'.format(name))\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n logger.info('=> init final conv weights from normal distribution')\n for m in self.final_layer.modules():\n if isinstance(m, nn.Conv2d):\n # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n logger.info('=> init {}.weight as normal(0, 0.001)'.format(name))\n logger.info('=> init {}.bias as 0'.format(name))\n nn.init.normal_(m.weight, std=0.001)\n nn.init.constant_(m.bias, 0)\n #load_state_dict(self, pretrained_state_dict, prefix='resnet.')\n #load_state_dict(self, pretrained_state_dict, prefix='backbone.')\n load_state_dict(self, pretrained_state_dict, strict=False, ignored_layers=['final_layer.bias', 'final_layer.weight'], prefix=cfg.WEIGHTS_PREFIX, prefix_replace=cfg.WEIGHTS_PREFIX_REPLACE)\n #self.load_state_dict(pretrained_state_dict, strict=False)\n else:\n logger.info('=> init weights from normal distribution')\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n nn.init.normal_(m.weight, std=0.001)\n # nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.ConvTranspose2d):\n nn.init.normal_(m.weight, std=0.001)\n if self.deconv_with_bias:\n nn.init.constant_(m.bias, 0)\n\n\nresnet_spec = {'18': (BasicBlock, [2, 2, 2, 2]),\n '34': (BasicBlock, [3, 4, 6, 3]),\n '50': (Bottleneck, [3, 4, 6, 3]),\n '101': (Bottleneck, [3, 4, 23, 3]),\n '152': (Bottleneck, [3, 8, 36, 3])}\n\[email protected]('poseR-18')\[email protected]('poseR-34')\[email protected]('poseR-50')\[email protected]('poseR-101')\[email protected]('poseR-152')\[email protected]('epipolarposeR-18')\[email protected]('epipolarposeR-34')\[email protected]('epipolarposeR-50')\[email protected]('epipolarposeR-101')\[email protected]('epipolarposeR-152')\ndef get_pose_net(cfg, **kwargs):\n num_layers = cfg.BACKBONE.BODY.split('-')[-1]\n\n block_class, layers = resnet_spec[num_layers]\n\n model = PoseResNet(block_class, layers, cfg, **kwargs)\n\n if cfg.BACKBONE.PRETRAINED:\n # model.init_weights(cfg.NETWORK.PRETRAINED)\n if cfg.BACKBONE.PRETRAINED_WEIGHTS:\n model.init_weights(cfg.BACKBONE.PRETRAINED_WEIGHTS)\n else:\n model.init_weights(model_zoo.load_url(model_urls['resnet'+num_layers]))\n\n return model\n" ]
[ [ "torch.nn.MaxPool2d", "torch.nn.BatchNorm2d", "torch.stack", "torch.nn.init.kaiming_normal_", "torch.load", "torch.nn.init.constant_", "torch.nn.AdaptiveAvgPool2d", "torch.nn.init.normal_", "torch.nn.Conv2d", "torch.nn.Sequential", "torch.utils.model_zoo.load_url", "torch.nn.ReLU", "torch.nn.ConvTranspose2d" ] ]
AntoineDidisheim/didipack
[ "9c9266bf248cae79e6ffddd98b7e573108abaa57" ]
[ "didipack/latex_table.py" ]
[ "import pandas as pd\nimport numpy as np\nimport statsmodels.api as sm\nfrom enum import Enum\n\nclass ParValue(Enum):\n TSTAT = 1\n PVALUE = 2\n STD = 3\n\nclass OneReg:\n def __init__(self, reg, show_list=[], hide_list=[], blocks=[], bottom_blocks=[]):\n self.reg = reg\n if show_list == []:\n self.show_list = []\n for s in self.reg.params.keys():\n if s not in hide_list:\n self.show_list.append(s)\n else:\n self.show_list = show_list\n\n self.blocks = blocks\n self.bottom_block = bottom_blocks\n\n def create_columns(self):\n # first add the parameters of the reg\n d = pd.Series(dtype=object)\n for k in self.show_list:\n if k in self.reg.params.keys():\n v = self.reg.pvalues[k]\n p = f'{np.round(self.reg.params[k], TableReg.round):,}'\n for tr in TableReg.sign_tr:\n if v <= tr:\n p += '*'\n # self = table_2.reg_list[0]\n # update the v to be tstat or std depending on parameters\n if TableReg.par_value == ParValue.TSTAT:\n v = self.reg.tvalues[k]\n if TableReg.par_value == ParValue.STD:\n v = self.reg.bse[k]\n v = r'(' + f'{np.round(v, TableReg.round):,}' + r')'\n v_l = [len(x) for x in v.split('.')]\n p_l = [len(x) for x in p.split('.')]\n\n t = abs(v_l[0] - p_l[0])\n t = r'\\phantom{' + '*' * t + '}'\n if v_l[0] > p_l[0]:\n p = t + p\n if v_l[0] < p_l[0]:\n v = t + v\n t = abs(v_l[1] - p_l[1])\n t = r'\\phantom{' + '*' * t + '}'\n if v_l[1] > p_l[1]:\n p = p+t\n if v_l[1] < p_l[1]:\n v = v+t\n\n # else:\n # p = r'\\phantom{(}' + p + r'\\phantom{)}'\n d[k] = p\n\n t = pd.Series(dtype=object)\n t[''] =v\n\n d = d.append(t)\n else:\n t = pd.Series(dtype=object)\n t[k] = TableReg.missing_symbol\n t[''] = TableReg.missing_symbol\n d = d.append(t)\n # now we can add the \"blocks\", that is fix effects and others\n for block in self.blocks:\n t = pd.Series(dtype=object)\n t[TableReg.group_key] = ''\n\n for k in block.keys():\n t[k] = block[k]\n d = d.append(t)\n\n # finaly additional info (r² and n.obs per default, but you can add anything through bottom blocks\n if TableReg.show_obs | TableReg.show_r2 | (len(self.bottom_block)>0):\n t = pd.Series(dtype=object)\n t[TableReg.group_key] = ''\n t['Observations'] = f'{int(self.reg.nobs):,}'\n\n if hasattr(self.reg,'rsquared_adj'):\n\n t[r'$R^2$'] = np.round(self.reg.rsquared_adj,TableReg.round_r2)\n else:\n t[r'Pseudo $R^2$'] = np.round(self.reg.prsquared,TableReg.round_r2)\n\n first_block = True\n for block in self.bottom_block:\n if first_block:\n first_block = False\n else:\n t[TableReg.group_key] = ''\n t = pd.Series(dtype=object)\n for k in block.keys():\n t[k] = block[k]\n d = d.append(t)\n return d\n\n\nclass TableReg:\n missing_symbol = ' '\n par_value = ParValue.STD\n round = 4\n round_r2 = 4\n sign_tr = [0.1, 0.05, 0.01]\n show_obs = True\n show_r2 = True\n variable_skip = r'\\smallskip'\n group_key = 'asgeg'\n group_skip = r'\\medskip'\n equal_lines = False\n\n def __init__(self, **option):\n self.reg_list = []\n self.hide_list = []\n self.order = []\n self.df = None\n self.final_show_list = []\n self.show_only_list = []\n self.col_groups = []\n self.rename_dict = {}\n if 'hide_list' in option:\n assert type(option['hide_list']) == list, \"The overall hide list has to be a list\"\n self.hide_list = option['hide_list']\n\n if 'show_only_list' in option:\n assert type(option['show_only_list']) == list, \"The show only list has to be a list\"\n self.show_only_list = option['show_only_list']\n\n if 'order' in option:\n assert type(option['order']) == list, \"The order has to be a list\"\n self.order = option['order']\n\n if 'col_groups' in option:\n self.set_col_groups(option['col_groups'])\n\n if 'rename_dict' in option:\n self.set_rename_dict(option['rename_dict'])\n\n\n def set_rename_dict(self, rename_dict):\n assert type(rename_dict) == dict, \"The rename dict must be a dictionary\"\n self.rename_dict = rename_dict\n\n\n\n def set_col_groups(self, groups):\n assert type(groups) == list, \"The col order has to be a list of list\"\n for group in groups:\n assert type(group) == list, \"Each col group must be a list ['name of group', first columne in the group (int), last col in group (int)]\"\n self.col_groups = groups\n\n\n def add_reg(self, reg, show_list=[], hide_list=[], blocks=[],bottom_blocks=[]):\n hide_list = hide_list + self.hide_list\n self.reg_list.append(OneReg(reg, show_list, hide_list, blocks, bottom_blocks))\n\n def update_show_list(self):\n if len(self.show_only_list) == 0:\n show_list = []\n for oneReg in self.reg_list:\n show_list = list(set(show_list + oneReg.show_list))\n show_list = list(np.sort(show_list))\n show_list = self.order + [x for x in show_list if x not in self.order]\n else:\n show_list = self.show_only_list\n\n col = []\n for oneReg in self.reg_list:\n oneReg.show_list = show_list\n col.append(oneReg.create_columns())\n self.df = pd.concat(col,1)\n\n self.df.columns = [r'\\parboxc{c}{0.6cm}{('+str(int(i+1))+')}' for i in range(self.df.shape[1])]\n self.df = self.df.rename(index=self.rename_dict)\n\n self.final_show_list = show_list\n self.final_show_list = pd.Series(self.final_show_list).replace(self.rename_dict).values.tolist()\n self.tex=''\n\n def create_tex(self):\n self.update_show_list()\n\n # writing the tex modification to include name templatess\n tex = self.df.to_latex(escape=False)\n cols = tex.split('\\\\begin{tabular}{')[1].split('}')[0]\n rep = list(cols.replace('l','c'))\n rep[0] = 'l'\n tex = tex.replace(cols,''.join(rep))\n\n if len(self.col_groups)>0:\n # adding \"group col names\"\n s = '\\n '\n s_line = '\\n '\n for g in self.col_groups:\n s += '& \\multicolumn{'+str(1+g[2]-g[1])+'}{c}{\\parboxc{c}{0.6cm}{'+g[0]+'}}'\n # s += '& \\multicolumn{'+str(1+g[2]-g[1])+'}{c}{'+g[0]+'}'\n s_line += r'\\cmidrule(lr){'+str(g[1]+1)+'-'+str(g[2]+1)+'}'\n s += r' \\\\'+'\\n'\n s_line += '\\n'\n\n ts = tex.split(r'\\toprule')\n tex = ts[0]+r'\\toprule' + s +s_line+ ts[1]\n\n ts = tex.split(r'\\midrule')\n tex = ts[0]+r'\\midrule' + ts[1]\n\n # adding the skip between variable\n # first we extract the maxium length of a column on the first one\n L = 0\n for x in self.df.index:\n L = max(L,len(x))\n L+=1\n for i in range(1,len(self.final_show_list)):\n a = self.final_show_list[i]\n a += ' '*(L-len(a))+'&'\n ts = tex.split(a)\n temp = ts[0][:-4] + TableReg.variable_skip + ts[0][-4:]\n tex=temp+a+ts[1]\n\n\n # processing the group skip\n t = None\n for item in tex.split(\"\\n\"):\n if TableReg.group_key in item:\n t = item\n # replacing specific rule\n\n if t is not None:\n self.tex = tex.replace(t, TableReg.group_skip + r'\\\\')\n else:\n self.tex = tex\n\n def save_tex(self, save_dir):\n\n self.create_tex()\n tex = self.tex\n if TableReg.equal_lines:\n tex=tex.replace(r'\\toprule',r'\\hline')\n tex=tex.replace(r'\\midrule',r'\\hline')\n tex=tex.replace(r'\\bottomrule',r'\\hline')\n\n with open(save_dir,'w') as txt:\n txt.write(tex)\n\n @staticmethod\n def create_panel_of_tables(table_list, name_list, save_dir):\n numbers = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split()\n title_list = []\n for i in range(len(table_list)):\n table_list[i].create_tex()\n title_list.append('Panel '+numbers[i]+': '+name_list[i])\n\n\n tex = table_list[0].tex\n temp = r' \\multicolumn{6}{c}{\\parboxc{c}{0.7cm}{'+title_list[i]+r'}} \\\\'\n ts = tex.split(r'\\toprule')\n tex = ts[0]+r'\\toprule' +temp+r'\\hline'+ts[1]\n tex = tex.replace(r'\\bottomrule','')\n tex = tex.replace(r'\\end{tabular}',r'asf')\n tex = tex.replace('\\\\\\\\\\n\\nasf','\\\\bigskip \\\\\\\\ \\n')\n\n\n for i in range(1,len(table_list)):\n t_tex = table_list[i].tex\n temp = r' \\multicolumn{6}{c}{\\parboxc{c}{0.6cm}{' + title_list[i] + r'}} \\\\'\n ts = t_tex.split(r'\\toprule')\n t_tex = ts[0] + r'\\hline' + temp + r'\\hline' + ts[1]\n t = None\n for item in t_tex.split(\"\\n\"):\n if r'\\begin{tabular}' in item:\n t = item\n t_tex = t_tex.replace(t,'')\n if i+1 < len(table_list):\n t_tex = t_tex.replace(r'\\bottomrule','')\n t_tex = t_tex.replace(r'\\end{tabular}', r'asf')\n t_tex = t_tex.replace('\\\\\\\\\\n\\nasf', '\\\\bigskip \\\\\\\\ \\n')\n tex +=t_tex\n\n\n\n with open(save_dir,'w') as txt:\n txt.write(tex)\n\n\n\n" ]
[ [ "numpy.round", "pandas.Series", "pandas.concat", "numpy.sort" ] ]
forgi86/pyMPC
[ "4b004ba707dab49cd36d96a3575b8593c870a904" ]
[ "test_scripts/main_cvxpy_simple.py" ]
[ "from cvxpy import Variable, Parameter, Minimize, Problem, OSQP, quad_form\nimport numpy as np\nimport scipy as sp\nimport scipy.sparse as sparse\nimport time\n\n\nif __name__ == \"__main__\":\n\n # Discrete time model of a quadcopter\n Ts = 0.2\n M = 2.0\n\n Ad = sparse.csc_matrix([\n [1.0, Ts],\n [0, 1.0]\n ])\n Bd = sparse.csc_matrix([\n [0.0],\n [Ts/M]])\n\n [nx, nu] = Bd.shape # number of states and number or inputs\n\n # Constraints\n uref = 0\n uinit = 0 # not used here\n umin = np.array([-1000.0]) - uref\n umax = np.array([1000.0]) - uref\n\n xmin = np.array([-100.0, -100.0])\n xmax = np.array([100.0, 100.0])\n\n # Objective function\n Q = sparse.diags([0.2, 0.3])\n QN = sparse.diags([0.4, 0.5]) # final cost\n R = 0.1*sparse.eye(1)\n\n # Initial and reference states\n x0 = np.array([0.1, 0.2]) # initial state\n # Reference input and states\n pref = 7.0\n vref = 0\n xref = np.array([pref, vref]) # reference state\n\n # Prediction horizon\n Np = 20\n\n # Define problem\n u = Variable((nu, Np))\n x = Variable((nx, Np + 1))\n x_init = Parameter(nx)\n objective = 0\n constraints = [x[:,0] == x_init]\n for k in range(Np):\n objective += quad_form(x[:, k] - xref, Q) + quad_form(u[:, k], R)\n constraints += [x[:, k+1] == Ad*x[:, k] + Bd*u[:, k]]\n constraints += [xmin <= x[:, k], x[:, k] <= xmax]\n constraints += [umin <= u[:, k], u[:, k] <= umax]\n objective += quad_form(x[:, Np] - xref, QN)\n prob = Problem(Minimize(objective), constraints)\n\n\n # Simulate in closed loop\n # Simulate in closed loop\n len_sim = 15 # simulation length (s)\n nsim = int(len_sim/Ts) # simulation length(timesteps)\n xsim = np.zeros((nsim,nx))\n usim = np.zeros((nsim,nu))\n tsim = np.arange(0,nsim)*Ts\n\n uminus1_val = uinit # initial previous measured input is the input at time instant -1.\n time_start = time.time()\n for i in range(nsim):\n x_init.value = x0\n #uminus1.value = uminus1_val\n prob.solve(solver=OSQP, warm_start=True)\n uMPC = u[:,0].value\n usim[i,:] = uMPC\n x0 = Ad.dot(x0) + Bd.dot(uMPC)\n xsim[i,:] = x0\n\n uminus1_val = uMPC # or a measurement if the input is affected by noise\n time_sim = time.time() - time_start\n\n # In [1]\n import matplotlib.pyplot as plt\n fig,axes = plt.subplots(3,1, figsize=(10,10))\n axes[0].plot(tsim, xsim[:,0], \"k\", label='p')\n axes[0].plot(tsim, xref[0]*np.ones(np.shape(tsim)), \"r--\", label=\"pref\")\n axes[0].set_title(\"Position (m)\")\n\n axes[1].plot(tsim, xsim[:,1], label=\"v\")\n axes[1].plot(tsim, xref[1]*np.ones(np.shape(tsim)), \"r--\", label=\"vref\")\n axes[1].set_title(\"Velocity (m/s)\")\n\n axes[2].plot(tsim, usim[:,0], label=\"u\")\n axes[2].plot(tsim, uref*np.ones(np.shape(tsim)), \"r--\", label=\"uref\")\n axes[2].set_title(\"Force (N)\")\n\n\n for ax in axes:\n ax.grid(True)\n ax.legend()\n" ]
[ [ "numpy.zeros", "scipy.sparse.csc_matrix", "matplotlib.pyplot.subplots", "scipy.sparse.diags", "scipy.sparse.eye", "numpy.arange", "numpy.shape", "numpy.array" ] ]
SuryaThiru/ppscore
[ "59df800e32d4ef5fda4be2bdf4b3235db2a39fee" ]
[ "src/ppscore/calculation.py" ]
[ "from sklearn import tree\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import mean_absolute_error, f1_score\n\nimport pandas as pd\nfrom pandas.api.types import (\n is_numeric_dtype,\n is_bool_dtype,\n is_categorical_dtype,\n is_string_dtype,\n is_datetime64_any_dtype,\n is_timedelta64_dtype,\n)\n\n# if the number is 4, then it is possible to detect patterns when there are at least 4 times the same observation. If the limit is increased, the minimum observations also increase. This is important, because this is the limit when sklearn will throw an error which will lead to a score of 0 if we catch it\nCV_ITERATIONS = 4\n\nRANDOM_SEED = 587136\n\n# if a numeric column has less than 15 unique values, it is inferred as categoric\n# thus, the ppscore will use a classification\n# this has important implications on the ppscore\n# eg if you have 4 equal categories encoded 0, 1, 2, 3 and treat it as a regression\n# then the baseline is 1 (median) which is okayish and a predictor will have a harder time\n# to beat the baseline, thus the ppscore will be considerably lower\n# if the column is encoded as category, then the baseline will be to always predict 0\n# this baseline will be way easier to beat and thus result in a higher ppscore\nNUMERIC_AS_CATEGORIC_BREAKPOINT = 15\n\n\ndef _calculate_model_cv_score_(df, target, feature, metric, model, **kwargs):\n \"Calculates the mean model score based on cross-validation\"\n # Sources about the used methods:\n # https://scikit-learn.org/stable/modules/tree.html\n # https://scikit-learn.org/stable/modules/cross_validation.html\n # https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html\n\n # shuffle the rows - this is important for crossvalidation\n # because the crossvalidation just takes the first n lines\n # if there is a strong pattern in the rows eg 0,0,0,0,1,1,1,1\n # then this will lead to problems because the first cv sees mostly 0 and the later 1\n # this approach might be wrong for timeseries because it might leak information\n df = df.sample(frac=1, random_state=RANDOM_SEED, replace=False)\n\n # preprocess target\n if df[target].dtype == object:\n le = preprocessing.LabelEncoder()\n df[target] = le.fit_transform(df[target])\n target_series = df[target]\n else:\n target_series = df[target]\n\n # preprocess feature\n if df[feature].dtype == object:\n one_hot_encoder = preprocessing.OneHotEncoder()\n sparse_matrix = one_hot_encoder.fit_transform(df[feature].values.reshape(-1, 1))\n feature_df = sparse_matrix\n else:\n # reshaping needed because there is only 1 feature\n feature_df = df[feature].values.reshape(-1, 1)\n\n # Crossvalidation is stratifiedKFold for classification, KFold for regression\n # CV on one core (n_job=1; default) has shown to be fastest\n scores = cross_val_score(\n model, feature_df, target_series, cv=CV_ITERATIONS, scoring=metric\n )\n\n return scores.mean()\n\n\ndef _normalized_mae_score(model_mae, naive_mae):\n \"Normalizes the model MAE score, given the baseline score\"\n # # Value range of MAE is [0, infinity), 0 is best\n # 10, 5 >> 0 because worse than naive\n # 10, 20 >> 0.5\n # 5, 20 >> 0.75 = 1 - (mae/base_mae)\n if model_mae > naive_mae:\n return 0\n else:\n return 1 - (model_mae / naive_mae)\n\n\ndef _mae_normalizer(df, y, model_score):\n \"In case of MAE, calculates the baseline score for y and derives the PPS.\"\n df[\"naive\"] = df[y].median()\n baseline_score = mean_absolute_error(df[y], df[\"naive\"]) # true, pred\n\n ppscore = _normalized_mae_score(abs(model_score), baseline_score)\n return ppscore, baseline_score\n\n\ndef _normalized_f1_score(model_f1, baseline_f1):\n \"Normalizes the model F1 score, given the baseline score\"\n # # F1 ranges from 0 to 1\n # # 1 is best\n # 0.5, 0.7 = 0 because worse than naive\n # 0.75, 0.5 > 0.5\n #\n if model_f1 < baseline_f1:\n return 0\n else:\n scale_range = 1.0 - baseline_f1 # eg 0.3\n f1_diff = model_f1 - baseline_f1 # eg 0.1\n return f1_diff / scale_range # 0.1/0.3 = 0.33\n\n\ndef _f1_normalizer(df, y, model_score):\n \"In case of F1, calculates the baseline score for y and derives the PPS.\"\n df[\"naive\"] = df[y].value_counts().index[0]\n baseline_score = f1_score(df[y], df[\"naive\"], average=\"weighted\")\n\n ppscore = _normalized_f1_score(model_score, baseline_score)\n return ppscore, baseline_score\n\n\nTASKS = {\n \"regression\": {\n \"metric_name\": \"mean absolute error\",\n \"metric_key\": \"neg_mean_absolute_error\",\n \"model\": tree.DecisionTreeRegressor(),\n \"score_normalizer\": _mae_normalizer,\n },\n \"classification\": {\n \"metric_name\": \"weighted F1\",\n \"metric_key\": \"f1_weighted\",\n \"model\": tree.DecisionTreeClassifier(),\n \"score_normalizer\": _f1_normalizer,\n },\n \"predict_itself\": {\n \"metric_name\": None,\n \"metric_key\": None,\n \"model\": None,\n \"score_normalizer\": None,\n },\n \"predict_constant\": {\n \"metric_name\": None,\n \"metric_key\": None,\n \"model\": None,\n \"score_normalizer\": None,\n },\n \"predict_id\": {\n \"metric_name\": None,\n \"metric_key\": None,\n \"model\": None,\n \"score_normalizer\": None,\n },\n}\n\n\ndef _infer_task(df, x, y):\n \"Returns str with the name of the inferred task based on the columns x and y\"\n if x == y:\n return \"predict_itself\"\n\n category_count = df[y].value_counts().count()\n if category_count == 1:\n return \"predict_constant\"\n if category_count == 2:\n return \"classification\"\n if category_count == len(df[y]) and (\n is_string_dtype(df[y]) or is_categorical_dtype(df[y])\n ):\n return \"predict_id\"\n if category_count <= NUMERIC_AS_CATEGORIC_BREAKPOINT and is_numeric_dtype(df[y]):\n return \"classification\"\n\n if is_bool_dtype(df[y]) or is_string_dtype(df[y]) or is_categorical_dtype(df[y]):\n return \"classification\"\n\n if is_datetime64_any_dtype(df[y]) or is_timedelta64_dtype(df[y]):\n raise Exception(\n f\"The target column {y} has the dtype {df[y].dtype} which is not supported. A possible solution might be to convert {y} to a string column\"\n )\n\n # this check needs to be after is_bool_dtype because bool is considered numeric by pandas\n if is_numeric_dtype(df[y]):\n return \"regression\"\n\n raise Exception(\n f\"Could not infer a valid task based on the target {y}. The dtype {df[y].dtype} is not yet supported\"\n ) # pragma: no cover\n\n\ndef _feature_is_id(df, x):\n \"Returns Boolean if the feature column x is an ID\"\n if not (is_string_dtype(df[x]) or is_categorical_dtype(df[x])):\n return False\n\n category_count = df[x].value_counts().count()\n return category_count == len(df[x])\n\n\ndef _maybe_sample(df, sample):\n \"\"\"\n Maybe samples the rows of the given df to have at most ``sample`` rows\n If sample is ``None`` or falsy, there will be no sampling.\n If the df has fewer rows than the sample, there will be no sampling.\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe that might be sampled\n sample : int or ``None``\n Number of rows to be sampled\n\n Returns\n -------\n pandas.DataFrame\n DataFrame after potential sampling\n \"\"\"\n if sample and len(df) > sample:\n # this is a problem if x or y have more than sample=5000 categories\n # TODO: dont sample when the problem occurs and show warning\n df = df.sample(sample, random_state=RANDOM_SEED, replace=False)\n return df\n\n\ndef score(df, x, y, task=None, sample=5000):\n \"\"\"\n Calculate the Predictive Power Score (PPS) for \"x predicts y\"\n The score always ranges from 0 to 1 and is data-type agnostic.\n\n A score of 0 means that the column x cannot predict the column y better than a naive baseline model.\n A score of 1 means that the column x can perfectly predict the column y given the model.\n A score between 0 and 1 states the ratio of how much potential predictive power the model achieved compared to the baseline model.\n\n Parameters\n ----------\n df : pandas.DataFrame\n Dataframe that contains the columns x and y\n x : str\n Name of the column x which acts as the feature\n y : str\n Name of the column y which acts as the target\n task : str, default ``None``\n Name of the prediction task, e.g. ``classification`` or ``regression``\n If the task is not specified, it is infered based on the y column\n The task determines which model and evaluation score is used for the PPS\n sample : int or ``None``\n Number of rows for sampling. The sampling decreases the calculation time of the PPS.\n If ``None`` there will be no sampling.\n\n Returns\n -------\n Dict\n A dict that contains multiple fields about the resulting PPS.\n The dict enables introspection into the calculations that have been performed under the hood\n \"\"\"\n\n if x == y:\n task_name = \"predict_itself\"\n else:\n # TODO: log.warning when values have been dropped\n df = df[[x, y]].dropna()\n if len(df) == 0:\n raise Exception(\"After dropping missing values, there are no valid rows left\")\n df = _maybe_sample(df, sample)\n\n if task is None:\n task_name = _infer_task(df, x, y)\n else:\n task_name = task\n\n task = TASKS[task_name]\n\n if task_name in [\"predict_constant\", \"predict_itself\"]:\n model_score = 1\n ppscore = 1\n baseline_score = 1\n elif task_name == \"predict_id\": # target is id\n model_score = 0\n ppscore = 0\n baseline_score = 0\n elif _feature_is_id(df, x):\n model_score = 0\n ppscore = 0\n baseline_score = 0\n else:\n model_score = _calculate_model_cv_score_(\n df, target=y, feature=x, metric=task[\"metric_key\"], model=task[\"model\"]\n )\n ppscore, baseline_score = task[\"score_normalizer\"](df, y, model_score)\n\n return {\n \"x\": x,\n \"y\": y,\n \"task\": task_name,\n \"ppscore\": ppscore,\n \"metric\": task[\"metric_name\"],\n \"baseline_score\": baseline_score,\n \"model_score\": abs(model_score), # sklearn returns negative mae\n \"model\": task[\"model\"],\n }\n\n\n# def predictors(df, y, task=None, sorted=True):\n# pass\n\n\ndef matrix(df, output=\"df\", **kwargs):\n \"\"\"\n Calculate the Predictive Power Score (PPS) matrix for all columns in the dataframe\n\n Parameters\n ----------\n df : pandas.DataFrame\n The dataframe that contains the data\n output: str - potential values: \"df\", \"dict\"\n Control the type of the output. Either return a df or a dict with all the PPS dicts arranged by the target column\n kwargs:\n Other key-word arguments that shall be forwarded to the pps.score method\n\n Returns\n -------\n pandas.DataFrame or Dict\n Either returns a df or a dict with all the PPS dicts arranged by the target column. This can be influenced by the output argument\n \"\"\"\n data = {}\n columns = list(df.columns)\n\n for target in columns:\n scores = []\n for feature in columns:\n # single_score = score(df, x=feature, y=target)[\"ppscore\"]\n try:\n single_score = score(df, x=feature, y=target, **kwargs)[\"ppscore\"]\n except:\n # TODO: log error\n single_score = 0\n scores.append(single_score)\n data[target] = scores\n\n if output == \"df\":\n matrix = pd.DataFrame.from_dict(data, orient=\"index\")\n matrix.columns = columns\n return matrix\n else: # output == \"dict\"\n return data\n" ]
[ [ "sklearn.preprocessing.OneHotEncoder", "pandas.api.types.is_categorical_dtype", "pandas.api.types.is_string_dtype", "pandas.api.types.is_numeric_dtype", "sklearn.metrics.mean_absolute_error", "sklearn.tree.DecisionTreeClassifier", "pandas.api.types.is_timedelta64_dtype", "pandas.DataFrame.from_dict", "sklearn.tree.DecisionTreeRegressor", "sklearn.metrics.f1_score", "pandas.api.types.is_bool_dtype", "sklearn.preprocessing.LabelEncoder", "pandas.api.types.is_datetime64_any_dtype", "sklearn.model_selection.cross_val_score" ] ]
joakimlindblad/py_alpha_amd_release
[ "6a95286753c48e9f0c882d650158b15b58bcdd46" ]
[ "register.py" ]
[ "\n#\n# Py-Alpha-AMD Registration Framework\n# Author: Johan Ofverstedt\n# Reference: Fast and Robust Symmetric Image Registration Based on Distances Combining Intensity and Spatial Information\n#\n# Copyright 2019 Johan Ofverstedt\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n#\n\n#\n# Registration framework\n#\n\n# Import Numpy/Scipy\nimport numpy as np\nimport scipy as sp\nimport scipy.misc\n\n# Import transforms\nfrom transforms import CompositeTransform\nfrom transforms import AffineTransform\nfrom transforms import Rigid2DTransform\nfrom transforms import Rotate2DTransform\nfrom transforms import TranslationTransform\nfrom transforms import ScalingTransform\n\n# Import distances\nfrom distances import QuantizedImage\nfrom distances import alpha_amd\nfrom distances import symmetric_amd_distance\n\n# Import optimizers\nfrom optimizers import GradientDescentOptimizer\n\n# Import generators and filters\nimport generators\nimport filters\n\n# Import misc\nimport math\nimport sys\nimport time\nimport cProfile, pstats\n\nclass Register:\n def __init__(self, dim):\n self.dim = dim\n self.sampling_fraction = 1.0\n self.step_lengths = np.array([[0.1, 1.0]])\n self.iterations = 1500\n self.alpha_levels = 7\n self.gradient_magnitude_threshold = 0.00001\n \n self.ref_im = None\n self.flo_im = None\n self.ref_mask = None\n self.flo_mask = None\n self.ref_weights = None\n self.flo_weights = None\n\n # Transforms\n self.initial_transforms = []\n self.transforms_param_scaling = []\n self.output_transforms = []\n self.values = []\n self.value_history = []\n\n # Resolution pyramid levels\n self.pyramid_factors = []\n self.pyramid_sigmas = []\n\n self.distances = []\n \n # Reporting/Output\n self.report_func = None\n self.report_freq = 25\n\n def add_initial_transform(self, transform, param_scaling=None):\n if param_scaling is None:\n param_scaling = np.ones((transforms.get_param_count(),))\n self.initial_transforms.append(transform)\n self.transforms_param_scaling.append(param_scaling)\n \n def add_initial_transforms(self, transforms, param_scaling=None):\n for i, t in enumerate(transforms):\n if param_scaling is None:\n pscaling = np.ones((transforms.get_param_count(),))\n else:\n pscaling = param_scaling[i]\n self.add_initial_transform(t, pscaling)\n \n def clear_transforms(self):\n self.initial_transforms = []\n self.output_transforms = []\n self.transforms_param_scaling = []\n self.values = []\n self.value_history = []\n \n def get_output(self, index):\n return self.output_transforms[index], self.values[index]\n\n def get_value_history(self, index, level):\n return self.value_history[index][level]\n\n def add_pyramid_level(self, factor, sigma):\n self.pyramid_factors.append(factor)\n self.pyramid_sigmas.append(sigma)\n \n def add_pyramid_levels(self, factors, sigmas):\n for i in range(len(factors)):\n self.add_pyramid_level(factors[i], sigmas[i])\n\n def get_pyramid_level_count(self):\n return len(self.pyramid_factors)\n\n def set_sampling_fraction(self, sampling_fraction):\n self.sampling_fraction = sampling_fraction\n \n def set_iterations(self, iterations):\n self.iterations = iterations\n\n def set_alpha_levels(self, alpha_levels):\n self.alpha_levels = alpha_levels\n \n def set_step_lengths(self, step_lengths):\n self.step_lengths = np.array(step_lengths)#np.array([start_step_length, end_step_length])\n \n def set_reference_image(self, image, spacing = None):\n self.ref_im = image\n if spacing is None:\n self.ref_spacing = np.ones(image.ndim)\n else:\n self.ref_spacing = spacing\n \n def set_floating_image(self, image, spacing = None):\n self.flo_im = image\n if spacing is None:\n self.flo_spacing = np.ones(image.ndim)\n else:\n self.flo_spacing = spacing\n\n def set_reference_mask(self, mask):\n self.ref_mask = mask\n\n def set_floating_mask(self, mask):\n self.flo_mask = mask\n\n def set_reference_weights(self, weights):\n self.ref_weights = weights\n\n def set_floating_weights(self, weights):\n self.flo_weights = weights\n\n def set_gradient_magnitude_threshold(self, t):\n self.gradient_magnitude_threshold = t\n\n def set_report_freq(self, freq):\n self.report_freq = freq\n \n def set_report_func(self, func):\n self.report_func = func\n \n def initialize(self, pyramid_images_output_path=None):\n if len(self.pyramid_factors) == 0:\n self.add_pyramid_level(1, 0.0)\n if len(self.initial_transforms) == 0:\n self.add_initial_transform(AffineTransform(self.dim))\n \n ### Preprocessing\n\n pyramid_levels = len(self.pyramid_factors)\n\n for i in range(pyramid_levels):\n factor = self.pyramid_factors[i]\n\n ref_resampled = filters.downsample(filters.gaussian_filter(self.ref_im, self.pyramid_sigmas[i]), factor)\n flo_resampled = filters.downsample(filters.gaussian_filter(self.flo_im, self.pyramid_sigmas[i]), factor)\n \n ref_mask_resampled = filters.downsample(self.ref_mask, factor)\n flo_mask_resampled = filters.downsample(self.flo_mask, factor)\n\n ref_resampled = filters.normalize(ref_resampled, 0.0, ref_mask_resampled)\n flo_resampled = filters.normalize(flo_resampled, 0.0, flo_mask_resampled)\n\n if pyramid_images_output_path is not None and ref_resampled.ndim == 2:\n scipy.misc.imsave('%sref_resampled_%d.png' % (pyramid_images_output_path, i+1), ref_resampled)\n scipy.misc.imsave('%sflo_resampled_%d.png' % (pyramid_images_output_path, i+1), flo_resampled)\n \n if self.ref_weights is None:\n ref_weights = np.zeros(ref_resampled.shape)\n ref_weights[ref_mask_resampled] = 1.0\n else:\n ref_weights = filters.downsample(self.ref_weights, factor)\n if self.flo_weights is None:\n flo_weights = np.zeros(flo_resampled.shape)\n flo_weights[flo_mask_resampled] = 1.0\n else:\n flo_weights = filters.downsample(self.flo_weights, factor)\n\n ref_diag = np.sqrt(np.square(np.array(ref_resampled.shape)*self.ref_spacing).sum())\n flo_diag = np.sqrt(np.square(np.array(flo_resampled.shape)*self.flo_spacing).sum())\n\n q_ref = QuantizedImage(ref_resampled, self.alpha_levels, ref_weights, self.ref_spacing*factor, remove_zero_weight_pnts = True)\n q_flo = QuantizedImage(flo_resampled, self.alpha_levels, flo_weights, self.flo_spacing*factor, remove_zero_weight_pnts = True)\n\n tf_ref = alpha_amd.AlphaAMD(q_ref, self.alpha_levels, ref_diag, self.ref_spacing*factor, ref_mask_resampled, ref_mask_resampled, interpolator_mode='linear', dt_fun = None, mask_out_edges = True)\n tf_flo = alpha_amd.AlphaAMD(q_flo, self.alpha_levels, flo_diag, self.flo_spacing*factor, flo_mask_resampled, flo_mask_resampled, interpolator_mode='linear', dt_fun = None, mask_out_edges = True)\n\n symmetric_measure = True\n squared_measure = False\n\n sym_dist = symmetric_amd_distance.SymmetricAMDDistance(symmetric_measure=symmetric_measure, squared_measure=squared_measure)\n\n sym_dist.set_ref_image_source(q_ref)\n sym_dist.set_ref_image_target(tf_ref)\n\n sym_dist.set_flo_image_source(q_flo)\n sym_dist.set_flo_image_target(tf_flo)\n\n sym_dist.set_sampling_fraction(self.sampling_fraction)\n\n sym_dist.initialize()\n\n self.distances.append(sym_dist)\n\n def run(self):\n pyramid_level_count = len(self.pyramid_factors)\n transform_count = len(self.initial_transforms)\n\n for t_it in range(transform_count):\n init_transform = self.initial_transforms[t_it]\n param_scaling = self.transforms_param_scaling[t_it]\n\n self.value_history.append([])\n\n for lvl_it in range(pyramid_level_count):\n \n opt = GradientDescentOptimizer(self.distances[lvl_it], init_transform.copy())\n\n if self.step_lengths.ndim == 1:\n opt.set_step_length(self.step_lengths[0], self.step_lengths[1])\n else:\n opt.set_step_length(self.step_lengths[lvl_it, 0], self.step_lengths[lvl_it, 1])\n opt.set_scalings(param_scaling)\n opt.set_gradient_magnitude_threshold(self.gradient_magnitude_threshold)\n opt.set_report_freq(self.report_freq)\n if type(self.report_func) is list or type(self.report_func) is tuple:\n opt.set_report_callback(self.report_func[t_it])\n else:\n opt.set_report_callback(self.report_func)\n\n if isinstance(self.iterations, int):\n itercount = self.iterations\n else:\n assert(len(self.iterations) == pyramid_level_count)\n itercount = self.iterations[lvl_it]\n \n opt.optimize(itercount)\n\n if lvl_it + 1 == pyramid_level_count:\n self.output_transforms.append(opt.get_transform())\n self.values.append(opt.get_value())\n self.initial_transforms[t_it] = opt.get_transform()\n else:\n init_transform = opt.get_transform()\n\n self.value_history[-1].append(opt.get_value_history())\n\n \n \n " ]
[ [ "numpy.array", "numpy.ones", "numpy.zeros" ] ]
DeepPSP/torch_ecg
[ "6db5ffb063d0e8fb4ce97029a0d184a658f43a37" ]
[ "torch_ecg/models/cnn/multi_scopic.py" ]
[ "\"\"\"\nThe core part of the SOTA model of CPSC2019,\nbranched, and has different scope (in terms of dilation) in each branch\n\"\"\"\nfrom copy import deepcopy\nfrom itertools import repeat\nfrom collections import OrderedDict\nfrom typing import Union, Optional, Sequence, NoReturn\n\nimport numpy as np\nnp.set_printoptions(precision=5, suppress=True)\nimport torch\nfrom torch import nn\nfrom torch import Tensor\n\nfrom ...cfg import CFG, DEFAULTS\nfrom ...utils.utils_nn import compute_module_size, SizeMixin\nfrom ...utils.misc import dict_to_str\nfrom ...models._nets import (\n Conv_Bn_Activation,\n DownSample,\n NonLocalBlock, SEBlock, GlobalContextBlock,\n)\n\n\nif DEFAULTS.torch_dtype == torch.float64:\n torch.set_default_tensor_type(torch.DoubleTensor)\n\n\n__all__ = [\n \"MultiScopicCNN\",\n \"MultiScopicBasicBlock\",\n \"MultiScopicBranch\",\n]\n\n\nclass MultiScopicBasicBlock(SizeMixin, nn.Sequential):\n \"\"\" finished, checked,\n\n basic building block of the CNN part of the SOTA model\n from CPSC2019 challenge (entry 0416)\n\n (conv -> activation) * N --> bn --> down_sample\n \"\"\"\n __DEBUG__ = False\n __name__ = \"MultiScopicBasicBlock\"\n\n def __init__(self,\n in_channels:int,\n scopes:Sequence[int],\n num_filters:Union[int,Sequence[int]],\n filter_lengths:Union[int,Sequence[int]],\n subsample_length:int,\n groups:int=1,\n **config) -> NoReturn:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n in_channels: int,\n number of channels in the input\n scopes: sequence of int,\n scopes of the convolutional layers, via `dilation`\n num_filters: int or sequence of int,\n number of filters of the convolutional layer(s)\n filter_lengths: int or sequence of int,\n filter length(s) (kernel size(s)) of the convolutional layer(s)\n subsample_length: int,\n subsample length (ratio) at the last layer of the block\n \"\"\"\n super().__init__()\n self.__in_channels = in_channels\n self.__scopes = scopes\n self.__num_convs = len(self.__scopes)\n if isinstance(num_filters, int):\n self.__out_channels = list(repeat(num_filters, self.__num_convs))\n else:\n self.__out_channels = num_filters\n assert len(self.__out_channels) == self.__num_convs, \\\n f\"`scopes` indicates {self.__num_convs} convolutional layers, while `num_filters` indicates {len(self.__out_channels)}\"\n if isinstance(filter_lengths, int):\n self.__filter_lengths = list(repeat(filter_lengths, self.__num_convs))\n else:\n self.__filter_lengths = filter_lengths\n assert len(self.__filter_lengths) == self.__num_convs, \\\n f\"`scopes` indicates {self.__num_convs} convolutional layers, while `filter_lengths` indicates {len(self.__filter_lengths)}\"\n self.__subsample_length = subsample_length\n self.__groups = groups\n self.config = CFG(deepcopy(config))\n\n conv_in_channels = self.__in_channels\n for idx in range(self.__num_convs):\n self.add_module(\n f\"ca_{idx}\",\n Conv_Bn_Activation(\n in_channels=conv_in_channels,\n out_channels=self.__out_channels[idx],\n kernel_size=self.__filter_lengths[idx],\n stride=1,\n dilation=self.__scopes[idx],\n groups=self.__groups,\n batch_norm=self.config.batch_norm,\n # kw_bn=self.config.kw_bn,\n activation=self.config.activation,\n kw_activation=self.config.kw_activation,\n kernel_initializer=self.config.kernel_initializer,\n kw_initializer=self.config.kw_initializer,\n bias=self.config.bias,\n )\n )\n conv_in_channels = self.__out_channels[idx]\n self.add_module(\n \"bn\",\n nn.BatchNorm1d(self.__out_channels[-1])\n )\n self.add_module(\n \"down\",\n DownSample(\n down_scale=self.__subsample_length,\n in_channels=self.__out_channels[-1],\n groups=self.__groups,\n # padding=\n batch_norm=False,\n mode=self.config.subsample_mode,\n )\n )\n if self.config.dropout > 0:\n self.add_module(\n \"dropout\",\n nn.Dropout(self.config.dropout, inplace=False)\n )\n\n def forward(self, input:Tensor) -> Tensor:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n input: Tensor,\n of shape (batch_size, n_channels, seq_len)\n\n Returns\n -------\n output: Tensor,\n of shape (batch_size, n_channels, seq_len)\n \"\"\"\n output = super().forward(input)\n return output\n\n def compute_output_shape(self, seq_len:Optional[int]=None, batch_size:Optional[int]=None) -> Sequence[Union[int, None]]:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n seq_len: int,\n length of the 1d sequence\n batch_size: int, optional,\n the batch size, can be None\n\n Returns\n -------\n output_shape: sequence,\n the output shape of this block, given `seq_len` and `batch_size`\n \"\"\"\n _seq_len = seq_len\n for idx, module in enumerate(self):\n if idx == self.__num_convs: # bn layer\n continue\n elif self.config.dropout > 0 and idx == len(self)-1: # dropout layer\n continue\n output_shape = module.compute_output_shape(_seq_len, batch_size)\n _, _, _seq_len = output_shape\n return output_shape\n\n\nclass MultiScopicBranch(SizeMixin, nn.Sequential):\n \"\"\" finished, checked,\n \n branch path of the CNN part of the SOTA model\n from CPSC2019 challenge (entry 0416)\n \"\"\"\n __DEBUG__ = False\n __name__ = \"MultiScopicBranch\"\n\n def __init__(self,\n in_channels:int,\n scopes:Sequence[Sequence[int]],\n num_filters:Union[Sequence[int],Sequence[Sequence[int]]],\n filter_lengths:Union[Sequence[int],Sequence[Sequence[int]]],\n subsample_lengths:Union[int,Sequence[int]],\n groups:int=1,\n **config) -> NoReturn:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n in_channels: int,\n number of features (channels) of the input\n scopes: sequence of sequences of int,\n scopes (in terms of `dilation`) for the convolutional layers,\n each sequence of int is for one branch\n num_filters: sequence of int, or sequence of sequences of int,\n number of filters for the convolutional layers,\n if is sequence of int,\n then convolutionaly layers in one branch will have the same number of filters\n filter_lengths: sequence of int, or sequence of sequences of int,\n filter length (kernel size) of the convolutional layers,\n if is sequence of int,\n then convolutionaly layers in one branch will have the same filter length\n subsample_lengths: int, or sequence of int,\n subsample length (stride) of the convolutional layers,\n if is sequence of int,\n then convolutionaly layers in one branch will have the same subsample length\n groups: int, default 1,\n connection pattern (of channels) of the inputs and outputs\n config: dict,\n other hyper-parameters, including\n dropout, activation choices, weight initializer, etc.\n \"\"\"\n super().__init__()\n self.__in_channels = in_channels\n self.__scopes = scopes\n self.__num_blocks = len(self.__scopes)\n self.__num_filters = num_filters\n assert len(self.__num_filters) == self.__num_blocks, \\\n f\"`scopes` indicates {self.__num_blocks} `MultiScopicBasicBlock`s, while `num_filters` indicates {len(self.__num_filters)}\"\n self.__filter_lengths = filter_lengths\n assert len(self.__filter_lengths) == self.__num_blocks, \\\n f\"`scopes` indicates {self.__num_blocks} `MultiScopicBasicBlock`s, while `filter_lengths` indicates {len(self.__filter_lengths)}\"\n if isinstance(subsample_lengths, int):\n self.__subsample_lengths = list(repeat(subsample_lengths, self.__num_blocks))\n else:\n self.__subsample_lengths = filter_lengths\n assert len(self.__subsample_lengths) == self.__num_blocks, \\\n f\"`scopes` indicates {self.__num_blocks} `MultiScopicBasicBlock`s, while `subsample_lengths` indicates {len(self.__subsample_lengths)}\"\n self.__groups = groups\n self.config = CFG(deepcopy(config))\n\n block_in_channels = self.__in_channels\n for idx in range(self.__num_blocks):\n self.add_module(\n f\"block_{idx}\",\n MultiScopicBasicBlock(\n in_channels=block_in_channels,\n scopes=self.__scopes[idx],\n num_filters=self.__num_filters[idx],\n filter_lengths=self.__filter_lengths[idx],\n subsample_length=self.__subsample_lengths[idx],\n groups=self.__groups,\n dropout=self.config.dropouts[idx],\n **(self.config.block)\n )\n )\n block_in_channels = self.__num_filters[idx]\n\n def forward(self, input:Tensor) -> Tensor:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n input: Tensor,\n of shape (batch_size, n_channels, seq_len)\n\n Returns\n -------\n output: Tensor,\n of shape (batch_size, n_channels, seq_len)\n \"\"\"\n output = super().forward(input)\n return output\n\n def compute_output_shape(self, seq_len:Optional[int]=None, batch_size:Optional[int]=None) -> Sequence[Union[int, None]]:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n seq_len: int,\n length of the 1d sequence\n batch_size: int, optional,\n the batch size, can be None\n\n Returns\n -------\n output_shape: sequence,\n the output shape of this block, given `seq_len` and `batch_size`\n \"\"\"\n _seq_len = seq_len\n for idx, module in enumerate(self):\n output_shape = module.compute_output_shape(_seq_len, batch_size)\n _, _, _seq_len = output_shape\n return output_shape\n\n\nclass MultiScopicCNN(SizeMixin, nn.Module):\n \"\"\" finished, checked,\n\n CNN part of the SOTA model from CPSC2019 challenge (entry 0416)\n \"\"\"\n __DEBUG__ = False\n __name__ = \"MultiScopicCNN\"\n\n def __init__(self, in_channels:int, **config) -> NoReturn:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n in_channels: int,\n number of channels in the input\n config: dict,\n other hyper-parameters of the Module, ref. corresponding config file\n key word arguments that have to be set:\n scopes: sequence of sequences of sequences of int,\n scopes (in terms of dilation) of each convolution\n num_filters: sequence of sequences (of int or of sequences of int),\n number of filters of the convolutional layers,\n with granularity to each block of each branch,\n or to each convolution of each block of each branch\n filter_lengths: sequence of sequences (of int or of sequences of int),\n filter length(s) (kernel size(s)) of the convolutions,\n with granularity to each block of each branch,\n or to each convolution of each block of each branch\n subsample_lengths: sequence of int or sequence of sequences of int,\n subsampling length(s) (ratio(s)) of all blocks,\n with granularity to each branch or to each block of each branch,\n each subsamples after the last convolution of each block\n dropouts: sequence of int or sequence of sequences of int,\n dropout rates of all blocks,\n with granularity to each branch or to each block of each branch,\n each dropouts at the last of each block\n groups: int,\n connection pattern (of channels) of the inputs and outputs\n block: dict,\n other parameters that can be set for the building blocks\n for a full list of configurable parameters, ref. corr. config file\n \"\"\"\n super().__init__()\n self.__in_channels = in_channels\n self.config = CFG(deepcopy(config))\n self.__scopes = self.config.scopes\n self.__num_branches = len(self.__scopes)\n\n if self.__DEBUG__:\n print(f\"configuration of {self.__name__} is as follows\\n{dict_to_str(self.config)}\")\n\n self.branches = nn.ModuleDict()\n for idx in range(self.__num_branches):\n self.branches[f\"branch_{idx}\"] = \\\n MultiScopicBranch(\n in_channels=self.__in_channels,\n scopes=self.__scopes[idx],\n num_filters=self.config.num_filters[idx],\n filter_lengths=self.config.filter_lengths[idx],\n subsample_lengths=self.config.subsample_lengths[idx],\n groups=self.config.groups,\n dropouts=self.config.dropouts[idx],\n block=self.config.block, # a dict\n )\n\n def forward(self, input:Tensor) -> Tensor:\n \"\"\" finished, checked,\n \n Parameters\n ----------\n input: Tensor,\n of shape (batch_size, n_channels, seq_len)\n\n Returns\n -------\n output: Tensor,\n of shape (batch_size, n_channels, seq_len)\n \"\"\"\n branch_out = OrderedDict()\n for idx in range(self.__num_branches):\n key = f\"branch_{idx}\"\n branch_out[key] = self.branches[key].forward(input)\n output = torch.cat(\n [branch_out[f\"branch_{idx}\"] for idx in range(self.__num_branches)],\n dim=1, # along channels\n )\n return output\n \n def compute_output_shape(self, seq_len:Optional[int]=None, batch_size:Optional[int]=None) -> Sequence[Union[int, None]]:\n \"\"\" finished, checked,\n\n Parameters\n ----------\n seq_len: int,\n length of the 1d sequence\n batch_size: int, optional,\n the batch size, can be None\n\n Returns\n -------\n output_shape: sequence,\n the output shape of this block, given `seq_len` and `batch_size`\n \"\"\"\n out_channels = 0\n for idx in range(self.__num_branches):\n key = f\"branch_{idx}\"\n _, _branch_oc, _seq_len = \\\n self.branches[key].compute_output_shape(seq_len, batch_size)\n out_channels += _branch_oc\n output_shape = (batch_size, out_channels, _seq_len)\n return output_shape\n" ]
[ [ "torch.nn.BatchNorm1d", "numpy.set_printoptions", "torch.set_default_tensor_type", "torch.nn.ModuleDict", "torch.nn.Dropout" ] ]
My-Technical-Architect/tensorflow
[ "35cf4653e6fe15953e2e565afc5a0fd2ab4d5290" ]
[ "tensorflow/contrib/distributions/python/kernel_tests/distribution_test.py" ]
[ "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import tensor_util\n\ndists = tf.contrib.distributions\n\n\nclass DistributionTest(tf.test.TestCase):\n\n def testParamShapesAndFromParams(self):\n classes = [\n dists.Normal,\n dists.Bernoulli,\n dists.Beta,\n dists.Chi2,\n dists.Exponential,\n dists.Gamma,\n dists.InverseGamma,\n dists.Laplace,\n dists.StudentT,\n dists.Uniform]\n\n sample_shapes = [(), (10,), (10, 20, 30)]\n with self.test_session():\n for cls in classes:\n for sample_shape in sample_shapes:\n param_shapes = cls.param_shapes(sample_shape)\n params = dict([(name, tf.random_normal(shape))\n for name, shape in param_shapes.items()])\n dist = cls(**params)\n self.assertAllEqual(sample_shape, tf.shape(dist.sample()).eval())\n dist_copy = dist.copy()\n self.assertAllEqual(sample_shape,\n tf.shape(dist_copy.sample()).eval())\n self.assertEqual(dist.parameters, dist_copy.parameters)\n\n def testCopyExtraArgs(self):\n with self.test_session():\n # Note: we cannot easily test all distributions since each requires\n # different initialization arguments. We therefore spot test a few.\n normal = dists.Normal(mu=1., sigma=2., validate_args=True)\n self.assertEqual(normal.parameters, normal.copy().parameters)\n wishart = dists.WishartFull(df=2, scale=[[1., 2], [2, 5]],\n validate_args=True)\n self.assertEqual(wishart.parameters, wishart.copy().parameters)\n\n def testCopyOverride(self):\n with self.test_session():\n normal = dists.Normal(mu=1., sigma=2., validate_args=True)\n normal_copy = normal.copy(validate_args=False)\n base_params = normal.parameters.copy()\n copy_params = normal.copy(validate_args=False).parameters.copy()\n self.assertNotEqual(base_params.pop(\"validate_args\"),\n copy_params.pop(\"validate_args\"))\n self.assertEqual(base_params, copy_params)\n\n def testIsScalar(self):\n with self.test_session():\n mu = 1.\n sigma = 2.\n\n normal = dists.Normal(mu, sigma,\n validate_args=True)\n self.assertTrue(tensor_util.constant_value(normal.is_scalar_event))\n self.assertTrue(tensor_util.constant_value(normal.is_scalar_batch))\n\n normal = dists.Normal([mu], [sigma],\n validate_args=True)\n self.assertTrue(tensor_util.constant_value(normal.is_scalar_event))\n self.assertFalse(tensor_util.constant_value(normal.is_scalar_batch))\n\n mvn = dists.MultivariateNormalDiag([mu], [sigma],\n validate_args=True)\n self.assertFalse(tensor_util.constant_value(mvn.is_scalar_event))\n self.assertTrue(tensor_util.constant_value(mvn.is_scalar_batch))\n\n mvn = dists.MultivariateNormalDiag([[mu]], [[sigma]],\n validate_args=True)\n self.assertFalse(tensor_util.constant_value(mvn.is_scalar_event))\n self.assertFalse(tensor_util.constant_value(mvn.is_scalar_batch))\n\n # We now test every codepath within the underlying is_scalar_helper\n # function.\n\n # Test case 1, 2.\n x = tf.placeholder(dtype=tf.int32, shape=[])\n # None would fire an exception were it actually executed.\n self.assertTrue(normal._is_scalar_helper(x.get_shape, lambda: None))\n self.assertTrue(normal._is_scalar_helper(lambda: tf.TensorShape(None),\n lambda: tf.shape(x)))\n\n x = tf.placeholder(dtype=tf.int32, shape=[1])\n # None would fire an exception were it actually executed.\n self.assertFalse(normal._is_scalar_helper(x.get_shape, lambda: None))\n self.assertFalse(normal._is_scalar_helper(lambda: tf.TensorShape(None),\n lambda: tf.shape(x)))\n\n # Test case 3.\n x = tf.placeholder(dtype=tf.int32)\n is_scalar = normal._is_scalar_helper(x.get_shape, lambda: tf.shape(x))\n self.assertTrue(is_scalar.eval(feed_dict={x: 1}))\n self.assertFalse(is_scalar.eval(feed_dict={x: [1]}))\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.placeholder", "tensorflow.shape", "tensorflow.test.main", "tensorflow.TensorShape", "tensorflow.random_normal", "tensorflow.python.framework.tensor_util.constant_value" ] ]
project-delphi/ACS-QG
[ "03aa5b79030b5ba4c09a99363a58454743876592" ]
[ "model/encoder.py" ]
[ "\"\"\"\nImplement input sentence encoder.\n\"\"\"\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pad_packed_sequence as unpack\nfrom torch.nn.utils.rnn import pack_padded_sequence as pack\nfrom .config import *\nfrom common.constants import DEVICE\nfrom util.tensor_utils import to_sorted_tensor, to_original_tensor\n\n\nclass Encoder(nn.Module):\n \"\"\"\n Transform embeddings to encoding representations.\n \"\"\"\n\n def __init__(self, config, input_size, dropout=0.1):\n \"\"\"\n Initialize a GRU encoder.\n :param config: configuration, includes total enc size, is bi-direction, etc.\n :param input_size: input dimension.\n :param dropout: dropout rate for GRU\n \"\"\"\n super(Encoder, self).__init__()\n self.config = config\n self.layers = config.layers\n self.num_directions = 2 if config.brnn else 1\n assert config.enc_rnn_size % self.num_directions == 0\n self.hidden_size = config.enc_rnn_size // self.num_directions\n self.rnn = nn.GRU(\n input_size, self.hidden_size,\n num_layers=config.layers, dropout=config.dropout,\n bidirectional=config.brnn, batch_first=True)\n\n def forward(self, input_emb, lengths, hidden=None):\n \"\"\"\n Given input embeddings and input seq lengths, calculate encoding representations.\n :param input_emb: embedding of a batch.\n Input shape - [seq_len, batch_size, hidden_dim]\n :param lengths: lengths of each sample.\n :param hidden: hidden of previous layer. Default None.\n :return: encoding of a batch.\n Output shape - [unpadded_max_thisbatch_seq_len, batch_size, hidden_dim * num_layers]\n TODO: revise code to make input and output shape be [batch, length, dim]\n \"\"\"\n # input_emb shape: [seq_len, batch_size, hidden_dim] [100, 32, 412]\n # sorted_emb shape: [seq_len, batch_size, hidden_dim] [100, 32, 412]\n sorted_input_emb, sorted_lengths, sorted_idx = to_sorted_tensor(\n input_emb, lengths, sort_dim=1, device=DEVICE)\n emb = pack(sorted_input_emb, sorted_lengths, batch_first=False)\n self.rnn.flatten_parameters()\n outputs, hidden_t = self.rnn(emb, hidden)\n # hidden_t shape: [num_layers, batch_size, hidden_dim] [2, 32, 256]\n # outputs shape: [unpadded_seq_len, batch_size, hidden_dim * num_layers] [79, 32, 512]\n # !!! NOTICE: it will unpack to max_unpadded_length.\n outputs = unpack(outputs, batch_first=False)[0]\n outputs = to_original_tensor(\n outputs, sorted_idx, sort_dim=1, device=DEVICE)\n return hidden_t, outputs\n" ]
[ [ "torch.nn.GRU", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.utils.rnn.pad_packed_sequence" ] ]
RangeKing/Paddle
[ "2d87300809ae75d76f5b0b457d8112cb88dc3e27" ]
[ "python/paddle/fluid/tests/unittests/distribution/test_distribution_dirichlet_static.py" ]
[ "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport numpy as np\nimport paddle\nimport scipy.stats\n\nfrom config import ATOL, DEVICES, RTOL\nfrom parameterize import TEST_CASE_NAME, parameterize_cls, place, xrand\n\npaddle.enable_static()\n\n\n@place(DEVICES)\n@parameterize_cls((TEST_CASE_NAME, 'concentration'),\n [('test-one-dim', np.random.rand(89) + 5.0)])\nclass TestDirichlet(unittest.TestCase):\n def setUp(self):\n self.program = paddle.static.Program()\n self.executor = paddle.static.Executor()\n with paddle.static.program_guard(self.program):\n conc = paddle.static.data('conc', self.concentration.shape,\n self.concentration.dtype)\n self._paddle_diric = paddle.distribution.Dirichlet(conc)\n self.feeds = {'conc': self.concentration}\n\n def test_mean(self):\n with paddle.static.program_guard(self.program):\n [out] = self.executor.run(self.program,\n feed=self.feeds,\n fetch_list=[self._paddle_diric.mean])\n np.testing.assert_allclose(\n out,\n scipy.stats.dirichlet.mean(self.concentration),\n rtol=RTOL.get(str(self.concentration.dtype)),\n atol=ATOL.get(str(self.concentration.dtype)))\n\n def test_variance(self):\n with paddle.static.program_guard(self.program):\n [out] = self.executor.run(self.program,\n feed=self.feeds,\n fetch_list=[self._paddle_diric.variance])\n np.testing.assert_allclose(\n out,\n scipy.stats.dirichlet.var(self.concentration),\n rtol=RTOL.get(str(self.concentration.dtype)),\n atol=ATOL.get(str(self.concentration.dtype)))\n\n def test_prob(self):\n with paddle.static.program_guard(self.program):\n random_number = np.random.rand(*self.concentration.shape)\n random_number = random_number / random_number.sum()\n feeds = dict(self.feeds, value=random_number)\n value = paddle.static.data('value', random_number.shape,\n random_number.dtype)\n out = self._paddle_diric.prob(value)\n [out] = self.executor.run(self.program,\n feed=feeds,\n fetch_list=[out])\n np.testing.assert_allclose(\n out,\n scipy.stats.dirichlet.pdf(random_number, self.concentration),\n rtol=RTOL.get(str(self.concentration.dtype)),\n atol=ATOL.get(str(self.concentration.dtype)))\n\n def test_log_prob(self):\n with paddle.static.program_guard(self.program):\n random_number = np.random.rand(*self.concentration.shape)\n random_number = random_number / random_number.sum()\n feeds = dict(self.feeds, value=random_number)\n value = paddle.static.data('value', random_number.shape,\n random_number.dtype)\n out = self._paddle_diric.log_prob(value)\n [out] = self.executor.run(self.program,\n feed=feeds,\n fetch_list=[out])\n np.testing.assert_allclose(\n out,\n scipy.stats.dirichlet.logpdf(random_number, self.concentration),\n rtol=RTOL.get(str(self.concentration.dtype)),\n atol=ATOL.get(str(self.concentration.dtype)))\n\n def test_entropy(self):\n with paddle.static.program_guard(self.program):\n [out] = self.executor.run(\n self.program,\n feed=self.feeds,\n fetch_list=[self._paddle_diric.entropy()])\n np.testing.assert_allclose(\n out,\n scipy.stats.dirichlet.entropy(self.concentration),\n rtol=RTOL.get(str(self.concentration.dtype)),\n atol=ATOL.get(str(self.concentration.dtype)))\n" ]
[ [ "numpy.random.rand" ] ]
luckmoon/nmt
[ "4f6a4acf8d8e086f9d894444a2877ac1f0856ad0", "4f6a4acf8d8e086f9d894444a2877ac1f0856ad0" ]
[ "nmt/utils/iterator_utils_test.py", "nmt/model_helper.py" ]
[ "# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for iterator_utils.py\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import lookup_ops\n\nfrom ..utils import iterator_utils\n\n\nclass IteratorUtilsTest(tf.test.TestCase):\n\n def testGetIterator(self):\n tf.set_random_seed(1)\n tgt_vocab_table = src_vocab_table = lookup_ops.index_table_from_tensor(\n tf.constant([\"a\", \"b\", \"c\", \"eos\", \"sos\"]))\n src_dataset = tf.data.Dataset.from_tensor_slices(\n tf.constant([\"f e a g\", \"c c a\", \"d\", \"c a\"]))\n tgt_dataset = tf.data.Dataset.from_tensor_slices(\n tf.constant([\"c c\", \"a b\", \"\", \"b c\"]))\n hparams = tf.contrib.training.HParams(\n random_seed=3,\n num_buckets=5,\n eos=\"eos\",\n sos=\"sos\")\n batch_size = 2\n src_max_len = 3\n iterator = iterator_utils.get_iterator(\n src_dataset=src_dataset,\n tgt_dataset=tgt_dataset,\n src_vocab_table=src_vocab_table,\n tgt_vocab_table=tgt_vocab_table,\n batch_size=batch_size,\n sos=hparams.sos,\n eos=hparams.eos,\n random_seed=hparams.random_seed,\n num_buckets=hparams.num_buckets,\n src_max_len=src_max_len,\n reshuffle_each_iteration=False)\n table_initializer = tf.tables_initializer()\n source = iterator.source\n target_input = iterator.target_input\n target_output = iterator.target_output\n src_seq_len = iterator.source_sequence_length\n tgt_seq_len = iterator.target_sequence_length\n self.assertEqual([None, None], source.shape.as_list())\n self.assertEqual([None, None], target_input.shape.as_list())\n self.assertEqual([None, None], target_output.shape.as_list())\n self.assertEqual([None], src_seq_len.shape.as_list())\n self.assertEqual([None], tgt_seq_len.shape.as_list())\n with self.test_session() as sess:\n sess.run(table_initializer)\n sess.run(iterator.initializer)\n\n (source_v, src_len_v, target_input_v, target_output_v, tgt_len_v) = (\n sess.run((source, src_seq_len, target_input, target_output,\n tgt_seq_len)))\n self.assertAllEqual(\n [[-1, -1, 0], # \"f\" == unknown, \"e\" == unknown, a\n [2, 0, 3]], # c a eos -- eos is padding\n source_v)\n self.assertAllEqual([3, 2], src_len_v)\n self.assertAllEqual(\n [[4, 2, 2], # sos c c\n [4, 1, 2]], # sos b c\n target_input_v)\n self.assertAllEqual(\n [[2, 2, 3], # c c eos\n [1, 2, 3]], # b c eos\n target_output_v)\n self.assertAllEqual([3, 3], tgt_len_v)\n\n (source_v, src_len_v, target_input_v, target_output_v, tgt_len_v) = (\n sess.run((source, src_seq_len, target_input, target_output,\n tgt_seq_len)))\n self.assertAllEqual(\n [[2, 2, 0]], # c c a\n source_v)\n self.assertAllEqual([3], src_len_v)\n self.assertAllEqual(\n [[4, 0, 1]], # sos a b\n target_input_v)\n self.assertAllEqual(\n [[0, 1, 3]], # a b eos\n target_output_v)\n self.assertAllEqual([3], tgt_len_v)\n\n with self.assertRaisesOpError(\"End of sequence\"):\n sess.run(source)\n\n def testGetIteratorWithShard(self):\n tf.set_random_seed(1)\n tgt_vocab_table = src_vocab_table = lookup_ops.index_table_from_tensor(\n tf.constant([\"a\", \"b\", \"c\", \"eos\", \"sos\"]))\n src_dataset = tf.data.Dataset.from_tensor_slices(\n tf.constant([\"c c a\", \"f e a g\", \"d\", \"c a\"]))\n tgt_dataset = tf.data.Dataset.from_tensor_slices(\n tf.constant([\"a b\", \"c c\", \"\", \"b c\"]))\n hparams = tf.contrib.training.HParams(\n random_seed=3,\n num_buckets=5,\n eos=\"eos\",\n sos=\"sos\")\n batch_size = 2\n src_max_len = 3\n iterator = iterator_utils.get_iterator(\n src_dataset=src_dataset,\n tgt_dataset=tgt_dataset,\n src_vocab_table=src_vocab_table,\n tgt_vocab_table=tgt_vocab_table,\n batch_size=batch_size,\n sos=hparams.sos,\n eos=hparams.eos,\n random_seed=hparams.random_seed,\n num_buckets=hparams.num_buckets,\n src_max_len=src_max_len,\n num_shards=2,\n shard_index=1,\n reshuffle_each_iteration=False)\n table_initializer = tf.tables_initializer()\n source = iterator.source\n target_input = iterator.target_input\n target_output = iterator.target_output\n src_seq_len = iterator.source_sequence_length\n tgt_seq_len = iterator.target_sequence_length\n self.assertEqual([None, None], source.shape.as_list())\n self.assertEqual([None, None], target_input.shape.as_list())\n self.assertEqual([None, None], target_output.shape.as_list())\n self.assertEqual([None], src_seq_len.shape.as_list())\n self.assertEqual([None], tgt_seq_len.shape.as_list())\n with self.test_session() as sess:\n sess.run(table_initializer)\n sess.run(iterator.initializer)\n\n (source_v, src_len_v, target_input_v, target_output_v, tgt_len_v) = (\n sess.run((source, src_seq_len, target_input, target_output,\n tgt_seq_len)))\n self.assertAllEqual(\n [[-1, -1, 0], # \"f\" == unknown, \"e\" == unknown, a\n [2, 0, 3]], # c a eos -- eos is padding\n source_v)\n self.assertAllEqual([3, 2], src_len_v)\n self.assertAllEqual(\n [[4, 2, 2], # sos c c\n [4, 1, 2]], # sos b c\n target_input_v)\n self.assertAllEqual(\n [[2, 2, 3], # c c eos\n [1, 2, 3]], # b c eos\n target_output_v)\n self.assertAllEqual([3, 3], tgt_len_v)\n\n with self.assertRaisesOpError(\"End of sequence\"):\n sess.run(source)\n\n def testGetIteratorWithSkipCount(self):\n tf.set_random_seed(1)\n tgt_vocab_table = src_vocab_table = lookup_ops.index_table_from_tensor(\n tf.constant([\"a\", \"b\", \"c\", \"eos\", \"sos\"]))\n src_dataset = tf.data.Dataset.from_tensor_slices(\n tf.constant([\"c a\", \"c c a\", \"d\", \"f e a g\"]))\n tgt_dataset = tf.data.Dataset.from_tensor_slices(\n tf.constant([\"b c\", \"a b\", \"\", \"c c\"]))\n hparams = tf.contrib.training.HParams(\n random_seed=3,\n num_buckets=5,\n eos=\"eos\",\n sos=\"sos\")\n batch_size = 2\n src_max_len = 3\n skip_count = tf.placeholder(shape=(), dtype=tf.int64)\n iterator = iterator_utils.get_iterator(\n src_dataset=src_dataset,\n tgt_dataset=tgt_dataset,\n src_vocab_table=src_vocab_table,\n tgt_vocab_table=tgt_vocab_table,\n batch_size=batch_size,\n sos=hparams.sos,\n eos=hparams.eos,\n random_seed=hparams.random_seed,\n num_buckets=hparams.num_buckets,\n src_max_len=src_max_len,\n skip_count=skip_count,\n reshuffle_each_iteration=False)\n table_initializer = tf.tables_initializer()\n source = iterator.source\n target_input = iterator.target_input\n target_output = iterator.target_output\n src_seq_len = iterator.source_sequence_length\n tgt_seq_len = iterator.target_sequence_length\n self.assertEqual([None, None], source.shape.as_list())\n self.assertEqual([None, None], target_input.shape.as_list())\n self.assertEqual([None, None], target_output.shape.as_list())\n self.assertEqual([None], src_seq_len.shape.as_list())\n self.assertEqual([None], tgt_seq_len.shape.as_list())\n with self.test_session() as sess:\n sess.run(table_initializer)\n sess.run(iterator.initializer, feed_dict={skip_count: 3})\n\n (source_v, src_len_v, target_input_v, target_output_v, tgt_len_v) = (\n sess.run((source, src_seq_len, target_input, target_output,\n tgt_seq_len)))\n self.assertAllEqual(\n [[-1, -1, 0]], # \"f\" == unknown, \"e\" == unknown, a\n source_v)\n self.assertAllEqual([3], src_len_v)\n self.assertAllEqual(\n [[4, 2, 2]], # sos c c\n target_input_v)\n self.assertAllEqual(\n [[2, 2, 3]], # c c eos\n target_output_v)\n self.assertAllEqual([3], tgt_len_v)\n\n with self.assertRaisesOpError(\"End of sequence\"):\n sess.run(source)\n\n # Re-init iterator with skip_count=0.\n sess.run(iterator.initializer, feed_dict={skip_count: 0})\n\n (source_v, src_len_v, target_input_v, target_output_v, tgt_len_v) = (\n sess.run((source, src_seq_len, target_input, target_output,\n tgt_seq_len)))\n self.assertAllEqual(\n [[2, 0, 3], # c a eos -- eos is padding\n [-1, -1, 0]], # \"f\" == unknown, \"e\" == unknown, a\n source_v)\n self.assertAllEqual([2, 3], src_len_v)\n self.assertAllEqual(\n [[4, 1, 2], # sos b c\n [4, 2, 2]], # sos c c\n target_input_v)\n self.assertAllEqual(\n [[1, 2, 3], # b c eos\n [2, 2, 3]], # c c eos\n target_output_v)\n self.assertAllEqual([3, 3], tgt_len_v)\n\n (source_v, src_len_v, target_input_v, target_output_v, tgt_len_v) = (\n sess.run((source, src_seq_len, target_input, target_output,\n tgt_seq_len)))\n self.assertAllEqual(\n [[2, 2, 0]], # c c a\n source_v)\n self.assertAllEqual([3], src_len_v)\n self.assertAllEqual(\n [[4, 0, 1]], # sos a b\n target_input_v)\n self.assertAllEqual(\n [[0, 1, 3]], # a b eos\n target_output_v)\n self.assertAllEqual([3], tgt_len_v)\n\n with self.assertRaisesOpError(\"End of sequence\"):\n sess.run(source)\n\n def testGetInferIterator(self):\n src_vocab_table = lookup_ops.index_table_from_tensor(\n tf.constant([\"a\", \"b\", \"c\", \"eos\", \"sos\"]))\n src_dataset = tf.data.Dataset.from_tensor_slices(\n tf.constant([\"c c a\", \"c a\", \"d\", \"f e a g\"]))\n hparams = tf.contrib.training.HParams(\n random_seed=3,\n eos=\"eos\",\n sos=\"sos\")\n batch_size = 2\n src_max_len = 3\n iterator = iterator_utils.get_infer_iterator(\n src_dataset=src_dataset,\n src_vocab_table=src_vocab_table,\n batch_size=batch_size,\n eos=hparams.eos,\n src_max_len=src_max_len)\n table_initializer = tf.tables_initializer()\n source = iterator.source\n seq_len = iterator.source_sequence_length\n self.assertEqual([None, None], source.shape.as_list())\n self.assertEqual([None], seq_len.shape.as_list())\n with self.test_session() as sess:\n sess.run(table_initializer)\n sess.run(iterator.initializer)\n\n (source_v, seq_len_v) = sess.run((source, seq_len))\n self.assertAllEqual(\n [[2, 2, 0], # c c a\n [2, 0, 3]], # c a eos\n source_v)\n self.assertAllEqual([3, 2], seq_len_v)\n\n (source_v, seq_len_v) = sess.run((source, seq_len))\n self.assertAllEqual(\n [[-1, 3, 3], # \"d\" == unknown, eos eos\n [-1, -1, 0]], # \"f\" == unknown, \"e\" == unknown, a\n source_v)\n self.assertAllEqual([1, 3], seq_len_v)\n\n with self.assertRaisesOpError(\"End of sequence\"):\n sess.run((source, seq_len))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Utility functions for building models.\"\"\"\nfrom __future__ import print_function\n\nimport collections\nimport os\nimport time\nimport numpy as np\nimport six\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import lookup_ops\nfrom .utils import iterator_utils\nfrom .utils import misc_utils as utils\nfrom .utils import vocab_utils\n\n__all__ = [\n \"get_initializer\", \"get_device_str\", \"create_train_model\",\n \"create_eval_model\", \"create_infer_model\",\n \"create_emb_for_encoder_and_decoder\", \"create_rnn_cell\", \"gradient_clip\",\n \"create_or_load_model\", \"load_model\", \"avg_checkpoints\",\n \"compute_perplexity\"\n]\n\n# If a vocab size is greater than this value, put the embedding on cpu instead\nVOCAB_SIZE_THRESHOLD_CPU = 50000\n\n\ndef get_initializer(init_op, seed=None, init_weight=None):\n \"\"\"Create an initializer. init_weight is only for uniform.\"\"\"\n if init_op == \"uniform\":\n assert init_weight\n return tf.random_uniform_initializer(\n -init_weight, init_weight, seed=seed)\n elif init_op == \"glorot_normal\":\n return tf.keras.initializers.glorot_normal(\n seed=seed)\n elif init_op == \"glorot_uniform\":\n return tf.keras.initializers.glorot_uniform(\n seed=seed)\n else:\n raise ValueError(\"Unknown init_op %s\" % init_op)\n\n\ndef get_device_str(device_id, num_gpus):\n \"\"\"Return a device string for multi-GPU setup.\"\"\"\n if num_gpus == 0:\n return \"/cpu:0\"\n device_str_output = \"/gpu:%d\" % (device_id % num_gpus)\n return device_str_output\n\n\nclass ExtraArgs(collections.namedtuple(\n \"ExtraArgs\", (\"single_cell_fn\", \"model_device_fn\",\n \"attention_mechanism_fn\", \"encoder_emb_lookup_fn\"))):\n pass\n\n\nclass TrainModel(\n collections.namedtuple(\"TrainModel\", (\"graph\", \"model\", \"iterator\",\n \"skip_count_placeholder\"))):\n pass\n\n\ndef create_train_model(\n model_creator, hparams, scope=None, num_workers=1, jobid=0,\n extra_args=None):\n \"\"\"Create train graph, model, and iterator.\"\"\"\n src_file = \"%s.%s\" % (hparams.train_prefix, hparams.src)\n tgt_file = \"%s.%s\" % (hparams.train_prefix, hparams.tgt)\n src_vocab_file = hparams.src_vocab_file\n tgt_vocab_file = hparams.tgt_vocab_file\n\n graph = tf.Graph()\n\n with graph.as_default(), tf.container(scope or \"train\"):\n src_vocab_table, tgt_vocab_table = vocab_utils.create_vocab_tables(\n src_vocab_file, tgt_vocab_file, hparams.share_vocab)\n\n src_dataset = tf.data.TextLineDataset(tf.gfile.Glob(src_file))\n tgt_dataset = tf.data.TextLineDataset(tf.gfile.Glob(tgt_file))\n skip_count_placeholder = tf.placeholder(shape=(), dtype=tf.int64)\n\n iterator = iterator_utils.get_iterator(\n src_dataset,\n tgt_dataset,\n src_vocab_table,\n tgt_vocab_table,\n batch_size=hparams.batch_size,\n sos=hparams.sos,\n eos=hparams.eos,\n random_seed=hparams.random_seed,\n num_buckets=hparams.num_buckets,\n src_max_len=hparams.src_max_len,\n tgt_max_len=hparams.tgt_max_len,\n skip_count=skip_count_placeholder,\n num_shards=num_workers,\n shard_index=jobid,\n use_char_encode=hparams.use_char_encode)\n\n # Note: One can set model_device_fn to\n # `tf.train.replica_device_setter(ps_tasks)` for distributed training.\n model_device_fn = None\n if extra_args: model_device_fn = extra_args.model_device_fn\n with tf.device(model_device_fn):\n model = model_creator(\n hparams,\n iterator=iterator,\n mode=tf.contrib.learn.ModeKeys.TRAIN,\n source_vocab_table=src_vocab_table,\n target_vocab_table=tgt_vocab_table,\n scope=scope,\n extra_args=extra_args)\n\n return TrainModel(\n graph=graph,\n model=model,\n iterator=iterator,\n skip_count_placeholder=skip_count_placeholder)\n\n\nclass EvalModel(\n collections.namedtuple(\"EvalModel\",\n (\"graph\", \"model\", \"src_file_placeholder\",\n \"tgt_file_placeholder\", \"iterator\"))):\n pass\n\n\ndef create_eval_model(model_creator, hparams, scope=None, extra_args=None):\n \"\"\"Create train graph, model, src/tgt file holders, and iterator.\"\"\"\n src_vocab_file = hparams.src_vocab_file\n tgt_vocab_file = hparams.tgt_vocab_file\n graph = tf.Graph()\n\n with graph.as_default(), tf.container(scope or \"eval\"):\n src_vocab_table, tgt_vocab_table = vocab_utils.create_vocab_tables(\n src_vocab_file, tgt_vocab_file, hparams.share_vocab)\n reverse_tgt_vocab_table = lookup_ops.index_to_string_table_from_file(\n tgt_vocab_file, default_value=vocab_utils.UNK)\n\n src_file_placeholder = tf.placeholder(shape=(), dtype=tf.string)\n tgt_file_placeholder = tf.placeholder(shape=(), dtype=tf.string)\n src_dataset = tf.data.TextLineDataset(src_file_placeholder)\n tgt_dataset = tf.data.TextLineDataset(tgt_file_placeholder)\n iterator = iterator_utils.get_iterator(\n src_dataset,\n tgt_dataset,\n src_vocab_table,\n tgt_vocab_table,\n hparams.batch_size,\n sos=hparams.sos,\n eos=hparams.eos,\n random_seed=hparams.random_seed,\n num_buckets=hparams.num_buckets,\n src_max_len=hparams.src_max_len_infer,\n tgt_max_len=hparams.tgt_max_len_infer,\n use_char_encode=hparams.use_char_encode)\n model = model_creator(\n hparams,\n iterator=iterator,\n mode=tf.contrib.learn.ModeKeys.EVAL,\n source_vocab_table=src_vocab_table,\n target_vocab_table=tgt_vocab_table,\n reverse_target_vocab_table=reverse_tgt_vocab_table,\n scope=scope,\n extra_args=extra_args)\n return EvalModel(\n graph=graph,\n model=model,\n src_file_placeholder=src_file_placeholder,\n tgt_file_placeholder=tgt_file_placeholder,\n iterator=iterator)\n\n\nclass InferModel(\n collections.namedtuple(\"InferModel\",\n (\"graph\", \"model\", \"src_placeholder\",\n \"batch_size_placeholder\", \"iterator\"))):\n pass\n\n\ndef create_infer_model(model_creator, hparams, scope=None, extra_args=None):\n \"\"\"Create inference model.\"\"\"\n graph = tf.Graph()\n src_vocab_file = hparams.src_vocab_file\n tgt_vocab_file = hparams.tgt_vocab_file\n\n with graph.as_default(), tf.container(scope or \"infer\"):\n src_vocab_table, tgt_vocab_table = vocab_utils.create_vocab_tables(\n src_vocab_file, tgt_vocab_file, hparams.share_vocab)\n reverse_tgt_vocab_table = lookup_ops.index_to_string_table_from_file(\n tgt_vocab_file, default_value=vocab_utils.UNK)\n\n src_placeholder = tf.placeholder(shape=[None], dtype=tf.string)\n batch_size_placeholder = tf.placeholder(shape=[], dtype=tf.int64)\n\n src_dataset = tf.data.Dataset.from_tensor_slices(\n src_placeholder)\n iterator = iterator_utils.get_infer_iterator(\n src_dataset,\n src_vocab_table,\n batch_size=batch_size_placeholder,\n eos=hparams.eos,\n src_max_len=hparams.src_max_len_infer,\n use_char_encode=hparams.use_char_encode)\n model = model_creator(\n hparams,\n iterator=iterator,\n mode=tf.contrib.learn.ModeKeys.INFER,\n source_vocab_table=src_vocab_table,\n target_vocab_table=tgt_vocab_table,\n reverse_target_vocab_table=reverse_tgt_vocab_table,\n scope=scope,\n extra_args=extra_args)\n return InferModel(\n graph=graph,\n model=model,\n src_placeholder=src_placeholder,\n batch_size_placeholder=batch_size_placeholder,\n iterator=iterator)\n\n\ndef _get_embed_device(vocab_size):\n \"\"\"Decide on which device to place an embed matrix given its vocab size.\"\"\"\n if vocab_size > VOCAB_SIZE_THRESHOLD_CPU:\n return \"/cpu:0\"\n else:\n return \"/gpu:0\"\n\n\ndef _create_pretrained_emb_from_txt(\n vocab_file, embed_file, num_trainable_tokens=3, dtype=tf.float32,\n scope=None):\n \"\"\"Load pretrain embeding from embed_file, and return an embedding matrix.\n\n Args:\n embed_file: Path to a Glove formated embedding txt file.\n num_trainable_tokens: Make the first n tokens in the vocab file as trainable\n variables. Default is 3, which is \"<unk>\", \"<s>\" and \"</s>\".\n \"\"\"\n vocab, _ = vocab_utils.load_vocab(vocab_file)\n trainable_tokens = vocab[:num_trainable_tokens]\n\n utils.print_out(\"# Using pretrained embedding: %s.\" % embed_file)\n utils.print_out(\" with trainable tokens: \")\n\n emb_dict, emb_size = vocab_utils.load_embed_txt(embed_file)\n for token in trainable_tokens:\n utils.print_out(\" %s\" % token)\n if token not in emb_dict:\n emb_dict[token] = [0.0] * emb_size\n\n emb_mat = np.array(\n [emb_dict[token] for token in vocab], dtype=dtype.as_numpy_dtype())\n emb_mat = tf.constant(emb_mat)\n emb_mat_const = tf.slice(emb_mat, [num_trainable_tokens, 0], [-1, -1])\n with tf.variable_scope(scope or \"pretrain_embeddings\", dtype=dtype) as scope:\n with tf.device(_get_embed_device(num_trainable_tokens)):\n emb_mat_var = tf.get_variable(\n \"emb_mat_var\", [num_trainable_tokens, emb_size])\n return tf.concat([emb_mat_var, emb_mat_const], 0)\n\n\ndef _create_or_load_embed(embed_name, vocab_file, embed_file,\n vocab_size, embed_size, dtype):\n \"\"\"Create a new or load an existing embedding matrix.\"\"\"\n if vocab_file and embed_file:\n embedding = _create_pretrained_emb_from_txt(vocab_file, embed_file)\n else:\n with tf.device(_get_embed_device(vocab_size)):\n embedding = tf.get_variable(\n embed_name, [vocab_size, embed_size], dtype)\n return embedding\n\n\ndef create_emb_for_encoder_and_decoder(share_vocab,\n src_vocab_size,\n tgt_vocab_size,\n src_embed_size,\n tgt_embed_size,\n dtype=tf.float32,\n num_enc_partitions=0,\n num_dec_partitions=0,\n src_vocab_file=None,\n tgt_vocab_file=None,\n src_embed_file=None,\n tgt_embed_file=None,\n use_char_encode=False,\n scope=None):\n \"\"\"Create embedding matrix for both encoder and decoder.\n\n Args:\n share_vocab: A boolean. Whether to share embedding matrix for both\n encoder and decoder.\n src_vocab_size: An integer. The source vocab size.\n tgt_vocab_size: An integer. The target vocab size.\n src_embed_size: An integer. The embedding dimension for the encoder's\n embedding.\n tgt_embed_size: An integer. The embedding dimension for the decoder's\n embedding.\n dtype: dtype of the embedding matrix. Default to float32.\n num_enc_partitions: number of partitions used for the encoder's embedding\n vars.\n num_dec_partitions: number of partitions used for the decoder's embedding\n vars.\n scope: VariableScope for the created subgraph. Default to \"embedding\".\n\n Returns:\n embedding_encoder: Encoder's embedding matrix.\n embedding_decoder: Decoder's embedding matrix.\n\n Raises:\n ValueError: if use share_vocab but source and target have different vocab\n size.\n \"\"\"\n if num_enc_partitions <= 1:\n enc_partitioner = None\n else:\n # Note: num_partitions > 1 is required for distributed training due to\n # embedding_lookup tries to colocate single partition-ed embedding variable\n # with lookup ops. This may cause embedding variables being placed on worker\n # jobs.\n enc_partitioner = tf.fixed_size_partitioner(num_enc_partitions)\n\n if num_dec_partitions <= 1:\n dec_partitioner = None\n else:\n # Note: num_partitions > 1 is required for distributed training due to\n # embedding_lookup tries to colocate single partition-ed embedding variable\n # with lookup ops. This may cause embedding variables being placed on worker\n # jobs.\n dec_partitioner = tf.fixed_size_partitioner(num_dec_partitions)\n\n if src_embed_file and enc_partitioner:\n raise ValueError(\n \"Can't set num_enc_partitions > 1 when using pretrained encoder \"\n \"embedding\")\n\n if tgt_embed_file and dec_partitioner:\n raise ValueError(\n \"Can't set num_dec_partitions > 1 when using pretrained decdoer \"\n \"embedding\")\n\n with tf.variable_scope(\n scope or \"embeddings\", dtype=dtype, partitioner=enc_partitioner) as scope:\n # Share embedding\n if share_vocab:\n if src_vocab_size != tgt_vocab_size:\n raise ValueError(\"Share embedding but different src/tgt vocab sizes\"\n \" %d vs. %d\" % (src_vocab_size, tgt_vocab_size))\n assert src_embed_size == tgt_embed_size\n utils.print_out(\"# Use the same embedding for source and target\")\n vocab_file = src_vocab_file or tgt_vocab_file\n embed_file = src_embed_file or tgt_embed_file\n\n embedding_encoder = _create_or_load_embed(\n \"embedding_share\", vocab_file, embed_file,\n src_vocab_size, src_embed_size, dtype)\n embedding_decoder = embedding_encoder\n else:\n if not use_char_encode:\n with tf.variable_scope(\"encoder\", partitioner=enc_partitioner):\n embedding_encoder = _create_or_load_embed(\n \"embedding_encoder\", src_vocab_file, src_embed_file,\n src_vocab_size, src_embed_size, dtype)\n else:\n embedding_encoder = None\n\n with tf.variable_scope(\"decoder\", partitioner=dec_partitioner):\n embedding_decoder = _create_or_load_embed(\n \"embedding_decoder\", tgt_vocab_file, tgt_embed_file,\n tgt_vocab_size, tgt_embed_size, dtype)\n\n return embedding_encoder, embedding_decoder\n\n\ndef _single_cell(unit_type, num_units, forget_bias, dropout, mode,\n residual_connection=False, device_str=None, residual_fn=None):\n \"\"\"Create an instance of a single RNN cell.\"\"\"\n # dropout (= 1 - keep_prob) is set to 0 during eval and infer\n dropout = dropout if mode == tf.contrib.learn.ModeKeys.TRAIN else 0.0\n\n # Cell Type\n if unit_type == \"lstm\":\n utils.print_out(\" LSTM, forget_bias=%g\" % forget_bias, new_line=False)\n single_cell = tf.contrib.rnn.BasicLSTMCell(\n num_units,\n forget_bias=forget_bias)\n elif unit_type == \"gru\":\n utils.print_out(\" GRU\", new_line=False)\n single_cell = tf.contrib.rnn.GRUCell(num_units)\n elif unit_type == \"layer_norm_lstm\":\n utils.print_out(\" Layer Normalized LSTM, forget_bias=%g\" % forget_bias,\n new_line=False)\n single_cell = tf.contrib.rnn.LayerNormBasicLSTMCell(\n num_units,\n forget_bias=forget_bias,\n layer_norm=True)\n elif unit_type == \"nas\":\n utils.print_out(\" NASCell\", new_line=False)\n single_cell = tf.contrib.rnn.NASCell(num_units)\n else:\n raise ValueError(\"Unknown unit type %s!\" % unit_type)\n\n # Dropout (= 1 - keep_prob)\n if dropout > 0.0:\n single_cell = tf.contrib.rnn.DropoutWrapper(\n cell=single_cell, input_keep_prob=(1.0 - dropout))\n utils.print_out(\" %s, dropout=%g \" % (type(single_cell).__name__, dropout),\n new_line=False)\n\n # Residual\n if residual_connection:\n single_cell = tf.contrib.rnn.ResidualWrapper(\n single_cell, residual_fn=residual_fn)\n utils.print_out(\" %s\" % type(single_cell).__name__, new_line=False)\n\n # Device Wrapper\n if device_str:\n single_cell = tf.contrib.rnn.DeviceWrapper(single_cell, device_str)\n utils.print_out(\" %s, device=%s\" %\n (type(single_cell).__name__, device_str), new_line=False)\n\n return single_cell\n\n\ndef _cell_list(unit_type, num_units, num_layers, num_residual_layers,\n forget_bias, dropout, mode, num_gpus, base_gpu=0,\n single_cell_fn=None, residual_fn=None):\n \"\"\"Create a list of RNN cells.\"\"\"\n if not single_cell_fn:\n single_cell_fn = _single_cell\n\n # Multi-GPU\n cell_list = []\n for i in range(num_layers):\n utils.print_out(\" cell %d\" % i, new_line=False)\n single_cell = single_cell_fn(\n unit_type=unit_type,\n num_units=num_units,\n forget_bias=forget_bias,\n dropout=dropout,\n mode=mode,\n residual_connection=(i >= num_layers - num_residual_layers),\n device_str=get_device_str(i + base_gpu, num_gpus),\n residual_fn=residual_fn\n )\n utils.print_out(\"\")\n cell_list.append(single_cell)\n\n return cell_list\n\n\ndef create_rnn_cell(unit_type, num_units, num_layers, num_residual_layers,\n forget_bias, dropout, mode, num_gpus, base_gpu=0,\n single_cell_fn=None):\n \"\"\"Create multi-layer RNN cell.\n\n Args:\n unit_type: string representing the unit type, i.e. \"lstm\".\n num_units: the depth of each unit.\n num_layers: number of cells.\n num_residual_layers: Number of residual layers from top to bottom. For\n example, if `num_layers=4` and `num_residual_layers=2`, the last 2 RNN\n cells in the returned list will be wrapped with `ResidualWrapper`.\n forget_bias: the initial forget bias of the RNNCell(s).\n dropout: floating point value between 0.0 and 1.0:\n the probability of dropout. this is ignored if `mode != TRAIN`.\n mode: either tf.contrib.learn.TRAIN/EVAL/INFER\n num_gpus: The number of gpus to use when performing round-robin\n placement of layers.\n base_gpu: The gpu device id to use for the first RNN cell in the\n returned list. The i-th RNN cell will use `(base_gpu + i) % num_gpus`\n as its device id.\n single_cell_fn: allow for adding customized cell.\n When not specified, we default to model_helper._single_cell\n Returns:\n An `RNNCell` instance.\n \"\"\"\n cell_list = _cell_list(unit_type=unit_type,\n num_units=num_units,\n num_layers=num_layers,\n num_residual_layers=num_residual_layers,\n forget_bias=forget_bias,\n dropout=dropout,\n mode=mode,\n num_gpus=num_gpus,\n base_gpu=base_gpu,\n single_cell_fn=single_cell_fn)\n\n if len(cell_list) == 1: # Single layer.\n return cell_list[0]\n else: # Multi layers\n return tf.contrib.rnn.MultiRNNCell(cell_list)\n\n\ndef gradient_clip(gradients, max_gradient_norm):\n \"\"\"Clipping gradients of a model.\"\"\"\n clipped_gradients, gradient_norm = tf.clip_by_global_norm(\n gradients, max_gradient_norm)\n gradient_norm_summary = [tf.summary.scalar(\"grad_norm\", gradient_norm)]\n gradient_norm_summary.append(\n tf.summary.scalar(\"clipped_gradient\", tf.global_norm(clipped_gradients)))\n\n return clipped_gradients, gradient_norm_summary, gradient_norm\n\n\ndef print_variables_in_ckpt(ckpt_path):\n \"\"\"Print a list of variables in a checkpoint together with their shapes.\"\"\"\n utils.print_out(\"# Variables in ckpt %s\" % ckpt_path)\n reader = tf.train.NewCheckpointReader(ckpt_path)\n variable_map = reader.get_variable_to_shape_map()\n for key in sorted(variable_map.keys()):\n utils.print_out(\" %s: %s\" % (key, variable_map[key]))\n\n\ndef load_model(model, ckpt_path, session, name):\n \"\"\"Load model from a checkpoint.\"\"\"\n start_time = time.time()\n try:\n model.saver.restore(session, ckpt_path)\n except tf.errors.NotFoundError as e:\n utils.print_out(\"Can't load checkpoint\")\n print_variables_in_ckpt(ckpt_path)\n utils.print_out(\"%s\" % str(e))\n\n session.run(tf.tables_initializer())\n utils.print_out(\n \" loaded %s model parameters from %s, time %.2fs\" %\n (name, ckpt_path, time.time() - start_time))\n return model\n\n\ndef avg_checkpoints(model_dir, num_last_checkpoints, global_step,\n global_step_name):\n \"\"\"Average the last N checkpoints in the model_dir.\"\"\"\n checkpoint_state = tf.train.get_checkpoint_state(model_dir)\n if not checkpoint_state:\n utils.print_out(\"# No checkpoint file found in directory: %s\" % model_dir)\n return None\n\n # Checkpoints are ordered from oldest to newest.\n checkpoints = (\n checkpoint_state.all_model_checkpoint_paths[-num_last_checkpoints:])\n\n if len(checkpoints) < num_last_checkpoints:\n utils.print_out(\n \"# Skipping averaging checkpoints because not enough checkpoints is \"\n \"avaliable.\"\n )\n return None\n\n avg_model_dir = os.path.join(model_dir, \"avg_checkpoints\")\n if not tf.gfile.Exists(avg_model_dir):\n utils.print_out(\n \"# Creating new directory %s for saving averaged checkpoints.\" %\n avg_model_dir)\n tf.gfile.MakeDirs(avg_model_dir)\n\n utils.print_out(\"# Reading and averaging variables in checkpoints:\")\n var_list = tf.contrib.framework.list_variables(checkpoints[0])\n var_values, var_dtypes = {}, {}\n for (name, shape) in var_list:\n if name != global_step_name:\n var_values[name] = np.zeros(shape)\n\n for checkpoint in checkpoints:\n utils.print_out(\" %s\" % checkpoint)\n reader = tf.contrib.framework.load_checkpoint(checkpoint)\n for name in var_values:\n tensor = reader.get_tensor(name)\n var_dtypes[name] = tensor.dtype\n var_values[name] += tensor\n\n for name in var_values:\n var_values[name] /= len(checkpoints)\n\n # Build a graph with same variables in the checkpoints, and save the averaged\n # variables into the avg_model_dir.\n with tf.Graph().as_default():\n tf_vars = [\n tf.get_variable(v, shape=var_values[v].shape, dtype=var_dtypes[name])\n for v in var_values\n ]\n\n placeholders = [tf.placeholder(v.dtype, shape=v.shape) for v in tf_vars]\n assign_ops = [tf.assign(v, p) for (v, p) in zip(tf_vars, placeholders)]\n global_step_var = tf.Variable(\n global_step, name=global_step_name, trainable=False)\n saver = tf.train.Saver(tf.all_variables())\n\n with tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n for p, assign_op, (name, value) in zip(placeholders, assign_ops,\n six.iteritems(var_values)):\n sess.run(assign_op, {p: value})\n\n # Use the built saver to save the averaged checkpoint. Only keep 1\n # checkpoint and the best checkpoint will be moved to avg_best_metric_dir.\n saver.save(\n sess,\n os.path.join(avg_model_dir, \"translate.ckpt\"))\n\n return avg_model_dir\n\n\ndef create_or_load_model(model, model_dir, session, name):\n \"\"\"Create translation model and initialize or load parameters in session.\"\"\"\n latest_ckpt = tf.train.latest_checkpoint(model_dir)\n if latest_ckpt:\n model = load_model(model, latest_ckpt, session, name)\n else:\n start_time = time.time()\n session.run(tf.global_variables_initializer())\n session.run(tf.tables_initializer())\n utils.print_out(\" created %s model with fresh parameters, time %.2fs\" %\n (name, time.time() - start_time))\n\n global_step = model.global_step.eval(session=session)\n return model, global_step\n\n\ndef compute_perplexity(model, sess, name):\n \"\"\"Compute perplexity of the output of the model.\n\n Args:\n model: model for compute perplexity.\n sess: tensorflow session to use.\n name: name of the batch.\n\n Returns:\n The perplexity of the eval outputs.\n \"\"\"\n total_loss = 0\n total_predict_count = 0\n start_time = time.time()\n\n while True:\n try:\n output_tuple = model.eval(sess)\n total_loss += output_tuple.eval_loss * output_tuple.batch_size\n total_predict_count += output_tuple.predict_count\n except tf.errors.OutOfRangeError:\n break\n\n perplexity = utils.safe_exp(total_loss / total_predict_count)\n utils.print_time(\" eval %s: perplexity %.2f\" % (name, perplexity),\n start_time)\n return perplexity\n" ]
[ [ "tensorflow.placeholder", "tensorflow.set_random_seed", "tensorflow.contrib.training.HParams", "tensorflow.constant", "tensorflow.test.main", "tensorflow.tables_initializer" ], [ "tensorflow.data.TextLineDataset", "tensorflow.summary.scalar", "tensorflow.initialize_all_variables", "tensorflow.contrib.rnn.MultiRNNCell", "tensorflow.python.ops.lookup_ops.index_to_string_table_from_file", "tensorflow.variable_scope", "tensorflow.contrib.rnn.DropoutWrapper", "tensorflow.contrib.rnn.LayerNormBasicLSTMCell", "tensorflow.concat", "tensorflow.slice", "tensorflow.Variable", "tensorflow.all_variables", "tensorflow.contrib.rnn.NASCell", "tensorflow.tables_initializer", "tensorflow.contrib.rnn.GRUCell", "tensorflow.global_variables_initializer", "tensorflow.fixed_size_partitioner", "tensorflow.clip_by_global_norm", "tensorflow.device", "tensorflow.train.NewCheckpointReader", "tensorflow.gfile.Glob", "tensorflow.Graph", "tensorflow.random_uniform_initializer", "tensorflow.gfile.MakeDirs", "tensorflow.contrib.framework.load_checkpoint", "tensorflow.contrib.framework.list_variables", "tensorflow.constant", "tensorflow.contrib.rnn.BasicLSTMCell", "tensorflow.contrib.rnn.DeviceWrapper", "numpy.zeros", "tensorflow.assign", "tensorflow.Session", "tensorflow.contrib.rnn.ResidualWrapper", "tensorflow.keras.initializers.glorot_uniform", "tensorflow.placeholder", "tensorflow.train.get_checkpoint_state", "tensorflow.keras.initializers.glorot_normal", "tensorflow.train.latest_checkpoint", "tensorflow.container", "tensorflow.global_norm", "tensorflow.gfile.Exists", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.get_variable" ] ]
OlegSomov/light-motion-analysis
[ "4f510250aaa32929a6ccff3c796b53151addb9e9" ]
[ "misc/graph.py" ]
[ "import os\nimport matplotlib\nimport json\nfrom datetime import datetime\nfrom matplotlib import pyplot\n\n\ndef show_results_graph(timer, name=None):\n with (open('light_plot.json', 'r')) as f:\n data = json.load(f)\n\n with (open('light_plot_imporved.json', 'r')) as f:\n data_improved = json.load(f)\n\n os.remove('light_plot.json')\n os.remove('light_plot_imporved.json')\n x = []\n y = []\n x_improved = []\n y_improved = []\n\n for item in data:\n date = datetime.strptime(item['x'], \"%Y-%m-%d %H:%M:%S\")\n x.append(date)\n if item['y'] == 1:\n y.append(item['y'] + 0.1) # to distinct normal light and improved light states\n else:\n y.append(item['y'])\n\n for item in data_improved:\n date = datetime.strptime(item['x'], \"%Y-%m-%d %H:%M:%S\")\n x_improved.append(date)\n y_improved.append(item['y'])\n\n dates_normal = matplotlib.dates.date2num(x)\n dates_improved = matplotlib.dates.date2num(x_improved)\n\n matplotlib.pyplot.plot_date(dates_normal, y, 'b-', label=\"Regular data\", linewidth=2)\n matplotlib.pyplot.plot_date(dates_improved, y_improved, 'b-', color=\"red\", label=\"Possible improvement\", linewidth=2)\n pyplot.title(\"Compare actual data and possible improvement ({} minutes)\".format(timer))\n pyplot.legend()\n if name:\n pyplot.savefig(\"result.png\")\n pyplot.show()\n" ]
[ [ "matplotlib.pyplot.plot_date", "matplotlib.pyplot.legend", "matplotlib.pyplot.savefig", "matplotlib.pyplot.show", "matplotlib.dates.date2num" ] ]
wanghongsheng01/framework_enflame
[ "debf613e05e3f5ea8084c3e79b60d0dd9e349526", "debf613e05e3f5ea8084c3e79b60d0dd9e349526", "debf613e05e3f5ea8084c3e79b60d0dd9e349526", "debf613e05e3f5ea8084c3e79b60d0dd9e349526" ]
[ "oneflow/python/test/ops/test_function_input_output.py", "oneflow/python/test/ops/test_binary_elementwise_ops.py", "oneflow/python/test/ops/test_all_reduce_group.py", "oneflow/python/test/ops/test_gelu.py" ]
[ "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport unittest\nimport numpy as np\nimport oneflow as flow\nimport oneflow.typing as oft\nimport oneflow._oneflow_internal\nfrom typing import Tuple\n\n\[email protected]_unless_1n4d()\nclass TestFunctionInputOutput(flow.unittest.TestCase):\n def test_FixedTensorDef(test_case):\n @flow.global_function()\n def Foo(x: oft.Numpy.Placeholder((2, 5))):\n return x\n\n data = np.ones((2, 5), dtype=np.float32)\n of_ret = Foo(data).get()\n test_case.assertEqual(of_ret.numpy().max(), 1)\n test_case.assertEqual(of_ret.numpy().min(), 1)\n test_case.assertTrue(np.allclose(of_ret.numpy(), data))\n\n def test_FixedTensorDef_2_device(test_case):\n flow.config.gpu_device_num(2)\n\n @flow.global_function()\n def Foo(x: oft.Numpy.Placeholder((2, 5))):\n return x\n\n data = np.ones((2, 5), dtype=np.float32)\n of_ret = Foo(data).get()\n test_case.assertEqual(of_ret.numpy().max(), 1)\n test_case.assertEqual(of_ret.numpy().min(), 1)\n test_case.assertTrue(np.allclose(of_ret.numpy(), data))\n\n def test_MirroredTensorDef(test_case):\n func_config = flow.FunctionConfig()\n func_config.default_logical_view(flow.scope.mirrored_view())\n\n @flow.global_function(function_config=func_config)\n def Foo(x: oft.ListNumpy.Placeholder((2, 5))):\n return x\n\n data = np.ones((1, 5), dtype=np.float32)\n ndarray_list = Foo([data]).get().numpy_list()\n test_case.assertEqual(len(ndarray_list), 1)\n test_case.assertTrue(np.allclose(ndarray_list[0], data))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport unittest\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport oneflow as flow\nfrom collections import OrderedDict\nimport oneflow.typing as oft\n\nimport test_global_storage\nfrom test_util import (\n GenArgDict,\n GenArgList,\n type_name_to_flow_type,\n type_name_to_np_type,\n)\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n\n\ndef RunOneflowBinaryOp(device_type, flow_op, x, y, data_type):\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float)\n\n flow_type = type_name_to_flow_type[data_type]\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def FlowJob(\n x: oft.Numpy.Placeholder(x.shape, dtype=flow_type),\n y: oft.Numpy.Placeholder(y.shape, dtype=flow_type),\n ):\n with flow.scope.placement(device_type, \"0:0\"):\n x += flow.get_variable(\n name=\"x\",\n shape=x.shape,\n dtype=flow_type,\n initializer=flow.zeros_initializer(),\n trainable=True,\n )\n y += flow.get_variable(\n name=\"y\",\n shape=y.shape,\n dtype=flow_type,\n initializer=flow.zeros_initializer(),\n trainable=True,\n )\n loss = flow_op(x, y)\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [1e-4]), momentum=0\n ).minimize(loss)\n flow.watch_diff(x, test_global_storage.Setter(\"x_diff\"))\n flow.watch_diff(y, test_global_storage.Setter(\"y_diff\"))\n\n return loss\n\n # Oneflow\n out = FlowJob(x, y).get().numpy()\n x_diff = test_global_storage.Get(\"x_diff\")\n y_diff = test_global_storage.Get(\"y_diff\")\n return out, x_diff, y_diff\n\n\ndef RunTensorFlowBinaryOp(tf_op, x, y):\n # TensorFlow\n with tf.GradientTape(persistent=True) as tape:\n x = tf.Variable(x)\n y = tf.Variable(y)\n out = tf_op(x, y)\n x_diff = tape.gradient(out, x)\n y_diff = tape.gradient(out, y)\n return out.numpy(), x_diff, y_diff\n\n\ndef compare_with_tensorflow(\n test_case,\n device_type,\n flow_op,\n tf_op,\n x_shape,\n y_shape,\n data_type,\n x_minval=-10,\n x_maxval=10,\n y_minval=-10,\n y_maxval=10,\n compare_grad=True,\n out_rtol=1e-5,\n out_atol=1e-5,\n diff_rtol=1e-5,\n diff_atol=1e-5,\n):\n test_case.assertTrue(device_type in [\"gpu\", \"cpu\"])\n\n np_type = type_name_to_np_type[data_type]\n x = np.random.uniform(low=x_minval, high=x_maxval, size=x_shape).astype(np_type)\n y = np.random.uniform(low=y_minval, high=y_maxval, size=y_shape).astype(np_type)\n\n of_out, of_x_diff, of_y_diff, = RunOneflowBinaryOp(\n device_type, flow_op, x, y, data_type\n )\n tf_out, tf_x_diff, tf_y_diff = RunTensorFlowBinaryOp(tf_op, x, y)\n\n test_case.assertTrue(\n np.allclose(of_out, tf_out, rtol=out_rtol, atol=out_atol, equal_nan=True)\n )\n if compare_grad:\n test_case.assertTrue(\n np.allclose(\n of_x_diff,\n tf_x_diff.numpy(),\n rtol=diff_rtol,\n atol=diff_atol,\n equal_nan=True,\n )\n )\n test_case.assertTrue(\n np.allclose(\n of_y_diff,\n tf_y_diff.numpy(),\n rtol=diff_rtol,\n atol=diff_atol,\n equal_nan=True,\n )\n )\n flow.clear_default_session()\n\n\[email protected]_unless_1n1d()\nclass TestBinaryElementwiseOps(flow.unittest.TestCase):\n def test_floordiv(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_case\"] = [test_case]\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"flow_op\"] = [flow.math.floordiv]\n arg_dict[\"tf_op\"] = [tf.math.floordiv]\n arg_dict[\"x_shape\"] = [(5, 5,)]\n arg_dict[\"y_shape\"] = [(5, 5,)]\n arg_dict[\"data_type\"] = [\"float32\", \"double\"]\n arg_dict[\"x_minval\"] = [-10]\n arg_dict[\"x_maxval\"] = [10]\n arg_dict[\"y_minval\"] = [1]\n arg_dict[\"y_maxval\"] = [10]\n arg_dict[\"compare_grad\"] = [False]\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow(*arg)\n\n def test_pow(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_case\"] = [test_case]\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"flow_op\"] = [flow.math.pow]\n arg_dict[\"tf_op\"] = [tf.math.pow]\n arg_dict[\"x_shape\"] = [(5, 5,)]\n arg_dict[\"y_shape\"] = [(5, 5,)]\n arg_dict[\"data_type\"] = [\"float32\", \"double\"]\n arg_dict[\"x_minval\"] = [1]\n arg_dict[\"x_maxval\"] = [5]\n arg_dict[\"y_minval\"] = [1]\n arg_dict[\"y_maxval\"] = [5]\n arg_dict[\"compare_grad\"] = [True]\n\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow(*arg)\n\n def test_xdivy(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_case\"] = [test_case]\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"flow_op\"] = [flow.math.xdivy]\n arg_dict[\"tf_op\"] = [tf.math.xdivy]\n arg_dict[\"x_shape\"] = [(5, 5,)]\n arg_dict[\"y_shape\"] = [(5, 5,)]\n arg_dict[\"data_type\"] = [\"float32\", \"double\"]\n arg_dict[\"x_minval\"] = [1]\n arg_dict[\"x_maxval\"] = [100]\n arg_dict[\"y_minval\"] = [1]\n arg_dict[\"y_maxval\"] = [10]\n arg_dict[\"compare_grad\"] = [True]\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow(*arg)\n\n def test_xlogy(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_case\"] = [test_case]\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"flow_op\"] = [flow.math.xlogy]\n arg_dict[\"tf_op\"] = [tf.math.xlogy]\n arg_dict[\"x_shape\"] = [(5, 5,)]\n arg_dict[\"y_shape\"] = [(5, 5,)]\n arg_dict[\"data_type\"] = [\"float32\", \"double\"]\n arg_dict[\"x_minval\"] = [1]\n arg_dict[\"x_maxval\"] = [5]\n arg_dict[\"y_minval\"] = [1]\n arg_dict[\"y_maxval\"] = [5]\n arg_dict[\"compare_grad\"] = [True]\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow(*arg)\n\n def test_atan2(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_case\"] = [test_case]\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"flow_op\"] = [flow.math.atan2]\n arg_dict[\"tf_op\"] = [tf.math.atan2]\n arg_dict[\"x_shape\"] = [(5, 5,)]\n arg_dict[\"y_shape\"] = [(5, 5,)]\n arg_dict[\"data_type\"] = [\"float32\", \"double\"]\n arg_dict[\"x_minval\"] = [1]\n arg_dict[\"x_maxval\"] = [5]\n arg_dict[\"y_minval\"] = [1]\n arg_dict[\"y_maxval\"] = [5]\n arg_dict[\"compare_grad\"] = [True]\n\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow(*arg)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom collections import OrderedDict\n\nimport numpy as np\nimport oneflow as flow\nfrom test_util import GenArgList\nimport unittest\nimport os\n\n\ndef do_test(test_case, mirrored):\n flow.clear_default_session()\n flow.config.gpu_device_num(2)\n func_config = flow.FunctionConfig()\n\n if mirrored:\n func_config.default_logical_view(flow.scope.mirrored_view())\n else:\n func_config.default_logical_view(flow.scope.consistent_view())\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def Foo():\n w = flow.get_variable(\"w\", (10,), initializer=flow.constant_initializer(1))\n lr_scheduler = flow.optimizer.PiecewiseConstantScheduler([], [5])\n flow.optimizer.SGD(lr_scheduler, momentum=0).minimize(w)\n return w\n\n r1 = Foo().get().numpy()\n test_case.assertTrue(np.all(r1 == 1.0))\n r2 = Foo().get().numpy()\n test_case.assertTrue(np.all(r2 == 0.5))\n\n\[email protected]_unless_1n2d()\nclass TestAllReduceGroup(flow.unittest.TestCase):\n @unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\n def test_variable_as_loss_on_two_device(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"mirrored\"] = [True, False]\n for arg in GenArgList(arg_dict):\n do_test(test_case, *arg)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport unittest\nimport math\nimport os\nfrom collections import OrderedDict\n\nimport numpy as np\nimport oneflow as flow\nimport tensorflow as tf\nfrom test_util import GenArgDict, RunOneflowOp\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n\n\ndef tf_gelu(x):\n inv_sqrt2 = math.sqrt(0.5)\n with tf.GradientTape(persistent=True) as tape:\n x = tf.Variable(x)\n y = 0.5 * x * (1 + tf.math.erf(inv_sqrt2 * x))\n x_diff = tape.gradient(y, x)\n return y.numpy(), x_diff.numpy()\n\n\[email protected]_unless_1n1d()\nclass TestGelu(flow.unittest.TestCase):\n def test_gelu(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\"]\n arg_dict[\"flow_op\"] = [flow.math.gelu]\n arg_dict[\"flow_args\"] = [[]]\n arg_dict[\"x\"] = [\n np.random.uniform(low=-100, high=100, size=(10, 20, 30, 40)).astype(\n np.float32\n )\n ]\n for arg in GenArgDict(arg_dict):\n of_y, of_x_diff = RunOneflowOp(**arg)\n tf_y, tf_x_diff = tf_gelu(arg[\"x\"])\n\n assert np.allclose(of_y, tf_y, rtol=1e-5, atol=1e-5)\n assert np.allclose(of_x_diff, tf_x_diff, rtol=1e-5, atol=1e-5)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.ones", "numpy.allclose" ], [ "numpy.random.uniform", "numpy.allclose", "tensorflow.config.experimental.set_memory_growth", "tensorflow.GradientTape", "tensorflow.Variable", "tensorflow.config.experimental.list_physical_devices" ], [ "numpy.all" ], [ "numpy.random.uniform", "numpy.allclose", "tensorflow.config.experimental.set_memory_growth", "tensorflow.GradientTape", "tensorflow.Variable", "tensorflow.config.experimental.list_physical_devices", "tensorflow.math.erf" ] ]
ConsultingMD/covid-data-public
[ "2b7091f7cc3877df45a7887709e999b0ebdf30ec" ]
[ "scripts/update_forecast_hub.py" ]
[ "import enum\nfrom typing import Any\n\nimport click\nimport pandas as pd\nimport numpy as np\nimport structlog\nimport pathlib\nimport pydantic\nimport datetime\n\nimport zoltpy.util\n\nfrom covidactnow.datapublic import common_init, common_df\nfrom scripts import helpers\n\n\nfrom covidactnow.datapublic.common_fields import (\n GetByValueMixin,\n CommonFields,\n FieldNameAndCommonField,\n)\n\nDATA_ROOT = pathlib.Path(__file__).parent.parent / \"data\"\n\n_logger = structlog.get_logger(__name__)\n\n\nclass ForecastModel(enum.Enum):\n \"\"\"\"\"\"\n\n ENSEMBLE = \"COVIDhub-ensemble\"\n BASELINE = \"COVIDhub-baseline\"\n GOOGLE = \"Google_Harvard-CPF\"\n\n\nclass Fields(GetByValueMixin, FieldNameAndCommonField, enum.Enum):\n MODEL_ABBR = \"model_abbr\", CommonFields.MODEL_ABBR\n REGION = \"unit\", CommonFields.FIPS\n FORECAST_DATE = \"forecast_date\", CommonFields.FORECAST_DATE\n TARGET_DATE = \"target_date\", CommonFields.DATE\n QUANTILE = \"quantile\", CommonFields.QUANTILE\n WEEKLY_NEW_CASES = \"case\", CommonFields.WEEKLY_NEW_CASES\n WEEKLY_NEW_DEATHS = \"death\", CommonFields.WEEKLY_NEW_DEATHS\n\n\nclass ForecastHubUpdater(pydantic.BaseModel):\n \"\"\"Updates Forecast Lab Data Set with the Latest Available Forecast\n \"\"\"\n\n FORECAST_PROJECT_NAME = \"COVID-19 Forecasts\"\n RAW_CSV_FILENAME = \"raw.csv\"\n\n conn: Any # A valid zoltpy connection\n\n model: ForecastModel # The model to cache from Zoltar\n\n raw_data_root: pathlib.Path\n\n timeseries_output_path: pathlib.Path\n\n @classmethod\n def make_with_data_root(\n cls, model: ForecastModel, conn: Any, data_root: pathlib.Path,\n ) -> \"ForecastHubUpdater\":\n return cls(\n model=model,\n conn=conn,\n raw_data_root=data_root / \"forecast-hub\",\n timeseries_output_path=data_root / \"forecast-hub\" / \"timeseries-common.csv\",\n )\n\n @property\n def raw_path(self):\n return self.raw_data_root / self.RAW_CSV_FILENAME\n\n def write_version_file(self, forecast_date) -> None:\n stamp = datetime.datetime.utcnow().isoformat()\n version_path = self.raw_data_root / \"version.txt\"\n with version_path.open(\"w\") as vf:\n vf.write(f\"Updated on {stamp}\\n\")\n vf.write(f\"Using forecast from {forecast_date}\\n\")\n\n def update_source_data(self):\n \"\"\"\n See https://github.com/reichlab/zoltpy/tree/master for instructions.\n\n Note: Requires environment variables for Z_USERNAME and Z_PASSWORD with correct\n permissions.\n \"\"\"\n _logger.info(f\"Updating {self.model.name} from ForecastHub\")\n latest_forecast_date = get_latest_forecast_date(\n self.conn, self.FORECAST_PROJECT_NAME, self.model.value\n )\n # TODO: Save a call to the Forecast Hub by checking if latest_forecast_date is newer than\n # the current one saved in version.txt. We expect the cache to be invalidated only once a\n # week.\n ensemble = zoltpy.util.download_forecast(\n self.conn, self.FORECAST_PROJECT_NAME, self.model.value, latest_forecast_date\n )\n df = zoltpy.util.dataframe_from_json_io_dict(ensemble)\n df[\"forecast_date\"] = pd.to_datetime(latest_forecast_date)\n df[\"model_abbr\"] = self.model.value\n df.to_csv(self.raw_path, index=False)\n self.write_version_file(forecast_date=latest_forecast_date)\n\n def load_source_data(self) -> pd.DataFrame:\n _logger.info(\"Updating ForecastHub Ensemble dataset.\")\n data = pd.read_csv(\n self.raw_path, parse_dates=[\"forecast_date\"], dtype={\"unit\": str}, low_memory=False\n )\n return data\n\n @staticmethod\n def transform(df: pd.DataFrame) -> pd.DataFrame:\n df[\"target_date\"] = df.apply(\n lambda x: x.forecast_date + pd.Timedelta(weeks=int(x.target.split(\" \")[0])),\n axis=\"columns\",\n )\n # The targets have the form \"X wk inc/cum cases/deaths\"\n # Take the final split (death/cases) and use that as target type\n df[\"target_type\"] = df.target.str.split(\" \").str[-1]\n # Take the penultimate split (inc/cum) and use that as aggregation type\n df[\"target_summation\"] = df.target.str.split(\" \").str[-2]\n\n masks = [\n df[\"unit\"] != \"US\", # Drop the national forecast\n df[\"quantile\"].notna(), # Point forecasts are duplicate of quantile = 0.5\n df[\"target_summation\"] == \"inc\", # Only return incidence values\n # Some models return both incidence and cumulative values\n # Only keep incidence targets (drop cumulative targets)\n df[\"target_date\"] <= df[\"forecast_date\"] + pd.Timedelta(weeks=4)\n # Time Horizon - Only keep up to 4 week forecasts.\n # Almost all forecasts only provide 4 wks.\n ]\n mask = np.logical_and.reduce(masks)\n\n # The raw data is in long form and we need to pivot this to create a column for\n # WEEKLY_NEW_CASES and WEEKLY_NEW_DEATHS. \"target_type\" has either death or cases. \"value\"\n # has the predicted value. The rest of the columns create a unique index. For right now only\n # one model and one forecast_date are being served, but we need to maintain the option of\n # multiple values.\n COLUMNS = [\n Fields.MODEL_ABBR,\n Fields.REGION,\n Fields.FORECAST_DATE,\n Fields.TARGET_DATE,\n \"target_type\",\n Fields.QUANTILE,\n \"value\",\n ]\n df = df[mask][COLUMNS].copy()\n df = df.set_index(\n [\n Fields.MODEL_ABBR,\n Fields.REGION,\n Fields.FORECAST_DATE,\n Fields.TARGET_DATE,\n Fields.QUANTILE,\n ]\n )\n pivot = df.pivot(columns=\"target_type\")\n pivot = pivot.droplevel(level=0, axis=1).reset_index()\n # This cleans up a MultiIndex Column that is an artifact of the pivot in preparation for a\n # standard csv dump.\n\n # Rename and remove any columns without a CommonField\n data = helpers.rename_fields(pivot, Fields, set(), _logger)\n\n # Need to make the quantiles into a wide form for easier downstream processing\n # Mangling the column names into f\"weekly_new_{cases/deaths}_{quantile}\". This\n # would be a good candidate to handle in long/tidy-form and we could remove both pivots.\n # Using common_field because this is done after helpers.rename_fields\n\n # TODO(michael): Not sure why pylint is confused about the common_field member not existing.\n # pylint: disable=no-member\n wide_df = data.set_index(\n [\n Fields.REGION.common_field,\n Fields.TARGET_DATE.common_field,\n Fields.MODEL_ABBR.common_field,\n Fields.FORECAST_DATE.common_field,\n ]\n ).pivot(columns=Fields.QUANTILE.common_field)\n\n # TODO: Once requirements have settled, explicitly pass only the quantiles needed.\n wide_df.columns = [x[0] + \"_\" + str(x[1]) for x in wide_df.columns.to_flat_index()]\n wide_df = wide_df.reset_index()\n return wide_df\n\n\ndef get_latest_forecast_date(conn, project_name: str, model_abbr: str) -> str:\n \"\"\"\n Return the date string 'YYYY-MM-DD' of the latest submitted forecast for a given model in a\n given zoltar project\n\n https://github.com/reichlab/zoltpy/issues/42\n\n\n Return the str date representation of the latest forecast if available, else the empty string.\n \"\"\"\n\n project = [project for project in conn.projects if project.name == project_name][0]\n model = [model for model in project.models if model.abbreviation == model_abbr][0]\n latest_forecast_date = model.latest_forecast.timezero.timezero_date\n # Note: model.latest_forecast.timezero.timezero_date is of type datetime.datetime or None\n if latest_forecast_date:\n _logger.info(f\"Latest forecast for {model_abbr} is {latest_forecast_date}\")\n return str(latest_forecast_date)\n else:\n _logger.info(f\"No forecasts found for {model_abbr} in {project_name}\")\n return \"\"\n\n\[email protected]()\[email protected](\"--fetch/--no-fetch\", default=True)\ndef main(fetch: bool):\n common_init.configure_logging()\n connection = zoltpy.util.authenticate()\n transformer = ForecastHubUpdater.make_with_data_root(\n ForecastModel.ENSEMBLE, connection, DATA_ROOT\n )\n if fetch:\n _logger.info(\"Fetching new data.\")\n transformer.update_source_data()\n\n data = transformer.load_source_data()\n data = transformer.transform(data)\n common_df.write_csv(data, transformer.timeseries_output_path, _logger)\n\n\nif __name__ == \"__main__\":\n main() # pylint: disable=no-value-for-parameter\n" ]
[ [ "pandas.read_csv", "pandas.to_datetime", "numpy.logical_and.reduce", "pandas.Timedelta" ] ]
FlingeR/pandas
[ "01f399854f9febefa9e97005f3720aa312409b98" ]
[ "pandas/core/indexes/multi.py" ]
[ "from sys import getsizeof\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Hashable,\n Iterable,\n List,\n Optional,\n Sequence,\n Tuple,\n Union,\n)\nimport warnings\n\nimport numpy as np\n\nfrom pandas._config import get_option\n\nfrom pandas._libs import algos as libalgos, index as libindex, lib\nfrom pandas._libs.hashtable import duplicated_int64\nfrom pandas._typing import AnyArrayLike, ArrayLike, Scalar\nfrom pandas.compat.numpy import function as nv\nfrom pandas.errors import PerformanceWarning, UnsortedIndexError\nfrom pandas.util._decorators import Appender, cache_readonly\n\nfrom pandas.core.dtypes.cast import coerce_indexer_dtype\nfrom pandas.core.dtypes.common import (\n ensure_int64,\n ensure_platform_int,\n is_categorical_dtype,\n is_hashable,\n is_integer,\n is_iterator,\n is_list_like,\n is_object_dtype,\n is_scalar,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.dtypes import ExtensionDtype\nfrom pandas.core.dtypes.generic import ABCDataFrame\nfrom pandas.core.dtypes.missing import array_equivalent, isna\n\nimport pandas.core.algorithms as algos\nfrom pandas.core.arrays import Categorical\nfrom pandas.core.arrays.categorical import factorize_from_iterables\nimport pandas.core.common as com\nimport pandas.core.indexes.base as ibase\nfrom pandas.core.indexes.base import (\n Index,\n InvalidIndexError,\n _index_shared_docs,\n ensure_index,\n)\nfrom pandas.core.indexes.frozen import FrozenList\nimport pandas.core.missing as missing\nfrom pandas.core.sorting import (\n get_group_index,\n indexer_from_factorized,\n lexsort_indexer,\n)\n\nfrom pandas.io.formats.printing import (\n format_object_attrs,\n format_object_summary,\n pprint_thing,\n)\n\nif TYPE_CHECKING:\n from pandas import Series # noqa:F401\n\n_index_doc_kwargs = dict(ibase._index_doc_kwargs)\n_index_doc_kwargs.update(\n dict(klass=\"MultiIndex\", target_klass=\"MultiIndex or list of tuples\")\n)\n\n\nclass MultiIndexUIntEngine(libindex.BaseMultiIndexCodesEngine, libindex.UInt64Engine):\n \"\"\"\n This class manages a MultiIndex by mapping label combinations to positive\n integers.\n \"\"\"\n\n _base = libindex.UInt64Engine\n\n def _codes_to_ints(self, codes):\n \"\"\"\n Transform combination(s) of uint64 in one uint64 (each), in a strictly\n monotonic way (i.e. respecting the lexicographic order of integer\n combinations): see BaseMultiIndexCodesEngine documentation.\n\n Parameters\n ----------\n codes : 1- or 2-dimensional array of dtype uint64\n Combinations of integers (one per row)\n\n Returns\n -------\n scalar or 1-dimensional array, of dtype uint64\n Integer(s) representing one combination (each).\n \"\"\"\n # Shift the representation of each level by the pre-calculated number\n # of bits:\n codes <<= self.offsets\n\n # Now sum and OR are in fact interchangeable. This is a simple\n # composition of the (disjunct) significant bits of each level (i.e.\n # each column in \"codes\") in a single positive integer:\n if codes.ndim == 1:\n # Single key\n return np.bitwise_or.reduce(codes)\n\n # Multiple keys\n return np.bitwise_or.reduce(codes, axis=1)\n\n\nclass MultiIndexPyIntEngine(libindex.BaseMultiIndexCodesEngine, libindex.ObjectEngine):\n \"\"\"\n This class manages those (extreme) cases in which the number of possible\n label combinations overflows the 64 bits integers, and uses an ObjectEngine\n containing Python integers.\n \"\"\"\n\n _base = libindex.ObjectEngine\n\n def _codes_to_ints(self, codes):\n \"\"\"\n Transform combination(s) of uint64 in one Python integer (each), in a\n strictly monotonic way (i.e. respecting the lexicographic order of\n integer combinations): see BaseMultiIndexCodesEngine documentation.\n\n Parameters\n ----------\n codes : 1- or 2-dimensional array of dtype uint64\n Combinations of integers (one per row)\n\n Returns\n -------\n int, or 1-dimensional array of dtype object\n Integer(s) representing one combination (each).\n \"\"\"\n # Shift the representation of each level by the pre-calculated number\n # of bits. Since this can overflow uint64, first make sure we are\n # working with Python integers:\n codes = codes.astype(\"object\") << self.offsets\n\n # Now sum and OR are in fact interchangeable. This is a simple\n # composition of the (disjunct) significant bits of each level (i.e.\n # each column in \"codes\") in a single positive integer (per row):\n if codes.ndim == 1:\n # Single key\n return np.bitwise_or.reduce(codes)\n\n # Multiple keys\n return np.bitwise_or.reduce(codes, axis=1)\n\n\nclass MultiIndex(Index):\n \"\"\"\n A multi-level, or hierarchical, index object for pandas objects.\n\n Parameters\n ----------\n levels : sequence of arrays\n The unique labels for each level.\n codes : sequence of arrays\n Integers for each level designating which label at each location.\n\n .. versionadded:: 0.24.0\n sortorder : optional int\n Level of sortedness (must be lexicographically sorted by that\n level).\n names : optional sequence of objects\n Names for each of the index levels. (name is accepted for compat).\n copy : bool, default False\n Copy the meta-data.\n verify_integrity : bool, default True\n Check that the levels/codes are consistent and valid.\n\n Attributes\n ----------\n names\n levels\n codes\n nlevels\n levshape\n\n Methods\n -------\n from_arrays\n from_tuples\n from_product\n from_frame\n set_levels\n set_codes\n to_frame\n to_flat_index\n is_lexsorted\n sortlevel\n droplevel\n swaplevel\n reorder_levels\n remove_unused_levels\n get_locs\n\n See Also\n --------\n MultiIndex.from_arrays : Convert list of arrays to MultiIndex.\n MultiIndex.from_product : Create a MultiIndex from the cartesian product\n of iterables.\n MultiIndex.from_tuples : Convert list of tuples to a MultiIndex.\n MultiIndex.from_frame : Make a MultiIndex from a DataFrame.\n Index : The base pandas Index type.\n\n Notes\n -----\n See the `user guide\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html>`_\n for more.\n\n Examples\n --------\n A new ``MultiIndex`` is typically constructed using one of the helper\n methods :meth:`MultiIndex.from_arrays`, :meth:`MultiIndex.from_product`\n and :meth:`MultiIndex.from_tuples`. For example (using ``.from_arrays``):\n\n >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]\n >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))\n MultiIndex([(1, 'red'),\n (1, 'blue'),\n (2, 'red'),\n (2, 'blue')],\n names=['number', 'color'])\n\n See further examples for how to construct a MultiIndex in the doc strings\n of the mentioned helper methods.\n \"\"\"\n\n _deprecations = Index._deprecations | frozenset()\n\n # initialize to zero-length tuples to make everything work\n _typ = \"multiindex\"\n _names = FrozenList()\n _levels = FrozenList()\n _codes = FrozenList()\n _comparables = [\"names\"]\n rename = Index.set_names\n\n _tuples = None\n sortorder: Optional[int]\n\n # --------------------------------------------------------------------\n # Constructors\n\n def __new__(\n cls,\n levels=None,\n codes=None,\n sortorder=None,\n names=None,\n dtype=None,\n copy=False,\n name=None,\n verify_integrity: bool = True,\n _set_identity: bool = True,\n ):\n\n # compat with Index\n if name is not None:\n names = name\n if levels is None or codes is None:\n raise TypeError(\"Must pass both levels and codes\")\n if len(levels) != len(codes):\n raise ValueError(\"Length of levels and codes must be the same.\")\n if len(levels) == 0:\n raise ValueError(\"Must pass non-zero number of levels/codes\")\n\n result = object.__new__(MultiIndex)\n\n # we've already validated levels and codes, so shortcut here\n result._set_levels(levels, copy=copy, validate=False)\n result._set_codes(codes, copy=copy, validate=False)\n\n result._names = [None] * len(levels)\n if names is not None:\n # handles name validation\n result._set_names(names)\n\n if sortorder is not None:\n result.sortorder = int(sortorder)\n else:\n result.sortorder = sortorder\n\n if verify_integrity:\n new_codes = result._verify_integrity()\n result._codes = new_codes\n\n if _set_identity:\n result._reset_identity()\n\n return result\n\n def _validate_codes(self, level: List, code: List):\n \"\"\"\n Reassign code values as -1 if their corresponding levels are NaN.\n\n Parameters\n ----------\n code : list\n Code to reassign.\n level : list\n Level to check for missing values (NaN, NaT, None).\n\n Returns\n -------\n new code where code value = -1 if it corresponds\n to a level with missing values (NaN, NaT, None).\n \"\"\"\n null_mask = isna(level)\n if np.any(null_mask):\n code = np.where(null_mask[code], -1, code)\n return code\n\n def _verify_integrity(\n self, codes: Optional[List] = None, levels: Optional[List] = None\n ):\n \"\"\"\n Parameters\n ----------\n codes : optional list\n Codes to check for validity. Defaults to current codes.\n levels : optional list\n Levels to check for validity. Defaults to current levels.\n\n Raises\n ------\n ValueError\n If length of levels and codes don't match, if the codes for any\n level would exceed level bounds, or there are any duplicate levels.\n\n Returns\n -------\n new codes where code value = -1 if it corresponds to a\n NaN level.\n \"\"\"\n # NOTE: Currently does not check, among other things, that cached\n # nlevels matches nor that sortorder matches actually sortorder.\n codes = codes or self.codes\n levels = levels or self.levels\n\n if len(levels) != len(codes):\n raise ValueError(\n \"Length of levels and codes must match. NOTE: \"\n \"this index is in an inconsistent state.\"\n )\n codes_length = len(codes[0])\n for i, (level, level_codes) in enumerate(zip(levels, codes)):\n if len(level_codes) != codes_length:\n raise ValueError(\n f\"Unequal code lengths: {[len(code_) for code_ in codes]}\"\n )\n if len(level_codes) and level_codes.max() >= len(level):\n raise ValueError(\n f\"On level {i}, code max ({level_codes.max()}) >= length of \"\n f\"level ({len(level)}). NOTE: this index is in an \"\n \"inconsistent state\"\n )\n if len(level_codes) and level_codes.min() < -1:\n raise ValueError(f\"On level {i}, code value ({level_codes.min()}) < -1\")\n if not level.is_unique:\n raise ValueError(\n f\"Level values must be unique: {list(level)} on level {i}\"\n )\n if self.sortorder is not None:\n if self.sortorder > self._lexsort_depth():\n raise ValueError(\n \"Value for sortorder must be inferior or equal to actual \"\n f\"lexsort_depth: sortorder {self.sortorder} \"\n f\"with lexsort_depth {self._lexsort_depth()}\"\n )\n\n codes = [\n self._validate_codes(level, code) for level, code in zip(levels, codes)\n ]\n new_codes = FrozenList(codes)\n return new_codes\n\n @classmethod\n def from_arrays(cls, arrays, sortorder=None, names=lib.no_default):\n \"\"\"\n Convert arrays to MultiIndex.\n\n Parameters\n ----------\n arrays : list / sequence of array-likes\n Each array-like gives one level's value for each data point.\n len(arrays) is the number of levels.\n sortorder : int or None\n Level of sortedness (must be lexicographically sorted by that\n level).\n names : list / sequence of str, optional\n Names for the levels in the index.\n\n Returns\n -------\n MultiIndex\n\n See Also\n --------\n MultiIndex.from_tuples : Convert list of tuples to MultiIndex.\n MultiIndex.from_product : Make a MultiIndex from cartesian product\n of iterables.\n MultiIndex.from_frame : Make a MultiIndex from a DataFrame.\n\n Examples\n --------\n >>> arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]\n >>> pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))\n MultiIndex([(1, 'red'),\n (1, 'blue'),\n (2, 'red'),\n (2, 'blue')],\n names=['number', 'color'])\n \"\"\"\n error_msg = \"Input must be a list / sequence of array-likes.\"\n if not is_list_like(arrays):\n raise TypeError(error_msg)\n elif is_iterator(arrays):\n arrays = list(arrays)\n\n # Check if elements of array are list-like\n for array in arrays:\n if not is_list_like(array):\n raise TypeError(error_msg)\n\n # Check if lengths of all arrays are equal or not,\n # raise ValueError, if not\n for i in range(1, len(arrays)):\n if len(arrays[i]) != len(arrays[i - 1]):\n raise ValueError(\"all arrays must be same length\")\n\n codes, levels = factorize_from_iterables(arrays)\n if names is lib.no_default:\n names = [getattr(arr, \"name\", None) for arr in arrays]\n\n return MultiIndex(\n levels=levels,\n codes=codes,\n sortorder=sortorder,\n names=names,\n verify_integrity=False,\n )\n\n @classmethod\n def from_tuples(cls, tuples, sortorder=None, names=None):\n \"\"\"\n Convert list of tuples to MultiIndex.\n\n Parameters\n ----------\n tuples : list / sequence of tuple-likes\n Each tuple is the index of one row/column.\n sortorder : int or None\n Level of sortedness (must be lexicographically sorted by that\n level).\n names : list / sequence of str, optional\n Names for the levels in the index.\n\n Returns\n -------\n MultiIndex\n\n See Also\n --------\n MultiIndex.from_arrays : Convert list of arrays to MultiIndex.\n MultiIndex.from_product : Make a MultiIndex from cartesian product\n of iterables.\n MultiIndex.from_frame : Make a MultiIndex from a DataFrame.\n\n Examples\n --------\n >>> tuples = [(1, 'red'), (1, 'blue'),\n ... (2, 'red'), (2, 'blue')]\n >>> pd.MultiIndex.from_tuples(tuples, names=('number', 'color'))\n MultiIndex([(1, 'red'),\n (1, 'blue'),\n (2, 'red'),\n (2, 'blue')],\n names=['number', 'color'])\n \"\"\"\n if not is_list_like(tuples):\n raise TypeError(\"Input must be a list / sequence of tuple-likes.\")\n elif is_iterator(tuples):\n tuples = list(tuples)\n\n if len(tuples) == 0:\n if names is None:\n raise TypeError(\"Cannot infer number of levels from empty list\")\n arrays = [[]] * len(names)\n elif isinstance(tuples, (np.ndarray, Index)):\n if isinstance(tuples, Index):\n tuples = tuples._values\n\n arrays = list(lib.tuples_to_object_array(tuples).T)\n elif isinstance(tuples, list):\n arrays = list(lib.to_object_array_tuples(tuples).T)\n else:\n arrays = zip(*tuples)\n\n return MultiIndex.from_arrays(arrays, sortorder=sortorder, names=names)\n\n @classmethod\n def from_product(cls, iterables, sortorder=None, names=lib.no_default):\n \"\"\"\n Make a MultiIndex from the cartesian product of multiple iterables.\n\n Parameters\n ----------\n iterables : list / sequence of iterables\n Each iterable has unique labels for each level of the index.\n sortorder : int or None\n Level of sortedness (must be lexicographically sorted by that\n level).\n names : list / sequence of str, optional\n Names for the levels in the index.\n\n .. versionchanged:: 1.0.0\n\n If not explicitly provided, names will be inferred from the\n elements of iterables if an element has a name attribute\n\n Returns\n -------\n MultiIndex\n\n See Also\n --------\n MultiIndex.from_arrays : Convert list of arrays to MultiIndex.\n MultiIndex.from_tuples : Convert list of tuples to MultiIndex.\n MultiIndex.from_frame : Make a MultiIndex from a DataFrame.\n\n Examples\n --------\n >>> numbers = [0, 1, 2]\n >>> colors = ['green', 'purple']\n >>> pd.MultiIndex.from_product([numbers, colors],\n ... names=['number', 'color'])\n MultiIndex([(0, 'green'),\n (0, 'purple'),\n (1, 'green'),\n (1, 'purple'),\n (2, 'green'),\n (2, 'purple')],\n names=['number', 'color'])\n \"\"\"\n from pandas.core.reshape.util import cartesian_product\n\n if not is_list_like(iterables):\n raise TypeError(\"Input must be a list / sequence of iterables.\")\n elif is_iterator(iterables):\n iterables = list(iterables)\n\n codes, levels = factorize_from_iterables(iterables)\n if names is lib.no_default:\n names = [getattr(it, \"name\", None) for it in iterables]\n\n codes = cartesian_product(codes)\n return MultiIndex(levels, codes, sortorder=sortorder, names=names)\n\n @classmethod\n def from_frame(cls, df, sortorder=None, names=None):\n \"\"\"\n Make a MultiIndex from a DataFrame.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n df : DataFrame\n DataFrame to be converted to MultiIndex.\n sortorder : int, optional\n Level of sortedness (must be lexicographically sorted by that\n level).\n names : list-like, optional\n If no names are provided, use the column names, or tuple of column\n names if the columns is a MultiIndex. If a sequence, overwrite\n names with the given sequence.\n\n Returns\n -------\n MultiIndex\n The MultiIndex representation of the given DataFrame.\n\n See Also\n --------\n MultiIndex.from_arrays : Convert list of arrays to MultiIndex.\n MultiIndex.from_tuples : Convert list of tuples to MultiIndex.\n MultiIndex.from_product : Make a MultiIndex from cartesian product\n of iterables.\n\n Examples\n --------\n >>> df = pd.DataFrame([['HI', 'Temp'], ['HI', 'Precip'],\n ... ['NJ', 'Temp'], ['NJ', 'Precip']],\n ... columns=['a', 'b'])\n >>> df\n a b\n 0 HI Temp\n 1 HI Precip\n 2 NJ Temp\n 3 NJ Precip\n\n >>> pd.MultiIndex.from_frame(df)\n MultiIndex([('HI', 'Temp'),\n ('HI', 'Precip'),\n ('NJ', 'Temp'),\n ('NJ', 'Precip')],\n names=['a', 'b'])\n\n Using explicit names, instead of the column names\n\n >>> pd.MultiIndex.from_frame(df, names=['state', 'observation'])\n MultiIndex([('HI', 'Temp'),\n ('HI', 'Precip'),\n ('NJ', 'Temp'),\n ('NJ', 'Precip')],\n names=['state', 'observation'])\n \"\"\"\n if not isinstance(df, ABCDataFrame):\n raise TypeError(\"Input must be a DataFrame\")\n\n column_names, columns = zip(*df.items())\n names = column_names if names is None else names\n return cls.from_arrays(columns, sortorder=sortorder, names=names)\n\n # --------------------------------------------------------------------\n\n @property\n def _values(self):\n # We override here, since our parent uses _data, which we don't use.\n return self.values\n\n @property\n def values(self):\n if self._tuples is not None:\n return self._tuples\n\n values = []\n\n for i in range(self.nlevels):\n vals = self._get_level_values(i)\n if is_categorical_dtype(vals):\n vals = vals._internal_get_values()\n if isinstance(vals.dtype, ExtensionDtype) or hasattr(vals, \"_box_values\"):\n vals = vals.astype(object)\n vals = np.array(vals, copy=False)\n values.append(vals)\n\n self._tuples = lib.fast_zip(values)\n return self._tuples\n\n @property\n def array(self):\n \"\"\"\n Raises a ValueError for `MultiIndex` because there's no single\n array backing a MultiIndex.\n\n Raises\n ------\n ValueError\n \"\"\"\n raise ValueError(\n \"MultiIndex has no single backing array. Use \"\n \"'MultiIndex.to_numpy()' to get a NumPy array of tuples.\"\n )\n\n @property\n def shape(self):\n \"\"\"\n Return a tuple of the shape of the underlying data.\n \"\"\"\n # overriding the base Index.shape definition to avoid materializing\n # the values (GH-27384, GH-27775)\n return (len(self),)\n\n def __len__(self) -> int:\n return len(self.codes[0])\n\n # --------------------------------------------------------------------\n # Levels Methods\n\n @cache_readonly\n def levels(self):\n # Use cache_readonly to ensure that self.get_locs doesn't repeatedly\n # create new IndexEngine\n # https://github.com/pandas-dev/pandas/issues/31648\n result = [\n x._shallow_copy(name=name) for x, name in zip(self._levels, self._names)\n ]\n for level in result:\n # disallow midx.levels[0].name = \"foo\"\n level._no_setting_name = True\n return FrozenList(result)\n\n def _set_levels(\n self, levels, level=None, copy=False, validate=True, verify_integrity=False\n ):\n # This is NOT part of the levels property because it should be\n # externally not allowed to set levels. User beware if you change\n # _levels directly\n if validate:\n if len(levels) == 0:\n raise ValueError(\"Must set non-zero number of levels.\")\n if level is None and len(levels) != self.nlevels:\n raise ValueError(\"Length of levels must match number of levels.\")\n if level is not None and len(levels) != len(level):\n raise ValueError(\"Length of levels must match length of level.\")\n\n if level is None:\n new_levels = FrozenList(\n ensure_index(lev, copy=copy)._shallow_copy() for lev in levels\n )\n else:\n level_numbers = [self._get_level_number(lev) for lev in level]\n new_levels = list(self._levels)\n for lev_num, lev in zip(level_numbers, levels):\n new_levels[lev_num] = ensure_index(lev, copy=copy)._shallow_copy()\n new_levels = FrozenList(new_levels)\n\n if verify_integrity:\n new_codes = self._verify_integrity(levels=new_levels)\n self._codes = new_codes\n\n names = self.names\n self._levels = new_levels\n if any(names):\n self._set_names(names)\n\n self._tuples = None\n self._reset_cache()\n\n def set_levels(self, levels, level=None, inplace=False, verify_integrity=True):\n \"\"\"\n Set new levels on MultiIndex. Defaults to returning new index.\n\n Parameters\n ----------\n levels : sequence or list of sequence\n New level(s) to apply.\n level : int, level name, or sequence of int/level names (default None)\n Level(s) to set (None for all levels).\n inplace : bool\n If True, mutates in place.\n verify_integrity : bool, default True\n If True, checks that levels and codes are compatible.\n\n Returns\n -------\n new index (of same type and class...etc)\n\n Examples\n --------\n >>> idx = pd.MultiIndex.from_tuples([(1, 'one'), (1, 'two'),\n (2, 'one'), (2, 'two'),\n (3, 'one'), (3, 'two')],\n names=['foo', 'bar'])\n >>> idx.set_levels([['a', 'b', 'c'], [1, 2]])\n MultiIndex([('a', 1),\n ('a', 2),\n ('b', 1),\n ('b', 2),\n ('c', 1),\n ('c', 2)],\n names=['foo', 'bar'])\n >>> idx.set_levels(['a', 'b', 'c'], level=0)\n MultiIndex([('a', 'one'),\n ('a', 'two'),\n ('b', 'one'),\n ('b', 'two'),\n ('c', 'one'),\n ('c', 'two')],\n names=['foo', 'bar'])\n >>> idx.set_levels(['a', 'b'], level='bar')\n MultiIndex([(1, 'a'),\n (1, 'b'),\n (2, 'a'),\n (2, 'b'),\n (3, 'a'),\n (3, 'b')],\n names=['foo', 'bar'])\n\n If any of the levels passed to ``set_levels()`` exceeds the\n existing length, all of the values from that argument will\n be stored in the MultiIndex levels, though the values will\n be truncated in the MultiIndex output.\n\n >>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1])\n MultiIndex([('a', 1),\n ('a', 2),\n ('b', 1),\n ('b', 2)],\n names=['foo', 'bar'])\n >>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1]).levels\n FrozenList([['a', 'b', 'c'], [1, 2, 3, 4]])\n \"\"\"\n if is_list_like(levels) and not isinstance(levels, Index):\n levels = list(levels)\n\n if level is not None and not is_list_like(level):\n if not is_list_like(levels):\n raise TypeError(\"Levels must be list-like\")\n if is_list_like(levels[0]):\n raise TypeError(\"Levels must be list-like\")\n level = [level]\n levels = [levels]\n elif level is None or is_list_like(level):\n if not is_list_like(levels) or not is_list_like(levels[0]):\n raise TypeError(\"Levels must be list of lists-like\")\n\n if inplace:\n idx = self\n else:\n idx = self._shallow_copy()\n idx._reset_identity()\n idx._set_levels(\n levels, level=level, validate=True, verify_integrity=verify_integrity\n )\n if not inplace:\n return idx\n\n @property\n def nlevels(self) -> int:\n \"\"\"\n Integer number of levels in this MultiIndex.\n \"\"\"\n return len(self._levels)\n\n @property\n def levshape(self):\n \"\"\"\n A tuple with the length of each level.\n \"\"\"\n return tuple(len(x) for x in self.levels)\n\n # --------------------------------------------------------------------\n # Codes Methods\n\n @property\n def codes(self):\n return self._codes\n\n def _set_codes(\n self, codes, level=None, copy=False, validate=True, verify_integrity=False\n ):\n if validate:\n if level is None and len(codes) != self.nlevels:\n raise ValueError(\"Length of codes must match number of levels\")\n if level is not None and len(codes) != len(level):\n raise ValueError(\"Length of codes must match length of levels.\")\n\n if level is None:\n new_codes = FrozenList(\n _coerce_indexer_frozen(level_codes, lev, copy=copy).view()\n for lev, level_codes in zip(self._levels, codes)\n )\n else:\n level_numbers = [self._get_level_number(lev) for lev in level]\n new_codes = list(self._codes)\n for lev_num, level_codes in zip(level_numbers, codes):\n lev = self.levels[lev_num]\n new_codes[lev_num] = _coerce_indexer_frozen(level_codes, lev, copy=copy)\n new_codes = FrozenList(new_codes)\n\n if verify_integrity:\n new_codes = self._verify_integrity(codes=new_codes)\n\n self._codes = new_codes\n\n self._tuples = None\n self._reset_cache()\n\n def set_codes(self, codes, level=None, inplace=False, verify_integrity=True):\n \"\"\"\n Set new codes on MultiIndex. Defaults to returning\n new index.\n\n .. versionadded:: 0.24.0\n\n New name for deprecated method `set_labels`.\n\n Parameters\n ----------\n codes : sequence or list of sequence\n New codes to apply.\n level : int, level name, or sequence of int/level names (default None)\n Level(s) to set (None for all levels).\n inplace : bool\n If True, mutates in place.\n verify_integrity : bool (default True)\n If True, checks that levels and codes are compatible.\n\n Returns\n -------\n new index (of same type and class...etc)\n\n Examples\n --------\n >>> idx = pd.MultiIndex.from_tuples([(1, 'one'),\n (1, 'two'),\n (2, 'one'),\n (2, 'two')],\n names=['foo', 'bar'])\n >>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]])\n MultiIndex([(2, 'one'),\n (1, 'one'),\n (2, 'two'),\n (1, 'two')],\n names=['foo', 'bar'])\n >>> idx.set_codes([1, 0, 1, 0], level=0)\n MultiIndex([(2, 'one'),\n (1, 'two'),\n (2, 'one'),\n (1, 'two')],\n names=['foo', 'bar'])\n >>> idx.set_codes([0, 0, 1, 1], level='bar')\n MultiIndex([(1, 'one'),\n (1, 'one'),\n (2, 'two'),\n (2, 'two')],\n names=['foo', 'bar'])\n >>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]], level=[0, 1])\n MultiIndex([(2, 'one'),\n (1, 'one'),\n (2, 'two'),\n (1, 'two')],\n names=['foo', 'bar'])\n \"\"\"\n if level is not None and not is_list_like(level):\n if not is_list_like(codes):\n raise TypeError(\"Codes must be list-like\")\n if is_list_like(codes[0]):\n raise TypeError(\"Codes must be list-like\")\n level = [level]\n codes = [codes]\n elif level is None or is_list_like(level):\n if not is_list_like(codes) or not is_list_like(codes[0]):\n raise TypeError(\"Codes must be list of lists-like\")\n\n if inplace:\n idx = self\n else:\n idx = self._shallow_copy()\n idx._reset_identity()\n idx._set_codes(codes, level=level, verify_integrity=verify_integrity)\n if not inplace:\n return idx\n\n # --------------------------------------------------------------------\n # Index Internals\n\n @cache_readonly\n def _engine(self):\n # Calculate the number of bits needed to represent labels in each\n # level, as log2 of their sizes (including -1 for NaN):\n sizes = np.ceil(np.log2([len(l) + 1 for l in self.levels]))\n\n # Sum bit counts, starting from the _right_....\n lev_bits = np.cumsum(sizes[::-1])[::-1]\n\n # ... in order to obtain offsets such that sorting the combination of\n # shifted codes (one for each level, resulting in a unique integer) is\n # equivalent to sorting lexicographically the codes themselves. Notice\n # that each level needs to be shifted by the number of bits needed to\n # represent the _previous_ ones:\n offsets = np.concatenate([lev_bits[1:], [0]]).astype(\"uint64\")\n\n # Check the total number of bits needed for our representation:\n if lev_bits[0] > 64:\n # The levels would overflow a 64 bit uint - use Python integers:\n return MultiIndexPyIntEngine(self.levels, self.codes, offsets)\n return MultiIndexUIntEngine(self.levels, self.codes, offsets)\n\n @property\n def _constructor(self):\n return MultiIndex.from_tuples\n\n @Appender(Index._shallow_copy.__doc__)\n def _shallow_copy(self, values=None, **kwargs):\n if values is not None:\n names = kwargs.pop(\"names\", kwargs.pop(\"name\", self.names))\n # discards freq\n kwargs.pop(\"freq\", None)\n return MultiIndex.from_tuples(values, names=names, **kwargs)\n return self.copy(**kwargs)\n\n def _shallow_copy_with_infer(self, values, **kwargs):\n # On equal MultiIndexes the difference is empty.\n # Therefore, an empty MultiIndex is returned GH13490\n if len(values) == 0:\n return MultiIndex(\n levels=[[] for _ in range(self.nlevels)],\n codes=[[] for _ in range(self.nlevels)],\n **kwargs,\n )\n return self._shallow_copy(values, **kwargs)\n\n # --------------------------------------------------------------------\n\n def copy(\n self,\n names=None,\n dtype=None,\n levels=None,\n codes=None,\n deep=False,\n name=None,\n _set_identity=False,\n ):\n \"\"\"\n Make a copy of this object. Names, dtype, levels and codes can be\n passed and will be set on new copy.\n\n Parameters\n ----------\n names : sequence, optional\n dtype : numpy dtype or pandas type, optional\n levels : sequence, optional\n codes : sequence, optional\n deep : bool, default False\n name : Label\n Kept for compatibility with 1-dimensional Index. Should not be used.\n\n Returns\n -------\n MultiIndex\n\n Notes\n -----\n In most cases, there should be no functional difference from using\n ``deep``, but if ``deep`` is passed it will attempt to deepcopy.\n This could be potentially expensive on large MultiIndex objects.\n \"\"\"\n names = self._validate_names(name=name, names=names, deep=deep)\n if deep:\n from copy import deepcopy\n\n if levels is None:\n levels = deepcopy(self.levels)\n if codes is None:\n codes = deepcopy(self.codes)\n else:\n if levels is None:\n levels = self.levels\n if codes is None:\n codes = self.codes\n return MultiIndex(\n levels=levels,\n codes=codes,\n names=names,\n sortorder=self.sortorder,\n verify_integrity=False,\n _set_identity=_set_identity,\n )\n\n def __array__(self, dtype=None) -> np.ndarray:\n \"\"\" the array interface, return my values \"\"\"\n return self.values\n\n def view(self, cls=None):\n \"\"\" this is defined as a copy with the same identity \"\"\"\n result = self.copy()\n result._id = self._id\n return result\n\n @Appender(Index.__contains__.__doc__)\n def __contains__(self, key: Any) -> bool:\n hash(key)\n try:\n self.get_loc(key)\n return True\n except (LookupError, TypeError, ValueError):\n return False\n\n @cache_readonly\n def dtype(self) -> np.dtype:\n return np.dtype(\"O\")\n\n def _is_memory_usage_qualified(self) -> bool:\n \"\"\" return a boolean if we need a qualified .info display \"\"\"\n\n def f(l):\n return \"mixed\" in l or \"string\" in l or \"unicode\" in l\n\n return any(f(l) for l in self._inferred_type_levels)\n\n @Appender(Index.memory_usage.__doc__)\n def memory_usage(self, deep: bool = False) -> int:\n # we are overwriting our base class to avoid\n # computing .values here which could materialize\n # a tuple representation unnecessarily\n return self._nbytes(deep)\n\n @cache_readonly\n def nbytes(self) -> int:\n \"\"\" return the number of bytes in the underlying data \"\"\"\n return self._nbytes(False)\n\n def _nbytes(self, deep: bool = False) -> int:\n \"\"\"\n return the number of bytes in the underlying data\n deeply introspect the level data if deep=True\n\n include the engine hashtable\n\n *this is in internal routine*\n\n \"\"\"\n # for implementations with no useful getsizeof (PyPy)\n objsize = 24\n\n level_nbytes = sum(i.memory_usage(deep=deep) for i in self.levels)\n label_nbytes = sum(i.nbytes for i in self.codes)\n names_nbytes = sum(getsizeof(i, objsize) for i in self.names)\n result = level_nbytes + label_nbytes + names_nbytes\n\n # include our engine hashtable\n result += self._engine.sizeof(deep=deep)\n return result\n\n # --------------------------------------------------------------------\n # Rendering Methods\n\n def _formatter_func(self, tup):\n \"\"\"\n Formats each item in tup according to its level's formatter function.\n \"\"\"\n formatter_funcs = [level._formatter_func for level in self.levels]\n return tuple(func(val) for func, val in zip(formatter_funcs, tup))\n\n def _format_data(self, name=None):\n \"\"\"\n Return the formatted data as a unicode string\n \"\"\"\n return format_object_summary(\n self, self._formatter_func, name=name, line_break_each_value=True\n )\n\n def _format_attrs(self):\n \"\"\"\n Return a list of tuples of the (attr,formatted_value).\n \"\"\"\n return format_object_attrs(self, include_dtype=False)\n\n def _format_native_types(self, na_rep=\"nan\", **kwargs):\n new_levels = []\n new_codes = []\n\n # go through the levels and format them\n for level, level_codes in zip(self.levels, self.codes):\n level = level._format_native_types(na_rep=na_rep, **kwargs)\n # add nan values, if there are any\n mask = level_codes == -1\n if mask.any():\n nan_index = len(level)\n level = np.append(level, na_rep)\n assert not level_codes.flags.writeable # i.e. copy is needed\n level_codes = level_codes.copy() # make writeable\n level_codes[mask] = nan_index\n new_levels.append(level)\n new_codes.append(level_codes)\n\n if len(new_levels) == 1:\n # a single-level multi-index\n return Index(new_levels[0].take(new_codes[0]))._format_native_types()\n else:\n # reconstruct the multi-index\n mi = MultiIndex(\n levels=new_levels,\n codes=new_codes,\n names=self.names,\n sortorder=self.sortorder,\n verify_integrity=False,\n )\n return mi.values\n\n def format(\n self,\n space=2,\n sparsify=None,\n adjoin=True,\n names=False,\n na_rep=None,\n formatter=None,\n ):\n if len(self) == 0:\n return []\n\n stringified_levels = []\n for lev, level_codes in zip(self.levels, self.codes):\n na = na_rep if na_rep is not None else _get_na_rep(lev.dtype.type)\n\n if len(lev) > 0:\n\n formatted = lev.take(level_codes).format(formatter=formatter)\n\n # we have some NA\n mask = level_codes == -1\n if mask.any():\n formatted = np.array(formatted, dtype=object)\n formatted[mask] = na\n formatted = formatted.tolist()\n\n else:\n # weird all NA case\n formatted = [\n pprint_thing(na if isna(x) else x, escape_chars=(\"\\t\", \"\\r\", \"\\n\"))\n for x in algos.take_1d(lev._values, level_codes)\n ]\n stringified_levels.append(formatted)\n\n result_levels = []\n for lev, name in zip(stringified_levels, self.names):\n level = []\n\n if names:\n level.append(\n pprint_thing(name, escape_chars=(\"\\t\", \"\\r\", \"\\n\"))\n if name is not None\n else \"\"\n )\n\n level.extend(np.array(lev, dtype=object))\n result_levels.append(level)\n\n if sparsify is None:\n sparsify = get_option(\"display.multi_sparse\")\n\n if sparsify:\n sentinel = \"\"\n # GH3547\n # use value of sparsify as sentinel, unless it's an obvious\n # \"Truthy\" value\n if sparsify not in [True, 1]:\n sentinel = sparsify\n # little bit of a kludge job for #1217\n result_levels = _sparsify(\n result_levels, start=int(names), sentinel=sentinel\n )\n\n if adjoin:\n from pandas.io.formats.format import _get_adjustment\n\n adj = _get_adjustment()\n return adj.adjoin(space, *result_levels).split(\"\\n\")\n else:\n return result_levels\n\n # --------------------------------------------------------------------\n # Names Methods\n\n def _get_names(self):\n return FrozenList(self._names)\n\n def _set_names(self, names, level=None, validate=True):\n \"\"\"\n Set new names on index. Each name has to be a hashable type.\n\n Parameters\n ----------\n values : str or sequence\n name(s) to set\n level : int, level name, or sequence of int/level names (default None)\n If the index is a MultiIndex (hierarchical), level(s) to set (None\n for all levels). Otherwise level must be None\n validate : boolean, default True\n validate that the names match level lengths\n\n Raises\n ------\n TypeError if each name is not hashable.\n\n Notes\n -----\n sets names on levels. WARNING: mutates!\n\n Note that you generally want to set this *after* changing levels, so\n that it only acts on copies\n \"\"\"\n # GH 15110\n # Don't allow a single string for names in a MultiIndex\n if names is not None and not is_list_like(names):\n raise ValueError(\"Names should be list-like for a MultiIndex\")\n names = list(names)\n\n if validate:\n if level is not None and len(names) != len(level):\n raise ValueError(\"Length of names must match length of level.\")\n if level is None and len(names) != self.nlevels:\n raise ValueError(\n \"Length of names must match number of levels in MultiIndex.\"\n )\n\n if level is None:\n level = range(self.nlevels)\n else:\n level = [self._get_level_number(lev) for lev in level]\n\n # set the name\n for lev, name in zip(level, names):\n if name is not None:\n # GH 20527\n # All items in 'names' need to be hashable:\n if not is_hashable(name):\n raise TypeError(\n f\"{type(self).__name__}.name must be a hashable type\"\n )\n self._names[lev] = name\n\n # If .levels has been accessed, the names in our cache will be stale.\n self._reset_cache()\n\n names = property(\n fset=_set_names, fget=_get_names, doc=\"\"\"\\nNames of levels in MultiIndex.\\n\"\"\"\n )\n\n # --------------------------------------------------------------------\n\n @Appender(Index._get_grouper_for_level.__doc__)\n def _get_grouper_for_level(self, mapper, level):\n indexer = self.codes[level]\n level_index = self.levels[level]\n\n if mapper is not None:\n # Handle group mapping function and return\n level_values = self.levels[level].take(indexer)\n grouper = level_values.map(mapper)\n return grouper, None, None\n\n codes, uniques = algos.factorize(indexer, sort=True)\n\n if len(uniques) > 0 and uniques[0] == -1:\n # Handle NAs\n mask = indexer != -1\n ok_codes, uniques = algos.factorize(indexer[mask], sort=True)\n\n codes = np.empty(len(indexer), dtype=indexer.dtype)\n codes[mask] = ok_codes\n codes[~mask] = -1\n\n if len(uniques) < len(level_index):\n # Remove unobserved levels from level_index\n level_index = level_index.take(uniques)\n else:\n # break references back to us so that setting the name\n # on the output of a groupby doesn't reflect back here.\n level_index = level_index.copy()\n\n if level_index._can_hold_na:\n grouper = level_index.take(codes, fill_value=True)\n else:\n grouper = level_index.take(codes)\n\n return grouper, codes, level_index\n\n @cache_readonly\n def inferred_type(self) -> str:\n return \"mixed\"\n\n def _get_level_number(self, level) -> int:\n count = self.names.count(level)\n if (count > 1) and not is_integer(level):\n raise ValueError(\n f\"The name {level} occurs multiple times, use a level number\"\n )\n try:\n level = self.names.index(level)\n except ValueError as err:\n if not is_integer(level):\n raise KeyError(f\"Level {level} not found\") from err\n elif level < 0:\n level += self.nlevels\n if level < 0:\n orig_level = level - self.nlevels\n raise IndexError(\n f\"Too many levels: Index has only {self.nlevels} levels, \"\n f\"{orig_level} is not a valid level number\"\n ) from err\n # Note: levels are zero-based\n elif level >= self.nlevels:\n raise IndexError(\n f\"Too many levels: Index has only {self.nlevels} levels, \"\n f\"not {level + 1}\"\n ) from err\n return level\n\n @property\n def _has_complex_internals(self) -> bool:\n # used to avoid libreduction code paths, which raise or require conversion\n return True\n\n @cache_readonly\n def is_monotonic_increasing(self) -> bool:\n \"\"\"\n return if the index is monotonic increasing (only equal or\n increasing) values.\n \"\"\"\n if all(x.is_monotonic for x in self.levels):\n # If each level is sorted, we can operate on the codes directly. GH27495\n return libalgos.is_lexsorted(\n [x.astype(\"int64\", copy=False) for x in self.codes]\n )\n\n # reversed() because lexsort() wants the most significant key last.\n values = [\n self._get_level_values(i).values for i in reversed(range(len(self.levels)))\n ]\n try:\n sort_order = np.lexsort(values)\n return Index(sort_order).is_monotonic\n except TypeError:\n\n # we have mixed types and np.lexsort is not happy\n return Index(self.values).is_monotonic\n\n @cache_readonly\n def is_monotonic_decreasing(self) -> bool:\n \"\"\"\n return if the index is monotonic decreasing (only equal or\n decreasing) values.\n \"\"\"\n # monotonic decreasing if and only if reverse is monotonic increasing\n return self[::-1].is_monotonic_increasing\n\n @cache_readonly\n def _inferred_type_levels(self):\n \"\"\" return a list of the inferred types, one for each level \"\"\"\n return [i.inferred_type for i in self.levels]\n\n @Appender(Index.duplicated.__doc__)\n def duplicated(self, keep=\"first\"):\n shape = map(len, self.levels)\n ids = get_group_index(self.codes, shape, sort=False, xnull=False)\n\n return duplicated_int64(ids, keep)\n\n def fillna(self, value=None, downcast=None):\n \"\"\"\n fillna is not implemented for MultiIndex\n \"\"\"\n raise NotImplementedError(\"isna is not defined for MultiIndex\")\n\n @Appender(Index.dropna.__doc__)\n def dropna(self, how=\"any\"):\n nans = [level_codes == -1 for level_codes in self.codes]\n if how == \"any\":\n indexer = np.any(nans, axis=0)\n elif how == \"all\":\n indexer = np.all(nans, axis=0)\n else:\n raise ValueError(f\"invalid how option: {how}\")\n\n new_codes = [level_codes[~indexer] for level_codes in self.codes]\n return self.copy(codes=new_codes, deep=True)\n\n def _get_level_values(self, level, unique=False):\n \"\"\"\n Return vector of label values for requested level,\n equal to the length of the index\n\n **this is an internal method**\n\n Parameters\n ----------\n level : int level\n unique : bool, default False\n if True, drop duplicated values\n\n Returns\n -------\n values : ndarray\n \"\"\"\n lev = self.levels[level]\n level_codes = self.codes[level]\n name = self._names[level]\n if unique:\n level_codes = algos.unique(level_codes)\n filled = algos.take_1d(lev._values, level_codes, fill_value=lev._na_value)\n return lev._shallow_copy(filled, name=name)\n\n def get_level_values(self, level):\n \"\"\"\n Return vector of label values for requested level,\n equal to the length of the index.\n\n Parameters\n ----------\n level : int or str\n ``level`` is either the integer position of the level in the\n MultiIndex, or the name of the level.\n\n Returns\n -------\n values : Index\n Values is a level of this MultiIndex converted to\n a single :class:`Index` (or subclass thereof).\n\n Examples\n --------\n Create a MultiIndex:\n\n >>> mi = pd.MultiIndex.from_arrays((list('abc'), list('def')))\n >>> mi.names = ['level_1', 'level_2']\n\n Get level values by supplying level as either integer or name:\n\n >>> mi.get_level_values(0)\n Index(['a', 'b', 'c'], dtype='object', name='level_1')\n >>> mi.get_level_values('level_2')\n Index(['d', 'e', 'f'], dtype='object', name='level_2')\n \"\"\"\n level = self._get_level_number(level)\n values = self._get_level_values(level)\n return values\n\n @Appender(Index.unique.__doc__)\n def unique(self, level=None):\n\n if level is None:\n return super().unique()\n else:\n level = self._get_level_number(level)\n return self._get_level_values(level=level, unique=True)\n\n def _to_safe_for_reshape(self):\n \"\"\" convert to object if we are a categorical \"\"\"\n return self.set_levels([i._to_safe_for_reshape() for i in self.levels])\n\n def to_frame(self, index=True, name=None):\n \"\"\"\n Create a DataFrame with the levels of the MultiIndex as columns.\n\n Column ordering is determined by the DataFrame constructor with data as\n a dict.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n index : bool, default True\n Set the index of the returned DataFrame as the original MultiIndex.\n\n name : list / sequence of str, optional\n The passed names should substitute index level names.\n\n Returns\n -------\n DataFrame : a DataFrame containing the original MultiIndex data.\n\n See Also\n --------\n DataFrame\n \"\"\"\n from pandas import DataFrame\n\n if name is not None:\n if not is_list_like(name):\n raise TypeError(\"'name' must be a list / sequence of column names.\")\n\n if len(name) != len(self.levels):\n raise ValueError(\n \"'name' should have same length as number of levels on index.\"\n )\n idx_names = name\n else:\n idx_names = self.names\n\n # Guarantee resulting column order - PY36+ dict maintains insertion order\n result = DataFrame(\n {\n (level if lvlname is None else lvlname): self._get_level_values(level)\n for lvlname, level in zip(idx_names, range(len(self.levels)))\n },\n copy=False,\n )\n\n if index:\n result.index = self\n return result\n\n def to_flat_index(self):\n \"\"\"\n Convert a MultiIndex to an Index of Tuples containing the level values.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n pd.Index\n Index with the MultiIndex data represented in Tuples.\n\n Notes\n -----\n This method will simply return the caller if called by anything other\n than a MultiIndex.\n\n Examples\n --------\n >>> index = pd.MultiIndex.from_product(\n ... [['foo', 'bar'], ['baz', 'qux']],\n ... names=['a', 'b'])\n >>> index.to_flat_index()\n Index([('foo', 'baz'), ('foo', 'qux'),\n ('bar', 'baz'), ('bar', 'qux')],\n dtype='object')\n \"\"\"\n return Index(self.values, tupleize_cols=False)\n\n @property\n def is_all_dates(self) -> bool:\n return False\n\n def is_lexsorted(self) -> bool:\n \"\"\"\n Return True if the codes are lexicographically sorted.\n\n Returns\n -------\n bool\n \"\"\"\n return self.lexsort_depth == self.nlevels\n\n @cache_readonly\n def lexsort_depth(self):\n if self.sortorder is not None:\n return self.sortorder\n\n return self._lexsort_depth()\n\n def _lexsort_depth(self) -> int:\n \"\"\"\n Compute and return the lexsort_depth, the number of levels of the\n MultiIndex that are sorted lexically\n\n Returns\n -------\n int\n \"\"\"\n int64_codes = [ensure_int64(level_codes) for level_codes in self.codes]\n for k in range(self.nlevels, 0, -1):\n if libalgos.is_lexsorted(int64_codes[:k]):\n return k\n return 0\n\n def _sort_levels_monotonic(self):\n \"\"\"\n This is an *internal* function.\n\n Create a new MultiIndex from the current to monotonically sorted\n items IN the levels. This does not actually make the entire MultiIndex\n monotonic, JUST the levels.\n\n The resulting MultiIndex will have the same outward\n appearance, meaning the same .values and ordering. It will also\n be .equals() to the original.\n\n Returns\n -------\n MultiIndex\n\n Examples\n --------\n >>> mi = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],\n ... codes=[[0, 0, 1, 1], [0, 1, 0, 1]])\n >>> mi\n MultiIndex([('a', 'bb'),\n ('a', 'aa'),\n ('b', 'bb'),\n ('b', 'aa')],\n )\n\n >>> mi.sort_values()\n MultiIndex([('a', 'aa'),\n ('a', 'bb'),\n ('b', 'aa'),\n ('b', 'bb')],\n )\n \"\"\"\n if self.is_lexsorted() and self.is_monotonic:\n return self\n\n new_levels = []\n new_codes = []\n\n for lev, level_codes in zip(self.levels, self.codes):\n\n if not lev.is_monotonic:\n try:\n # indexer to reorder the levels\n indexer = lev.argsort()\n except TypeError:\n pass\n else:\n lev = lev.take(indexer)\n\n # indexer to reorder the level codes\n indexer = ensure_int64(indexer)\n ri = lib.get_reverse_indexer(indexer, len(indexer))\n level_codes = algos.take_1d(ri, level_codes)\n\n new_levels.append(lev)\n new_codes.append(level_codes)\n\n return MultiIndex(\n new_levels,\n new_codes,\n names=self.names,\n sortorder=self.sortorder,\n verify_integrity=False,\n )\n\n def remove_unused_levels(self):\n \"\"\"\n Create a new MultiIndex from the current that removes\n unused levels, meaning that they are not expressed in the labels.\n\n The resulting MultiIndex will have the same outward\n appearance, meaning the same .values and ordering. It will also\n be .equals() to the original.\n\n Returns\n -------\n MultiIndex\n\n Examples\n --------\n >>> mi = pd.MultiIndex.from_product([range(2), list('ab')])\n >>> mi\n MultiIndex([(0, 'a'),\n (0, 'b'),\n (1, 'a'),\n (1, 'b')],\n )\n\n >>> mi[2:]\n MultiIndex([(1, 'a'),\n (1, 'b')],\n )\n\n The 0 from the first level is not represented\n and can be removed\n\n >>> mi2 = mi[2:].remove_unused_levels()\n >>> mi2.levels\n FrozenList([[1], ['a', 'b']])\n \"\"\"\n new_levels = []\n new_codes = []\n\n changed = False\n for lev, level_codes in zip(self.levels, self.codes):\n\n # Since few levels are typically unused, bincount() is more\n # efficient than unique() - however it only accepts positive values\n # (and drops order):\n uniques = np.where(np.bincount(level_codes + 1) > 0)[0] - 1\n has_na = int(len(uniques) and (uniques[0] == -1))\n\n if len(uniques) != len(lev) + has_na:\n # We have unused levels\n changed = True\n\n # Recalculate uniques, now preserving order.\n # Can easily be cythonized by exploiting the already existing\n # \"uniques\" and stop parsing \"level_codes\" when all items\n # are found:\n uniques = algos.unique(level_codes)\n if has_na:\n na_idx = np.where(uniques == -1)[0]\n # Just ensure that -1 is in first position:\n uniques[[0, na_idx[0]]] = uniques[[na_idx[0], 0]]\n\n # codes get mapped from uniques to 0:len(uniques)\n # -1 (if present) is mapped to last position\n code_mapping = np.zeros(len(lev) + has_na)\n # ... and reassigned value -1:\n code_mapping[uniques] = np.arange(len(uniques)) - has_na\n\n level_codes = code_mapping[level_codes]\n\n # new levels are simple\n lev = lev.take(uniques[has_na:])\n\n new_levels.append(lev)\n new_codes.append(level_codes)\n\n result = self.view()\n\n if changed:\n result._reset_identity()\n result._set_levels(new_levels, validate=False)\n result._set_codes(new_codes, validate=False)\n\n return result\n\n # --------------------------------------------------------------------\n # Pickling Methods\n\n def __reduce__(self):\n \"\"\"Necessary for making this object picklable\"\"\"\n d = dict(\n levels=list(self.levels),\n codes=list(self.codes),\n sortorder=self.sortorder,\n names=list(self.names),\n )\n return ibase._new_Index, (type(self), d), None\n\n # --------------------------------------------------------------------\n\n def __getitem__(self, key):\n if is_scalar(key):\n key = com.cast_scalar_indexer(key)\n\n retval = []\n for lev, level_codes in zip(self.levels, self.codes):\n if level_codes[key] == -1:\n retval.append(np.nan)\n else:\n retval.append(lev[level_codes[key]])\n\n return tuple(retval)\n else:\n if com.is_bool_indexer(key):\n key = np.asarray(key, dtype=bool)\n sortorder = self.sortorder\n else:\n # cannot be sure whether the result will be sorted\n sortorder = None\n\n if isinstance(key, Index):\n key = np.asarray(key)\n\n new_codes = [level_codes[key] for level_codes in self.codes]\n\n return MultiIndex(\n levels=self.levels,\n codes=new_codes,\n names=self.names,\n sortorder=sortorder,\n verify_integrity=False,\n )\n\n @Appender(_index_shared_docs[\"take\"] % _index_doc_kwargs)\n def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):\n nv.validate_take(tuple(), kwargs)\n indices = ensure_platform_int(indices)\n taken = self._assert_take_fillable(\n self.codes,\n indices,\n allow_fill=allow_fill,\n fill_value=fill_value,\n na_value=-1,\n )\n return MultiIndex(\n levels=self.levels, codes=taken, names=self.names, verify_integrity=False\n )\n\n def _assert_take_fillable(\n self, values, indices, allow_fill=True, fill_value=None, na_value=None\n ):\n \"\"\" Internal method to handle NA filling of take \"\"\"\n # only fill if we are passing a non-None fill_value\n if allow_fill and fill_value is not None:\n if (indices < -1).any():\n msg = (\n \"When allow_fill=True and fill_value is not None, \"\n \"all indices must be >= -1\"\n )\n raise ValueError(msg)\n taken = [lab.take(indices) for lab in self.codes]\n mask = indices == -1\n if mask.any():\n masked = []\n for new_label in taken:\n label_values = new_label\n label_values[mask] = na_value\n masked.append(np.asarray(label_values))\n taken = masked\n else:\n taken = [lab.take(indices) for lab in self.codes]\n return taken\n\n def append(self, other):\n \"\"\"\n Append a collection of Index options together\n\n Parameters\n ----------\n other : Index or list/tuple of indices\n\n Returns\n -------\n appended : Index\n \"\"\"\n if not isinstance(other, (list, tuple)):\n other = [other]\n\n if all(\n (isinstance(o, MultiIndex) and o.nlevels >= self.nlevels) for o in other\n ):\n arrays = []\n for i in range(self.nlevels):\n label = self._get_level_values(i)\n appended = [o._get_level_values(i) for o in other]\n arrays.append(label.append(appended))\n return MultiIndex.from_arrays(arrays, names=self.names)\n\n to_concat = (self.values,) + tuple(k._values for k in other)\n new_tuples = np.concatenate(to_concat)\n\n # if all(isinstance(x, MultiIndex) for x in other):\n try:\n return MultiIndex.from_tuples(new_tuples, names=self.names)\n except (TypeError, IndexError):\n return Index(new_tuples)\n\n def argsort(self, *args, **kwargs) -> np.ndarray:\n return self.values.argsort(*args, **kwargs)\n\n @Appender(_index_shared_docs[\"repeat\"] % _index_doc_kwargs)\n def repeat(self, repeats, axis=None):\n nv.validate_repeat(tuple(), dict(axis=axis))\n repeats = ensure_platform_int(repeats)\n return MultiIndex(\n levels=self.levels,\n codes=[\n level_codes.view(np.ndarray).astype(np.intp).repeat(repeats)\n for level_codes in self.codes\n ],\n names=self.names,\n sortorder=self.sortorder,\n verify_integrity=False,\n )\n\n def where(self, cond, other=None):\n raise NotImplementedError(\".where is not supported for MultiIndex operations\")\n\n def drop(self, codes, level=None, errors=\"raise\"):\n \"\"\"\n Make new MultiIndex with passed list of codes deleted\n\n Parameters\n ----------\n codes : array-like\n Must be a list of tuples\n level : int or level name, default None\n errors : str, default 'raise'\n\n Returns\n -------\n dropped : MultiIndex\n \"\"\"\n if level is not None:\n return self._drop_from_level(codes, level, errors)\n\n if not isinstance(codes, (np.ndarray, Index)):\n try:\n codes = com.index_labels_to_array(codes, dtype=object)\n except ValueError:\n pass\n\n inds = []\n for level_codes in codes:\n try:\n loc = self.get_loc(level_codes)\n # get_loc returns either an integer, a slice, or a boolean\n # mask\n if isinstance(loc, int):\n inds.append(loc)\n elif isinstance(loc, slice):\n inds.extend(range(loc.start, loc.stop))\n elif com.is_bool_indexer(loc):\n if self.lexsort_depth == 0:\n warnings.warn(\n \"dropping on a non-lexsorted multi-index \"\n \"without a level parameter may impact performance.\",\n PerformanceWarning,\n stacklevel=3,\n )\n loc = loc.nonzero()[0]\n inds.extend(loc)\n else:\n msg = f\"unsupported indexer of type {type(loc)}\"\n raise AssertionError(msg)\n except KeyError:\n if errors != \"ignore\":\n raise\n\n return self.delete(inds)\n\n def _drop_from_level(self, codes, level, errors=\"raise\"):\n codes = com.index_labels_to_array(codes)\n i = self._get_level_number(level)\n index = self.levels[i]\n values = index.get_indexer(codes)\n\n mask = ~algos.isin(self.codes[i], values)\n if mask.all() and errors != \"ignore\":\n raise KeyError(f\"labels {codes} not found in level\")\n\n return self[mask]\n\n def swaplevel(self, i=-2, j=-1):\n \"\"\"\n Swap level i with level j.\n\n Calling this method does not change the ordering of the values.\n\n Parameters\n ----------\n i : int, str, default -2\n First level of index to be swapped. Can pass level name as string.\n Type of parameters can be mixed.\n j : int, str, default -1\n Second level of index to be swapped. Can pass level name as string.\n Type of parameters can be mixed.\n\n Returns\n -------\n MultiIndex\n A new MultiIndex.\n\n See Also\n --------\n Series.swaplevel : Swap levels i and j in a MultiIndex.\n Dataframe.swaplevel : Swap levels i and j in a MultiIndex on a\n particular axis.\n\n Examples\n --------\n >>> mi = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],\n ... codes=[[0, 0, 1, 1], [0, 1, 0, 1]])\n >>> mi\n MultiIndex([('a', 'bb'),\n ('a', 'aa'),\n ('b', 'bb'),\n ('b', 'aa')],\n )\n >>> mi.swaplevel(0, 1)\n MultiIndex([('bb', 'a'),\n ('aa', 'a'),\n ('bb', 'b'),\n ('aa', 'b')],\n )\n \"\"\"\n new_levels = list(self.levels)\n new_codes = list(self.codes)\n new_names = list(self.names)\n\n i = self._get_level_number(i)\n j = self._get_level_number(j)\n\n new_levels[i], new_levels[j] = new_levels[j], new_levels[i]\n new_codes[i], new_codes[j] = new_codes[j], new_codes[i]\n new_names[i], new_names[j] = new_names[j], new_names[i]\n\n return MultiIndex(\n levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False\n )\n\n def reorder_levels(self, order):\n \"\"\"\n Rearrange levels using input order. May not drop or duplicate levels.\n\n Parameters\n ----------\n order : list of int or list of str\n List representing new level order. Reference level by number\n (position) or by key (label).\n\n Returns\n -------\n MultiIndex\n \"\"\"\n order = [self._get_level_number(i) for i in order]\n if len(order) != self.nlevels:\n raise AssertionError(\n f\"Length of order must be same as number of levels ({self.nlevels}), \"\n f\"got {len(order)}\"\n )\n new_levels = [self.levels[i] for i in order]\n new_codes = [self.codes[i] for i in order]\n new_names = [self.names[i] for i in order]\n\n return MultiIndex(\n levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False\n )\n\n def _get_codes_for_sorting(self):\n \"\"\"\n we categorizing our codes by using the\n available categories (all, not just observed)\n excluding any missing ones (-1); this is in preparation\n for sorting, where we need to disambiguate that -1 is not\n a valid valid\n \"\"\"\n\n def cats(level_codes):\n return np.arange(\n np.array(level_codes).max() + 1 if len(level_codes) else 0,\n dtype=level_codes.dtype,\n )\n\n return [\n Categorical.from_codes(level_codes, cats(level_codes), ordered=True)\n for level_codes in self.codes\n ]\n\n def sortlevel(self, level=0, ascending=True, sort_remaining=True):\n \"\"\"\n Sort MultiIndex at the requested level. The result will respect the\n original ordering of the associated factor at that level.\n\n Parameters\n ----------\n level : list-like, int or str, default 0\n If a string is given, must be a name of the level.\n If list-like must be names or ints of levels.\n ascending : bool, default True\n False to sort in descending order.\n Can also be a list to specify a directed ordering.\n sort_remaining : sort by the remaining levels after level\n\n Returns\n -------\n sorted_index : pd.MultiIndex\n Resulting index.\n indexer : np.ndarray\n Indices of output values in original index.\n \"\"\"\n if isinstance(level, (str, int)):\n level = [level]\n level = [self._get_level_number(lev) for lev in level]\n sortorder = None\n\n # we have a directed ordering via ascending\n if isinstance(ascending, list):\n if not len(level) == len(ascending):\n raise ValueError(\"level must have same length as ascending\")\n\n indexer = lexsort_indexer(\n [self.codes[lev] for lev in level], orders=ascending\n )\n\n # level ordering\n else:\n\n codes = list(self.codes)\n shape = list(self.levshape)\n\n # partition codes and shape\n primary = tuple(codes[lev] for lev in level)\n primshp = tuple(shape[lev] for lev in level)\n\n # Reverse sorted to retain the order of\n # smaller indices that needs to be removed\n for lev in sorted(level, reverse=True):\n codes.pop(lev)\n shape.pop(lev)\n\n if sort_remaining:\n primary += primary + tuple(codes)\n primshp += primshp + tuple(shape)\n else:\n sortorder = level[0]\n\n indexer = indexer_from_factorized(primary, primshp, compress=False)\n\n if not ascending:\n indexer = indexer[::-1]\n\n indexer = ensure_platform_int(indexer)\n new_codes = [level_codes.take(indexer) for level_codes in self.codes]\n\n new_index = MultiIndex(\n codes=new_codes,\n levels=self.levels,\n names=self.names,\n sortorder=sortorder,\n verify_integrity=False,\n )\n\n return new_index, indexer\n\n def reindex(self, target, method=None, level=None, limit=None, tolerance=None):\n \"\"\"\n Create index with target's values (move/add/delete values as necessary)\n\n Returns\n -------\n new_index : pd.MultiIndex\n Resulting index\n indexer : np.ndarray or None\n Indices of output values in original index.\n\n \"\"\"\n # GH6552: preserve names when reindexing to non-named target\n # (i.e. neither Index nor Series).\n preserve_names = not hasattr(target, \"names\")\n\n if level is not None:\n if method is not None:\n raise TypeError(\"Fill method not supported if level passed\")\n\n # GH7774: preserve dtype/tz if target is empty and not an Index.\n # target may be an iterator\n target = ibase._ensure_has_len(target)\n if len(target) == 0 and not isinstance(target, Index):\n idx = self.levels[level]\n attrs = idx._get_attributes_dict()\n attrs.pop(\"freq\", None) # don't preserve freq\n target = type(idx)._simple_new(np.empty(0, dtype=idx.dtype), **attrs)\n else:\n target = ensure_index(target)\n target, indexer, _ = self._join_level(\n target, level, how=\"right\", return_indexers=True, keep_order=False\n )\n else:\n target = ensure_index(target)\n if self.equals(target):\n indexer = None\n else:\n if self.is_unique:\n indexer = self.get_indexer(\n target, method=method, limit=limit, tolerance=tolerance\n )\n else:\n raise ValueError(\"cannot handle a non-unique multi-index!\")\n\n if not isinstance(target, MultiIndex):\n if indexer is None:\n target = self\n elif (indexer >= 0).all():\n target = self.take(indexer)\n else:\n # hopefully?\n target = MultiIndex.from_tuples(target)\n\n if (\n preserve_names\n and target.nlevels == self.nlevels\n and target.names != self.names\n ):\n target = target.copy(deep=False)\n target.names = self.names\n\n return target, indexer\n\n # --------------------------------------------------------------------\n # Indexing Methods\n\n def get_value(self, series, key):\n # Label-based\n if not is_hashable(key) or is_iterator(key):\n # We allow tuples if they are hashable, whereas other Index\n # subclasses require scalar.\n # We have to explicitly exclude generators, as these are hashable.\n raise InvalidIndexError(key)\n\n try:\n loc = self.get_loc(key)\n except KeyError:\n if is_integer(key):\n loc = key\n else:\n raise\n\n return self._get_values_for_loc(series, loc, key)\n\n def _get_values_for_loc(self, series: \"Series\", loc, key):\n \"\"\"\n Do a positional lookup on the given Series, returning either a scalar\n or a Series.\n\n Assumes that `series.index is self`\n \"\"\"\n new_values = series._values[loc]\n if is_scalar(loc):\n return new_values\n\n new_index = self[loc]\n new_index = maybe_droplevels(new_index, key)\n new_ser = series._constructor(new_values, index=new_index, name=series.name)\n return new_ser.__finalize__(series)\n\n def _convert_listlike_indexer(self, keyarr):\n \"\"\"\n Parameters\n ----------\n keyarr : list-like\n Indexer to convert.\n\n Returns\n -------\n tuple (indexer, keyarr)\n indexer is an ndarray or None if cannot convert\n keyarr are tuple-safe keys\n \"\"\"\n indexer, keyarr = super()._convert_listlike_indexer(keyarr)\n\n # are we indexing a specific level\n if indexer is None and len(keyarr) and not isinstance(keyarr[0], tuple):\n level = 0\n _, indexer = self.reindex(keyarr, level=level)\n\n # take all\n if indexer is None:\n indexer = np.arange(len(self))\n\n check = self.levels[0].get_indexer(keyarr)\n mask = check == -1\n if mask.any():\n raise KeyError(f\"{keyarr[mask]} not in index\")\n\n return indexer, keyarr\n\n def _get_partial_string_timestamp_match_key(self, key):\n \"\"\"\n Translate any partial string timestamp matches in key, returning the\n new key.\n\n Only relevant for MultiIndex.\n \"\"\"\n # GH#10331\n if isinstance(key, str) and self.levels[0]._supports_partial_string_indexing:\n # Convert key '2016-01-01' to\n # ('2016-01-01'[, slice(None, None, None)]+)\n key = tuple([key] + [slice(None)] * (len(self.levels) - 1))\n\n if isinstance(key, tuple):\n # Convert (..., '2016-01-01', ...) in tuple to\n # (..., slice('2016-01-01', '2016-01-01', None), ...)\n new_key = []\n for i, component in enumerate(key):\n if (\n isinstance(component, str)\n and self.levels[i]._supports_partial_string_indexing\n ):\n new_key.append(slice(component, component, None))\n else:\n new_key.append(component)\n key = tuple(new_key)\n\n return key\n\n @Appender(_index_shared_docs[\"get_indexer\"] % _index_doc_kwargs)\n def get_indexer(self, target, method=None, limit=None, tolerance=None):\n method = missing.clean_reindex_fill_method(method)\n target = ensure_index(target)\n\n # empty indexer\n if is_list_like(target) and not len(target):\n return ensure_platform_int(np.array([]))\n\n if not isinstance(target, MultiIndex):\n try:\n target = MultiIndex.from_tuples(target)\n except (TypeError, ValueError):\n\n # let's instead try with a straight Index\n if method is None:\n return Index(self.values).get_indexer(\n target, method=method, limit=limit, tolerance=tolerance\n )\n\n if not self.is_unique:\n raise ValueError(\"Reindexing only valid with uniquely valued Index objects\")\n\n if method == \"pad\" or method == \"backfill\":\n if tolerance is not None:\n raise NotImplementedError(\n \"tolerance not implemented yet for MultiIndex\"\n )\n indexer = self._engine.get_indexer(target, method, limit)\n elif method == \"nearest\":\n raise NotImplementedError(\n \"method='nearest' not implemented yet \"\n \"for MultiIndex; see GitHub issue 9365\"\n )\n else:\n indexer = self._engine.get_indexer(target)\n\n return ensure_platform_int(indexer)\n\n @Appender(_index_shared_docs[\"get_indexer_non_unique\"] % _index_doc_kwargs)\n def get_indexer_non_unique(self, target):\n return super().get_indexer_non_unique(target)\n\n def get_slice_bound(\n self, label: Union[Hashable, Sequence[Hashable]], side: str, kind: str\n ) -> int:\n \"\"\"\n For an ordered MultiIndex, compute slice bound\n that corresponds to given label.\n\n Returns leftmost (one-past-the-rightmost if `side=='right') position\n of given label.\n\n Parameters\n ----------\n label : object or tuple of objects\n side : {'left', 'right'}\n kind : {'loc', 'getitem'}\n\n Returns\n -------\n int\n Index of label.\n\n Notes\n -----\n This method only works if level 0 index of the MultiIndex is lexsorted.\n\n Examples\n --------\n >>> mi = pd.MultiIndex.from_arrays([list('abbc'), list('gefd')])\n\n Get the locations from the leftmost 'b' in the first level\n until the end of the multiindex:\n\n >>> mi.get_slice_bound('b', side=\"left\", kind=\"loc\")\n 1\n\n Like above, but if you get the locations from the rightmost\n 'b' in the first level and 'f' in the second level:\n\n >>> mi.get_slice_bound(('b','f'), side=\"right\", kind=\"loc\")\n 3\n\n See Also\n --------\n MultiIndex.get_loc : Get location for a label or a tuple of labels.\n MultiIndex.get_locs : Get location for a label/slice/list/mask or a\n sequence of such.\n \"\"\"\n if not isinstance(label, tuple):\n label = (label,)\n return self._partial_tup_index(label, side=side)\n\n def slice_locs(self, start=None, end=None, step=None, kind=None):\n \"\"\"\n For an ordered MultiIndex, compute the slice locations for input\n labels.\n\n The input labels can be tuples representing partial levels, e.g. for a\n MultiIndex with 3 levels, you can pass a single value (corresponding to\n the first level), or a 1-, 2-, or 3-tuple.\n\n Parameters\n ----------\n start : label or tuple, default None\n If None, defaults to the beginning\n end : label or tuple\n If None, defaults to the end\n step : int or None\n Slice step\n kind : string, optional, defaults None\n\n Returns\n -------\n (start, end) : (int, int)\n\n Notes\n -----\n This method only works if the MultiIndex is properly lexsorted. So,\n if only the first 2 levels of a 3-level MultiIndex are lexsorted,\n you can only pass two levels to ``.slice_locs``.\n\n Examples\n --------\n >>> mi = pd.MultiIndex.from_arrays([list('abbd'), list('deff')],\n ... names=['A', 'B'])\n\n Get the slice locations from the beginning of 'b' in the first level\n until the end of the multiindex:\n\n >>> mi.slice_locs(start='b')\n (1, 4)\n\n Like above, but stop at the end of 'b' in the first level and 'f' in\n the second level:\n\n >>> mi.slice_locs(start='b', end=('b', 'f'))\n (1, 3)\n\n See Also\n --------\n MultiIndex.get_loc : Get location for a label or a tuple of labels.\n MultiIndex.get_locs : Get location for a label/slice/list/mask or a\n sequence of such.\n \"\"\"\n # This function adds nothing to its parent implementation (the magic\n # happens in get_slice_bound method), but it adds meaningful doc.\n return super().slice_locs(start, end, step, kind=kind)\n\n def _partial_tup_index(self, tup, side=\"left\"):\n if len(tup) > self.lexsort_depth:\n raise UnsortedIndexError(\n f\"Key length ({len(tup)}) was greater than MultiIndex lexsort depth \"\n f\"({self.lexsort_depth})\"\n )\n\n n = len(tup)\n start, end = 0, len(self)\n zipped = zip(tup, self.levels, self.codes)\n for k, (lab, lev, labs) in enumerate(zipped):\n section = labs[start:end]\n\n if lab not in lev and not isna(lab):\n if not lev.is_type_compatible(lib.infer_dtype([lab], skipna=False)):\n raise TypeError(f\"Level type mismatch: {lab}\")\n\n # short circuit\n loc = lev.searchsorted(lab, side=side)\n if side == \"right\" and loc >= 0:\n loc -= 1\n return start + section.searchsorted(loc, side=side)\n\n idx = self._get_loc_single_level_index(lev, lab)\n if k < n - 1:\n end = start + section.searchsorted(idx, side=\"right\")\n start = start + section.searchsorted(idx, side=\"left\")\n else:\n return start + section.searchsorted(idx, side=side)\n\n def _get_loc_single_level_index(self, level_index: Index, key: Hashable) -> int:\n \"\"\"\n If key is NA value, location of index unify as -1.\n\n Parameters\n ----------\n level_index: Index\n key : label\n\n Returns\n -------\n loc : int\n If key is NA value, loc is -1\n Else, location of key in index.\n\n See Also\n --------\n Index.get_loc : The get_loc method for (single-level) index.\n \"\"\"\n if is_scalar(key) and isna(key):\n return -1\n else:\n return level_index.get_loc(key)\n\n def get_loc(self, key, method=None):\n \"\"\"\n Get location for a label or a tuple of labels as an integer, slice or\n boolean mask.\n\n Parameters\n ----------\n key : label or tuple of labels (one for each level)\n method : None\n\n Returns\n -------\n loc : int, slice object or boolean mask\n If the key is past the lexsort depth, the return may be a\n boolean mask array, otherwise it is always a slice or int.\n\n See Also\n --------\n Index.get_loc : The get_loc method for (single-level) index.\n MultiIndex.slice_locs : Get slice location given start label(s) and\n end label(s).\n MultiIndex.get_locs : Get location for a label/slice/list/mask or a\n sequence of such.\n\n Notes\n -----\n The key cannot be a slice, list of same-level labels, a boolean mask,\n or a sequence of such. If you want to use those, use\n :meth:`MultiIndex.get_locs` instead.\n\n Examples\n --------\n >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')])\n\n >>> mi.get_loc('b')\n slice(1, 3, None)\n\n >>> mi.get_loc(('b', 'e'))\n 1\n \"\"\"\n if method is not None:\n raise NotImplementedError(\n \"only the default get_loc method is \"\n \"currently supported for MultiIndex\"\n )\n\n def _maybe_to_slice(loc):\n \"\"\"convert integer indexer to boolean mask or slice if possible\"\"\"\n if not isinstance(loc, np.ndarray) or loc.dtype != \"int64\":\n return loc\n\n loc = lib.maybe_indices_to_slice(loc, len(self))\n if isinstance(loc, slice):\n return loc\n\n mask = np.empty(len(self), dtype=\"bool\")\n mask.fill(False)\n mask[loc] = True\n return mask\n\n if not isinstance(key, (tuple, list)):\n # not including list here breaks some indexing, xref #30892\n loc = self._get_level_indexer(key, level=0)\n return _maybe_to_slice(loc)\n\n keylen = len(key)\n if self.nlevels < keylen:\n raise KeyError(\n f\"Key length ({keylen}) exceeds index depth ({self.nlevels})\"\n )\n\n if keylen == self.nlevels and self.is_unique:\n return self._engine.get_loc(key)\n\n # -- partial selection or non-unique index\n # break the key into 2 parts based on the lexsort_depth of the index;\n # the first part returns a continuous slice of the index; the 2nd part\n # needs linear search within the slice\n i = self.lexsort_depth\n lead_key, follow_key = key[:i], key[i:]\n start, stop = (\n self.slice_locs(lead_key, lead_key) if lead_key else (0, len(self))\n )\n\n if start == stop:\n raise KeyError(key)\n\n if not follow_key:\n return slice(start, stop)\n\n warnings.warn(\n \"indexing past lexsort depth may impact performance.\",\n PerformanceWarning,\n stacklevel=10,\n )\n\n loc = np.arange(start, stop, dtype=\"int64\")\n\n for i, k in enumerate(follow_key, len(lead_key)):\n mask = self.codes[i][loc] == self._get_loc_single_level_index(\n self.levels[i], k\n )\n if not mask.all():\n loc = loc[mask]\n if not len(loc):\n raise KeyError(key)\n\n return _maybe_to_slice(loc) if len(loc) != stop - start else slice(start, stop)\n\n def get_loc_level(self, key, level=0, drop_level: bool = True):\n \"\"\"\n Get both the location for the requested label(s) and the\n resulting sliced index.\n\n Parameters\n ----------\n key : label or sequence of labels\n level : int/level name or list thereof, optional\n drop_level : bool, default True\n If ``False``, the resulting index will not drop any level.\n\n Returns\n -------\n loc : A 2-tuple where the elements are:\n Element 0: int, slice object or boolean array\n Element 1: The resulting sliced multiindex/index. If the key\n contains all levels, this will be ``None``.\n\n See Also\n --------\n MultiIndex.get_loc : Get location for a label or a tuple of labels.\n MultiIndex.get_locs : Get location for a label/slice/list/mask or a\n sequence of such.\n\n Examples\n --------\n >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')],\n ... names=['A', 'B'])\n\n >>> mi.get_loc_level('b')\n (slice(1, 3, None), Index(['e', 'f'], dtype='object', name='B'))\n\n >>> mi.get_loc_level('e', level='B')\n (array([False, True, False], dtype=bool),\n Index(['b'], dtype='object', name='A'))\n\n >>> mi.get_loc_level(['b', 'e'])\n (1, None)\n \"\"\"\n # different name to distinguish from maybe_droplevels\n def maybe_mi_droplevels(indexer, levels, drop_level: bool):\n if not drop_level:\n return self[indexer]\n # kludgearound\n orig_index = new_index = self[indexer]\n levels = [self._get_level_number(i) for i in levels]\n for i in sorted(levels, reverse=True):\n try:\n new_index = new_index.droplevel(i)\n except ValueError:\n\n # no dropping here\n return orig_index\n return new_index\n\n if isinstance(level, (tuple, list)):\n if len(key) != len(level):\n raise AssertionError(\n \"Key for location must have same length as number of levels\"\n )\n result = None\n for lev, k in zip(level, key):\n loc, new_index = self.get_loc_level(k, level=lev)\n if isinstance(loc, slice):\n mask = np.zeros(len(self), dtype=bool)\n mask[loc] = True\n loc = mask\n\n result = loc if result is None else result & loc\n\n return result, maybe_mi_droplevels(result, level, drop_level)\n\n level = self._get_level_number(level)\n\n # kludge for #1796\n if isinstance(key, list):\n key = tuple(key)\n\n if isinstance(key, tuple) and level == 0:\n\n try:\n if key in self.levels[0]:\n indexer = self._get_level_indexer(key, level=level)\n new_index = maybe_mi_droplevels(indexer, [0], drop_level)\n return indexer, new_index\n except (TypeError, InvalidIndexError):\n pass\n\n if not any(isinstance(k, slice) for k in key):\n\n # partial selection\n # optionally get indexer to avoid re-calculation\n def partial_selection(key, indexer=None):\n if indexer is None:\n indexer = self.get_loc(key)\n ilevels = [\n i for i in range(len(key)) if key[i] != slice(None, None)\n ]\n return indexer, maybe_mi_droplevels(indexer, ilevels, drop_level)\n\n if len(key) == self.nlevels and self.is_unique:\n # Complete key in unique index -> standard get_loc\n try:\n return (self._engine.get_loc(key), None)\n except KeyError as e:\n raise KeyError(key) from e\n else:\n return partial_selection(key)\n else:\n indexer = None\n for i, k in enumerate(key):\n if not isinstance(k, slice):\n k = self._get_level_indexer(k, level=i)\n if isinstance(k, slice):\n # everything\n if k.start == 0 and k.stop == len(self):\n k = slice(None, None)\n else:\n k_index = k\n\n if isinstance(k, slice):\n if k == slice(None, None):\n continue\n else:\n raise TypeError(key)\n\n if indexer is None:\n indexer = k_index\n else: # pragma: no cover\n indexer &= k_index\n if indexer is None:\n indexer = slice(None, None)\n ilevels = [i for i in range(len(key)) if key[i] != slice(None, None)]\n return indexer, maybe_mi_droplevels(indexer, ilevels, drop_level)\n else:\n indexer = self._get_level_indexer(key, level=level)\n return indexer, maybe_mi_droplevels(indexer, [level], drop_level)\n\n def _get_level_indexer(self, key, level=0, indexer=None):\n # return an indexer, boolean array or a slice showing where the key is\n # in the totality of values\n # if the indexer is provided, then use this\n\n level_index = self.levels[level]\n level_codes = self.codes[level]\n\n def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes):\n # given the inputs and the codes/indexer, compute an indexer set\n # if we have a provided indexer, then this need not consider\n # the entire labels set\n\n r = np.arange(start, stop, step)\n if indexer is not None and len(indexer) != len(codes):\n\n # we have an indexer which maps the locations in the labels\n # that we have already selected (and is not an indexer for the\n # entire set) otherwise this is wasteful so we only need to\n # examine locations that are in this set the only magic here is\n # that the result are the mappings to the set that we have\n # selected\n from pandas import Series\n\n mapper = Series(indexer)\n indexer = codes.take(ensure_platform_int(indexer))\n result = Series(Index(indexer).isin(r).nonzero()[0])\n m = result.map(mapper)._ndarray_values\n\n else:\n m = np.zeros(len(codes), dtype=bool)\n m[np.in1d(codes, r, assume_unique=Index(codes).is_unique)] = True\n\n return m\n\n if isinstance(key, slice):\n # handle a slice, returning a slice if we can\n # otherwise a boolean indexer\n\n try:\n if key.start is not None:\n start = level_index.get_loc(key.start)\n else:\n start = 0\n if key.stop is not None:\n stop = level_index.get_loc(key.stop)\n else:\n stop = len(level_index) - 1\n step = key.step\n except KeyError:\n\n # we have a partial slice (like looking up a partial date\n # string)\n start = stop = level_index.slice_indexer(\n key.start, key.stop, key.step, kind=\"loc\"\n )\n step = start.step\n\n if isinstance(start, slice) or isinstance(stop, slice):\n # we have a slice for start and/or stop\n # a partial date slicer on a DatetimeIndex generates a slice\n # note that the stop ALREADY includes the stopped point (if\n # it was a string sliced)\n start = getattr(start, \"start\", start)\n stop = getattr(stop, \"stop\", stop)\n return convert_indexer(start, stop, step)\n\n elif level > 0 or self.lexsort_depth == 0 or step is not None:\n # need to have like semantics here to right\n # searching as when we are using a slice\n # so include the stop+1 (so we include stop)\n return convert_indexer(start, stop + 1, step)\n else:\n # sorted, so can return slice object -> view\n i = level_codes.searchsorted(start, side=\"left\")\n j = level_codes.searchsorted(stop, side=\"right\")\n return slice(i, j, step)\n\n else:\n\n code = self._get_loc_single_level_index(level_index, key)\n\n if level > 0 or self.lexsort_depth == 0:\n # Desired level is not sorted\n locs = np.array(level_codes == code, dtype=bool, copy=False)\n if not locs.any():\n # The label is present in self.levels[level] but unused:\n raise KeyError(key)\n return locs\n\n i = level_codes.searchsorted(code, side=\"left\")\n j = level_codes.searchsorted(code, side=\"right\")\n if i == j:\n # The label is present in self.levels[level] but unused:\n raise KeyError(key)\n return slice(i, j)\n\n def get_locs(self, seq):\n \"\"\"\n Get location for a sequence of labels.\n\n Parameters\n ----------\n seq : label, slice, list, mask or a sequence of such\n You should use one of the above for each level.\n If a level should not be used, set it to ``slice(None)``.\n\n Returns\n -------\n numpy.ndarray\n NumPy array of integers suitable for passing to iloc.\n\n See Also\n --------\n MultiIndex.get_loc : Get location for a label or a tuple of labels.\n MultiIndex.slice_locs : Get slice location given start label(s) and\n end label(s).\n\n Examples\n --------\n >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')])\n\n >>> mi.get_locs('b') # doctest: +SKIP\n array([1, 2], dtype=int64)\n\n >>> mi.get_locs([slice(None), ['e', 'f']]) # doctest: +SKIP\n array([1, 2], dtype=int64)\n\n >>> mi.get_locs([[True, False, True], slice('e', 'f')]) # doctest: +SKIP\n array([2], dtype=int64)\n \"\"\"\n from pandas.core.indexes.numeric import Int64Index\n\n # must be lexsorted to at least as many levels\n true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s]\n if true_slices and true_slices[-1] >= self.lexsort_depth:\n raise UnsortedIndexError(\n \"MultiIndex slicing requires the index to be lexsorted: slicing \"\n f\"on levels {true_slices}, lexsort depth {self.lexsort_depth}\"\n )\n # indexer\n # this is the list of all values that we want to select\n n = len(self)\n indexer = None\n\n def _convert_to_indexer(r):\n # return an indexer\n if isinstance(r, slice):\n m = np.zeros(n, dtype=bool)\n m[r] = True\n r = m.nonzero()[0]\n elif com.is_bool_indexer(r):\n if len(r) != n:\n raise ValueError(\n \"cannot index with a boolean indexer \"\n \"that is not the same length as the \"\n \"index\"\n )\n r = r.nonzero()[0]\n return Int64Index(r)\n\n def _update_indexer(idxr, indexer=indexer):\n if indexer is None:\n indexer = Index(np.arange(n))\n if idxr is None:\n return indexer\n return indexer & idxr\n\n for i, k in enumerate(seq):\n\n if com.is_bool_indexer(k):\n # a boolean indexer, must be the same length!\n k = np.asarray(k)\n indexer = _update_indexer(_convert_to_indexer(k), indexer=indexer)\n\n elif is_list_like(k):\n # a collection of labels to include from this level (these\n # are or'd)\n indexers = None\n for x in k:\n try:\n idxrs = _convert_to_indexer(\n self._get_level_indexer(x, level=i, indexer=indexer)\n )\n indexers = idxrs if indexers is None else indexers | idxrs\n except KeyError:\n\n # ignore not founds\n continue\n\n if indexers is not None:\n indexer = _update_indexer(indexers, indexer=indexer)\n else:\n # no matches we are done\n return Int64Index([])._ndarray_values\n\n elif com.is_null_slice(k):\n # empty slice\n indexer = _update_indexer(None, indexer=indexer)\n\n elif isinstance(k, slice):\n\n # a slice, include BOTH of the labels\n indexer = _update_indexer(\n _convert_to_indexer(\n self._get_level_indexer(k, level=i, indexer=indexer)\n ),\n indexer=indexer,\n )\n else:\n # a single label\n indexer = _update_indexer(\n _convert_to_indexer(\n self.get_loc_level(k, level=i, drop_level=False)[0]\n ),\n indexer=indexer,\n )\n\n # empty indexer\n if indexer is None:\n return Int64Index([])._ndarray_values\n\n indexer = self._reorder_indexer(seq, indexer)\n\n return indexer._ndarray_values\n\n def _reorder_indexer(\n self, seq: Tuple[Union[Scalar, Iterable, AnyArrayLike], ...], indexer: ArrayLike\n ) -> ArrayLike:\n \"\"\"\n Reorder an indexer of a MultiIndex (self) so that the label are in the\n same order as given in seq\n\n Parameters\n ----------\n seq : label/slice/list/mask or a sequence of such\n indexer: an Int64Index indexer of self\n\n Returns\n -------\n indexer : a sorted Int64Index indexer of self ordered as seq\n \"\"\"\n # If the index is lexsorted and the list_like label in seq are sorted\n # then we do not need to sort\n if self.is_lexsorted():\n need_sort = False\n for i, k in enumerate(seq):\n if is_list_like(k):\n if not need_sort:\n k_codes = self.levels[i].get_indexer(k)\n k_codes = k_codes[k_codes >= 0] # Filter absent keys\n # True if the given codes are not ordered\n need_sort = (k_codes[:-1] > k_codes[1:]).any()\n # Bail out if both index and seq are sorted\n if not need_sort:\n return indexer\n\n n = len(self)\n keys: Tuple[np.ndarray, ...] = tuple()\n # For each level of the sequence in seq, map the level codes with the\n # order they appears in a list-like sequence\n # This mapping is then use to reorder the indexer\n for i, k in enumerate(seq):\n if com.is_bool_indexer(k):\n new_order = np.arange(n)[indexer]\n elif is_list_like(k):\n # Generate a map with all level codes as sorted initially\n key_order_map = np.ones(len(self.levels[i]), dtype=np.uint64) * len(\n self.levels[i]\n )\n # Set order as given in the indexer list\n level_indexer = self.levels[i].get_indexer(k)\n level_indexer = level_indexer[level_indexer >= 0] # Filter absent keys\n key_order_map[level_indexer] = np.arange(len(level_indexer))\n\n new_order = key_order_map[self.codes[i][indexer]]\n else:\n # For all other case, use the same order as the level\n new_order = np.arange(n)[indexer]\n keys = (new_order,) + keys\n\n # Find the reordering using lexsort on the keys mapping\n ind = np.lexsort(keys)\n return indexer[ind]\n\n def truncate(self, before=None, after=None):\n \"\"\"\n Slice index between two labels / tuples, return new MultiIndex\n\n Parameters\n ----------\n before : label or tuple, can be partial. Default None\n None defaults to start\n after : label or tuple, can be partial. Default None\n None defaults to end\n\n Returns\n -------\n truncated : MultiIndex\n \"\"\"\n if after and before and after < before:\n raise ValueError(\"after < before\")\n\n i, j = self.levels[0].slice_locs(before, after)\n left, right = self.slice_locs(before, after)\n\n new_levels = list(self.levels)\n new_levels[0] = new_levels[0][i:j]\n\n new_codes = [level_codes[left:right] for level_codes in self.codes]\n new_codes[0] = new_codes[0] - i\n\n return MultiIndex(levels=new_levels, codes=new_codes, verify_integrity=False)\n\n def equals(self, other) -> bool:\n \"\"\"\n Determines if two MultiIndex objects have the same labeling information\n (the levels themselves do not necessarily have to be the same)\n\n See Also\n --------\n equal_levels\n \"\"\"\n if self.is_(other):\n return True\n\n if not isinstance(other, Index):\n return False\n\n if not isinstance(other, MultiIndex):\n # d-level MultiIndex can equal d-tuple Index\n if not is_object_dtype(other.dtype):\n if self.nlevels != other.nlevels:\n return False\n\n other_vals = com.values_from_object(ensure_index(other))\n return array_equivalent(self._ndarray_values, other_vals)\n\n if self.nlevels != other.nlevels:\n return False\n\n if len(self) != len(other):\n return False\n\n for i in range(self.nlevels):\n self_codes = self.codes[i]\n self_codes = self_codes[self_codes != -1]\n self_values = algos.take_nd(\n np.asarray(self.levels[i]._values), self_codes, allow_fill=False\n )\n\n other_codes = other.codes[i]\n other_codes = other_codes[other_codes != -1]\n other_values = algos.take_nd(\n np.asarray(other.levels[i]._values), other_codes, allow_fill=False\n )\n\n # since we use NaT both datetime64 and timedelta64\n # we can have a situation where a level is typed say\n # timedelta64 in self (IOW it has other values than NaT)\n # but types datetime64 in other (where its all NaT)\n # but these are equivalent\n if len(self_values) == 0 and len(other_values) == 0:\n continue\n\n if not array_equivalent(self_values, other_values):\n return False\n\n return True\n\n def equal_levels(self, other) -> bool:\n \"\"\"\n Return True if the levels of both MultiIndex objects are the same\n\n \"\"\"\n if self.nlevels != other.nlevels:\n return False\n\n for i in range(self.nlevels):\n if not self.levels[i].equals(other.levels[i]):\n return False\n return True\n\n # --------------------------------------------------------------------\n # Set Methods\n\n def union(self, other, sort=None):\n \"\"\"\n Form the union of two MultiIndex objects\n\n Parameters\n ----------\n other : MultiIndex or array / Index of tuples\n sort : False or None, default None\n Whether to sort the resulting Index.\n\n * None : Sort the result, except when\n\n 1. `self` and `other` are equal.\n 2. `self` has length 0.\n 3. Some values in `self` or `other` cannot be compared.\n A RuntimeWarning is issued in this case.\n\n * False : do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n Index\n\n >>> index.union(index2)\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other, result_names = self._convert_can_do_setop(other)\n\n if len(other) == 0 or self.equals(other):\n return self\n\n # TODO: Index.union returns other when `len(self)` is 0.\n\n uniq_tuples = lib.fast_unique_multiple(\n [self._ndarray_values, other._ndarray_values], sort=sort\n )\n\n return MultiIndex.from_arrays(\n zip(*uniq_tuples), sortorder=0, names=result_names\n )\n\n def intersection(self, other, sort=False):\n \"\"\"\n Form the intersection of two MultiIndex objects.\n\n Parameters\n ----------\n other : MultiIndex or array / Index of tuples\n sort : False or None, default False\n Sort the resulting MultiIndex if possible\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default from ``True`` to ``False``, to match\n behaviour from before 0.24.0\n\n Returns\n -------\n Index\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other, result_names = self._convert_can_do_setop(other)\n\n if self.equals(other):\n return self\n\n lvals = self._ndarray_values\n rvals = other._ndarray_values\n\n uniq_tuples = None # flag whether _inner_indexer was succesful\n if self.is_monotonic and other.is_monotonic:\n try:\n uniq_tuples = self._inner_indexer(lvals, rvals)[0]\n sort = False # uniq_tuples is already sorted\n except TypeError:\n pass\n\n if uniq_tuples is None:\n other_uniq = set(rvals)\n seen = set()\n uniq_tuples = [\n x for x in lvals if x in other_uniq and not (x in seen or seen.add(x))\n ]\n\n if sort is None:\n uniq_tuples = sorted(uniq_tuples)\n\n if len(uniq_tuples) == 0:\n return MultiIndex(\n levels=self.levels,\n codes=[[]] * self.nlevels,\n names=result_names,\n verify_integrity=False,\n )\n else:\n return MultiIndex.from_arrays(\n zip(*uniq_tuples), sortorder=0, names=result_names\n )\n\n def difference(self, other, sort=None):\n \"\"\"\n Compute set difference of two MultiIndex objects\n\n Parameters\n ----------\n other : MultiIndex\n sort : False or None, default None\n Sort the resulting MultiIndex if possible\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n diff : MultiIndex\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other, result_names = self._convert_can_do_setop(other)\n\n if len(other) == 0:\n return self\n\n if self.equals(other):\n return MultiIndex(\n levels=self.levels,\n codes=[[]] * self.nlevels,\n names=result_names,\n verify_integrity=False,\n )\n\n this = self._get_unique_index()\n\n indexer = this.get_indexer(other)\n indexer = indexer.take((indexer != -1).nonzero()[0])\n\n label_diff = np.setdiff1d(np.arange(this.size), indexer, assume_unique=True)\n difference = this.values.take(label_diff)\n if sort is None:\n difference = sorted(difference)\n\n if len(difference) == 0:\n return MultiIndex(\n levels=[[]] * self.nlevels,\n codes=[[]] * self.nlevels,\n names=result_names,\n verify_integrity=False,\n )\n else:\n return MultiIndex.from_tuples(difference, sortorder=0, names=result_names)\n\n def _convert_can_do_setop(self, other):\n result_names = self.names\n\n if not hasattr(other, \"names\"):\n if len(other) == 0:\n other = MultiIndex(\n levels=[[]] * self.nlevels,\n codes=[[]] * self.nlevels,\n verify_integrity=False,\n )\n else:\n msg = \"other must be a MultiIndex or a list of tuples\"\n try:\n other = MultiIndex.from_tuples(other)\n except TypeError as err:\n raise TypeError(msg) from err\n else:\n result_names = self.names if self.names == other.names else None\n return other, result_names\n\n # --------------------------------------------------------------------\n\n @Appender(Index.astype.__doc__)\n def astype(self, dtype, copy=True):\n dtype = pandas_dtype(dtype)\n if is_categorical_dtype(dtype):\n msg = \"> 1 ndim Categorical are not supported at this time\"\n raise NotImplementedError(msg)\n elif not is_object_dtype(dtype):\n raise TypeError(\n f\"Setting {type(self)} dtype to anything other \"\n \"than object is not supported\"\n )\n elif copy is True:\n return self._shallow_copy()\n return self\n\n def insert(self, loc: int, item):\n \"\"\"\n Make new MultiIndex inserting new item at location\n\n Parameters\n ----------\n loc : int\n item : tuple\n Must be same length as number of levels in the MultiIndex\n\n Returns\n -------\n new_index : Index\n \"\"\"\n # Pad the key with empty strings if lower levels of the key\n # aren't specified:\n if not isinstance(item, tuple):\n item = (item,) + (\"\",) * (self.nlevels - 1)\n elif len(item) != self.nlevels:\n raise ValueError(\"Item must have length equal to number of levels.\")\n\n new_levels = []\n new_codes = []\n for k, level, level_codes in zip(item, self.levels, self.codes):\n if k not in level:\n # have to insert into level\n # must insert at end otherwise you have to recompute all the\n # other codes\n lev_loc = len(level)\n level = level.insert(lev_loc, k)\n else:\n lev_loc = level.get_loc(k)\n\n new_levels.append(level)\n new_codes.append(np.insert(ensure_int64(level_codes), loc, lev_loc))\n\n return MultiIndex(\n levels=new_levels, codes=new_codes, names=self.names, verify_integrity=False\n )\n\n def delete(self, loc):\n \"\"\"\n Make new index with passed location deleted\n\n Returns\n -------\n new_index : MultiIndex\n \"\"\"\n new_codes = [np.delete(level_codes, loc) for level_codes in self.codes]\n return MultiIndex(\n levels=self.levels,\n codes=new_codes,\n names=self.names,\n verify_integrity=False,\n )\n\n def _wrap_joined_index(self, joined, other):\n names = self.names if self.names == other.names else None\n return MultiIndex.from_tuples(joined, names=names)\n\n @Appender(Index.isin.__doc__)\n def isin(self, values, level=None):\n if level is None:\n values = MultiIndex.from_tuples(values, names=self.names).values\n return algos.isin(self.values, values)\n else:\n num = self._get_level_number(level)\n levs = self.get_level_values(num)\n\n if levs.size == 0:\n return np.zeros(len(levs), dtype=np.bool_)\n return levs.isin(values)\n\n\nMultiIndex._add_numeric_methods_disabled()\nMultiIndex._add_numeric_methods_add_sub_disabled()\nMultiIndex._add_logical_methods_disabled()\n\n\ndef _sparsify(label_list, start: int = 0, sentinel=\"\"):\n pivoted = list(zip(*label_list))\n k = len(label_list)\n\n result = pivoted[: start + 1]\n prev = pivoted[start]\n\n for cur in pivoted[start + 1 :]:\n sparse_cur = []\n\n for i, (p, t) in enumerate(zip(prev, cur)):\n if i == k - 1:\n sparse_cur.append(t)\n result.append(sparse_cur)\n break\n\n if p == t:\n sparse_cur.append(sentinel)\n else:\n sparse_cur.extend(cur[i:])\n result.append(sparse_cur)\n break\n\n prev = cur\n\n return list(zip(*result))\n\n\ndef _get_na_rep(dtype) -> str:\n return {np.datetime64: \"NaT\", np.timedelta64: \"NaT\"}.get(dtype, \"NaN\")\n\n\ndef maybe_droplevels(index, key):\n \"\"\"\n Attempt to drop level or levels from the given index.\n\n Parameters\n ----------\n index: Index\n key : scalar or tuple\n\n Returns\n -------\n Index\n \"\"\"\n # drop levels\n original_index = index\n if isinstance(key, tuple):\n for _ in key:\n try:\n index = index.droplevel(0)\n except ValueError:\n # we have dropped too much, so back out\n return original_index\n else:\n try:\n index = index.droplevel(0)\n except ValueError:\n pass\n\n return index\n\n\ndef _coerce_indexer_frozen(array_like, categories, copy: bool = False) -> np.ndarray:\n \"\"\"\n Coerce the array_like indexer to the smallest integer dtype that can encode all\n of the given categories.\n\n Parameters\n ----------\n array_like : array-like\n categories : array-like\n copy : bool\n\n Returns\n -------\n np.ndarray\n Non-writeable.\n \"\"\"\n array_like = coerce_indexer_dtype(array_like, categories)\n if copy:\n array_like = array_like.copy()\n array_like.flags.writeable = False\n return array_like\n" ]
[ [ "pandas.core.common.cast_scalar_indexer", "pandas.core.indexes.frozen.FrozenList", "pandas.io.formats.format._get_adjustment", "pandas.core.algorithms.unique", "pandas.io.formats.printing.format_object_summary", "pandas._libs.lib.fast_zip", "pandas.Series", "numpy.dtype", "numpy.any", "numpy.asarray", "pandas.core.common.is_true_slices", "pandas.core.dtypes.common.ensure_int64", "pandas.core.sorting.lexsort_indexer", "pandas.core.dtypes.common.is_integer", "pandas.core.dtypes.common.pandas_dtype", "pandas.core.dtypes.common.is_list_like", "pandas.core.common.is_null_slice", "pandas.core.dtypes.cast.coerce_indexer_dtype", "pandas.core.indexes.base.InvalidIndexError", "pandas._libs.algos.is_lexsorted", "numpy.append", "pandas.core.dtypes.common.is_categorical_dtype", "pandas._libs.lib.fast_unique_multiple", "pandas.core.indexes.base._ensure_has_len", "pandas.core.dtypes.common.is_hashable", "pandas.io.formats.printing.pprint_thing", "pandas.core.algorithms.take_1d", "pandas.core.dtypes.common.is_iterator", "pandas.core.indexes.base.ensure_index", "numpy.delete", "pandas.core.common.index_labels_to_array", "numpy.where", "pandas.io.formats.printing.format_object_attrs", "pandas._libs.lib.infer_dtype", "pandas.core.indexes.base.Index", "numpy.bincount", "numpy.zeros", "pandas._libs.lib.to_object_array_tuples", "pandas.core.reshape.util.cartesian_product", "pandas._libs.hashtable.duplicated_int64", "numpy.arange", "numpy.lexsort", "pandas._config.get_option", "pandas.core.common.is_bool_indexer", "pandas.core.algorithms.isin", "numpy.all", "pandas.core.algorithms.factorize", "pandas._libs.lib.tuples_to_object_array", "pandas.errors.UnsortedIndexError", "pandas.core.dtypes.common.ensure_platform_int", "pandas.core.dtypes.common.is_scalar", "pandas.core.dtypes.missing.isna", "pandas.core.sorting.indexer_from_factorized", "pandas.util._decorators.Appender", "pandas.core.missing.clean_reindex_fill_method", "numpy.cumsum", "numpy.empty", "pandas.core.arrays.categorical.factorize_from_iterables", "pandas.core.indexes.numeric.Int64Index", "pandas.core.dtypes.common.is_object_dtype", "numpy.bitwise_or.reduce", "pandas.core.sorting.get_group_index", "numpy.array", "numpy.concatenate", "pandas.core.dtypes.missing.array_equivalent" ] ]
ihmeuw-msca/SLIME
[ "255dfc6fc1880545f1ca9a5062eff823571cc025" ]
[ "src/slime/core/utils.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n utils\n ~~~~~\n\"\"\"\nimport numpy as np\n\n\ndef sizes_to_indices(sizes):\n \"\"\"Converting sizes to corresponding indices.\n Args:\n sizes (numpy.dnarray):\n An array consist of non-negative number.\n Returns:\n list{range}:\n List the indices.\n \"\"\"\n u_id = np.cumsum(sizes)\n l_id = np.insert(u_id[:-1], 0, 0)\n\n return [\n np.arange(l, u) for l, u in zip(l_id, u_id)\n ]\n" ]
[ [ "numpy.arange", "numpy.cumsum", "numpy.insert" ] ]
KANG91/Deep_Learning
[ "e3e9de769ab835215d0ebeee79ff869afbe64ebf", "e3e9de769ab835215d0ebeee79ff869afbe64ebf" ]
[ "lab-12-2-char-seq-rnn.py", "lab-05-1-logistic_regression.py" ]
[ "import tensorflow as tf\nimport numpy as np\ntf.set_random_seed(777) # reproducibility\n\nsample = \" if you want you\"\nidx2char = list(set(sample)) # index -> char\nchar2idx = {c: i for i, c in enumerate(idx2char)} # char -> idex\n\n# hyper parameters\ndic_size = len(char2idx) # RNN input size (one hot size)\nrnn_hidden_size = len(char2idx) # RNN output size\nnum_classes = len(char2idx) # final output size (RNN or softmax, etc.)\nbatch_size = 1 # one sample data, one batch\nsequence_length = len(sample) - 1 # number of lstm rollings (unit #)\n\nsample_idx = [char2idx[c] for c in sample] # char to index\nx_data = [sample_idx[:-1]] # X data sample (0 ~ n-1) hello: hell\ny_data = [sample_idx[1:]] # Y label sample (1 ~ n) hello: ello\n\nX = tf.placeholder(tf.int32, [None, sequence_length]) # X data\nY = tf.placeholder(tf.int32, [None, sequence_length]) # Y label\n\nx_one_hot = tf.one_hot(X, num_classes) # one hot: 1 -> 0 1 0 0 0 0 0 0 0 0\ncell = tf.contrib.rnn.BasicLSTMCell(\n num_units=rnn_hidden_size, state_is_tuple=True)\ninitial_state = cell.zero_state(batch_size, tf.float32)\noutputs, _states = tf.nn.dynamic_rnn(\n cell, x_one_hot, initial_state=initial_state, dtype=tf.float32)\n\nweights = tf.ones([batch_size, sequence_length])\nsequence_loss = tf.contrib.seq2seq.sequence_loss(\n logits=outputs, targets=Y, weights=weights)\nloss = tf.reduce_mean(sequence_loss)\ntrain = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss)\n\nprediction = tf.argmax(outputs, axis=2)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(3000):\n l, _ = sess.run([loss, train], feed_dict={X: x_data, Y: y_data})\n result = sess.run(prediction, feed_dict={X: x_data})\n\n # print char using dic\n result_str = [idx2char[c] for c in np.squeeze(result)]\n\n print(i, \"loss:\", l, \"Prediction:\", ''.join(result_str))\n\n\n'''\n0 loss: 2.29895 Prediction: nnuffuunnuuuyuy\n1 loss: 2.29675 Prediction: nnuffuunnuuuyuy\n2 loss: 2.29459 Prediction: nnuffuunnuuuyuy\n3 loss: 2.29247 Prediction: nnuffuunnuuuyuy\n\n...\n\n1413 loss: 1.3745 Prediction: if you want you\n1414 loss: 1.3743 Prediction: if you want you\n1415 loss: 1.3741 Prediction: if you want you\n1416 loss: 1.3739 Prediction: if you want you\n1417 loss: 1.3737 Prediction: if you want you\n1418 loss: 1.37351 Prediction: if you want you\n1419 loss: 1.37331 Prediction: if you want you\n'''\n", "# Lab 5 Logistic Regression Classifier\nimport tensorflow as tf\ntf.set_random_seed(777) # for reproducibility\n\nx_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]\ny_data = [[0], [0], [0], [1], [1], [1]]\n\n# placeholders for a tensor that will be always fed.\nX = tf.placeholder(tf.float32, shape=[None, 2])\nY = tf.placeholder(tf.float32, shape=[None, 1])\n\nW = tf.Variable(tf.random_normal([2, 1]), name='weight')\nb = tf.Variable(tf.random_normal([1]), name='bias')\n\n# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W)))\nhypothesis = tf.sigmoid(tf.matmul(X, W) + b)\n\n# Cost function\ncost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) *\n tf.log(1 - hypothesis))\n\ntrain = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)\n\n# Accuracy computation\n# True if hypothesis>0.5 else False\npredicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)\naccuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))\n\n# Launch graph\nwith tf.Session() as sess:\n # Initialize TensorFlow variables\n sess.run(tf.global_variables_initializer())\n feed = {X: x_data, Y: y_data}\n\n for step in range(10001):\n sess.run(train, feed_dict=feed)\n if step % 200 == 0:\n print(step, sess.run(cost, feed_dict=feed), sess.run(W))\n\n # Accuracy report\n h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict=feed)\n print(\"\\nHypothesis: \", h, \"\\nCorrect (Y): \", c, \"\\nAccuracy: \", a)\n\n'''\nHypothesis: [[ 0.03074029]\n [ 0.15884677]\n [ 0.30486736]\n [ 0.78138196]\n [ 0.93957496]\n [ 0.98016882]]\nCorrect (Y): [[ 0.]\n [ 0.]\n [ 0.]\n [ 1.]\n [ 1.]\n [ 1.]]\nAccuracy: 1.0\n'''\n" ]
[ [ "tensorflow.placeholder", "tensorflow.contrib.rnn.BasicLSTMCell", "numpy.squeeze", "tensorflow.global_variables_initializer", "tensorflow.ones", "tensorflow.reduce_mean", "tensorflow.nn.dynamic_rnn", "tensorflow.contrib.seq2seq.sequence_loss", "tensorflow.set_random_seed", "tensorflow.one_hot", "tensorflow.argmax", "tensorflow.Session", "tensorflow.train.GradientDescentOptimizer" ], [ "tensorflow.placeholder", "tensorflow.equal", "tensorflow.global_variables_initializer", "tensorflow.matmul", "tensorflow.cast", "tensorflow.set_random_seed", "tensorflow.train.GradientDescentOptimizer", "tensorflow.Session", "tensorflow.log", "tensorflow.random_normal" ] ]
zhulingchen/deep-reinforcement-learning
[ "193486659e17861208fa0a8703487e7be5868ff9" ]
[ "p2_continuous-control/agent_ddpg.py" ]
[ "import numpy as np\nimport random\nimport copy\nfrom collections import namedtuple, deque\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom model_ddpg import Actor, Critic\nfrom replay_buffer import ReplayBuffer, PrioritizedReplayBuffer\n\nBUFFER_SIZE = int(1e6) # replay buffer size\nSTART_SIZE = 1024 # when to start training\nBATCH_SIZE = 512 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR_ACTOR = 1e-3 # learning rate of the actor\nLR_CRITIC = 1e-3 # learning rate of the critic\nWEIGHT_DECAY = 0 # L2 weight decay\nTRAIN_EVERY = 5 # how often to train a batch\nTRAIN_STEPS = 3 # how many training steps when a batch is trained\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass Agent():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n \n def __init__(self, num_agents, state_size, action_size, random_seed, use_per=False):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n num_agents (int): number of agents\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n random_seed (int): random seed\n use_per (bool): whether to use prioritized replay buffer\n \"\"\"\n self.num_agents = num_agents\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(random_seed)\n self.use_per = use_per\n\n # Actor Network (w/ Target Network)\n self.actor_local = Actor(state_size, action_size, random_seed).to(device)\n self.actor_target = Actor(state_size, action_size, random_seed).to(device)\n self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR)\n\n # Critic Network (w/ Target Network)\n self.critic_local = Critic(state_size, action_size, random_seed).to(device)\n self.critic_target = Critic(state_size, action_size, random_seed).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY)\n\n # Noise process\n self.noise = OUNoise(action_size, random_seed)\n\n # Replay memory\n if use_per:\n self.memory = PrioritizedReplayBuffer(BUFFER_SIZE, BATCH_SIZE)\n else:\n self.memory = ReplayBuffer(BUFFER_SIZE, BATCH_SIZE, random_seed)\n\n # Initialize time step\n self.t_step = 0\n\n def get_critic_Q(self, states, actions, rewards, next_states, dones, gamma, is_train=True):\n # Get max predicted Q values (for next states) from target model\n if is_train:\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n # Compute Q targets for current states (y_i)\n Q_targets = rewards + (gamma * (1 - dones) * Q_targets_next)\n Q_expected = self.critic_local(states, actions)\n else:\n self.actor_local.eval()\n self.actor_target.eval()\n self.critic_local.eval()\n self.critic_target.eval()\n with torch.no_grad():\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n # Compute Q targets for current states (y_i)\n Q_targets = rewards + (gamma * (1 - dones) * Q_targets_next)\n Q_expected = self.critic_local(states, actions)\n self.actor_local.train()\n self.actor_target.train()\n self.critic_local.train()\n self.critic_target.train()\n return Q_expected, Q_targets\n\n def step(self, states, actions, rewards, next_states, dones):\n \"\"\"Save experience in replay memory, and use random sample from buffer to learn.\"\"\"\n # Save experience / reward\n if self.use_per:\n # Convert numpy array to torch tensor\n states = torch.from_numpy(states).float().to(device)\n actions = torch.from_numpy(actions).float().to(device)\n rewards = torch.from_numpy(np.array(rewards)).float().unsqueeze(1).to(device)\n next_states = torch.from_numpy(next_states).float().to(device)\n dones = torch.from_numpy(np.array(dones).astype(np.uint8)).float().unsqueeze(1).to(device)\n # Get max predicted Q values (for next states) from target model\n Q_expected, Q_targets = self.get_critic_Q(states, actions, rewards, next_states, dones, GAMMA, is_train=False)\n # Convert torch tensor to numpy array\n states = states.cpu().data.numpy()\n actions = actions.cpu().data.numpy()\n rewards = rewards.cpu().data.numpy().squeeze(1).tolist()\n next_states = next_states.cpu().data.numpy()\n dones = dones.cpu().data.numpy().squeeze(1).astype(np.bool).tolist()\n # Calculate error\n errors = Q_expected - Q_targets\n errors = errors.cpu().data.numpy().squeeze(1)\n for i in range(self.num_agents):\n self.memory.add(states[i], actions[i], rewards[i], next_states[i], dones[i], errors[i])\n else:\n for i in range(self.num_agents):\n self.memory.add(states[i], actions[i], rewards[i], next_states[i], dones[i])\n\n # Update time step\n self.t_step += 1\n\n # If enough samples are available in memory,\n if len(self.memory) >= START_SIZE:\n # Get random subset and learn every TRAIN_EVERY time steps,\n if self.t_step % TRAIN_EVERY == 0:\n for _ in range(TRAIN_STEPS):\n if self.use_per:\n experiences, idx_tree, is_weight = self.memory.sample()\n self.learn(experiences, GAMMA, idx_tree, is_weight)\n else:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, states, add_noise=True):\n \"\"\"Returns epsilon-greedy actions for given state as per current policy.\"\"\"\n states = torch.from_numpy(states).float().to(device)\n self.actor_local.eval()\n with torch.no_grad():\n actions = self.actor_local(states).cpu().data.numpy()\n self.actor_local.train()\n if add_noise:\n actions += np.concatenate([np.expand_dims(self.noise.sample(), axis=0) for _ in range(self.num_agents)], axis=0)\n return np.clip(actions, -1, 1)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self, experiences, gamma, idx_tree=None, is_weight=None):\n \"\"\"Update policy and value parameters using given batch of experience tuples.\n Q_targets = r + γ * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # ---------------------------- update critic ---------------------------- #\n # Get predicted next-state actions and Q values from target models\n Q_expected, Q_targets = self.get_critic_Q(states, actions, rewards, next_states, dones, gamma, is_train=True)\n # Compute critic loss\n if self.use_per:\n assert ((is_weight is not None) and (is_weight.size > 0))\n is_weight = torch.from_numpy(is_weight).float().to(device)\n critic_loss = (is_weight * F.smooth_l1_loss(Q_expected, Q_targets, reduction='none').squeeze()).mean()\n else:\n critic_loss = F.mse_loss(Q_expected, Q_targets)\n # Minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n # torch.nn.utils.clip_grad_norm_(self.critic_local.parameters(), 1) # use gradient norm clipping\n self.critic_optimizer.step()\n\n # ---------------------------- update actor ---------------------------- #\n # Compute actor loss\n actions_pred = self.actor_local(states)\n actor_loss = -self.critic_local(states, actions_pred).mean()\n # Minimize the loss\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # ----------------------- update target networks ----------------------- #\n self.soft_update(self.critic_local, self.critic_target, TAU)\n self.soft_update(self.actor_local, self.actor_target, TAU)\n\n # update priority\n if self.use_per:\n assert((idx_tree is not None) and (len(idx_tree) > 0))\n errors = Q_expected - Q_targets\n errors = errors.cpu().data.numpy().squeeze()\n for i in range(self.memory.batch_size):\n self.memory.update(idx_tree[i], errors[i])\n \n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model: PyTorch model (weights will be copied from)\n target_model: PyTorch model (weights will be copied to)\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n\n \nclass OUNoise:\n \"\"\"Ornstein-Uhlenbeck process.\"\"\"\n\n def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2):\n \"\"\"Initialize parameters and noise process.\"\"\"\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.seed = random.seed(seed)\n self.reset()\n\n def reset(self):\n \"\"\"Reset the internal state (= noise) to mean (mu).\"\"\"\n self.state = copy.copy(self.mu)\n\n def sample(self):\n \"\"\"Update internal state and return it as a noise sample.\"\"\"\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))])\n self.state = x + dx\n return self.state" ]
[ [ "numpy.ones", "torch.nn.functional.mse_loss", "torch.no_grad", "torch.nn.functional.smooth_l1_loss", "torch.cuda.is_available", "numpy.clip", "torch.from_numpy", "numpy.array" ] ]
KustomApe/nerdape
[ "aef6fb2d1f8c364b26d91bf8570b4487a24de69a" ]
[ ".history/mercari/mercari_search_20201124185000.py" ]
[ "from selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nimport pandas as pd\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport PyQt5\nimport time\n\"\"\"[Initial Settings]\n初期設定\n\"\"\"\noptions = webdriver.ChromeOptions()\noptions.add_argument('--headeless')\noptions.add_argument('--disable-gpu')\noptions.add_argument('--lang-ja')\nbrowser = webdriver.Chrome(chrome_options=options, executable_path='./chromedriver')\n\n\"\"\"[CSS Selector Settings]\nCSSセレクターの設定\n\"\"\"\nPAGER = \"li.pager-next a\"\nword = input(\"検索したいキーワードを入力してください:\")\ndf_main = pd.DataFrame(columns=['在庫有無','タイトル','値段','URL'])\ndf_graf = pd.DataFrame(columns=['SOLD','PRICE'])\nn = 1\nres = browser.get(\"https://www.mercari.com/jp/search/?page=\" + str(n) +\"&keyword=\"+ word)\nres = browser.get(\"https://www.mercari.com/jp/search/?page=\"+str(num)+\"&keyword=\"+word)\n\nprint(res)\nbrowser.get(res)\nwhile True:\n if PAGER:\n item_boxlist = browser.find_elements_by_css_selector(\".items-box\")\n for item_box in item_boxlist:\n try:\n if len(item_box.find_elements_by_css_selector(\".item-sold-out-badge\")) > 0:\n sold = \"SOLD\"\n else:\n sold = \"NOT SOLD\"\n sub_title = item_box.find_element_by_class_name(\"items-box-body\")\n title = sub_title.find_element_by_tag_name(\"h3\").text\n item_price = item_box.find_element_by_css_selector(\".items-box-price\")\n price_text = item_price.text\n price_text = re.sub(r\",\", \"\", price_text).lstrip(\"¥ \")\n price_text_int = int(price_text)\n print(price_text_int)\n url = item_box.find_element_by_tag_name(\"a\").get_attribute(\"href\")\n data = pd.Series( [ sold,title,price_text_int,url ], index=df_main.columns )\n grdata = pd.Series( [ sold,price_text_int ], index=df_graf.columns )\n df_main = df_main.append( data, ignore_index=True )\n df_graf = df_graf.append( grdata, ignore_index=True )\n except Exception as e:\n print(e)\n btn = browser.find_element_by_css_selector(PAGER).get_attribute('href')\n n += 1\n print('next url:{}'.format(btn))\n time.sleep(3)\n browser.get(btn)\n print('Moving to next page...')\n else:\n print('No items anymore...')\n break\nprint(df_main)\nsns.stripplot(x='SOLD', y='PRICE', data=df_graf)\nplt.show()\nsns.pairplot(df_graf,hue=\"SOLD\")\nplt.show()\nprint('Writing out to CSV file...')\ndf_main.to_csv(\"pricedata.csv\", encoding=\"utf_8_sig\")\nprint(\"Done\")" ]
[ [ "pandas.Series", "matplotlib.pyplot.show", "pandas.DataFrame" ] ]
sanghuynh1501/mlcollect
[ "e85fe6a08e14fa6502166c1a7bfffdcd8c3a25b2" ]
[ "mlcollect/cnn/lenet.py" ]
[ "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras import backend as K\n\n\nclass LeNet:\n @staticmethod\n def build(width, height, depth, classes, last_active=\"softmax\"):\n # Initialize the model\n model = Sequential()\n input_shape = (height, width, depth)\n\n # If we are using 'channels-first', update the input shape\n if K.image_data_format() == 'channels_first':\n input_shape = (depth, height, width)\n\n # First set of CONV => RELU => POOL layers\n model.add(Conv2D(20, (5, 5), padding='same', input_shape=input_shape))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n # Second set of CONV => RELU => POOL layers\n model.add(Conv2D(50, (5, 5), padding='same'))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n # First (and only) set of FC => RELU layers\n model.add(Flatten())\n model.add(Dense(500))\n model.add(Activation('relu'))\n\n model.add(Dense(classes))\n model.add(Activation(last_active))\n \n # return the constructed network architecture\n return model\n" ]
[ [ "tensorflow.keras.models.Sequential", "tensorflow.keras.layers.Flatten", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.backend.image_data_format" ] ]
keisukefukuda/optuna
[ "ac4ea8d0c74726f8a603ba2cb0bfb7f4112f736e" ]
[ "optuna/visualization/matplotlib/_contour.py" ]
[ "from typing import Callable\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\nimport numpy as np\nimport scipy\n\nfrom optuna._experimental import experimental\nfrom optuna.logging import get_logger\nfrom optuna.study import Study\nfrom optuna.study import StudyDirection\nfrom optuna.trial import FrozenTrial\nfrom optuna.trial import TrialState\nfrom optuna.visualization._utils import _check_plot_args\nfrom optuna.visualization._utils import _get_param_values\nfrom optuna.visualization.matplotlib._matplotlib_imports import _imports\nfrom optuna.visualization.matplotlib._utils import _is_log_scale\nfrom optuna.visualization.matplotlib._utils import _is_numerical\n\n\nif _imports.is_successful():\n from optuna.visualization.matplotlib._matplotlib_imports import Axes\n from optuna.visualization.matplotlib._matplotlib_imports import Colormap\n from optuna.visualization.matplotlib._matplotlib_imports import ContourSet\n from optuna.visualization.matplotlib._matplotlib_imports import plt\n\n_logger = get_logger(__name__)\n\n\nAXES_PADDING_RATIO = 5e-2\n\n\n@experimental(\"2.2.0\")\ndef plot_contour(\n study: Study,\n params: Optional[List[str]] = None,\n *,\n target: Optional[Callable[[FrozenTrial], float]] = None,\n target_name: str = \"Objective Value\",\n) -> \"Axes\":\n \"\"\"Plot the parameter relationship as contour plot in a study with Matplotlib.\n\n Note that, if a parameter contains missing values, a trial with missing values is not plotted.\n\n .. seealso::\n Please refer to :func:`optuna.visualization.plot_contour` for an example.\n\n Warnings:\n Output figures of this Matplotlib-based\n :func:`~optuna.visualization.matplotlib.plot_contour` function would be different from\n those of the Plotly-based :func:`~optuna.visualization.plot_contour`.\n\n Example:\n\n The following code snippet shows how to plot the parameter relationship as contour plot.\n\n .. plot::\n\n import optuna\n\n\n def objective(trial):\n x = trial.suggest_float(\"x\", -100, 100)\n y = trial.suggest_categorical(\"y\", [-1, 0, 1])\n return x ** 2 + y\n\n\n sampler = optuna.samplers.TPESampler(seed=10)\n study = optuna.create_study(sampler=sampler)\n study.optimize(objective, n_trials=30)\n\n optuna.visualization.matplotlib.plot_contour(study, params=[\"x\", \"y\"])\n\n Args:\n study:\n A :class:`~optuna.study.Study` object whose trials are plotted for their target values.\n params:\n Parameter list to visualize. The default is all parameters.\n target:\n A function to specify the value to display. If it is :obj:`None` and ``study`` is being\n used for single-objective optimization, the objective values are plotted.\n\n .. note::\n Specify this argument if ``study`` is being used for multi-objective optimization.\n target_name:\n Target's name to display on the color bar.\n\n Returns:\n A :class:`matplotlib.axes.Axes` object.\n\n Raises:\n :exc:`ValueError`:\n If ``target`` is :obj:`None` and ``study`` is being used for multi-objective\n optimization.\n \"\"\"\n\n _imports.check()\n _check_plot_args(study, target, target_name)\n _logger.warning(\n \"Output figures of this Matplotlib-based `plot_contour` function would be different from \"\n \"those of the Plotly-based `plot_contour`.\"\n )\n return _get_contour_plot(study, params, target, target_name)\n\n\ndef _get_contour_plot(\n study: Study,\n params: Optional[List[str]] = None,\n target: Optional[Callable[[FrozenTrial], float]] = None,\n target_name: str = \"Objective Value\",\n) -> \"Axes\":\n # Calculate basic numbers for plotting.\n trials = [trial for trial in study.trials if trial.state == TrialState.COMPLETE]\n\n if len(trials) == 0:\n _logger.warning(\"Your study does not have any completed trials.\")\n _, ax = plt.subplots()\n return ax\n\n all_params = {p_name for t in trials for p_name in t.params.keys()}\n\n if params is None:\n sorted_params = sorted(all_params)\n elif len(params) <= 1:\n _logger.warning(\"The length of params must be greater than 1.\")\n _, ax = plt.subplots()\n return ax\n else:\n for input_p_name in params:\n if input_p_name not in all_params:\n raise ValueError(\"Parameter {} does not exist in your study.\".format(input_p_name))\n sorted_params = sorted(set(params))\n n_params = len(sorted_params)\n\n plt.style.use(\"ggplot\") # Use ggplot style sheet for similar outputs to plotly.\n if n_params == 2:\n # Set up the graph style.\n fig, axs = plt.subplots()\n axs.set_title(\"Contour Plot\")\n cmap = _set_cmap(study, target)\n contour_point_num = 100\n\n # Prepare data and draw contour plots.\n if params:\n x_param = params[0]\n y_param = params[1]\n else:\n x_param = sorted_params[0]\n y_param = sorted_params[1]\n cs = _generate_contour_subplot(\n trials, x_param, y_param, axs, cmap, contour_point_num, target\n )\n if isinstance(cs, ContourSet):\n axcb = fig.colorbar(cs)\n axcb.set_label(target_name)\n else:\n # Set up the graph style.\n fig, axs = plt.subplots(n_params, n_params)\n fig.suptitle(\"Contour Plot\")\n cmap = _set_cmap(study, target)\n contour_point_num = 100\n\n # Prepare data and draw contour plots.\n cs_list = []\n for x_i, x_param in enumerate(sorted_params):\n for y_i, y_param in enumerate(sorted_params):\n ax = axs[y_i, x_i]\n cs = _generate_contour_subplot(\n trials, x_param, y_param, ax, cmap, contour_point_num, target\n )\n if isinstance(cs, ContourSet):\n cs_list.append(cs)\n if cs_list:\n axcb = fig.colorbar(cs_list[0], ax=axs)\n axcb.set_label(target_name)\n\n return axs\n\n\ndef _set_cmap(study: Study, target: Optional[Callable[[FrozenTrial], float]]) -> \"Colormap\":\n cmap = \"Blues_r\" if target is None and study.direction == StudyDirection.MAXIMIZE else \"Blues\"\n return plt.get_cmap(cmap)\n\n\nclass _LabelEncoder:\n def __init__(self) -> None:\n self.labels: List[str] = []\n\n def fit(self, labels: List[str]) -> \"_LabelEncoder\":\n self.labels = sorted(set(labels))\n return self\n\n def transform(self, labels: List[str]) -> List[int]:\n return [self.labels.index(label) for label in labels]\n\n def fit_transform(self, labels: List[str]) -> List[int]:\n return self.fit(labels).transform(labels)\n\n def get_labels(self) -> List[str]:\n return self.labels\n\n def get_indices(self) -> List[int]:\n return list(range(len(self.labels)))\n\n\ndef _calculate_griddata(\n trials: List[FrozenTrial],\n x_param: str,\n x_indices: List[Union[str, int, float]],\n y_param: str,\n y_indices: List[Union[str, int, float]],\n contour_point_num: int,\n target: Optional[Callable[[FrozenTrial], float]],\n) -> Tuple[\n np.ndarray,\n np.ndarray,\n np.ndarray,\n List[Union[int, float]],\n List[Union[int, float]],\n List[Union[int, float]],\n List[Union[int, float]],\n List[int],\n List[str],\n List[int],\n List[str],\n int,\n int,\n]:\n\n # Extract values for x, y, z axes from each trail.\n x_values = []\n y_values = []\n z_values = []\n x_range_values = []\n y_range_values = []\n for trial in trials:\n contains_x_param = x_param in trial.params\n if contains_x_param:\n x_range_values.append(trial.params[x_param])\n\n contains_y_param = y_param in trial.params\n if contains_y_param:\n y_range_values.append(trial.params[y_param])\n\n if not contains_x_param or not contains_y_param:\n continue\n x_values.append(trial.params[x_param])\n y_values.append(trial.params[y_param])\n\n if target is None:\n value = trial.value\n else:\n value = target(trial)\n\n if isinstance(value, int):\n value = float(value)\n elif not isinstance(value, float):\n raise ValueError(\n \"Trial{} has COMPLETE state, but its target value is non-numeric.\".format(\n trial.number\n )\n )\n z_values.append(value)\n\n # Return empty values when x or y has no value.\n if len(x_values) == 0 or len(y_values) == 0:\n return (\n np.array([]),\n np.array([]),\n np.array([]),\n x_values,\n y_values,\n [],\n [],\n [],\n [],\n [],\n [],\n 0,\n 0,\n )\n\n # Add dummy values for grid data calculation when a parameter has one unique value.\n x_values_dummy = []\n y_values_dummy = []\n if len(set(x_values)) == 1:\n x_values_dummy = [x for x in x_indices if x not in x_values]\n x_values = x_values + x_values_dummy * len(x_values)\n y_values = y_values + (y_values * len(x_values_dummy))\n z_values = z_values + (z_values * len(x_values_dummy))\n if len(set(y_values)) == 1:\n y_values_dummy = [y for y in y_indices if y not in y_values]\n y_values = y_values + y_values_dummy * len(y_values)\n x_values = x_values + (x_values * len(y_values_dummy))\n z_values = z_values + (z_values * len(y_values_dummy))\n\n # Convert categorical values to int.\n cat_param_labels_x = [] # type: List[str]\n cat_param_pos_x = [] # type: List[int]\n cat_param_labels_y = [] # type: List[str]\n cat_param_pos_y = [] # type: List[int]\n if not _is_numerical(trials, x_param):\n enc = _LabelEncoder()\n x_range_values = enc.fit_transform(list(map(str, x_range_values)))\n x_values = enc.transform(list(map(str, x_values)))\n cat_param_labels_x = enc.get_labels()\n cat_param_pos_x = enc.get_indices()\n if not _is_numerical(trials, y_param):\n enc = _LabelEncoder()\n y_range_values = enc.fit_transform(list(map(str, y_range_values)))\n y_values = enc.transform(list(map(str, y_values)))\n cat_param_labels_y = enc.get_labels()\n cat_param_pos_y = enc.get_indices()\n\n # Calculate min and max of x and y.\n x_values_min = min(x_range_values)\n x_values_max = max(x_range_values)\n y_values_min = min(y_range_values)\n y_values_max = max(y_range_values)\n\n # Calculate grid data points.\n # For x and y, create 1-D array of evenly spaced coordinates on linear or log scale.\n xi = np.array([])\n yi = np.array([])\n zi = np.array([])\n\n if _is_log_scale(trials, x_param):\n padding_x = (np.log10(x_values_max) - np.log10(x_values_min)) * AXES_PADDING_RATIO\n x_values_min = np.power(10, np.log10(x_values_min) - padding_x)\n x_values_max = np.power(10, np.log10(x_values_max) + padding_x)\n xi = np.logspace(np.log10(x_values_min), np.log10(x_values_max), contour_point_num)\n else:\n padding_x = (x_values_max - x_values_min) * AXES_PADDING_RATIO\n x_values_min -= padding_x\n x_values_max += padding_x\n xi = np.linspace(x_values_min, x_values_max, contour_point_num)\n\n if _is_log_scale(trials, y_param):\n padding_y = (np.log10(y_values_max) - np.log10(y_values_min)) * AXES_PADDING_RATIO\n y_values_min = np.power(10, np.log10(y_values_min) - padding_y)\n y_values_max = np.power(10, np.log10(y_values_max) + padding_y)\n yi = np.logspace(np.log10(y_values_min), np.log10(y_values_max), contour_point_num)\n else:\n padding_y = (y_values_max - y_values_min) * AXES_PADDING_RATIO\n y_values_min -= padding_y\n y_values_max += padding_y\n yi = np.linspace(y_values_min, y_values_max, contour_point_num)\n\n # create irregularly spaced map of trial values\n # and interpolate it with Plotly's interpolation formulation\n if x_param != y_param:\n zmap = _create_zmap(x_values, y_values, z_values, xi, yi)\n zi = _interpolate_zmap(zmap, contour_point_num)\n\n return (\n xi,\n yi,\n zi,\n x_values,\n y_values,\n [x_values_min, x_values_max],\n [y_values_min, y_values_max],\n cat_param_pos_x,\n cat_param_labels_x,\n cat_param_pos_y,\n cat_param_labels_y,\n len(x_values_dummy),\n len(y_values_dummy),\n )\n\n\ndef _generate_contour_subplot(\n trials: List[FrozenTrial],\n x_param: str,\n y_param: str,\n ax: \"Axes\",\n cmap: \"Colormap\",\n contour_point_num: int,\n target: Optional[Callable[[FrozenTrial], float]],\n) -> \"ContourSet\":\n\n x_indices = sorted(set(_get_param_values(trials, x_param)))\n y_indices = sorted(set(_get_param_values(trials, y_param)))\n if len(x_indices) < 2:\n _logger.warning(\"Param {} unique value length is less than 2.\".format(x_param))\n return ax\n if len(y_indices) < 2:\n _logger.warning(\"Param {} unique value length is less than 2.\".format(y_param))\n return ax\n\n (\n xi,\n yi,\n zi,\n x_values,\n y_values,\n x_values_range,\n y_values_range,\n x_cat_param_pos,\n x_cat_param_label,\n y_cat_param_pos,\n y_cat_param_label,\n x_values_dummy_count,\n y_values_dummy_count,\n ) = _calculate_griddata(\n trials, x_param, x_indices, y_param, y_indices, contour_point_num, target\n )\n cs = None\n ax.set(xlabel=x_param, ylabel=y_param)\n ax.set_xlim(x_values_range[0], x_values_range[1])\n ax.set_ylim(y_values_range[0], y_values_range[1])\n if len(zi) > 0:\n if _is_log_scale(trials, x_param):\n ax.set_xscale(\"log\")\n if _is_log_scale(trials, y_param):\n ax.set_yscale(\"log\")\n if x_param != y_param:\n # Contour the gridded data.\n ax.contour(xi, yi, zi, 15, linewidths=0.5, colors=\"k\")\n cs = ax.contourf(xi, yi, zi, 15, cmap=cmap.reversed())\n # Plot data points.\n if x_values_dummy_count > 0:\n x_org_len = int(len(x_values) / (x_values_dummy_count + 1))\n y_org_len = int(len(y_values) / (x_values_dummy_count + 1))\n elif y_values_dummy_count > 0:\n x_org_len = int(len(x_values) / (y_values_dummy_count + 1))\n y_org_len = int(len(y_values) / (y_values_dummy_count + 1))\n else:\n x_org_len = len(x_values)\n y_org_len = len(x_values)\n ax.scatter(\n x_values[:x_org_len],\n y_values[:y_org_len],\n marker=\"o\",\n c=\"black\",\n s=20,\n edgecolors=\"grey\",\n linewidth=2.0,\n )\n if x_cat_param_pos:\n ax.set_xticks(x_cat_param_pos)\n ax.set_xticklabels(x_cat_param_label)\n if y_cat_param_pos:\n ax.set_yticks(y_cat_param_pos)\n ax.set_yticklabels(y_cat_param_label)\n ax.label_outer()\n return cs\n\n\ndef _create_zmap(\n x_values: List[Union[int, float]],\n y_values: List[Union[int, float]],\n z_values: List[float],\n xi: np.ndarray,\n yi: np.ndarray,\n) -> Dict[Tuple[int, int], float]:\n\n # creates z-map from trial values and params.\n # z-map is represented by hashmap of coordinate and trial value pairs\n #\n # coordinates are represented by tuple of integers, where the first item\n # indicates x-axis index and the second item indicates y-axis index\n # and refer to a position of trial value on irregular param grid\n #\n # since params were resampled either with linspace or logspace\n # original params might not be on the x and y axes anymore\n # so we are going with close approximations of trial value positions\n zmap = dict()\n for x, y, z in zip(x_values, y_values, z_values):\n xindex = int(np.argmin(np.abs(xi - x)))\n yindex = int(np.argmin(np.abs(yi - y)))\n zmap[(xindex, yindex)] = z\n\n return zmap\n\n\ndef _interpolate_zmap(zmap: Dict[Tuple[int, int], float], contour_plot_num: int) -> np.ndarray:\n\n # implements interpolation formulation used in Plotly\n # to interpolate heatmaps and contour plots\n # https://github.com/plotly/plotly.js/blob/master/src/traces/heatmap/interp2d.js#L30\n # citing their doc:\n #\n # > Fill in missing data from a 2D array using an iterative\n # > poisson equation solver with zero-derivative BC at edges.\n # > Amazingly, this just amounts to repeatedly averaging all the existing\n # > nearest neighbors\n #\n # Plotly's algorithm is equivalent to solve the following linear simultaneous equation.\n # It is discretization form of the Poisson equation.\n #\n # z[x, y] = zmap[(x, y)] (if zmap[(x, y)] is given)\n # 4 * z[x, y] = z[x-1, y] + z[x+1, y] + z[x, y-1] + z[x, y+1] (if zmap[(x, y)] is not given)\n\n a_data = []\n a_row = []\n a_col = []\n b = np.zeros(contour_plot_num**2)\n for x in range(contour_plot_num):\n for y in range(contour_plot_num):\n grid_index = y * contour_plot_num + x\n if (x, y) in zmap:\n a_data.append(1)\n a_row.append(grid_index)\n a_col.append(grid_index)\n b[grid_index] = zmap[(x, y)]\n else:\n for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n if 0 <= x + dx < contour_plot_num and 0 <= y + dy < contour_plot_num:\n a_data.append(1)\n a_row.append(grid_index)\n a_col.append(grid_index)\n a_data.append(-1)\n a_row.append(grid_index)\n a_col.append(grid_index + dy * contour_plot_num + dx)\n\n z = scipy.sparse.linalg.spsolve(scipy.sparse.csc_matrix((a_data, (a_row, a_col))), b)\n\n return z.reshape((contour_plot_num, contour_plot_num))\n" ]
[ [ "numpy.zeros", "scipy.sparse.csc_matrix", "numpy.abs", "numpy.log10", "numpy.array", "numpy.linspace" ] ]
kotori-y/kotori_work
[ "51ebfdf49571ae34c246dc5b37cc86e25f4ccf3d" ]
[ "py_work/AI/ML/FeatureSelection.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 24 21:46:41 2019\n\nYou are not expected to understand my codes!\n\n@Author: Kotori_Y\n@Blog: blog.moyule.me\n@Weibo: Kotori-Y\n@Mail: [email protected]\n\nI love Megumi forerver!\n\"\"\"\n\nprint(__doc__)\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split,KFold\nfrom sklearn.metrics import accuracy_score,precision_score,recall_score\nimport pandas as pd\nimport time\nimport os\nfrom tqdm import tqdm\n\nkf = KFold(n_splits=5)#kfold\n\n\nstart = time.clock()\n\n#os.chdir(r'E:\\student\\yzy\\Importance')\n#files = os.listdir()\n#os.makedirs('FeatureAna')\n\n#df = df.sample(frac=1).reset_index(drop=True)\n#df.drop('SMILES',axis=1,inplace=True)\n#y = df.pop('Label')\n\n#fold = 0\n\n\n####################################### 5-Fold #######################################\n\n#df_i = pd.DataFrame()#creat a dataframe for importance\n#df_m = pd.DataFrame()#creat a dataframe for metrics\n\n#for train_index, test_index in kf.split(df):\n# col = list(df.columns)\n# fold += 1\n# X_train, x_test = df.iloc[train_index], df.iloc[test_index]\n# Y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n# X = X_train.copy()\n# x = x_test.copy()\n# \n# for _ in tqdm(range(len(df.columns))):\n# \n# rfc = RandomForestClassifier(n_estimators=500,n_jobs=-1)\n## print('----------------Fitting----------------')\n# rfc.fit(X,Y_train)\n# \n# fea = pd.DataFrame(\n# {\n# 'Feature':col,\n# 'Importance':rfc.feature_importances_,\n# 'Fold':'fold_{}'.format(fold),\n# 'Class':len(col)\n# }\n# )\n# fea.sort_values('Importance',ascending=False,inplace=True)\n# df_i = pd.concat([df_i,fea],ignore_index=True)\n# \n# #cal correlate metrics\n# acc = accuracy_score(y_test,rfc.predict(x))\n# pre = precision_score(y_test,rfc.predict(x))\n# rec = recall_score(y_test,rfc.predict(x))\n# \n# me = pd.DataFrame(\n# {\n# 'Precision':[pre],\n# 'Recall':[rec],\n# 'Accuracy':[acc],\n# 'Fold':['fold_{}'.format(fold)],\n# 'Class':[len(col)]\n# }\n# ) \n# df_m = pd.concat([df_m,me],ignore_index=True)\n# \n# #drop the most unimportant feature\n# drop = list(fea['Feature'])[-1]\n# \n# X.drop(drop,axis=1,inplace=True)\n# x.drop(drop,axis=1,inplace=True)\n# col.remove(drop)\n# \n# del rfc,fea,me\n# \n# \n#end = time.clock()\n#\n#print(end-start)\n#\n#df_i.to_csv('Importances.csv')\n#df_m.to_csv('Metrics.csv')\n\n###########################################################################################\n\n\n\n\n\n\n\n\n\n\n\n\n####################################### ONCE #######################################\ndef Selection(file,filepath):\n os.chdir(filepath)\n print('-----{} start-----'.format(file.replace('.csv','')))\n df_i = pd.DataFrame()#creat a dataframe for importance\n df_m = pd.DataFrame()#creat a dataframe for metrics\n \n #df_1 = pd.read_csv(r'E:\\student\\kotori\\Lemon\\backup\\2C9_In_MACCS-1.csv')\n #df_0 = pd.read_csv(r'E:\\student\\kotori\\Lemon\\backup\\2C9_In_MACCS-0.csv')\n #df_1 = df_1.sample(len(df_0),replace=True)\n #df = pd.concat([df_1,df_0],ignore_index=True,sort=False)\n \n df = pd.read_csv(file)\n df = df.sample(frac=1).reset_index(drop=True)\n# df = df.iloc[:,3:]\n# try:\n# df.drop('SMILES',axis=1,inplace=True)\n# except:\n# df.drop('Smiles',axis=1,inplace=True)\n y = df.pop('grades')\n \n col = list(df.columns)\n X_train,x_test,Y_train,y_test = train_test_split(df,y,test_size=0.2)\n X = X_train.copy()\n x = x_test.copy()\n \n for _ in tqdm(range(len(df.columns))):\n \n rfc = RandomForestClassifier(n_estimators=500,n_jobs=-1)\n # print('----------------Fitting----------------')\n rfc.fit(X,Y_train)\n \n fea = pd.DataFrame(\n {\n 'Feature':col\n ,'Importance':rfc.feature_importances_\n \n ,'Class':len(col)\n }\n )\n fea.sort_values('Importance',ascending=False,inplace=True)\n df_i = pd.concat([df_i,fea],ignore_index=True,sort=False)\n \n #cal correlate metrics\n acc = accuracy_score(y_test,rfc.predict(x))\n pre = precision_score(y_test,rfc.predict(x))\n rec = recall_score(y_test,rfc.predict(x))\n \n me = pd.DataFrame(\n {\n 'Precision':[pre]\n ,'Recall':[rec]\n ,'Accuracy':[acc]\n #,'Fold':['fold_{}'.format(fold)]\n ,'Class':[len(col)]\n }\n ) \n df_m = pd.concat([df_m,me],ignore_index=True,sort=False)\n \n #drop the most unimportant feature\n drop = list(fea['Feature'])[-1]\n \n X.drop(drop,axis=1,inplace=True)\n x.drop(drop,axis=1,inplace=True)\n col.remove(drop)\n \n del rfc,fea,me\n #file = '2C9_In_MACCS'\n #df_i.to_csv('FeatureAna/{}_Importances_oversampling.csv'.format(file),index=False)\n #df_m.to_csv('FeatureAna/{}_Metrics_oversampling.csv'.format(file),index=False)\n return df_i,df_m\n \ndef main():\n tempt = print(\"Input the absolute path of your file locate and ensure the file only contain 'SMILES', 'Label' and the features vector\\n\")\n filepath = input(\"The absolute path: \")\n files = os.listdir(filepath)\n for file in files: \n df_i, df_m = Selection(file,filepath)\n# os.chdir(r'E:\\student\\yzy\\All')\n# \n# part_1_class = list(range(1000,1717))\n# \n# df_i_a = df_i[df_i['Class'].isin(part_1_class)]\n# df_i_b = df_i[~df_i['Class'].isin(part_1_class)]\n# df_i.iloc[:,:].to_csv(file.replace('.csv','') + '_Importances.csv',index=False)\n# df_m.to_csv(file.replace('.csv','') + '_Metrics.csv',index=False)\n df_i.to_csv('{}_Importances.csv'.format(file.replace('.csv','')))\n\nif '__main__' == __name__: \n main()\n #,'Fold':'fold_{}'.format(fold)\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame", "pandas.concat", "sklearn.ensemble.RandomForestClassifier", "sklearn.model_selection.KFold", "sklearn.model_selection.train_test_split" ] ]
jni/vispy
[ "8b61cd439076aa3f50ac5f6dacb4c0af8c1d0684" ]
[ "vispy/visuals/line/line.py" ]
[ "# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\"\"\"\nLine visual implementing Agg- and GL-based drawing modes.\n\"\"\"\n\nfrom __future__ import division\n\nimport numpy as np\n\nfrom ... import gloo, glsl\nfrom ...color import Color, ColorArray, get_colormap\nfrom ...ext.six import string_types\nfrom ..shaders import Function\nfrom ..visual import Visual, CompoundVisual\nfrom ...util.profiler import Profiler\n\nfrom .dash_atlas import DashAtlas\n\n\nvec2to4 = Function(\"\"\"\n vec4 vec2to4(vec2 inp) {\n return vec4(inp, 0, 1);\n }\n\"\"\")\n\nvec3to4 = Function(\"\"\"\n vec4 vec3to4(vec3 inp) {\n return vec4(inp, 1);\n }\n\"\"\")\n\n\n\"\"\"\nTODO:\n\n* Agg support is very minimal; needs attention.\n* Optimization--avoid creating new buffers, avoid triggering program\n recompile.\n\"\"\"\n\n\njoins = {'miter': 0, 'round': 1, 'bevel': 2}\n\ncaps = {'': 0, 'none': 0, '.': 0,\n 'round': 1, ')': 1, '(': 1, 'o': 1,\n 'triangle in': 2, '<': 2,\n 'triangle out': 3, '>': 3,\n 'square': 4, '=': 4, 'butt': 4,\n '|': 5}\n\n\nclass LineVisual(CompoundVisual):\n \"\"\"Line visual\n\n Parameters\n ----------\n pos : array\n Array of shape (..., 2) or (..., 3) specifying vertex coordinates.\n color : Color, tuple, or array\n The color to use when drawing the line. If an array is given, it\n must be of shape (..., 4) and provide one rgba color per vertex.\n Can also be a colormap name, or appropriate `Function`.\n width:\n The width of the line in px. Line widths > 1px are only\n guaranteed to work when using 'agg' method.\n connect : str or array\n Determines which vertices are connected by lines.\n\n * \"strip\" causes the line to be drawn with each vertex\n connected to the next.\n * \"segments\" causes each pair of vertices to draw an\n independent line segment\n * numpy arrays specify the exact set of segment pairs to\n connect.\n\n method : str\n Mode to use for drawing.\n\n * \"agg\" uses anti-grain geometry to draw nicely antialiased lines\n with proper joins and endcaps.\n * \"gl\" uses OpenGL's built-in line rendering. This is much faster,\n but produces much lower-quality results and is not guaranteed to\n obey the requested line width or join/endcap styles.\n\n antialias : bool\n Enables or disables antialiasing.\n For method='gl', this specifies whether to use GL's line smoothing,\n which may be unavailable or inconsistent on some platforms.\n \"\"\"\n def __init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1,\n connect='strip', method='gl', antialias=False):\n self._line_visual = None\n\n self._changed = {'pos': False, 'color': False, 'width': False,\n 'connect': False}\n\n self._pos = None\n self._color = None\n self._width = None\n self._connect = None\n self._bounds = None\n self._antialias = None\n self._method = 'none'\n\n CompoundVisual.__init__(self, [])\n\n # don't call subclass set_data; these often have different\n # signatures.\n LineVisual.set_data(self, pos=pos, color=color, width=width,\n connect=connect)\n self.antialias = antialias\n self.method = method\n\n @property\n def antialias(self):\n return self._antialias\n\n @antialias.setter\n def antialias(self, aa):\n self._antialias = bool(aa)\n self.update()\n\n @property\n def method(self):\n \"\"\"The current drawing method\"\"\"\n return self._method\n\n @method.setter\n def method(self, method):\n if method not in ('agg', 'gl'):\n raise ValueError('method argument must be \"agg\" or \"gl\".')\n if method == self._method:\n return\n\n self._method = method\n if self._line_visual is not None:\n self.remove_subvisual(self._line_visual)\n\n if method == 'gl':\n self._line_visual = _GLLineVisual(self)\n elif method == 'agg':\n self._line_visual = _AggLineVisual(self)\n self.add_subvisual(self._line_visual)\n\n for k in self._changed:\n self._changed[k] = True\n\n def set_data(self, pos=None, color=None, width=None, connect=None):\n \"\"\"Set the data used to draw this visual.\n\n Parameters\n ----------\n pos : array\n Array of shape (..., 2) or (..., 3) specifying vertex coordinates.\n color : Color, tuple, or array\n The color to use when drawing the line. If an array is given, it\n must be of shape (..., 4) and provide one rgba color per vertex.\n width:\n The width of the line in px. Line widths < 1 px will be rounded up\n to 1 px when using the 'gl' method.\n connect : str or array\n Determines which vertices are connected by lines.\n\n * \"strip\" causes the line to be drawn with each vertex\n connected to the next.\n * \"segments\" causes each pair of vertices to draw an\n independent line segment\n * int numpy arrays specify the exact set of segment pairs to\n connect.\n * bool numpy arrays specify which _adjacent_ pairs to connect.\n\n \"\"\"\n if pos is not None:\n self._bounds = None\n self._pos = pos\n self._changed['pos'] = True\n\n if color is not None:\n self._color = color\n self._changed['color'] = True\n\n if width is not None:\n self._width = width\n self._changed['width'] = True\n\n if connect is not None:\n self._connect = connect\n self._changed['connect'] = True\n\n self.update()\n\n @property\n def color(self):\n return self._color\n\n @property\n def width(self):\n return self._width\n\n @property\n def connect(self):\n return self._connect\n\n @property\n def pos(self):\n return self._pos\n\n def _interpret_connect(self):\n if isinstance(self._connect, np.ndarray):\n # Convert a boolean connection array to a vertex index array\n if self._connect.ndim == 1 and self._connect.dtype == bool:\n index = np.empty((len(self._connect), 2), dtype=np.uint32)\n index[:] = np.arange(len(self._connect))[:, np.newaxis]\n index[:, 1] += 1\n return index[self._connect]\n elif self._connect.ndim == 2 and self._connect.shape[1] == 2:\n return self._connect.astype(np.uint32)\n else:\n raise TypeError(\"Got invalid connect array of shape %r and \"\n \"dtype %r\" % (self._connect.shape,\n self._connect.dtype))\n else:\n return self._connect\n\n def _interpret_color(self, color_in=None):\n color_in = self._color if color_in is None else color_in\n colormap = None\n if isinstance(color_in, string_types):\n try:\n colormap = get_colormap(color_in)\n color = Function(colormap.glsl_map)\n except KeyError:\n color = Color(color_in).rgba\n elif isinstance(color_in, Function):\n color = Function(color_in)\n else:\n color = ColorArray(color_in).rgba\n if len(color) == 1:\n color = color[0]\n return color, colormap\n\n def _compute_bounds(self, axis, view):\n \"\"\"Get the bounds\n\n Parameters\n ----------\n mode : str\n Describes the type of boundary requested. Can be \"visual\", \"data\",\n or \"mouse\".\n axis : 0, 1, 2\n The axis along which to measure the bounding values, in\n x-y-z order.\n \"\"\"\n # Can and should we calculate bounds?\n if (self._bounds is None) and self._pos is not None:\n pos = self._pos\n self._bounds = [(pos[:, d].min(), pos[:, d].max())\n for d in range(pos.shape[1])]\n # Return what we can\n if self._bounds is None:\n return\n else:\n if axis < len(self._bounds):\n return self._bounds[axis]\n else:\n return (0, 0)\n\n def _prepare_draw(self, view):\n if self._width == 0:\n return False\n CompoundVisual._prepare_draw(self, view)\n\n\nclass _GLLineVisual(Visual):\n VERTEX_SHADER = \"\"\"\n varying vec4 v_color;\n\n void main(void) {\n gl_Position = $transform($to_vec4($position));\n v_color = $color;\n }\n \"\"\"\n\n FRAGMENT_SHADER = \"\"\"\n varying vec4 v_color;\n void main() {\n gl_FragColor = v_color;\n }\n \"\"\"\n\n def __init__(self, parent):\n self._parent = parent\n self._pos_vbo = gloo.VertexBuffer()\n self._color_vbo = gloo.VertexBuffer()\n self._connect_ibo = gloo.IndexBuffer()\n self._connect = None\n\n Visual.__init__(self, vcode=self.VERTEX_SHADER,\n fcode=self.FRAGMENT_SHADER)\n self.set_gl_state('translucent')\n\n def _prepare_transforms(self, view):\n xform = view.transforms.get_transform()\n view.view_program.vert['transform'] = xform\n\n def _prepare_draw(self, view):\n prof = Profiler()\n\n if self._parent._changed['pos']:\n if self._parent._pos is None:\n return False\n # todo: does this result in unnecessary copies?\n pos = np.ascontiguousarray(self._parent._pos.astype(np.float32))\n self._pos_vbo.set_data(pos)\n self._program.vert['position'] = self._pos_vbo\n if pos.shape[-1] == 2:\n self._program.vert['to_vec4'] = vec2to4\n elif pos.shape[-1] == 3:\n self._program.vert['to_vec4'] = vec3to4\n else:\n raise TypeError(\"Got bad position array shape: %r\"\n % (pos.shape,))\n\n if self._parent._changed['color']:\n color, cmap = self._parent._interpret_color()\n # If color is not visible, just quit now\n if isinstance(color, Color) and color.is_blank:\n return False\n if isinstance(color, Function):\n # TODO: Change to the parametric coordinate once that is done\n self._program.vert['color'] = color(\n '(gl_Position.x + 1.0) / 2.0')\n else:\n if color.ndim == 1:\n self._program.vert['color'] = color\n else:\n self._color_vbo.set_data(color)\n self._program.vert['color'] = self._color_vbo\n\n self.shared_program['texture2D_LUT'] = cmap.texture_lut() \\\n if (hasattr(cmap, 'texture_lut')) else None\n\n # Do we want to use OpenGL, and can we?\n GL = None\n from ...app._default_app import default_app\n if default_app is not None and \\\n default_app.backend_name != 'ipynb_webgl':\n try:\n import OpenGL.GL as GL\n except Exception: # can be other than ImportError sometimes\n pass\n\n # Turn on line smooth and/or line width\n if GL:\n if self._parent._antialias:\n GL.glEnable(GL.GL_LINE_SMOOTH)\n else:\n GL.glDisable(GL.GL_LINE_SMOOTH)\n px_scale = self.transforms.pixel_scale\n width = px_scale * self._parent._width\n GL.glLineWidth(max(width, 1.))\n\n if self._parent._changed['connect']:\n self._connect = self._parent._interpret_connect()\n if isinstance(self._connect, np.ndarray):\n self._connect_ibo.set_data(self._connect)\n if self._connect is None:\n return False\n\n prof('prepare')\n\n # Draw\n if isinstance(self._connect, string_types) and \\\n self._connect == 'strip':\n self._draw_mode = 'line_strip'\n self._index_buffer = None\n elif isinstance(self._connect, string_types) and \\\n self._connect == 'segments':\n self._draw_mode = 'lines'\n self._index_buffer = None\n elif isinstance(self._connect, np.ndarray):\n self._draw_mode = 'lines'\n self._index_buffer = self._connect_ibo\n else:\n raise ValueError(\"Invalid line connect mode: %r\" % self._connect)\n\n prof('draw')\n\n\nclass _AggLineVisual(Visual):\n _agg_vtype = np.dtype([('a_position', np.float32, (2,)),\n ('a_tangents', np.float32, (4,)),\n ('a_segment', np.float32, (2,)),\n ('a_angles', np.float32, (2,)),\n ('a_texcoord', np.float32, (2,)),\n ('alength', np.float32),\n ('color', np.float32, (4,))])\n\n VERTEX_SHADER = glsl.get('lines/agg.vert')\n FRAGMENT_SHADER = glsl.get('lines/agg.frag')\n\n def __init__(self, parent):\n self._parent = parent\n self._vbo = gloo.VertexBuffer()\n\n self._pos = None\n self._color = None\n\n self._da = DashAtlas()\n dash_index, dash_period = self._da['solid']\n self._U = dict(dash_index=dash_index, dash_period=dash_period,\n linejoin=joins['round'],\n linecaps=(caps['round'], caps['round']),\n dash_caps=(caps['round'], caps['round']),\n antialias=1.0)\n self._dash_atlas = gloo.Texture2D(self._da._data)\n\n Visual.__init__(self, vcode=self.VERTEX_SHADER,\n fcode=self.FRAGMENT_SHADER)\n self._index_buffer = gloo.IndexBuffer()\n self.set_gl_state('translucent', depth_test=False)\n self._draw_mode = 'triangles'\n\n def _prepare_transforms(self, view):\n data_doc = view.get_transform('visual', 'document')\n doc_px = view.get_transform('document', 'framebuffer')\n px_ndc = view.get_transform('framebuffer', 'render')\n\n vert = view.view_program.vert\n vert['transform'] = data_doc\n vert['doc_px_transform'] = doc_px\n vert['px_ndc_transform'] = px_ndc\n\n def _prepare_draw(self, view):\n bake = False\n if self._parent._changed['pos']:\n if self._parent._pos is None:\n return False\n # todo: does this result in unnecessary copies?\n self._pos = np.ascontiguousarray(\n self._parent._pos.astype(np.float32))\n bake = True\n\n if self._parent._changed['color']:\n color, cmap = self._parent._interpret_color()\n self._color = color\n bake = True\n\n if self._parent._changed['connect']:\n if self._parent._connect not in [None, 'strip']:\n raise NotImplementedError(\"Only 'strip' connection mode \"\n \"allowed for agg-method lines.\")\n\n if bake:\n V, idxs = self._agg_bake(self._pos, self._color)\n self._vbo.set_data(V)\n self._index_buffer.set_data(idxs)\n\n # self._program.prepare()\n self.shared_program.bind(self._vbo)\n uniforms = dict(closed=False, miter_limit=4.0, dash_phase=0.0,\n linewidth=self._parent._width)\n for n, v in uniforms.items():\n self.shared_program[n] = v\n for n, v in self._U.items():\n self.shared_program[n] = v\n self.shared_program['u_dash_atlas'] = self._dash_atlas\n\n @classmethod\n def _agg_bake(cls, vertices, color, closed=False):\n \"\"\"\n Bake a list of 2D vertices for rendering them as thick line. Each line\n segment must have its own vertices because of antialias (this means no\n vertex sharing between two adjacent line segments).\n \"\"\"\n\n n = len(vertices)\n P = np.array(vertices).reshape(n, 2).astype(float)\n idx = np.arange(n) # used to eventually tile the color array\n\n dx, dy = P[0] - P[-1]\n d = np.sqrt(dx*dx+dy*dy)\n\n # If closed, make sure first vertex = last vertex (+/- epsilon=1e-10)\n if closed and d > 1e-10:\n P = np.append(P, P[0]).reshape(n+1, 2)\n idx = np.append(idx, idx[-1])\n n += 1\n\n V = np.zeros(len(P), dtype=cls._agg_vtype)\n V['a_position'] = P\n\n # Tangents & norms\n T = P[1:] - P[:-1]\n\n N = np.sqrt(T[:, 0]**2 + T[:, 1]**2)\n # T /= N.reshape(len(T),1)\n V['a_tangents'][+1:, :2] = T\n V['a_tangents'][0, :2] = T[-1] if closed else T[0]\n V['a_tangents'][:-1, 2:] = T\n V['a_tangents'][-1, 2:] = T[0] if closed else T[-1]\n\n # Angles\n T1 = V['a_tangents'][:, :2]\n T2 = V['a_tangents'][:, 2:]\n A = np.arctan2(T1[:, 0]*T2[:, 1]-T1[:, 1]*T2[:, 0],\n T1[:, 0]*T2[:, 0]+T1[:, 1]*T2[:, 1])\n V['a_angles'][:-1, 0] = A[:-1]\n V['a_angles'][:-1, 1] = A[+1:]\n\n # Segment\n L = np.cumsum(N)\n V['a_segment'][+1:, 0] = L\n V['a_segment'][:-1, 1] = L\n # V['a_lengths'][:,2] = L[-1]\n\n # Step 1: A -- B -- C => A -- B, B' -- C\n V = np.repeat(V, 2, axis=0)[1:-1]\n V['a_segment'][1:] = V['a_segment'][:-1]\n V['a_angles'][1:] = V['a_angles'][:-1]\n V['a_texcoord'][0::2] = -1\n V['a_texcoord'][1::2] = +1\n idx = np.repeat(idx, 2)[1:-1]\n\n # Step 2: A -- B, B' -- C -> A0/A1 -- B0/B1, B'0/B'1 -- C0/C1\n V = np.repeat(V, 2, axis=0)\n V['a_texcoord'][0::2, 1] = -1\n V['a_texcoord'][1::2, 1] = +1\n idx = np.repeat(idx, 2)\n\n idxs = np.resize(np.array([0, 1, 2, 1, 2, 3], dtype=np.uint32),\n (n-1)*(2*3))\n idxs += np.repeat(4*np.arange(n-1, dtype=np.uint32), 6)\n\n # Length\n V['alength'] = L[-1] * np.ones(len(V))\n\n # Color\n if color.ndim == 1:\n color = np.tile(color, (len(V), 1))\n elif color.ndim == 2 and len(color) == n:\n color = color[idx]\n else:\n raise ValueError('Color length %s does not match number of '\n 'vertices %s' % (len(color), n))\n V['color'] = color\n\n return V, idxs\n" ]
[ [ "numpy.arctan2", "numpy.cumsum", "numpy.append", "numpy.dtype", "numpy.repeat", "numpy.arange", "numpy.sqrt", "numpy.array" ] ]
nghugo88/tf-pose-estimation
[ "0df660feeb52957f40f4a5e18920adc317af3653" ]
[ "src/slim/nets/nets_factory_test.py" ]
[ "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for slim.inception.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nimport tensorflow as tf\n\nfrom nets import nets_factory\n\n\nclass NetworksTest(tf.test.TestCase):\n\n def testGetNetworkFnFirstHalf(self):\n batch_size = 5\n num_classes = 1000\n for net in nets_factory.networks_map.keys()[:10]:\n with tf.Graph().as_default() as g, self.test_session(g):\n net_fn = nets_factory.get_network_fn(net, num_classes)\n # Most networks use 224 as their default_image_size\n image_size = getattr(net_fn, 'default_image_size', 224)\n inputs = tf.random_uniform((batch_size, image_size, image_size, 3))\n logits, end_points = net_fn(inputs)\n self.assertTrue(isinstance(logits, tf.Tensor))\n self.assertTrue(isinstance(end_points, dict))\n self.assertEqual(logits.get_shape().as_list()[0], batch_size)\n self.assertEqual(logits.get_shape().as_list()[-1], num_classes)\n\n def testGetNetworkFnSecondHalf(self):\n batch_size = 5\n num_classes = 1000\n for net in nets_factory.networks_map.keys()[10:]:\n with tf.Graph().as_default() as g, self.test_session(g):\n net_fn = nets_factory.get_network_fn(net, num_classes)\n # Most networks use 224 as their default_image_size\n image_size = getattr(net_fn, 'default_image_size', 224)\n inputs = tf.random_uniform((batch_size, image_size, image_size, 3))\n logits, end_points = net_fn(inputs)\n self.assertTrue(isinstance(logits, tf.Tensor))\n self.assertTrue(isinstance(end_points, dict))\n self.assertEqual(logits.get_shape().as_list()[0], batch_size)\n self.assertEqual(logits.get_shape().as_list()[-1], num_classes)\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.random_uniform", "tensorflow.Graph", "tensorflow.test.main" ] ]
JacopoTeneggi/InnerEye-DeepLearning
[ "988d9fa318a19cfd435370248970d976ee2e78b0" ]
[ "InnerEye/ML/pipelines/inference.py" ]
[ "# ------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n# ------------------------------------------------------------------------------------------\nfrom __future__ import annotations\n\nimport logging\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional\n\nimport numpy as np\nimport torch\nfrom radio import CTImagesMaskedBatch\nfrom radio.batchflow import Dataset, action, inbatch_parallel\n\nfrom InnerEye.Common.type_annotations import TupleFloat3\nfrom InnerEye.ML import config\nfrom InnerEye.ML.common import ModelExecutionMode\nfrom InnerEye.ML.config import SegmentationModelBase\nfrom InnerEye.ML.lightning_helpers import load_from_checkpoint_and_adjust_for_inference\nfrom InnerEye.ML.lightning_models import SegmentationLightning\nfrom InnerEye.ML.model_config_base import ModelConfigBase\nfrom InnerEye.ML.models.architectures.base_model import BaseSegmentationModel\nfrom InnerEye.ML.utils import image_util, ml_util\nfrom InnerEye.ML.utils.image_util import compute_uncertainty_map_from_posteriors, gaussian_smooth_posteriors, \\\n posteriors_to_segmentation\n\n\nclass InferencePipelineBase:\n \"\"\"Base class for all inference pipelines.\"\"\"\n\n def __init__(self, model_config: ModelConfigBase):\n self.model_config = model_config\n\n\nclass FullImageInferencePipelineBase(InferencePipelineBase):\n \"\"\"\n Base Class for full image inference intended to be inherited by inference pipelines\n that can perform full image prediction\n \"\"\"\n\n def __init__(self, model_config: SegmentationModelBase):\n super().__init__(model_config)\n\n def predict_and_post_process_whole_image(self, image_channels: np.ndarray,\n voxel_spacing_mm: TupleFloat3,\n mask: np.ndarray = None,\n patient_id: int = 0) -> InferencePipeline.Result:\n return self.post_process(self.predict_whole_image(image_channels, voxel_spacing_mm, mask, patient_id))\n\n def predict_whole_image(self, image_channels: np.ndarray,\n voxel_spacing_mm: TupleFloat3,\n mask: np.ndarray = None,\n patient_id: int = 0) -> InferencePipeline.Result:\n raise NotImplementedError(\"Full image inference capability must be implemented by concrete classes\")\n\n def post_process(self, results: InferencePipeline.Result) -> InferencePipeline.Result:\n \"\"\"\n Perform connected component analysis to update segmentation with largest\n connected component based on the configurations\n :param results: inference results to post-process\n :return: post-processed version of results\n \"\"\"\n if self.model_config.posterior_smoothing_mm:\n posteriors = gaussian_smooth_posteriors(\n posteriors=results.posteriors,\n kernel_size_mm=self.model_config.posterior_smoothing_mm,\n voxel_spacing_mm=results.voxel_spacing_mm\n )\n\n results = InferencePipeline.Result(\n patient_id=results.patient_id,\n posteriors=posteriors,\n segmentation=posteriors_to_segmentation(posteriors),\n voxel_spacing_mm=results.voxel_spacing_mm\n )\n\n if self.model_config.summed_probability_rules and not self.model_config.disable_extra_postprocessing:\n assert isinstance(self.model_config, SegmentationModelBase)\n results = results.with_new_segmentation(\n image_util.apply_summed_probability_rules(self.model_config, results.posteriors, results.segmentation))\n\n if self.model_config.largest_connected_component_foreground_classes is not None:\n # get indices for classes to restrict\n restrict_class_indices_and_thresholds = []\n for name, idx in self.model_config.class_and_index_with_background().items():\n for name2, threshold in self.model_config.largest_connected_component_foreground_classes:\n if name2 == name:\n restrict_class_indices_and_thresholds.append((idx, threshold))\n results = results.with_new_segmentation(\n image_util.extract_largest_foreground_connected_component(\n multi_label_array=results.segmentation,\n # mypy gets confused below because List is invariant. Sequence is covariant\n # but does not allow \"append\".\n restrictions=restrict_class_indices_and_thresholds)) # type: ignore\n\n if self.model_config.slice_exclusion_rules and not self.model_config.disable_extra_postprocessing:\n results = results.with_new_segmentation(\n image_util.apply_slice_exclusion_rules(self.model_config, results.segmentation))\n\n return results\n\n\nclass InferencePipeline(FullImageInferencePipelineBase):\n \"\"\"\n Pipeline class for model for whole image inference on ct-images.\n \"\"\"\n\n # the model output is expected to be a valid probability distribution\n MODEL_OUTPUT_POSTERIOR_RANGE = (0, 1)\n\n class Variables(Enum):\n \"\"\"\n Variables associated with the inference pipeline\n \"\"\"\n\n # an instantiated model to use for inference.\n Model = 'model'\n # the configuration associated with the model.\n ModelConfig = 'model_config'\n # the shape of the image required as output from the pipeline.\n OutputImageShape = 'output_image_shape'\n # A Tuple[int,int,int] with the crop size that should be used. For large images, this will be\n # the test_crop_size from the model config, but for smaller images, it will be the componentwise\n # minimum of test_crop_size and image_size\n CropSize = 'crop_size'\n # The stride size to use, possibly adjusted for small images (see above for crop_size)\n Stride = 'stride'\n # The size of the output tensor that the model will produce when fed with an input tensor that\n # has the given crop_size.\n OutputSize = 'output_size'\n\n class Result:\n \"\"\"\n Contains the inference results from a single pass of the inference pipeline\n \"\"\"\n\n def __init__(self,\n patient_id: int,\n segmentation: np.ndarray,\n posteriors: np.ndarray,\n voxel_spacing_mm: TupleFloat3):\n \"\"\"\n :param patient_id: The id of the patient instance for with inference is being performed on.\n :param segmentation: Z x Y x X (argmaxed over the posteriors in the class dimension)\n :param voxel_spacing_mm: Voxel spacing to use for each dimension in (Z x Y x X) order\n :param posteriors: Class x Z x Y x X\n \"\"\"\n self.patient_id = patient_id\n self.segmentation = segmentation\n self.posteriors = posteriors\n self.voxel_spacing_mm = voxel_spacing_mm\n\n if len(self.voxel_spacing_mm) != 3:\n raise ValueError(f\"voxel_spacing_mm must have length 3, found: {voxel_spacing_mm}\")\n if any(np.array(self.voxel_spacing_mm) <= 0):\n raise ValueError(f\"voxel_spacing_mm must have values > 0 in each dimension, found: {voxel_spacing_mm}\")\n\n ml_util.check_size_matches(self.segmentation,\n self.posteriors,\n dim1=3,\n dim2=4,\n matching_dimensions=[-3, -2, -1],\n arg1_name=\"segmentation\",\n arg2_name=\"posteriors\")\n\n segmentation_value_range = np.unique(self.segmentation)\n if not np.all([x in range(self.posteriors.shape[0]) for x in segmentation_value_range]):\n raise Exception(\"values in the segmentation map must be in range [0, classes), \"\n \"found classes:{}, segmentation range:{}\"\n .format(self.posteriors.shape[0], segmentation_value_range))\n\n self._uncertainty = compute_uncertainty_map_from_posteriors(self.posteriors)\n\n @property\n def uncertainty(self) -> np.ndarray:\n return self._uncertainty\n\n def with_new_segmentation(self, segmentation: np.ndarray) -> InferencePipeline.Result:\n if segmentation.shape != self.segmentation.shape:\n raise ValueError(f\"Attempt to replace segmentation of shape {self.segmentation.shape} \"\n f\"with one of shape {segmentation.shape}\")\n return InferencePipeline.Result(\n patient_id=self.patient_id,\n segmentation=segmentation,\n posteriors=self.posteriors,\n voxel_spacing_mm=self.voxel_spacing_mm)\n\n def __init__(self, model: SegmentationLightning, model_config: config.SegmentationModelBase,\n pipeline_id: int = 0):\n super().__init__(model_config)\n self.model = model\n self.model.model.eval()\n self.pipeline_id = pipeline_id\n\n @staticmethod\n def create_from_checkpoint(path_to_checkpoint: Path,\n model_config: SegmentationModelBase,\n pipeline_id: int = 0) -> Optional[InferencePipeline]:\n \"\"\"\n Creates an instance of the inference pipeline for a given epoch from a stored checkpoint.\n After loading, the model parameters are checked for NaN and Infinity values.\n If there is no checkpoint file for the given epoch, return None.\n :param path_to_checkpoint: The path to the checkpoint that we want to load\n model_config.checkpoint_folder\n :param model_config: Model related configurations.\n :param pipeline_id: Numeric identifier for the pipeline (useful for logging when ensembling)\n :return InferencePipeline: an instantiated inference pipeline instance, or None if there was no checkpoint\n file for this epoch.\n \"\"\"\n if not path_to_checkpoint.is_file():\n # not raising a value error here: This is used to create individual pipelines for ensembles,\n # possible one model cannot be created but others can\n logging.warning(f\"Could not recover model from checkpoint path {path_to_checkpoint}\")\n return None\n lightning_model = load_from_checkpoint_and_adjust_for_inference(model_config, path_to_checkpoint)\n assert isinstance(lightning_model, SegmentationLightning)\n return InferencePipeline(model=lightning_model, model_config=model_config, pipeline_id=pipeline_id)\n\n def predict_whole_image(self, image_channels: np.ndarray,\n voxel_spacing_mm: TupleFloat3,\n mask: np.ndarray = None,\n patient_id: int = 0) -> InferencePipeline.Result:\n \"\"\"\n Performs a single inference pass through the pipeline for the provided image\n :param image_channels: The input image channels to perform inference on in format: Channels x Z x Y x X.\n :param voxel_spacing_mm: Voxel spacing to use for each dimension in (Z x Y x X) order\n :param mask: A binary image used to ignore results outside it in format: Z x Y x X.\n :param patient_id: The identifier of the patient this image belongs to (defaults to 0 if None provided).\n :return InferenceResult: that contains Segmentation for each of the classes and their posterior probabilities.\n \"\"\"\n if image_channels is None:\n raise Exception(\"image_channels cannot be None\")\n if image_channels.ndim != 4:\n raise NotImplementedError(\"image_channels must be in shape: Channels x Z x Y x X\"\n \"found image_channels shape: {}\".format(image_channels.shape))\n if mask is not None:\n ml_util.check_size_matches(image_channels, mask, 4, 3, [-1, -2, -3])\n self.model.eval()\n # create the dataset for the batch\n batch_dataset = Dataset(index=[patient_id], batch_class=InferenceBatch)\n # setup the pipeline\n pipeline = (batch_dataset.p\n # define pipeline variables\n .init_variables([InferencePipeline.Variables.Model,\n InferencePipeline.Variables.ModelConfig,\n InferencePipeline.Variables.CropSize,\n InferencePipeline.Variables.OutputSize,\n InferencePipeline.Variables.OutputImageShape,\n InferencePipeline.Variables.Stride])\n # update the variables for the batch actions\n .update_variable(name=InferencePipeline.Variables.Model, value=self.model)\n .update_variable(name=InferencePipeline.Variables.ModelConfig, value=self.model_config)\n # perform cascaded batch actions\n .load(image_channels=image_channels, mask=mask)\n .pre_process()\n .predict()\n .post_process()\n )\n # run the batch through the pipeline\n logging.info(f\"Inference pipeline ({self.pipeline_id}), Predicting patient: {patient_id}\")\n processed_batch: InferenceBatch = pipeline.next_batch(batch_size=1)\n posteriors = processed_batch.get_component(InferenceBatch.Components.Posteriors)\n image_util.check_array_range(posteriors, error_prefix=\"Whole image posteriors\")\n # prepare pipeline results from the processed batch\n return InferencePipeline.Result(\n patient_id=patient_id,\n segmentation=processed_batch.get_component(InferenceBatch.Components.Segmentation),\n posteriors=posteriors,\n voxel_spacing_mm=voxel_spacing_mm\n )\n\n\nclass InferenceBatch(CTImagesMaskedBatch):\n \"\"\"\n Batch class for IO with the inference pipeline. One instance of a batch will load the image\n into the 'images' component of the pipeline, and store the results of the full pass\n of the pipeline into the 'segmentation' and 'posteriors' components.\n \"\"\"\n\n class Components(Enum):\n \"\"\"\n Components associated with the inference batch class\n \"\"\"\n\n # the input image channels in Channels x Z x Y x X format.\n ImageChannels = 'channels'\n # a set of 2D image slices (ie: a 3D image channel), stacked in Z x Y x X format.\n Images = 'images'\n # a binary mask used to ignore predictions in Z x Y x X format.\n Mask = 'mask'\n # a numpy.ndarray in Z x Y x X format with class labels for each voxel in the original image.\n Segmentation = 'segmentation'\n # a numpy.ndarray with the first dimension indexing each class in C x Z x Y x X format\n # with each Z x Y x X being the same shape as the Images component, and consisting of\n # [0, 1] values representing the model confidence for each voxel.\n Posteriors = 'posteriors'\n\n def __init__(self, index: int, *args: Any, **kwargs: Any):\n super().__init__(index, *args, **kwargs)\n self.components = [x.value for x in InferenceBatch.Components]\n\n @action\n def load(self, image_channels: np.ndarray, mask: np.ndarray) -> InferenceBatch:\n \"\"\"\n Load image channels and mask into their respective pipeline components.\n \"\"\"\n self.set_component(component=InferenceBatch.Components.ImageChannels, data=image_channels)\n model_config = self.get_configs()\n if model_config is None:\n raise ValueError(\"model_config is None\")\n if model_config.test_crop_size is None:\n raise ValueError(\"model_config.test_crop_size is None\")\n if model_config.inference_stride_size is None:\n raise ValueError(\"model_config.inference_stride_size is None\")\n\n # fetch the image channels from the batch\n image_channels = self.get_component(InferenceBatch.Components.ImageChannels)\n self.pipeline.set_variable(name=InferencePipeline.Variables.OutputImageShape, value=image_channels[0].shape)\n # There may be cases where the test image is smaller than the test_crop_size. Adjust crop_size\n # to always fit into image. If test_crop_size is smaller than the image, crop will remain unchanged.\n image_size = image_channels.shape[1:]\n model: BaseSegmentationModel = self.pipeline.get_variable(InferencePipeline.Variables.Model).model\n effective_crop, effective_stride = \\\n model.crop_size_constraints.restrict_crop_size_to_image(image_size,\n model_config.test_crop_size,\n model_config.inference_stride_size)\n self.pipeline.set_variable(name=InferencePipeline.Variables.CropSize, value=effective_crop)\n self.pipeline.set_variable(name=InferencePipeline.Variables.Stride, value=effective_stride)\n logging.debug(\n f\"Inference on image size {image_size} will run \"\n f\"with crop size {effective_crop} and stride {effective_stride}\")\n # In most cases, we will be able to read the output size from the pre-computed values\n # via get_output_size. Only if we have a non-standard (smaller) crop size, re-computed the output size.\n output_size = model_config.get_output_size(execution_mode=ModelExecutionMode.TEST)\n if effective_crop != model_config.test_crop_size:\n output_size = model.get_output_shape(input_shape=effective_crop) # type: ignore\n self.pipeline.set_variable(name=InferencePipeline.Variables.OutputSize, value=output_size)\n\n if mask is not None:\n self.set_component(component=InferenceBatch.Components.Mask, data=mask)\n\n return self\n\n @action\n def pre_process(self) -> InferenceBatch:\n \"\"\"\n Prepare the input components of the batch for further processing.\n \"\"\"\n model_config = self.get_configs()\n\n # fetch the image channels from the batch\n image_channels = self.get_component(InferenceBatch.Components.ImageChannels)\n\n crop_size = self.pipeline.get_variable(InferencePipeline.Variables.CropSize)\n output_size = self.pipeline.get_variable(InferencePipeline.Variables.OutputSize)\n image_channels = image_util.pad_images_for_inference(\n images=image_channels,\n crop_size=crop_size,\n output_size=output_size,\n padding_mode=model_config.padding_mode\n )\n\n # update the post-processed components\n self.set_component(component=InferenceBatch.Components.ImageChannels, data=image_channels)\n\n return self\n\n @action\n def predict(self) -> InferenceBatch:\n \"\"\"\n Perform a forward pass of the model on the provided image, this generates\n a set of posterior maps for each class, as well as a segmentation output\n stored in the respective 'posteriors' and 'segmentation' components.\n \"\"\"\n model_config = self.get_configs()\n\n # extract patches for each image channel: Num patches x Channels x Z x Y x X\n patches = self._extract_patches_for_image_channels()\n\n # split the generated patches into batches and perform forward passes\n predictions = []\n batch_size = model_config.inference_batch_size\n\n for batch_idx in range(0, len(patches), batch_size):\n # slice over the batches to prepare batch\n batch = torch.tensor(patches[batch_idx: batch_idx + batch_size, ...]).float()\n if model_config.use_gpu:\n batch = batch.cuda()\n # perform the forward pass\n batch_predictions = self._model_fn(batch).detach().cpu().numpy()\n # collect the predictions over each of the batches\n predictions.append(batch_predictions)\n\n # map the batched predictions to the original batch shape\n # of shape but with an added class dimension: Num patches x Class x Z x Y x X\n predictions = np.concatenate(predictions, axis=0)\n\n # create posterior output for each class with the shape: Class x Z x Y x x. We use float32 as these\n # arrays can be big.\n output_image_shape = self.pipeline.get_variable(InferencePipeline.Variables.OutputImageShape)\n posteriors = np.zeros(shape=[model_config.number_of_classes] + list(output_image_shape), dtype=np.float32)\n stride = self.pipeline.get_variable(InferencePipeline.Variables.Stride)\n\n for c in range(len(posteriors)):\n # stitch the patches for each posterior class\n self.load_from_patches(predictions[:, c, ...], # type: ignore\n stride=stride,\n scan_shape=output_image_shape,\n data_attr=InferenceBatch.Components.Posteriors.value)\n # extract computed output from the component so the pipeline buffer can be reused\n posteriors[c] = self.get_component(InferenceBatch.Components.Posteriors)\n\n # store the stitched up results for the batch\n self.set_component(component=InferenceBatch.Components.Posteriors, data=posteriors)\n\n return self\n\n @action\n def post_process(self) -> InferenceBatch:\n \"\"\"\n Perform post processing on the computed outputs of the a single pass of the pipelines.\n Currently the following operations are performed:\n -------------------------------------------------------------------------------------\n 1) the mask is applied to the posteriors (if required).\n 2) the final posteriors are used to perform an argmax to generate a multi-label segmentation.\n 3) extract the largest foreground connected component in the segmentation if required\n \"\"\"\n mask = self.get_component(InferenceBatch.Components.Mask)\n posteriors = self.get_component(InferenceBatch.Components.Posteriors)\n if mask is not None:\n posteriors = image_util.apply_mask_to_posteriors(posteriors=posteriors, mask=mask)\n\n # create segmentation using an argmax over the posterior probabilities\n segmentation = image_util.posteriors_to_segmentation(posteriors)\n\n # update the post-processed posteriors and save the segmentation\n self.set_component(component=InferenceBatch.Components.Posteriors, data=posteriors)\n self.set_component(component=InferenceBatch.Components.Segmentation, data=segmentation)\n\n return self\n\n def get_configs(self) -> config.SegmentationModelBase:\n return self.pipeline.get_variable(InferencePipeline.Variables.ModelConfig)\n\n def get_component(self, component: InferenceBatch.Components) -> np.ndarray:\n return getattr(self, component.value) if hasattr(self, component.value) else None\n\n @inbatch_parallel(init='indices', post='_post_custom_components', target='threads')\n def set_component(self, batch_idx: int, component: InferenceBatch.Components, data: np.ndarray) \\\n -> Dict[str, Any]:\n logging.debug(\"Updated data in pipeline component: {}, for batch: {}.\".format(component.value, batch_idx))\n return {\n component.value: {'type': component.value, 'data': data}\n }\n\n def _extract_patches_for_image_channels(self) -> np.ndarray:\n \"\"\"\n Extracts deterministically, patches from each image channel\n :return: Patches for each image channel in format: Num patches x Channels x Z x Y x X\n \"\"\"\n model_config = self.get_configs()\n image_channels = self.get_component(InferenceBatch.Components.ImageChannels)\n # There may be cases where the test image is smaller than the test_crop_size. Adjust crop_size\n # to always fit into image, and adjust stride accordingly. If test_crop_size is smaller than the\n # image, crop and stride will remain unchanged.\n crop_size = self.pipeline.get_variable(InferencePipeline.Variables.CropSize)\n stride = self.pipeline.get_variable(InferencePipeline.Variables.Stride)\n patches = []\n for channel_index, channel in enumerate(image_channels):\n # set the current image channel component to process\n self.set_component(component=InferenceBatch.Components.Images, data=channel)\n channel_patches = self.get_patches(patch_shape=crop_size,\n stride=stride,\n padding=model_config.padding_mode.value,\n data_attr=InferenceBatch.Components.Images.value)\n logging.debug(\n f\"Image channel {channel_index}: Tensor with extracted patches has size {channel_patches.shape}\")\n patches.append(channel_patches)\n # reset the images component\n self.set_component(component=InferenceBatch.Components.Images, data=[])\n\n return np.stack(patches, axis=1)\n\n def _model_fn(self, patches: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Wrapper function to handle the model forward pass\n :param patches: Image patches to be passed to the model in format Patches x Channels x Z x Y x X\n :return posteriors: Confidence maps [0,1] for each patch per class\n in format: Patches x Channels x Class x Z x Y x X\n \"\"\"\n model = self.pipeline.get_variable(InferencePipeline.Variables.Model)\n # Model forward pass returns posteriors\n with torch.no_grad():\n return model(patches)\n" ]
[ [ "torch.no_grad", "torch.tensor", "numpy.stack", "numpy.concatenate", "numpy.array", "numpy.unique" ] ]
smartdolphin/variational-autoencoder
[ "999e00c1f630d1e3b6b433c965f87d236ba18668" ]
[ "util/metric.py" ]
[ "from collections import Counter\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, confusion_matrix\n\n\ndef __majority(arr):\n counter = Counter(arr)\n value, _ = counter.most_common(1)[0]\n return value\n\n\ndef clustering_accuracy(y_true, y_clustering):\n clustering_labels = list(set(y_clustering))\n new_labels = np.zeros_like(y_clustering)\n for clustering_label in clustering_labels:\n locator = y_clustering == clustering_label\n locations = np.argwhere(locator)\n real_labels = y_true[locations].ravel()\n major_label = __majority(real_labels)\n new_labels[locator] = major_label\n return accuracy_score(y_true, new_labels)\n\n\ndef confusion_matrix_majority(y_true, y_clustering):\n clustering_labels = list(set(y_clustering))\n new_labels = np.zeros_like(y_clustering)\n for clustering_label in clustering_labels:\n locator = y_clustering == clustering_label\n locations = np.argwhere(locator)\n real_labels = y_true[locations].ravel()\n major_label = __majority(real_labels)\n new_labels[locator] = major_label\n return confusion_matrix(y_true, new_labels)\n" ]
[ [ "sklearn.metrics.accuracy_score", "numpy.zeros_like", "sklearn.metrics.confusion_matrix", "numpy.argwhere" ] ]
patelshival/ga-dsmp
[ "c355d28daf50c51b1610930f963dcd17b770e17a" ]
[ "numpy-arrays/code.py" ]
[ "# --------------\n# Importing header files\r\nimport numpy as np\r\n\r\n# Path of the file has been stored in variable called 'path'\r\n\r\n#New record\r\nnew_record=[[50, 9, 4, 1, 0, 0, 40, 0]]\r\n\r\ndata = np.genfromtxt(path, delimiter=\",\", skip_header=1)\r\n\r\nprint(\"\\nData: \\n\\n\", data)\r\n\r\nprint(\"\\nType of data: \\n\\n\", type(data))\r\n\r\ncensus = np.concatenate((data, new_record), axis=0)\r\n\r\nprint(census)\r\n#Code starts here\r\n\n\n\n# --------------\n#Code starts here\r\nage=census[:,0]\r\n\r\nprint(age)\r\n\r\nmax_age = np.max(age)\r\nmin_age = np.min(age)\r\nage_mean = np.mean(age)\r\nage_std = np.std(age)\r\n\r\nprint(\"max of age : \", max_age)\r\nprint(\"min of age : \", min_age)\r\nprint(\"mean of age : \", age_mean)\r\nprint(\"standard deviation of age : \", age_std)\n\n\n# --------------\n#Code starts here\r\nrace_0 = census[census[:,2] == 0]\r\nrace_1 = census[census[:,2] == 1]\r\nrace_2 = census[census[:,2] == 2]\r\nrace_3 = census[census[:,2] == 3]\r\nrace_4 = census[census[:,2] == 4]\r\n\r\nlen_0 = len(race_0)\r\nlen_1 = len(race_1)\r\nlen_2 = len(race_2)\r\nlen_3 = len(race_3)\r\nlen_4 = len(race_4)\r\n\r\nminority_race = 3\r\nprint(race_0)\r\n\n\n\n# --------------\n#Code starts here\r\nsenior_citizens = census[census[:, 0] > 60]\r\nworking_hours = senior_citizens[:,6]\r\nworking_hours_sum = working_hours.sum()\r\nsenior_citizens_len = len(senior_citizens)\r\navg_working_hours = working_hours_sum / senior_citizens_len\r\nprint(avg_working_hours)\n\n\n# --------------\n#Code starts here\r\nhigh = census[census[:,1] > 10]\r\nlow = census[census[:,1] <= 10]\r\n\r\navg_pay_high = high[:, 7].mean()\r\navg_pay_low = low[:, 7].mean()\r\n\r\nif avg_pay_high > avg_pay_low:\r\n print(\"Better education leads to better pay\")\r\nelse:\r\n print(\"Better education does not lead to better pay\") \n\n\n" ]
[ [ "numpy.genfromtxt", "numpy.max", "numpy.min", "numpy.std", "numpy.concatenate", "numpy.mean" ] ]
jloveric/high-order-layers-torch
[ "a50ccf0cf82c21fdda4c20c671e7d233a0b6f793" ]
[ "high_order_layers_torch/FunctionalConvolution.py" ]
[ "from .LagrangePolynomial import LagrangeExpand\nfrom pytorch_lightning import LightningModule, Trainer\n\nfrom high_order_layers_torch.PolynomialLayers import *\nfrom torch.nn import Conv2d\nimport torch.nn as nn\nimport torch\nfrom .utils import *\n\n\ndef conv2d_wrapper(\n in_channels: int,\n out_channels: int,\n kernel_size: int,\n stride: int = 1,\n padding: int = 0,\n dilation: int = 1,\n groups: int = 1,\n padding_mode: str = 'zeros',\n weight_magnitude: float = 1.0,\n rescale_output: bool = False,\n verbose: bool = False,\n ** kwargs\n):\n \"\"\"\n Inputs need to be an exact clone of those in torch conv2d including\n defaults. Function allows you to pass extra arguments without braking\n conv2d.\n \"\"\"\n\n conv = Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n # Bias should always be false as the bias is already included in these methods.\n bias=False,\n padding_mode=padding_mode,\n )\n in_features = in_channels*kernel_size*kernel_size\n\n if verbose is True:\n print('in_channels', in_channels, 'out_channels', out_channels)\n print('conv.weight.shape', conv.weight.shape)\n\n # We don't want to use the standard conv initialization\n # since this is a bit different.\n if rescale_output is False:\n conv.weight.data.uniform_(-weight_magnitude/in_features,\n weight_magnitude/in_features)\n elif rescale_output is True:\n conv.weight.data.uniform_(-weight_magnitude, weight_magnitude)\n else:\n print('Using kaiming for weight initialization')\n\n return conv\n\n\nclass Expansion2d(nn.Module):\n def __init__(self, basis=None):\n \"\"\"\n Expand an input by a function defined by basis.\n\n Args :\n - basis: function to expand input by.\n \"\"\"\n super().__init__()\n if basis == None:\n raise Exception(\n 'You must define the basis function in ExpansionLayer2D')\n self.basis = basis\n\n def build(self, input_shape):\n pass\n\n def __call__(self, inputs):\n \"\"\"\n Expand input\n Args :\n inputs : Tensor of shape [batches, channels, height, width]\n Return :\n Tensor of shape [batches, channels*(basis size), height, width]\n \"\"\"\n res = self.basis(\n inputs) # outputs [basis_size, batches, channels, height, width]\n res = res.permute(1, 3, 4, 2, 0)\n res = torch.reshape(\n res, [res.shape[0], res.shape[1],\n res.shape[2], res.shape[3]*res.shape[4]]\n )\n res = res.permute(0, 3, 1, 2)\n return res\n\n\nclass Expansion1d(nn.Module):\n def __init__(self, basis=None):\n \"\"\"\n Expand an input by a function defined by basis.\n\n Args :\n - basis: function to expand input by.\n \"\"\"\n super().__init__()\n if basis == None:\n raise Exception(\n 'You must define the basis function in ExpansionLayer2D')\n self.basis = basis\n\n def build(self, input_shape):\n pass\n\n def __call__(self, inputs):\n \"\"\"\n Expand input\n Args :\n inputs : Tensor of shape [batches, channels, width]\n Return :\n Tensor of shape [batches, channels*(basis size), width]\n \"\"\"\n res = self.basis(\n inputs) # outputs [basis_size, batches, channels, width]\n res = res.permute(1, 3, 2, 0)\n res = torch.reshape(\n res, [res.shape[0], res.shape[1], res.shape[2]*res.shape[3]]\n )\n res = res.permute(0, 2, 1) # batches, basis_size*channels, width\n return res\n\n\nclass FourierConvolution2d(nn.Module):\n\n def __init__(self, n: int, in_channels: int, kernel_size: int, length: float = 2.0, rescale_output=False, *args, **kwargs):\n \"\"\"\n Fourier series convolutional layer.\n\n Args :\n - n : number of fourier series components. n=1 is a constant, n=3 contains both first sin an consine components.\n - in_channels : number of input channels\n - kernel_size : size of the kernel\n - length : Range of the polynomial interpolation points. length = 2 implies [-1, 1] so the interpolation points\n are in that range. Anything outside that range could grow.\n - rescale_output: If rescale output is True then the output is divided by the number of inputs for each output,\n in effect taking the average. This is generally not necessary for the fourier series.\n \"\"\"\n super().__init__()\n self.poly = Expansion2d(FourierExpand(n, length))\n self._channels = n*in_channels\n self.conv = conv2d_wrapper(in_channels=self._channels,\n kernel_size=kernel_size, **kwargs)\n self._total_in = in_channels*kernel_size*kernel_size\n self._rescale = 1.0\n if rescale_output is True:\n self._rescale = 1.0/self._total_in\n\n def forward(self, x):\n x = self.poly(x)\n out = self.conv(x)\n return out*self._rescale\n\n\nclass PolynomialConvolution2d(nn.Module):\n def __init__(self, n: int, in_channels: int, kernel_size: int, length: float = 2.0, rescale_output=False, periodicity: float = None, *args, **kwargs):\n \"\"\"\n Polynomial convolutional layer.\n\n Args :\n - n : number of weights or nodes. Polynomial order is n-1 so quadratic would be n=3.\n - in_channels : number of input channels\n - kernel_size : size of the kernel\n - length : Range of the polynomial interpolation points. length = 2 implies [-1, 1] so the interpolation points\n are in that range. Anything outside that range could grow.\n - rescale_output: If rescale output is True then the output is divided by the number of inputs for each output,\n in effect taking the average.\n \"\"\"\n super().__init__()\n self.poly = Expansion2d(LagrangeExpand(n, length=length))\n self._channels = n*in_channels\n self.periodicity = periodicity\n self.conv = conv2d_wrapper(in_channels=self._channels,\n kernel_size=kernel_size, **kwargs)\n self._total_in = in_channels*kernel_size*kernel_size\n self._rescale = 1.0\n if rescale_output is True:\n self._rescale = 1.0/self._total_in\n\n def forward(self, x):\n periodicity = self.periodicity\n if periodicity is not None:\n x = make_periodic(x, periodicity)\n x = self.poly(x)\n out = self.conv(x)\n return out*self._rescale\n\n\nclass PiecewisePolynomialConvolution2d(nn.Module):\n def __init__(self, n: int, segments: int, in_channels: int, kernel_size: int, length: float = 2.0, rescale_output: bool = False, periodicity: float = None, *args, **kwargs):\n \"\"\"\n Piecewise continuous polynomial convolutional layer. The boundary between each polynomial are continuous. \n\n Args :\n - n : number of weights or nodes. Polynomial order is n-1 so quadratic would be n=3.\n - segments: The number of segments in the piecewise polynomial.\n - in_channels : number of input channels\n - kernel_size : size of the kernel\n - length : Range of the piecewise polynomial interpolation points. length = 2 implies [-1, 1] so the interpolation points\n are in that range.\n - rescale_output: If rescale output is True then the output is divided by the number of inputs for each output,\n in effect taking the average.\n \"\"\"\n super().__init__()\n self.poly = Expansion2d(\n PiecewisePolynomialExpand(n=n, segments=segments, length=length))\n self._channels = ((n-1)*segments+1)*in_channels\n self.periodicity = periodicity\n self.conv = conv2d_wrapper(in_channels=self._channels,\n kernel_size=kernel_size, **kwargs)\n self._total_in = in_channels*kernel_size*kernel_size\n self._rescale = 1.0\n if rescale_output is True:\n self._rescale = 1.0/self._total_in\n\n def forward(self, x):\n periodicity = self.periodicity\n if periodicity is not None:\n x = make_periodic(x, periodicity)\n x = self.poly(x)\n out = self.conv(x)\n return out*self._rescale\n\n\nclass PiecewiseDiscontinuousPolynomialConvolution2d(nn.Module):\n def __init__(self, n: int, segments: int, in_channels: int, kernel_size: int, length: float = 2.0, rescale_output: bool = False, periodicity: float = None, *args, **kwargs):\n \"\"\"\n Discontinuous piecewise polynomial convolutional layer. The boundary between each polynomial can be discontinuous. \n Args :\n - n : number of weights or nodes. Polynomial order is n-1 so quadratic would be n=3.\n - segments: The number of segments in the piecewise polynomial.\n - in_channels : number of input channels\n - kernel_size : size of the kernel\n - length : Range of the piecewise polynomial interpolation points. length = 2 implies [-1, 1] so the interpolation points\n are in that range.\n - rescale_output: If rescale output is True then the output is divided by the number of inputs for each output,\n in effect taking the average.\n \"\"\"\n super().__init__()\n self.poly = Expansion2d(\n PiecewiseDiscontinuousPolynomialExpand(n=n, segments=segments, length=length))\n self._channels = n*segments*in_channels\n self.periodicity = periodicity\n self.conv = conv2d_wrapper(in_channels=self._channels,\n kernel_size=kernel_size, **kwargs)\n self._total_in = in_channels*kernel_size*kernel_size\n self._rescale = 1.0\n if rescale_output is True:\n self._rescale = 1.0/self._total_in\n\n def forward(self, x):\n periodicity = self.periodicity\n if periodicity is not None:\n x = make_periodic(x, periodicity)\n x = self.poly(x)\n out = self.conv(x)\n return out*self._rescale\n" ]
[ [ "torch.reshape", "torch.nn.Conv2d" ] ]
KnockerPulsar/pytorch-image-models
[ "893f5dde27ae6b17389f738bd6e37160e2868c72" ]
[ "timm/models/byobnet.py" ]
[ "\"\"\" Bring-Your-Own-Blocks Network\r\n\r\nA flexible network w/ dataclass based config for stacking those NN blocks.\r\n\r\nThis model is currently used to implement the following networks:\r\n\r\nGPU Efficient (ResNets) - gernet_l/m/s (original versions called genet, but this was already used (by SENet author)).\r\nPaper: `Neural Architecture Design for GPU-Efficient Networks` - https://arxiv.org/abs/2006.14090\r\nCode and weights: https://github.com/idstcv/GPU-Efficient-Networks, licensed Apache 2.0\r\n\r\nRepVGG - repvgg_*\r\nPaper: `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\nCode and weights: https://github.com/DingXiaoH/RepVGG, licensed MIT\r\n\r\nIn all cases the models have been modified to fit within the design of ByobNet. I've remapped\r\nthe original weights and verified accuracies.\r\n\r\nFor GPU Efficient nets, I used the original names for the blocks since they were for the most part\r\nthe same as original residual blocks in ResNe(X)t, DarkNet, and other existing models. Note also some\r\nchanges introduced in RegNet were also present in the stem and bottleneck blocks for this model.\r\n\r\nA significant number of different network archs can be implemented here, including variants of the\r\nabove nets that include attention.\r\n\r\nHacked together by / copyright Ross Wightman, 2021.\r\n\"\"\"\r\nimport math\r\nfrom dataclasses import dataclass, field, replace\r\nfrom typing import Tuple, List, Dict, Optional, Union, Any, Callable, Sequence\r\nfrom functools import partial\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\nfrom timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD\r\nfrom .helpers import build_model_with_cfg, named_apply\r\nfrom .layers import ClassifierHead, ConvBnAct, BatchNormAct2d, DropPath, AvgPool2dSame, \\\r\n create_conv2d, get_act_layer, convert_norm_act, get_attn, make_divisible, to_2tuple\r\nfrom .registry import register_model\r\n\r\n__all__ = ['ByobNet', 'ByoModelCfg', 'ByoBlockCfg', 'create_byob_stem', 'create_block']\r\n\r\n\r\ndef _cfg(url='', **kwargs):\r\n return {\r\n 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7),\r\n 'crop_pct': 0.875, 'interpolation': 'bilinear',\r\n 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD,\r\n 'first_conv': 'stem.conv', 'classifier': 'head.fc',\r\n **kwargs\r\n }\r\n\r\n\r\ndefault_cfgs = {\r\n # GPU-Efficient (ResNet) weights\r\n 'gernet_s': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-ger-weights/gernet_s-756b4751.pth'),\r\n 'gernet_m': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-ger-weights/gernet_m-0873c53a.pth'),\r\n 'gernet_l': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-ger-weights/gernet_l-f31e2e8d.pth',\r\n input_size=(3, 256, 256), pool_size=(8, 8)),\r\n\r\n # RepVGG weights\r\n 'repvgg_a2': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_a2-c1ee6d2b.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n 'repvgg_b0': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_b0-80ac3f1b.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n 'repvgg_b1': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_b1-77ca2989.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n 'repvgg_b1g4': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_b1g4-abde5d92.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n 'repvgg_b2': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_b2-25b7494e.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n 'repvgg_b2g4': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_b2g4-165a85f2.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n 'repvgg_b3': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_b3-199bc50d.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n 'repvgg_b3g4': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-repvgg-weights/repvgg_b3g4-73c370bf.pth',\r\n first_conv=('stem.conv_kxk.conv', 'stem.conv_1x1.conv')),\r\n\r\n # experimental configs\r\n 'resnet51q': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet51q_ra2-d47dcc76.pth',\r\n first_conv='stem.conv1', input_size=(3, 256, 256), pool_size=(8, 8),\r\n test_input_size=(3, 288, 288), crop_pct=1.0),\r\n 'resnet61q': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/resnet61q_ra2-6afc536c.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8),\r\n test_input_size=(3, 288, 288), crop_pct=1.0, interpolation='bicubic'),\r\n\r\n 'resnext26ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/resnext26ts_256_ra2-8bbd9106.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'gcresnext26ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/gcresnext26ts_256-e414378b.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'seresnext26ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/seresnext26ts_256-6f0d74a3.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'eca_resnext26ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/eca_resnext26ts_256-5a1d030f.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'bat_resnext26ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/bat_resnext26ts_256-fa6fd595.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic',\r\n min_input_size=(3, 256, 256)),\r\n\r\n 'resnet32ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/resnet32ts_256-aacf5250.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'resnet33ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/resnet33ts_256-e91b09a4.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'gcresnet33ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/gcresnet33ts_256-0e0cd345.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'seresnet33ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/seresnet33ts_256-f8ad44d9.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n 'eca_resnet33ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/eca_resnet33ts_256-8f98face.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n\r\n 'gcresnet50t': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/gcresnet50t_256-96374d1c.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n\r\n 'gcresnext50ts': _cfg(\r\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-attn-weights/gcresnext50ts_256-3e0f515e.pth',\r\n first_conv='stem.conv1.conv', input_size=(3, 256, 256), pool_size=(8, 8), interpolation='bicubic'),\r\n}\r\n\r\n\r\n@dataclass\r\nclass ByoBlockCfg:\r\n type: Union[str, nn.Module]\r\n d: int # block depth (number of block repeats in stage)\r\n c: int # number of output channels for each block in stage\r\n s: int = 2 # stride of stage (first block)\r\n gs: Optional[Union[int, Callable]] = None # group-size of blocks in stage, conv is depthwise if gs == 1\r\n br: float = 1. # bottleneck-ratio of blocks in stage\r\n\r\n # NOTE: these config items override the model cfgs that are applied to all blocks by default\r\n attn_layer: Optional[str] = None\r\n attn_kwargs: Optional[Dict[str, Any]] = None\r\n self_attn_layer: Optional[str] = None\r\n self_attn_kwargs: Optional[Dict[str, Any]] = None\r\n block_kwargs: Optional[Dict[str, Any]] = None\r\n\r\n\r\n@dataclass\r\nclass ByoModelCfg:\r\n blocks: Tuple[Union[ByoBlockCfg, Tuple[ByoBlockCfg, ...]], ...]\r\n downsample: str = 'conv1x1'\r\n stem_type: str = '3x3'\r\n stem_pool: Optional[str] = 'maxpool'\r\n stem_chs: int = 32\r\n width_factor: float = 1.0\r\n num_features: int = 0 # num out_channels for final conv, no final 1x1 conv if 0\r\n zero_init_last: bool = True # zero init last weight (usually bn) in residual path\r\n fixed_input_size: bool = False # model constrained to a fixed-input size / img_size must be provided on creation\r\n\r\n act_layer: str = 'relu'\r\n norm_layer: str = 'batchnorm'\r\n\r\n # NOTE: these config items will be overridden by the block cfg (per-block) if they are set there\r\n attn_layer: Optional[str] = None\r\n attn_kwargs: dict = field(default_factory=lambda: dict())\r\n self_attn_layer: Optional[str] = None\r\n self_attn_kwargs: dict = field(default_factory=lambda: dict())\r\n block_kwargs: Dict[str, Any] = field(default_factory=lambda: dict())\r\n\r\n\r\ndef _rep_vgg_bcfg(d=(4, 6, 16, 1), wf=(1., 1., 1., 1.), groups=0):\r\n c = (64, 128, 256, 512)\r\n group_size = 0\r\n if groups > 0:\r\n group_size = lambda chs, idx: chs // groups if (idx + 1) % 2 == 0 else 0\r\n bcfg = tuple([ByoBlockCfg(type='rep', d=d, c=c * wf, gs=group_size) for d, c, wf in zip(d, c, wf)])\r\n return bcfg\r\n\r\n\r\ndef interleave_blocks(\r\n types: Tuple[str, str], d, every: Union[int, List[int]] = 1, first: bool = False, **kwargs\r\n) -> Tuple[ByoBlockCfg]:\r\n \"\"\" interleave 2 block types in stack\r\n \"\"\"\r\n assert len(types) == 2\r\n if isinstance(every, int):\r\n every = list(range(0 if first else every, d, every + 1))\r\n if not every:\r\n every = [d - 1]\r\n set(every)\r\n blocks = []\r\n for i in range(d):\r\n block_type = types[1] if i in every else types[0]\r\n blocks += [ByoBlockCfg(type=block_type, d=1, **kwargs)]\r\n return tuple(blocks)\r\n\r\n\r\nmodel_cfgs = dict(\r\n gernet_l=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='basic', d=1, c=128, s=2, gs=0, br=1.),\r\n ByoBlockCfg(type='basic', d=2, c=192, s=2, gs=0, br=1.),\r\n ByoBlockCfg(type='bottle', d=6, c=640, s=2, gs=0, br=1 / 4),\r\n ByoBlockCfg(type='bottle', d=5, c=640, s=2, gs=1, br=3.),\r\n ByoBlockCfg(type='bottle', d=4, c=640, s=1, gs=1, br=3.),\r\n ),\r\n stem_chs=32,\r\n stem_pool=None,\r\n num_features=2560,\r\n ),\r\n gernet_m=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='basic', d=1, c=128, s=2, gs=0, br=1.),\r\n ByoBlockCfg(type='basic', d=2, c=192, s=2, gs=0, br=1.),\r\n ByoBlockCfg(type='bottle', d=6, c=640, s=2, gs=0, br=1 / 4),\r\n ByoBlockCfg(type='bottle', d=4, c=640, s=2, gs=1, br=3.),\r\n ByoBlockCfg(type='bottle', d=1, c=640, s=1, gs=1, br=3.),\r\n ),\r\n stem_chs=32,\r\n stem_pool=None,\r\n num_features=2560,\r\n ),\r\n gernet_s=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='basic', d=1, c=48, s=2, gs=0, br=1.),\r\n ByoBlockCfg(type='basic', d=3, c=48, s=2, gs=0, br=1.),\r\n ByoBlockCfg(type='bottle', d=7, c=384, s=2, gs=0, br=1 / 4),\r\n ByoBlockCfg(type='bottle', d=2, c=560, s=2, gs=1, br=3.),\r\n ByoBlockCfg(type='bottle', d=1, c=256, s=1, gs=1, br=3.),\r\n ),\r\n stem_chs=13,\r\n stem_pool=None,\r\n num_features=1920,\r\n ),\r\n\r\n repvgg_a2=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(d=(2, 4, 14, 1), wf=(1.5, 1.5, 1.5, 2.75)),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n repvgg_b0=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(wf=(1., 1., 1., 2.5)),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n repvgg_b1=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(wf=(2., 2., 2., 4.)),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n repvgg_b1g4=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(wf=(2., 2., 2., 4.), groups=4),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n repvgg_b2=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(wf=(2.5, 2.5, 2.5, 5.)),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n repvgg_b2g4=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(wf=(2.5, 2.5, 2.5, 5.), groups=4),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n repvgg_b3=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(wf=(3., 3., 3., 5.)),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n repvgg_b3g4=ByoModelCfg(\r\n blocks=_rep_vgg_bcfg(wf=(3., 3., 3., 5.), groups=4),\r\n stem_type='rep',\r\n stem_chs=64,\r\n ),\r\n\r\n # 4 x conv stem w/ 2 act, no maxpool, 2,4,6,4 repeats, group size 32 in first 3 blocks\r\n # DW convs in last block, 2048 pre-FC, silu act \r\n resnet51q=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=4, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=6, c=1536, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=4, c=1536, s=2, gs=1, br=1.0),\r\n ),\r\n stem_chs=128,\r\n stem_type='quad2',\r\n stem_pool=None,\r\n num_features=2048,\r\n act_layer='silu',\r\n ),\r\n\r\n # 4 x conv stem w/ 4 act, no maxpool, 1,4,6,4 repeats, edge block first, group size 32 in next 2 blocks\r\n # DW convs in last block, 4 conv for each bottle block, 2048 pre-FC, silu act \r\n resnet61q=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='edge', d=1, c=256, s=1, gs=0, br=1.0, block_kwargs=dict()),\r\n ByoBlockCfg(type='bottle', d=4, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=6, c=1536, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=4, c=1536, s=2, gs=1, br=1.0),\r\n ),\r\n stem_chs=128,\r\n stem_type='quad',\r\n stem_pool=None,\r\n num_features=2048,\r\n act_layer='silu',\r\n block_kwargs=dict(extra_conv=True),\r\n ),\r\n\r\n # A series of ResNeXt-26 models w/ one of none, GC, SE, ECA, BAT attn, group size 32, SiLU act,\r\n # and a tiered stem w/ maxpool\r\n resnext26ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1024, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=2048, s=2, gs=32, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='maxpool',\r\n act_layer='silu',\r\n ),\r\n gcresnext26ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1024, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=2048, s=2, gs=32, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='maxpool',\r\n act_layer='silu',\r\n attn_layer='gca',\r\n ),\r\n seresnext26ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1024, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=2048, s=2, gs=32, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='maxpool',\r\n act_layer='silu',\r\n attn_layer='se',\r\n ),\r\n eca_resnext26ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1024, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=2048, s=2, gs=32, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='maxpool',\r\n act_layer='silu',\r\n attn_layer='eca',\r\n ),\r\n bat_resnext26ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1024, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=2048, s=2, gs=32, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='maxpool',\r\n act_layer='silu',\r\n attn_layer='bat',\r\n attn_kwargs=dict(block_size=8)\r\n ),\r\n\r\n # ResNet-32 (2, 3, 3, 2) models w/ no attn, no groups, SiLU act, no pre-fc feat layer, tiered stem w/o maxpool\r\n resnet32ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=512, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=1536, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1536, s=2, gs=0, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='',\r\n num_features=0,\r\n act_layer='silu',\r\n ),\r\n\r\n # ResNet-33 (2, 3, 3, 2) models w/ no attn, no groups, SiLU act, 1280 pre-FC feat, tiered stem w/o maxpool\r\n resnet33ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=512, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=1536, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1536, s=2, gs=0, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='',\r\n num_features=1280,\r\n act_layer='silu',\r\n ),\r\n\r\n # A series of ResNet-33 (2, 3, 3, 2) models w/ one of GC, SE, ECA attn, no groups, SiLU act, 1280 pre-FC feat \r\n # and a tiered stem w/ no maxpool\r\n gcresnet33ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=512, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=1536, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1536, s=2, gs=0, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='',\r\n num_features=1280,\r\n act_layer='silu',\r\n attn_layer='gca',\r\n ),\r\n seresnet33ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=512, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=1536, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1536, s=2, gs=0, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='',\r\n num_features=1280,\r\n act_layer='silu',\r\n attn_layer='se',\r\n ),\r\n eca_resnet33ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=2, c=256, s=1, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=512, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=1536, s=2, gs=0, br=0.25),\r\n ByoBlockCfg(type='bottle', d=2, c=1536, s=2, gs=0, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='',\r\n num_features=1280,\r\n act_layer='silu',\r\n attn_layer='eca',\r\n ),\r\n\r\n gcresnet50t=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=3, c=256, s=1, br=0.25),\r\n ByoBlockCfg(type='bottle', d=4, c=512, s=2, br=0.25),\r\n ByoBlockCfg(type='bottle', d=6, c=1024, s=2, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=2048, s=2, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='',\r\n attn_layer='gca',\r\n ),\r\n\r\n gcresnext50ts=ByoModelCfg(\r\n blocks=(\r\n ByoBlockCfg(type='bottle', d=3, c=256, s=1, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=4, c=512, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=6, c=1024, s=2, gs=32, br=0.25),\r\n ByoBlockCfg(type='bottle', d=3, c=2048, s=2, gs=32, br=0.25),\r\n ),\r\n stem_chs=64,\r\n stem_type='tiered',\r\n stem_pool='maxpool',\r\n # stem_pool=None,\r\n act_layer='silu',\r\n attn_layer='gca',\r\n ),\r\n)\r\n\r\n\r\n@register_model\r\ndef gernet_l(pretrained=False, **kwargs):\r\n \"\"\" GEResNet-Large (GENet-Large from official impl)\r\n `Neural Architecture Design for GPU-Efficient Networks` - https://arxiv.org/abs/2006.14090\r\n \"\"\"\r\n return _create_byobnet('gernet_l', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef gernet_m(pretrained=False, **kwargs):\r\n \"\"\" GEResNet-Medium (GENet-Normal from official impl)\r\n `Neural Architecture Design for GPU-Efficient Networks` - https://arxiv.org/abs/2006.14090\r\n \"\"\"\r\n return _create_byobnet('gernet_m', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef gernet_s(pretrained=False, **kwargs):\r\n \"\"\" EResNet-Small (GENet-Small from official impl)\r\n `Neural Architecture Design for GPU-Efficient Networks` - https://arxiv.org/abs/2006.14090\r\n \"\"\"\r\n return _create_byobnet('gernet_s', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_a2(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-A2\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_a2', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_b0(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-B0\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_b0', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_b1(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-B1\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_b1', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_b1g4(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-B1g4\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_b1g4', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_b2(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-B2\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_b2', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_b2g4(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-B2g4\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_b2g4', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_b3(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-B3\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_b3', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef repvgg_b3g4(pretrained=False, **kwargs):\r\n \"\"\" RepVGG-B3g4\r\n `Making VGG-style ConvNets Great Again` - https://arxiv.org/abs/2101.03697\r\n \"\"\"\r\n return _create_byobnet('repvgg_b3g4', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef resnet51q(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('resnet51q', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef resnet61q(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('resnet61q', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef resnext26ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('resnext26ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef gcresnext26ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('gcresnext26ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef seresnext26ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('seresnext26ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef eca_resnext26ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('eca_resnext26ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef bat_resnext26ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('bat_resnext26ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef resnet32ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('resnet32ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef resnet33ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('resnet33ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef gcresnet33ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('gcresnet33ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef seresnet33ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('seresnet33ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef eca_resnet33ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('eca_resnet33ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef gcresnet50t(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('gcresnet50t', pretrained=pretrained, **kwargs)\r\n\r\n\r\n@register_model\r\ndef gcresnext50ts(pretrained=False, **kwargs):\r\n \"\"\"\r\n \"\"\"\r\n return _create_byobnet('gcresnext50ts', pretrained=pretrained, **kwargs)\r\n\r\n\r\ndef expand_blocks_cfg(stage_blocks_cfg: Union[ByoBlockCfg, Sequence[ByoBlockCfg]]) -> List[ByoBlockCfg]:\r\n if not isinstance(stage_blocks_cfg, Sequence):\r\n stage_blocks_cfg = (stage_blocks_cfg,)\r\n block_cfgs = []\r\n for i, cfg in enumerate(stage_blocks_cfg):\r\n block_cfgs += [replace(cfg, d=1) for _ in range(cfg.d)]\r\n return block_cfgs\r\n\r\n\r\ndef num_groups(group_size, channels):\r\n if not group_size: # 0 or None\r\n return 1 # normal conv with 1 group\r\n else:\r\n # NOTE group_size == 1 -> depthwise conv\r\n assert channels % group_size == 0\r\n return channels // group_size\r\n\r\n\r\n@dataclass\r\nclass LayerFn:\r\n conv_norm_act: Callable = ConvBnAct\r\n norm_act: Callable = BatchNormAct2d\r\n act: Callable = nn.ReLU\r\n attn: Optional[Callable] = None\r\n self_attn: Optional[Callable] = None\r\n\r\n\r\nclass DownsampleAvg(nn.Module):\r\n def __init__(self, in_chs, out_chs, stride=1, dilation=1, apply_act=False, layers: LayerFn = None):\r\n \"\"\" AvgPool Downsampling as in 'D' ResNet variants.\"\"\"\r\n super(DownsampleAvg, self).__init__()\r\n layers = layers or LayerFn()\r\n avg_stride = stride if dilation == 1 else 1\r\n if stride > 1 or dilation > 1:\r\n avg_pool_fn = AvgPool2dSame if avg_stride == 1 and dilation > 1 else nn.AvgPool2d\r\n self.pool = avg_pool_fn(2, avg_stride, ceil_mode=True, count_include_pad=False)\r\n else:\r\n self.pool = nn.Identity()\r\n self.conv = layers.conv_norm_act(in_chs, out_chs, 1, apply_act=apply_act)\r\n\r\n def forward(self, x):\r\n return self.conv(self.pool(x))\r\n\r\n\r\ndef create_downsample(downsample_type, layers: LayerFn, **kwargs):\r\n if downsample_type == 'avg':\r\n return DownsampleAvg(**kwargs)\r\n else:\r\n return layers.conv_norm_act(kwargs.pop('in_chs'), kwargs.pop('out_chs'), kernel_size=1, **kwargs)\r\n\r\n\r\nclass BasicBlock(nn.Module):\r\n \"\"\" ResNet Basic Block - kxk + kxk\r\n \"\"\"\r\n\r\n def __init__(\r\n self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), group_size=None, bottle_ratio=1.0,\r\n downsample='avg', attn_last=True, linear_out=False, layers: LayerFn = None, drop_block=None,\r\n drop_path_rate=0.):\r\n super(BasicBlock, self).__init__()\r\n layers = layers or LayerFn()\r\n mid_chs = make_divisible(out_chs * bottle_ratio)\r\n groups = num_groups(group_size, mid_chs)\r\n\r\n if in_chs != out_chs or stride != 1 or dilation[0] != dilation[1]:\r\n self.shortcut = create_downsample(\r\n downsample, in_chs=in_chs, out_chs=out_chs, stride=stride, dilation=dilation[0],\r\n apply_act=False, layers=layers)\r\n else:\r\n self.shortcut = nn.Identity()\r\n\r\n self.conv1_kxk = layers.conv_norm_act(in_chs, mid_chs, kernel_size, stride=stride, dilation=dilation[0])\r\n self.attn = nn.Identity() if attn_last or layers.attn is None else layers.attn(mid_chs)\r\n self.conv2_kxk = layers.conv_norm_act(\r\n mid_chs, out_chs, kernel_size, dilation=dilation[1], groups=groups, drop_block=drop_block, apply_act=False)\r\n self.attn_last = nn.Identity() if not attn_last or layers.attn is None else layers.attn(out_chs)\r\n self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()\r\n self.act = nn.Identity() if linear_out else layers.act(inplace=True)\r\n\r\n def init_weights(self, zero_init_last: bool = False):\r\n if zero_init_last:\r\n nn.init.zeros_(self.conv2_kxk.bn.weight)\r\n for attn in (self.attn, self.attn_last):\r\n if hasattr(attn, 'reset_parameters'):\r\n attn.reset_parameters()\r\n\r\n def forward(self, x):\r\n shortcut = self.shortcut(x)\r\n\r\n # residual path\r\n x = self.conv1_kxk(x)\r\n x = self.conv2_kxk(x)\r\n x = self.attn(x)\r\n x = self.drop_path(x)\r\n\r\n x = self.act(x + shortcut)\r\n return x\r\n\r\n\r\nclass BottleneckBlock(nn.Module):\r\n \"\"\" ResNet-like Bottleneck Block - 1x1 - kxk - 1x1\r\n \"\"\"\r\n\r\n def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), bottle_ratio=1., group_size=None,\r\n downsample='avg', attn_last=False, linear_out=False, extra_conv=False, layers: LayerFn = None,\r\n drop_block=None, drop_path_rate=0.):\r\n super(BottleneckBlock, self).__init__()\r\n layers = layers or LayerFn()\r\n mid_chs = make_divisible(out_chs * bottle_ratio)\r\n groups = num_groups(group_size, mid_chs)\r\n\r\n if in_chs != out_chs or stride != 1 or dilation[0] != dilation[1]:\r\n self.shortcut = create_downsample(\r\n downsample, in_chs=in_chs, out_chs=out_chs, stride=stride, dilation=dilation[0],\r\n apply_act=False, layers=layers)\r\n else:\r\n self.shortcut = nn.Identity()\r\n\r\n self.conv1_1x1 = layers.conv_norm_act(in_chs, mid_chs, 1)\r\n self.conv2_kxk = layers.conv_norm_act(\r\n mid_chs, mid_chs, kernel_size, stride=stride, dilation=dilation[0],\r\n groups=groups, drop_block=drop_block)\r\n self.conv2_kxk = layers.conv_norm_act(\r\n mid_chs, mid_chs, kernel_size, stride=stride, dilation=dilation[0],\r\n groups=groups, drop_block=drop_block)\r\n if extra_conv:\r\n self.conv2b_kxk = layers.conv_norm_act(\r\n mid_chs, mid_chs, kernel_size, dilation=dilation[1], groups=groups, drop_block=drop_block)\r\n else:\r\n self.conv2b_kxk = nn.Identity()\r\n self.attn = nn.Identity() if attn_last or layers.attn is None else layers.attn(mid_chs)\r\n self.conv3_1x1 = layers.conv_norm_act(mid_chs, out_chs, 1, apply_act=False)\r\n self.attn_last = nn.Identity() if not attn_last or layers.attn is None else layers.attn(out_chs)\r\n self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()\r\n self.act = nn.Identity() if linear_out else layers.act(inplace=True)\r\n\r\n def init_weights(self, zero_init_last: bool = False):\r\n if zero_init_last:\r\n nn.init.zeros_(self.conv3_1x1.bn.weight)\r\n for attn in (self.attn, self.attn_last):\r\n if hasattr(attn, 'reset_parameters'):\r\n attn.reset_parameters()\r\n\r\n def forward(self, x):\r\n shortcut = self.shortcut(x)\r\n\r\n x = self.conv1_1x1(x)\r\n x = self.conv2_kxk(x)\r\n x = self.conv2b_kxk(x)\r\n x = self.attn(x)\r\n x = self.conv3_1x1(x)\r\n x = self.attn_last(x)\r\n x = self.drop_path(x)\r\n\r\n x = self.act(x + shortcut)\r\n return x\r\n\r\n\r\nclass DarkBlock(nn.Module):\r\n \"\"\" DarkNet-like (1x1 + 3x3 w/ stride) block\r\n\r\n The GE-Net impl included a 1x1 + 3x3 block in their search space. It was not used in the feature models.\r\n This block is pretty much a DarkNet block (also DenseNet) hence the name. Neither DarkNet or DenseNet\r\n uses strides within the block (external 3x3 or maxpool downsampling is done in front of the block repeats).\r\n\r\n If one does want to use a lot of these blocks w/ stride, I'd recommend using the EdgeBlock (3x3 /w stride + 1x1)\r\n for more optimal compute.\r\n \"\"\"\r\n\r\n def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), bottle_ratio=1.0, group_size=None,\r\n downsample='avg', attn_last=True, linear_out=False, layers: LayerFn = None, drop_block=None,\r\n drop_path_rate=0.):\r\n super(DarkBlock, self).__init__()\r\n layers = layers or LayerFn()\r\n mid_chs = make_divisible(out_chs * bottle_ratio)\r\n groups = num_groups(group_size, mid_chs)\r\n\r\n if in_chs != out_chs or stride != 1 or dilation[0] != dilation[1]:\r\n self.shortcut = create_downsample(\r\n downsample, in_chs=in_chs, out_chs=out_chs, stride=stride, dilation=dilation[0],\r\n apply_act=False, layers=layers)\r\n else:\r\n self.shortcut = nn.Identity()\r\n\r\n self.conv1_1x1 = layers.conv_norm_act(in_chs, mid_chs, 1)\r\n self.attn = nn.Identity() if attn_last or layers.attn is None else layers.attn(mid_chs)\r\n self.conv2_kxk = layers.conv_norm_act(\r\n mid_chs, out_chs, kernel_size, stride=stride, dilation=dilation[0],\r\n groups=groups, drop_block=drop_block, apply_act=False)\r\n self.attn_last = nn.Identity() if not attn_last or layers.attn is None else layers.attn(out_chs)\r\n self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()\r\n self.act = nn.Identity() if linear_out else layers.act(inplace=True)\r\n\r\n def init_weights(self, zero_init_last: bool = False):\r\n if zero_init_last:\r\n nn.init.zeros_(self.conv2_kxk.bn.weight)\r\n for attn in (self.attn, self.attn_last):\r\n if hasattr(attn, 'reset_parameters'):\r\n attn.reset_parameters()\r\n\r\n def forward(self, x):\r\n shortcut = self.shortcut(x)\r\n\r\n x = self.conv1_1x1(x)\r\n x = self.attn(x)\r\n x = self.conv2_kxk(x)\r\n x = self.attn_last(x)\r\n x = self.drop_path(x)\r\n x = self.act(x + shortcut)\r\n return x\r\n\r\n\r\nclass EdgeBlock(nn.Module):\r\n \"\"\" EdgeResidual-like (3x3 + 1x1) block\r\n\r\n A two layer block like DarkBlock, but with the order of the 3x3 and 1x1 convs reversed.\r\n Very similar to the EfficientNet Edge-Residual block but this block it ends with activations, is\r\n intended to be used with either expansion or bottleneck contraction, and can use DW/group/non-grouped convs.\r\n\r\n FIXME is there a more common 3x3 + 1x1 conv block to name this after?\r\n \"\"\"\r\n\r\n def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), bottle_ratio=1.0, group_size=None,\r\n downsample='avg', attn_last=False, linear_out=False, layers: LayerFn = None,\r\n drop_block=None, drop_path_rate=0.):\r\n super(EdgeBlock, self).__init__()\r\n layers = layers or LayerFn()\r\n mid_chs = make_divisible(out_chs * bottle_ratio)\r\n groups = num_groups(group_size, mid_chs)\r\n\r\n if in_chs != out_chs or stride != 1 or dilation[0] != dilation[1]:\r\n self.shortcut = create_downsample(\r\n downsample, in_chs=in_chs, out_chs=out_chs, stride=stride, dilation=dilation[0],\r\n apply_act=False, layers=layers)\r\n else:\r\n self.shortcut = nn.Identity()\r\n\r\n self.conv1_kxk = layers.conv_norm_act(\r\n in_chs, mid_chs, kernel_size, stride=stride, dilation=dilation[0],\r\n groups=groups, drop_block=drop_block)\r\n self.attn = nn.Identity() if attn_last or layers.attn is None else layers.attn(mid_chs)\r\n self.conv2_1x1 = layers.conv_norm_act(mid_chs, out_chs, 1, apply_act=False)\r\n self.attn_last = nn.Identity() if not attn_last or layers.attn is None else layers.attn(out_chs)\r\n self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()\r\n self.act = nn.Identity() if linear_out else layers.act(inplace=True)\r\n\r\n def init_weights(self, zero_init_last: bool = False):\r\n if zero_init_last:\r\n nn.init.zeros_(self.conv2_1x1.bn.weight)\r\n for attn in (self.attn, self.attn_last):\r\n if hasattr(attn, 'reset_parameters'):\r\n attn.reset_parameters()\r\n\r\n def forward(self, x):\r\n shortcut = self.shortcut(x)\r\n\r\n x = self.conv1_kxk(x)\r\n x = self.attn(x)\r\n x = self.conv2_1x1(x)\r\n x = self.attn_last(x)\r\n x = self.drop_path(x)\r\n x = self.act(x + shortcut)\r\n return x\r\n\r\n\r\nclass RepVggBlock(nn.Module):\r\n \"\"\" RepVGG Block.\r\n\r\n Adapted from impl at https://github.com/DingXiaoH/RepVGG\r\n\r\n This version does not currently support the deploy optimization. It is currently fixed in 'train' mode.\r\n \"\"\"\r\n\r\n def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), bottle_ratio=1.0, group_size=None,\r\n downsample='', layers: LayerFn = None, drop_block=None, drop_path_rate=0.):\r\n super(RepVggBlock, self).__init__()\r\n layers = layers or LayerFn()\r\n groups = num_groups(group_size, in_chs)\r\n\r\n use_ident = in_chs == out_chs and stride == 1 and dilation[0] == dilation[1]\r\n self.identity = layers.norm_act(out_chs, apply_act=False) if use_ident else None\r\n self.conv_kxk = layers.conv_norm_act(\r\n in_chs, out_chs, kernel_size, stride=stride, dilation=dilation[0],\r\n groups=groups, drop_block=drop_block, apply_act=False)\r\n self.conv_1x1 = layers.conv_norm_act(in_chs, out_chs, 1, stride=stride, groups=groups, apply_act=False)\r\n self.attn = nn.Identity() if layers.attn is None else layers.attn(out_chs)\r\n self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. and use_ident else nn.Identity()\r\n self.act = layers.act(inplace=True)\r\n\r\n def init_weights(self, zero_init_last: bool = False):\r\n # NOTE this init overrides that base model init with specific changes for the block type\r\n for m in self.modules():\r\n if isinstance(m, nn.BatchNorm2d):\r\n nn.init.normal_(m.weight, .1, .1)\r\n nn.init.normal_(m.bias, 0, .1)\r\n if hasattr(self.attn, 'reset_parameters'):\r\n self.attn.reset_parameters()\r\n\r\n def forward(self, x):\r\n if self.identity is None:\r\n x = self.conv_1x1(x) + self.conv_kxk(x)\r\n else:\r\n identity = self.identity(x)\r\n x = self.conv_1x1(x) + self.conv_kxk(x)\r\n x = self.drop_path(x) # not in the paper / official impl, experimental\r\n x = x + identity\r\n x = self.attn(x) # no attn in the paper / official impl, experimental\r\n x = self.act(x)\r\n return x\r\n\r\n\r\nclass SelfAttnBlock(nn.Module):\r\n \"\"\" ResNet-like Bottleneck Block - 1x1 - optional kxk - self attn - 1x1\r\n \"\"\"\r\n\r\n def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), bottle_ratio=1., group_size=None,\r\n downsample='avg', extra_conv=False, linear_out=False, post_attn_na=True, feat_size=None,\r\n layers: LayerFn = None, drop_block=None, drop_path_rate=0.):\r\n super(SelfAttnBlock, self).__init__()\r\n assert layers is not None\r\n mid_chs = make_divisible(out_chs * bottle_ratio)\r\n groups = num_groups(group_size, mid_chs)\r\n\r\n if in_chs != out_chs or stride != 1 or dilation[0] != dilation[1]:\r\n self.shortcut = create_downsample(\r\n downsample, in_chs=in_chs, out_chs=out_chs, stride=stride, dilation=dilation[0],\r\n apply_act=False, layers=layers)\r\n else:\r\n self.shortcut = nn.Identity()\r\n\r\n self.conv1_1x1 = layers.conv_norm_act(in_chs, mid_chs, 1)\r\n if extra_conv:\r\n self.conv2_kxk = layers.conv_norm_act(\r\n mid_chs, mid_chs, kernel_size, stride=stride, dilation=dilation[0],\r\n groups=groups, drop_block=drop_block)\r\n stride = 1 # striding done via conv if enabled\r\n else:\r\n self.conv2_kxk = nn.Identity()\r\n opt_kwargs = {} if feat_size is None else dict(feat_size=feat_size)\r\n # FIXME need to dilate self attn to have dilated network support, moop moop\r\n self.self_attn = layers.self_attn(mid_chs, stride=stride, **opt_kwargs)\r\n self.post_attn = layers.norm_act(mid_chs) if post_attn_na else nn.Identity()\r\n self.conv3_1x1 = layers.conv_norm_act(mid_chs, out_chs, 1, apply_act=False)\r\n self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()\r\n self.act = nn.Identity() if linear_out else layers.act(inplace=True)\r\n\r\n def init_weights(self, zero_init_last: bool = False):\r\n if zero_init_last:\r\n nn.init.zeros_(self.conv3_1x1.bn.weight)\r\n if hasattr(self.self_attn, 'reset_parameters'):\r\n self.self_attn.reset_parameters()\r\n\r\n def forward(self, x):\r\n shortcut = self.shortcut(x)\r\n\r\n x = self.conv1_1x1(x)\r\n x = self.conv2_kxk(x)\r\n x = self.self_attn(x)\r\n x = self.post_attn(x)\r\n x = self.conv3_1x1(x)\r\n x = self.drop_path(x)\r\n\r\n x = self.act(x + shortcut)\r\n return x\r\n\r\n\r\n_block_registry = dict(\r\n basic=BasicBlock,\r\n bottle=BottleneckBlock,\r\n dark=DarkBlock,\r\n edge=EdgeBlock,\r\n rep=RepVggBlock,\r\n self_attn=SelfAttnBlock,\r\n)\r\n\r\n\r\ndef register_block(block_type:str, block_fn: nn.Module):\r\n _block_registry[block_type] = block_fn\r\n\r\n\r\ndef create_block(block: Union[str, nn.Module], **kwargs):\r\n if isinstance(block, (nn.Module, partial)):\r\n return block(**kwargs)\r\n assert block in _block_registry, f'Unknown block type ({block}'\r\n return _block_registry[block](**kwargs)\r\n\r\n\r\nclass Stem(nn.Sequential):\r\n\r\n def __init__(self, in_chs, out_chs, kernel_size=3, stride=4, pool='maxpool',\r\n num_rep=3, num_act=None, chs_decay=0.5, layers: LayerFn = None):\r\n super().__init__()\r\n assert stride in (2, 4)\r\n layers = layers or LayerFn()\r\n\r\n if isinstance(out_chs, (list, tuple)):\r\n num_rep = len(out_chs)\r\n stem_chs = out_chs\r\n else:\r\n stem_chs = [round(out_chs * chs_decay ** i) for i in range(num_rep)][::-1]\r\n\r\n self.stride = stride\r\n self.feature_info = [] # track intermediate features\r\n prev_feat = ''\r\n stem_strides = [2] + [1] * (num_rep - 1)\r\n if stride == 4 and not pool:\r\n # set last conv in stack to be strided if stride == 4 and no pooling layer\r\n stem_strides[-1] = 2\r\n\r\n num_act = num_rep if num_act is None else num_act\r\n # if num_act < num_rep, first convs in stack won't have bn + act\r\n stem_norm_acts = [False] * (num_rep - num_act) + [True] * num_act\r\n prev_chs = in_chs\r\n curr_stride = 1\r\n for i, (ch, s, na) in enumerate(zip(stem_chs, stem_strides, stem_norm_acts)):\r\n layer_fn = layers.conv_norm_act if na else create_conv2d\r\n conv_name = f'conv{i + 1}'\r\n if i > 0 and s > 1:\r\n self.feature_info.append(dict(num_chs=prev_chs, reduction=curr_stride, module=prev_feat))\r\n self.add_module(conv_name, layer_fn(prev_chs, ch, kernel_size=kernel_size, stride=s))\r\n prev_chs = ch\r\n curr_stride *= s\r\n prev_feat = conv_name\r\n\r\n if pool and 'max' in pool.lower():\r\n self.feature_info.append(dict(num_chs=prev_chs, reduction=curr_stride, module=prev_feat))\r\n self.add_module('pool', nn.MaxPool2d(3, 2, 1))\r\n curr_stride *= 2\r\n prev_feat = 'pool'\r\n\r\n self.feature_info.append(dict(num_chs=prev_chs, reduction=curr_stride, module=prev_feat))\r\n assert curr_stride == stride\r\n\r\n\r\ndef create_byob_stem(in_chs, out_chs, stem_type='', pool_type='', feat_prefix='stem', layers: LayerFn = None):\r\n layers = layers or LayerFn()\r\n assert stem_type in ('', 'quad', 'quad2', 'tiered', 'deep', 'rep', '7x7', '3x3')\r\n if 'quad' in stem_type:\r\n # based on NFNet stem, stack of 4 3x3 convs\r\n num_act = 2 if 'quad2' in stem_type else None\r\n stem = Stem(in_chs, out_chs, num_rep=4, num_act=num_act, pool=pool_type, layers=layers)\r\n elif 'tiered' in stem_type:\r\n # 3x3 stack of 3 convs as in my ResNet-T\r\n stem = Stem(in_chs, (3 * out_chs // 8, out_chs // 2, out_chs), pool=pool_type, layers=layers)\r\n elif 'deep' in stem_type:\r\n # 3x3 stack of 3 convs as in ResNet-D\r\n stem = Stem(in_chs, out_chs, num_rep=3, chs_decay=1.0, pool=pool_type, layers=layers)\r\n elif 'rep' in stem_type:\r\n stem = RepVggBlock(in_chs, out_chs, stride=2, layers=layers)\r\n elif '7x7' in stem_type:\r\n # 7x7 stem conv as in ResNet\r\n if pool_type:\r\n stem = Stem(in_chs, out_chs, 7, num_rep=1, pool=pool_type, layers=layers)\r\n else:\r\n stem = layers.conv_norm_act(in_chs, out_chs, 7, stride=2)\r\n else:\r\n # 3x3 stem conv as in RegNet is the default\r\n if pool_type:\r\n stem = Stem(in_chs, out_chs, 3, num_rep=1, pool=pool_type, layers=layers)\r\n else:\r\n stem = layers.conv_norm_act(in_chs, out_chs, 3, stride=2)\r\n\r\n if isinstance(stem, Stem):\r\n feature_info = [dict(f, module='.'.join([feat_prefix, f['module']])) for f in stem.feature_info]\r\n else:\r\n feature_info = [dict(num_chs=out_chs, reduction=2, module=feat_prefix)]\r\n return stem, feature_info\r\n\r\n\r\ndef reduce_feat_size(feat_size, stride=2):\r\n return None if feat_size is None else tuple([s // stride for s in feat_size])\r\n\r\n\r\ndef override_kwargs(block_kwargs, model_kwargs):\r\n \"\"\" Override model level attn/self-attn/block kwargs w/ block level\r\n\r\n NOTE: kwargs are NOT merged across levels, block_kwargs will fully replace model_kwargs\r\n for the block if set to anything that isn't None.\r\n\r\n i.e. an empty block_kwargs dict will remove kwargs set at model level for that block\r\n \"\"\"\r\n out_kwargs = block_kwargs if block_kwargs is not None else model_kwargs\r\n return out_kwargs or {} # make sure None isn't returned\r\n\r\n\r\ndef update_block_kwargs(block_kwargs: Dict[str, Any], block_cfg: ByoBlockCfg, model_cfg: ByoModelCfg, ):\r\n layer_fns = block_kwargs['layers']\r\n\r\n # override attn layer / args with block local config\r\n attn_set = block_cfg.attn_layer is not None\r\n if attn_set or block_cfg.attn_kwargs is not None:\r\n # override attn layer config\r\n if attn_set and not block_cfg.attn_layer:\r\n # empty string for attn_layer type will disable attn for this block\r\n attn_layer = None\r\n else:\r\n attn_kwargs = override_kwargs(block_cfg.attn_kwargs, model_cfg.attn_kwargs)\r\n attn_layer = block_cfg.attn_layer or model_cfg.attn_layer\r\n attn_layer = partial(get_attn(attn_layer), **attn_kwargs) if attn_layer is not None else None\r\n layer_fns = replace(layer_fns, attn=attn_layer)\r\n\r\n # override self-attn layer / args with block local cfg\r\n self_attn_set = block_cfg.self_attn_layer is not None\r\n if self_attn_set or block_cfg.self_attn_kwargs is not None:\r\n # override attn layer config\r\n if self_attn_set and not block_cfg.self_attn_layer: # attn_layer == ''\r\n # empty string for self_attn_layer type will disable attn for this block\r\n self_attn_layer = None\r\n else:\r\n self_attn_kwargs = override_kwargs(block_cfg.self_attn_kwargs, model_cfg.self_attn_kwargs)\r\n self_attn_layer = block_cfg.self_attn_layer or model_cfg.self_attn_layer\r\n self_attn_layer = partial(get_attn(self_attn_layer), **self_attn_kwargs) \\\r\n if self_attn_layer is not None else None\r\n layer_fns = replace(layer_fns, self_attn=self_attn_layer)\r\n\r\n block_kwargs['layers'] = layer_fns\r\n\r\n # add additional block_kwargs specified in block_cfg or model_cfg, precedence to block if set\r\n block_kwargs.update(override_kwargs(block_cfg.block_kwargs, model_cfg.block_kwargs))\r\n\r\n\r\ndef create_byob_stages(\r\n cfg: ByoModelCfg, drop_path_rate: float, output_stride: int, stem_feat: Dict[str, Any],\r\n feat_size: Optional[int] = None,\r\n layers: Optional[LayerFn] = None,\r\n block_kwargs_fn: Optional[Callable] = update_block_kwargs):\r\n\r\n layers = layers or LayerFn()\r\n feature_info = []\r\n block_cfgs = [expand_blocks_cfg(s) for s in cfg.blocks]\r\n depths = [sum([bc.d for bc in stage_bcs]) for stage_bcs in block_cfgs]\r\n dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(depths)).split(depths)]\r\n dilation = 1\r\n net_stride = stem_feat['reduction']\r\n prev_chs = stem_feat['num_chs']\r\n prev_feat = stem_feat\r\n stages = []\r\n for stage_idx, stage_block_cfgs in enumerate(block_cfgs):\r\n stride = stage_block_cfgs[0].s\r\n if stride != 1 and prev_feat:\r\n feature_info.append(prev_feat)\r\n if net_stride >= output_stride and stride > 1:\r\n dilation *= stride\r\n stride = 1\r\n net_stride *= stride\r\n first_dilation = 1 if dilation in (1, 2) else 2\r\n\r\n blocks = []\r\n for block_idx, block_cfg in enumerate(stage_block_cfgs):\r\n out_chs = make_divisible(block_cfg.c * cfg.width_factor)\r\n group_size = block_cfg.gs\r\n if isinstance(group_size, Callable):\r\n group_size = group_size(out_chs, block_idx)\r\n block_kwargs = dict( # Blocks used in this model must accept these arguments\r\n in_chs=prev_chs,\r\n out_chs=out_chs,\r\n stride=stride if block_idx == 0 else 1,\r\n dilation=(first_dilation, dilation),\r\n group_size=group_size,\r\n bottle_ratio=block_cfg.br,\r\n downsample=cfg.downsample,\r\n drop_path_rate=dpr[stage_idx][block_idx],\r\n layers=layers,\r\n )\r\n if block_cfg.type in ('self_attn',):\r\n # add feat_size arg for blocks that support/need it\r\n block_kwargs['feat_size'] = feat_size\r\n block_kwargs_fn(block_kwargs, block_cfg=block_cfg, model_cfg=cfg)\r\n blocks += [create_block(block_cfg.type, **block_kwargs)]\r\n first_dilation = dilation\r\n prev_chs = out_chs\r\n if stride > 1 and block_idx == 0:\r\n feat_size = reduce_feat_size(feat_size, stride)\r\n\r\n stages += [nn.Sequential(*blocks)]\r\n prev_feat = dict(num_chs=prev_chs, reduction=net_stride, module=f'stages.{stage_idx}')\r\n\r\n feature_info.append(prev_feat)\r\n return nn.Sequential(*stages), feature_info\r\n\r\n\r\ndef get_layer_fns(cfg: ByoModelCfg):\r\n act = get_act_layer(cfg.act_layer)\r\n norm_act = convert_norm_act(norm_layer=cfg.norm_layer, act_layer=act)\r\n conv_norm_act = partial(ConvBnAct, norm_layer=cfg.norm_layer, act_layer=act)\r\n attn = partial(get_attn(cfg.attn_layer), **cfg.attn_kwargs) if cfg.attn_layer else None\r\n self_attn = partial(get_attn(cfg.self_attn_layer), **cfg.self_attn_kwargs) if cfg.self_attn_layer else None\r\n layer_fn = LayerFn(conv_norm_act=conv_norm_act, norm_act=norm_act, act=act, attn=attn, self_attn=self_attn)\r\n return layer_fn\r\n\r\n\r\nclass ByobNet(nn.Module):\r\n \"\"\" 'Bring-your-own-blocks' Net\r\n\r\n A flexible network backbone that allows building model stem + blocks via\r\n dataclass cfg definition w/ factory functions for module instantiation.\r\n\r\n Current assumption is that both stem and blocks are in conv-bn-act order (w/ block ending in act).\r\n \"\"\"\r\n def __init__(self, cfg: ByoModelCfg, num_classes=1000, in_chans=3, global_pool='avg', output_stride=32,\r\n zero_init_last=True, img_size=None, drop_rate=0., drop_path_rate=0.):\r\n super().__init__()\r\n self.num_classes = num_classes\r\n self.drop_rate = drop_rate\r\n layers = get_layer_fns(cfg)\r\n if cfg.fixed_input_size:\r\n assert img_size is not None, 'img_size argument is required for fixed input size model'\r\n feat_size = to_2tuple(img_size) if img_size is not None else None\r\n\r\n self.feature_info = []\r\n stem_chs = int(round((cfg.stem_chs or cfg.blocks[0].c) * cfg.width_factor))\r\n self.stem, stem_feat = create_byob_stem(in_chans, stem_chs, cfg.stem_type, cfg.stem_pool, layers=layers)\r\n self.feature_info.extend(stem_feat[:-1])\r\n feat_size = reduce_feat_size(feat_size, stride=stem_feat[-1]['reduction'])\r\n\r\n self.stages, stage_feat = create_byob_stages(\r\n cfg, drop_path_rate, output_stride, stem_feat[-1], layers=layers, feat_size=feat_size)\r\n self.feature_info.extend(stage_feat[:-1])\r\n\r\n prev_chs = stage_feat[-1]['num_chs']\r\n if cfg.num_features:\r\n self.num_features = int(round(cfg.width_factor * cfg.num_features))\r\n self.final_conv = layers.conv_norm_act(prev_chs, self.num_features, 1)\r\n else:\r\n self.num_features = prev_chs\r\n self.final_conv = nn.Identity()\r\n self.feature_info += [\r\n dict(num_chs=self.num_features, reduction=stage_feat[-1]['reduction'], module='final_conv')]\r\n\r\n self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate)\r\n\r\n # init weights\r\n named_apply(partial(_init_weights, zero_init_last=zero_init_last), self)\r\n\r\n def get_classifier(self):\r\n return self.head.fc\r\n\r\n def reset_classifier(self, num_classes, global_pool='avg'):\r\n self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate)\r\n\r\n def forward_features(self, x):\r\n x = self.stem(x)\r\n x = self.stages(x)\r\n x = self.final_conv(x)\r\n return x\r\n\r\n def forward(self, x):\r\n x = self.forward_features(x)\r\n x = self.head(x)\r\n return x\r\n\r\n\r\ndef _init_weights(module, name='', zero_init_last=False):\r\n if isinstance(module, nn.Conv2d):\r\n fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels\r\n fan_out //= module.groups\r\n module.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\r\n if module.bias is not None:\r\n module.bias.data.zero_()\r\n elif isinstance(module, nn.Linear):\r\n nn.init.normal_(module.weight, mean=0.0, std=0.01)\r\n if module.bias is not None:\r\n nn.init.zeros_(module.bias)\r\n elif isinstance(module, nn.BatchNorm2d):\r\n nn.init.ones_(module.weight)\r\n nn.init.zeros_(module.bias)\r\n elif hasattr(module, 'init_weights'):\r\n module.init_weights(zero_init_last=zero_init_last)\r\n\r\n\r\ndef _create_byobnet(variant, pretrained=False, **kwargs):\r\n return build_model_with_cfg(\r\n ByobNet, variant, pretrained,\r\n default_cfg=default_cfgs[variant],\r\n model_cfg=model_cfgs[variant],\r\n feature_cfg=dict(flatten_sequential=True),\r\n **kwargs)\r\n" ]
[ [ "torch.nn.MaxPool2d", "torch.nn.init.normal_", "torch.nn.init.ones_", "torch.nn.Identity", "torch.nn.Sequential", "torch.nn.init.zeros_" ] ]
whn09/incubator-tvm
[ "657a6fa6554cc8402eca225f80e1b2cc2803c71a" ]
[ "tests/python/relay/test_op_level3.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level3 operator test cases.\n\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nfrom tvm import te\nfrom tvm import relay\nfrom tvm.error import TVMError\nfrom tvm.relay import create_executor, transform\nfrom tvm.relay.testing import check_grad, run_infer_type\nimport tvm.testing\n\n\ndef test_zeros_ones():\n for op, ref in [(relay.zeros, np.zeros), (relay.ones, np.ones)]:\n y = op(shape=(124, 50), dtype=\"float64\")\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((124, 50), \"float64\")\n intrp = create_executor()\n intrp_res = intrp.evaluate(y).asnumpy()\n np.testing.assert_allclose(intrp_res, ref((124, 50), 'float64'))\n\ndef test_unary_identity():\n for op, ref in [(relay.zeros_like, np.zeros_like),\n (relay.ones_like, np.ones_like),\n (relay.ceil, np.ceil),\n (relay.floor, np.floor),\n (relay.trunc, np.trunc),\n (relay.round, np.round),\n (relay.abs, np.abs),\n (relay.copy, None), # np.copy\n (relay.negative, np.negative),\n (relay.sign, np.sign)]:\n shape = (8, 9, 4)\n x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n y = op(x)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(shape, \"float32\")\n\n if ref is not None:\n data = np.random.rand(*shape).astype('float32')\n intrp = create_executor()\n op_res = intrp.evaluate(y, { x: relay.const(data) })\n ref_res = ref(data)\n np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=0.01)\n\ndef test_cast():\n x = relay.var(\"x\", relay.TensorType((8, 9, 4), \"float32\"))\n y = x.astype(\"int32\")\n yy = run_infer_type(y)\n assert \"dtype=\" in yy.astext()\n assert yy.checked_type == relay.TensorType((8, 9, 4), \"int32\")\n\n x = relay.var(\"x\", relay.TensorType((8, 9, 4), \"float32\"))\n y = relay.cast(x, \"int32\")\n yy = run_infer_type(y)\n assert \"dtype=\" in yy.astext()\n assert yy.checked_type == relay.TensorType((8, 9, 4), \"int32\")\n\n\ndef test_clip():\n a = relay.var(\"a\", relay.TensorType((10, 4), \"float32\"))\n y = relay.clip(a, 1., 4.)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((10, 4), \"float32\")\n\n data = np.random.rand(10, 4).astype('float32')\n intrp = create_executor()\n op_res = intrp.evaluate(y, { a: relay.const(data) })\n ref_res = np.clip(data, 1., 4.)\n np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=0.01)\n\ndef test_fixed_point_multiply():\n # Test 23 * 1/16\n # [m,s] = [0.5, -3] = frexp(1/16)\n # M = 0.5*2^31 = 1073741824\n # so M = 1073741824 and s = -3\n\n a = relay.var(\"a\", relay.TensorType((10, 4), \"int32\"))\n y = relay.fixed_point_multiply(a, 1073741824, -3)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((10, 4), \"int32\")\n\n data = 23*np.ones((10, 4)).astype('int32')\n intrp = create_executor()\n op_res = intrp.evaluate(y, { a: relay.const(data) })\n ref_res = np.ones((10, 4)).astype('int32')\n np.testing.assert_allclose(op_res.asnumpy(), ref_res, atol=1)\n\ndef test_reinterpret():\n a = relay.var(\"a\", relay.TensorType((1000, 4), \"float32\"))\n y = relay.reinterpret(a, \"int32\")\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((1000, 4), \"int32\")\n\n data = np.random.randn(1000, 4).astype('float32') * 1000\n intrp = create_executor()\n op_res = intrp.evaluate(y, {a: relay.const(data)})\n ref_res = data.view(\"int32\")\n np.testing.assert_equal(op_res.asnumpy(), ref_res)\n\n\ndef test_approximate_transcendental():\n def C(x):\n return relay.expr.const(x, \"float32\")\n\n def approx_exp(x):\n # An approximation derived from Opus,\n # https://github.com/xiph/opus/blob/c1c247/celt/mathops.h#L147-L165\n x = relay.minimum(relay.maximum(x, C(-88.0)), C(88.0))\n x = C(127.0) + x * C(1.44269504)\n xf = relay.floor(x)\n i = relay.cast(xf, \"int32\")\n x = x - xf\n Y = C(0.99992522) + x * (C(0.69583354) + x * (C(0.22606716) + x * C(0.078024523)))\n exponent = relay.left_shift(i, relay.expr.const(23, \"int32\"))\n exponent = relay.reinterpret(exponent, \"float32\")\n return exponent * Y\n\n def approximate_sigmoid(x):\n y = approx_exp(x)\n return y / (y + C(1.0))\n\n def approximate_tanh(x):\n x = x * C(2.0)\n y = approx_exp(x)\n return (y - C(1.0)) / (y + C(1.0))\n\n a = relay.var(\"a\", relay.TensorType((1000,), \"float32\"))\n y = approximate_sigmoid(a)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((1000,), \"float32\")\n data = np.linspace(-5, 5, 1000).astype(\"float32\")\n intrp = create_executor()\n op_res = intrp.evaluate(y, {a: relay.const(data)})\n\n def reference_sigmoid(x):\n return np.exp(-np.logaddexp(0, -x))\n np.testing.assert_allclose(op_res.asnumpy(), reference_sigmoid(data), atol=2e-5, rtol=1e-9)\n\n y = approximate_tanh(a)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((1000,), \"float32\")\n data = np.linspace(-5, 5, 1000).astype(\"float32\")\n intrp = create_executor()\n op_res = intrp.evaluate(y, {a: relay.const(data)})\n\n def reference_tanh(x):\n return np.tanh(x)\n np.testing.assert_allclose(op_res.asnumpy(), reference_tanh(data), atol=4e-5, rtol=1e-9)\n\n\ndef test_squeeze():\n def verify_squeeze(shape, dtype, axis):\n x = relay.var(\"x\", relay.TensorType(shape, dtype))\n squeeze = relay.squeeze(x, axis=axis)\n\n np_axis = tuple(axis) if axis is not None else None\n\n data = np.random.random_sample(shape).astype(dtype)\n intrp = create_executor()\n op_res = intrp.evaluate(squeeze, { x : relay.const(data) })\n ref_res = np.squeeze(data, axis=np_axis)\n np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=0.01)\n\n verify_squeeze((1, 3, 2, 5), \"float32\", None)\n verify_squeeze((1, 3, 1), \"float32\", [0])\n verify_squeeze((1, 2, 1, 2, 1), \"float32\", [0, 2])\n\n\ndef test_transpose_infer_type():\n n, t, d = te.size_var(\"n\"), te.size_var(\"t\"), 100\n x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n y = relay.transpose(x, axes=(1, 0, 2))\n assert \"axes=\" in y.astext()\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(\n (t, n, 100), \"float32\")\n\n y = relay.transpose(x)\n assert \"axes=\" in y.astext()\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(\n (100, t, n), \"float32\")\n\n\[email protected]_gpu\ndef test_transpose():\n def verify_transpose(dshape, axes):\n x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n z = relay.transpose(x, axes=axes)\n\n func = relay.Function([x], z)\n x_data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n ref_res = np.transpose(x_data, axes=axes)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_transpose((2, 3, 4), (0, 2, 1))\n\n\ndef test_squeeze_infer_type():\n n, t, d = 1, 4, 1\n x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n y = relay.squeeze(x, axis=(2,))\n assert \"axis=\" in y.astext()\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(\n (1, 4), \"float32\")\n\n n, t, d = 1, 4, 1\n x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n y = relay.squeeze(x)\n assert \"axis=\" not in y.astext()\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(\n (4,), \"float32\")\n\[email protected](raises=tvm._ffi.base.TVMError)\ndef test_squeeze_bad_axes_infer_type():\n n, t, d = 1, 4, 1\n x = relay.var(\"x\", relay.TensorType((n, t, d), \"float32\"))\n y = relay.squeeze(x, axis=(1,))\n yy = run_infer_type(y)\n\n\ndef test_reshape_infer_type():\n n, t, d1, d2 = 10, 20, 100, 20\n x = relay.var(\"x\", relay.TensorType((n, t, d1, d2), \"float32\"))\n y = relay.reshape(x, newshape=(n, t, 2000))\n assert \"newshape=\" in y.astext()\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(\n (n, t, 2000), \"float32\")\n\[email protected]_gpu\ndef test_reshape():\n def verify_reshape(shape, newshape, oshape):\n x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n z = relay.reshape(x, newshape=newshape)\n zz = run_infer_type(z)\n assert \"newshape=\" in z.astext()\n assert zz.checked_type == relay.ty.TensorType(oshape, \"float32\")\n\n func = relay.Function([x], z)\n check_grad(func)\n x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n ref_res = np.reshape(x_data, oshape)\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_reshape((2, 3, 4), (8, 3), (8, 3))\n verify_reshape((4, 7), (2, 7, 2), (2, 7, 2))\n verify_reshape((2, 3, 4), (4, 0, 2), (4, 3, 2))\n verify_reshape((2, 3, 4), (2, 0, 0), (2, 3, 4))\n verify_reshape((2, 3, 4), (0, -1), (2, 12))\n verify_reshape((2, 3, 4), (-1, 0), (8, 3))\n verify_reshape((2, 3, 4), (2, -2), (2, 3, 4))\n verify_reshape((2, 3, 4), (-2, 1, 1), (2, 3, 4, 1, 1))\n verify_reshape((2, 3, 4), (-3, 4), (6, 4))\n verify_reshape((2, 3, 4, 5), (-3, -3), (6, 20))\n verify_reshape((2, 3, 4), (0, -3), (2, 12))\n verify_reshape((2, 3, 4), (-3, -2), (6, 4))\n verify_reshape((2, 3, 4), (-4, 1, 2, -2), (1, 2, 3, 4))\n verify_reshape((2, 3, 4), (2, -4, -1, 3, -2), (2, 1, 3, 4))\n\n\ndef test_reshape_fail():\n with pytest.raises(TVMError) as reshape_err:\n x = relay.var(\"x\", relay.TensorType([2,3], \"float32\"))\n z = relay.reshape(x, [7])\n zz = run_infer_type(z)\n\n\ndef test_reshape_like_infer_type():\n # concrete shape\n x = relay.var(\"x\", relay.TensorType((1, 2, 3), \"float32\"))\n y = relay.var(\"y\", relay.TensorType((1,6), \"float32\"))\n z = relay.reshape_like(x, y)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.TensorType((1, 6), \"float32\")\n\n # symbolic shape\n n, c, h, w = te.size_var(\"n\"), 2, 3, te.size_var(\"w\")\n x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n y = relay.var(\"y\", relay.TensorType((1, 8, 8), \"float32\"))\n z = relay.reshape_like(x, y)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.TensorType((1, 8, 8), \"float32\")\n\n\[email protected]_gpu\ndef test_reshape_like():\n def verify_reshape_like(shape, oshape):\n x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n y_data = np.random.uniform(low=-1, high=1, size=oshape).astype(\"float32\")\n ref_res = np.reshape(x_data, y_data.shape)\n\n x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n y = relay.var(\"x\", relay.TensorType(oshape, \"float32\"))\n z = relay.reshape_like(x, y)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.ty.TensorType(ref_res.shape, \"float32\")\n\n func = relay.Function([x, y], z)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data, y_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n\n verify_reshape_like((2, 3, 4), (1, 8, 3))\n verify_reshape_like((4, 7), (2, 7, 2))\n\ndef test_take_infer_type():\n def verify_take(dshape, indices_shape, oshape, axis=None):\n x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n indices = relay.var(\"indices\", relay.TensorType(indices_shape, \"int32\"))\n y = relay.take(x, indices, axis=axis)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(oshape, \"float32\")\n\n d1, d2, d3 = te.var(\"d1\"), te.var(\"d2\"), te.var(\"d3\")\n d4, d5, d6 = te.var(\"d4\"), te.var(\"d5\"), te.var(\"d6\")\n verify_take((d1,), (1,), (1,), 0)\n verify_take((4,), (d1, d2), (d1, d2))\n verify_take((3, 3, 3), (1, d2), (1, d2))\n verify_take((d1, d2), (d3, d4, d5), (d3, d4, d5, d2), 0)\n verify_take((d1, d2), (d3, d4, d5), (d1, d3, d4, d5), 1)\n verify_take((d1, d2, d3, d4), (d5, d6), (d1, d2, d5, d6, d4), -2)\n\[email protected]_gpu\ndef test_take():\n def verify_take(src_shape, indices_src, axis=None, mode=\"clip\"):\n src_dtype = \"float32\"\n indices_dtype = \"int32\"\n indices_src = np.array(indices_src, dtype=indices_dtype)\n x = relay.var(\"x\", relay.TensorType(src_shape, src_dtype))\n indices = relay.var(\"indices\", relay.TensorType(indices_src.shape, indices_dtype))\n z = relay.take(x, indices, axis=axis, mode=mode)\n\n func = relay.Function([x, indices], z)\n x_data = np.random.uniform(low=-1, high=1, size=src_shape).astype(src_dtype)\n np_mode = \"raise\" if mode == \"fast\" else mode\n ref_res = np.take(x_data, indices=indices_src, axis=axis, mode=np_mode)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data, indices_src)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n\n verify_take((4,), [1])\n verify_take((4,), [[0,1,2,3]])\n verify_take((3,3,3), [[11,25]])\n verify_take((4,), [[0,1],[2,3]])\n verify_take((4,), [1], 0)\n verify_take((2,2), [[[1,0],[0,1]]], 0)\n verify_take((2,2), [[[1,0],[0,1]]], 1)\n verify_take((4,3,5,6), [[2,1,0,0]], -2)\n verify_take((3,4), [-5, 20])\n verify_take((3,4), [-5, 20], mode=\"wrap\")\n verify_take((3,4), [-1, 2], axis=0)\n verify_take((3,4), [-1, 2], axis=0, mode=\"wrap\")\n verify_take((3,4), [-1, 2], axis=1)\n verify_take((3,4), [-1, 2], axis=1, mode=\"wrap\")\n verify_take((3,3,3), [[11,25]], mode=\"fast\")\n verify_take((3,4), [0, 2], axis=0, mode=\"fast\")\n verify_take((3,4), [0, 2], axis=1, mode=\"fast\")\n\n\ndef test_split_infer_type():\n def verify_split(dshape, indices_or_sections, ret_type, axis=None):\n x = relay.var(\"x\", relay.ty.TensorType(dshape, \"float32\"))\n y = relay.split(x, indices_or_sections, axis=axis)\n yy = run_infer_type(y.astuple())\n assert yy.checked_type == ret_type\n\n idxd = tvm.tir.indexdiv\n\n d1, d2, d3, d4 = te.var(\"d1\"), te.var(\"d2\"), te.var(\"d3\"), te.var(\"d4\")\n axis = te.var(\"axis\")\n verify_split((5, 5, 2, 2), 5,\n relay.ty.TupleType(tvm.runtime.convert([\n relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n relay.ty.TensorType((5, 1, 2, 2), \"float32\"),\n relay.ty.TensorType((5, 1, 2, 2), \"float32\")])),\n axis=1)\n verify_split((5, 5, 2, 2), 5,\n relay.ty.TupleType(tvm.runtime.convert([\n relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n relay.ty.TensorType((1, 5, 2, 2), \"float32\"),\n relay.ty.TensorType((1, 5, 2, 2), \"float32\")])),\n axis=0)\n verify_split((d1, d2, d3, d4), 4,\n relay.ty.TupleType(tvm.runtime.convert([\n relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\"),\n relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\"),\n relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\"),\n relay.ty.TensorType((d1, d2, idxd(d3, 4), d4), \"float32\")])),\n axis=2)\n verify_split((d1, d2, d3, d4), 2,\n relay.ty.TupleType(tvm.runtime.convert([\n relay.ty.TensorType((idxd(d1, 2), d2, d3, d4), \"float32\"),\n relay.ty.TensorType((idxd(d1, 2), d2, d3, d4), \"float32\")])),\n axis=0)\n verify_split((d1, d2, d3, d4), (2, 4, 7),\n relay.ty.TupleType(tvm.runtime.convert([\n relay.ty.TensorType((d1, 2, d3, d4), \"float32\"),\n relay.ty.TensorType((d1, 2, d3, d4), \"float32\"),\n relay.ty.TensorType((d1, 3, d3, d4), \"float32\"),\n relay.ty.TensorType((d1, (d2-7), d3, d4), \"float32\")])),\n axis=1)\n\ndef test_full_infer_type():\n # default settings: match input dtype\n x = relay.var(\"x\", relay.TensorType((), \"int8\"))\n y = relay.full(x, ())\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((), \"int8\")\n\n # change the shape and dtype\n x = relay.var(\"x\", relay.TensorType((), \"float32\"))\n y = relay.full(x, (1, 2), \"int8\")\n \"shape=\" in y.astext()\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((1, 2), \"int8\")\n\n\[email protected]_gpu\ndef test_full():\n def verify_full(fill_value, src_shape, dtype):\n x = relay.var(\"x\", relay.scalar_type(dtype))\n z = relay.full(x, src_shape, dtype)\n func = relay.Function([x], z)\n ref_res = np.full(src_shape, fill_value)\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(np.array(fill_value, dtype))\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_full(4, (1, 3, 4, 4), \"int32\")\n #verify_full(4, (1, 3, 4, 4), \"int64\") # This does not pass, python int32 is not upcast to int64, not sure how to fix it.\n verify_full(4.0, (1, 4), \"float32\")\n\n\ndef test_full_like_infer_type():\n # concrete shape\n base = relay.var(\"base\", relay.TensorType((1, 2, 3), \"float32\"))\n fill = relay.var(\"fill\", relay.TensorType((), \"float32\"))\n y = relay.full_like(base, fill)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((1, 2, 3), \"float32\")\n\n # symbolic shape\n n, c, h, w = te.size_var(\"n\"), 2, 3, te.size_var(\"w\")\n base = relay.var(\"base\", relay.TensorType((n, c, h, w), \"float32\"))\n fill = relay.var(\"fill\", relay.TensorType((), \"float32\"))\n y = relay.full_like(base, fill)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((n, c, h, w), \"float32\")\n\n\[email protected]_gpu\ndef test_full_like():\n def verify_full_like(base, fill_value, dtype):\n x_data = np.random.uniform(low=-1, high=1, size=base).astype(dtype)\n x = relay.var(\"x\", relay.TensorType(base, dtype))\n y = relay.var(\"y\", relay.scalar_type(dtype))\n z = relay.full_like(x, y)\n\n func = relay.Function([x, y], z)\n ref_res = np.full_like(x_data, fill_value)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data, np.array(fill_value, dtype))\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_full_like((1, 3, 4, 4), 4, \"int32\")\n verify_full_like((1, 1), 44.0, \"float32\")\n\n\[email protected]_gpu\ndef test_infer_type_leaky_relu():\n n, c , h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n x = relay.var(\"x\", relay.TensorType((n, c, h, w), \"float32\"))\n y = relay.nn.leaky_relu(x, alpha=0.1)\n \"alpha=0.1\" in y.astext()\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType((n, c, h, w), \"float32\")\n\n shape = (1, 5, 10, 10)\n dtype = \"float32\"\n x = relay.var(\"x\", relay.TensorType(shape, dtype))\n z = relay.nn.leaky_relu(x, alpha=0.1)\n assert \"alpha=0.1\" in z.astext()\n zz = run_infer_type(z)\n assert zz.checked_type == relay.TensorType(shape, dtype)\n func = relay.Function([x], z)\n x_data = np.random.uniform(low=-1, high=1, size=shape).astype(dtype)\n ref_res = np.where(x_data > 0, x_data, x_data * 0.1)\n\n for target, ctx in tvm.testing.enabled_targets():\n intrp1 = relay.create_executor(\"graph\", ctx=ctx, target=target)\n intrp2 = relay.create_executor(\"debug\", ctx=ctx, target=target)\n op_res1 = intrp1.evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5)\n op_res2 = intrp2.evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=1e-5)\n\ndef verify_infer_type_prelu(data, alpha, axis, output, dtype=\"float32\"):\n x = relay.var(\"data\", relay.TensorType(data, dtype))\n if alpha:\n y = relay.var(\"alpha\", relay.TensorType(alpha, dtype))\n else:\n y = relay.var(\"alpha\", relay.IncompleteType())\n z = relay.nn.prelu(x, y, axis=axis)\n zz = run_infer_type(z)\n if axis != 1:\n assert \"axis\" in z.astext()\n assert zz.checked_type == relay.ty.TensorType(output, dtype)\n if not alpha:\n axis = axis if axis else 1\n alpha_shape = (data[axis],)\n assert zz.args[1].checked_type == relay.TensorType(alpha_shape, \"float32\")\n\n if all(isinstance(v, tvm.tir.Var) == 1 for v in data) or not alpha:\n return\n\n func = relay.Function([x, y], z)\n x_data = np.random.uniform(low=-1, high=1, size=data).astype(dtype)\n a_data = np.random.uniform(low=-1, high=1, size=alpha).astype(dtype)\n\n if axis == 1:\n ref_res = (x_data < 0) * (x_data * a_data.reshape(3, 1, 1)) + (x_data>=0) * x_data\n else:\n ref_res = (x_data < 0) * (x_data * a_data.reshape(1, 1, 3)) + (x_data>=0) * x_data\n\n for target, ctx in tvm.testing.enabled_targets():\n intrp1 = relay.create_executor(\"graph\", ctx=ctx, target=target)\n intrp2 = relay.create_executor(\"debug\", ctx=ctx, target=target)\n op_res1 = intrp1.evaluate(func)(x_data, a_data)\n tvm.testing.assert_allclose(op_res1.asnumpy(), ref_res, rtol=1e-5)\n op_res2 = intrp2.evaluate(func)(x_data, a_data)\n tvm.testing.assert_allclose(op_res2.asnumpy(), ref_res, rtol=1e-5)\n\n\[email protected]_gpu\ndef test_infer_type_prelu():\n n, c , h, w = te.size_var(\"n\"), te.size_var(\"c\"), te.size_var(\"h\"), te.size_var(\"w\")\n verify_infer_type_prelu((n, c, h, w), (c,), 1, (n, c, h, w))\n verify_infer_type_prelu((n, h, w, c), (c,), 3, (n, h, w, c))\n verify_infer_type_prelu((n, c, h, w), None, 1, (n, c, h, w))\n verify_infer_type_prelu((n, h, w, c), None, 3, (n, h, w, c))\n verify_infer_type_prelu((1, 3, 2, 2), (3,), 1, (1, 3, 2, 2))\n verify_infer_type_prelu((1, 2, 2, 3), (3,), 3, (1, 2, 2, 3))\n verify_infer_type_prelu((1, 3, 2, 2), None, 1, (1, 3, 2, 2))\n verify_infer_type_prelu((1, 2, 2, 3), None, 3, (1, 2, 2, 3))\n\n\[email protected]_gpu\ndef test_arange():\n def verify_arange(start, stop, step):\n dtype = \"float32\"\n if start is None and step is None:\n x = relay.arange(relay.const(stop, dtype=dtype))\n ref_res = np.arange(stop).astype(dtype)\n elif start is None:\n x = relay.arange(relay.const(stop, dtype=dtype), step=relay.const(step, dtype=dtype))\n ref_res = np.arange(stop, step=step).astype(dtype)\n elif step is None:\n x = relay.arange(relay.const(start, dtype=dtype), relay.const(stop, dtype=dtype))\n ref_res = np.arange(start, stop).astype(dtype)\n else:\n x = relay.arange(\n relay.const(start, dtype=dtype),\n relay.const(stop, dtype=dtype),\n relay.const(step, dtype=dtype))\n ref_res = np.arange(start, stop, step).astype(dtype)\n\n func = relay.Function([], x)\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)()\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_arange(None, 20, None)\n verify_arange(None, 20, 2)\n verify_arange(1, 20, None)\n verify_arange(1, 20, 2)\n # arange doesnt' support floating point right now, see type relation\n # verify_arange(1, 20, 1.5)\n verify_arange(1, 20.5, None)\n verify_arange(1, 20, 3)\n verify_arange(20, 1, -1)\n # arange doesnt' support floating point right now, see type relation\n # verify_arange(20, 1, -1.5)\n\[email protected]_gpu\ndef test_meshgrid():\n def verify_meshgrid(lengths, indexing=\"ij\"):\n input_vars = []\n input_data = []\n for i, length in enumerate(lengths):\n input_name = \"x_{}\".format(i)\n if length == 0:\n # Scalar\n input_vars.append(relay.var(input_name, relay.scalar_type(\"float32\")))\n input_data.append(np.array(1, \"float32\"))\n else:\n input_vars.append(relay.var(input_name, relay.TensorType((length,), \"float32\")))\n input_data.append(np.arange(length).astype(\"float32\"))\n\n z = relay.meshgrid(input_vars, indexing=indexing).astuple()\n func = relay.Function(input_vars, z)\n # Get ref\n ref_res = np.meshgrid(*input_data, indexing=indexing)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(*input_data)\n assert len(op_res) == len(ref_res)\n for i in range(len(op_res)):\n tvm.testing.assert_allclose(op_res[i].asnumpy(), ref_res[i], rtol=1e-5)\n verify_meshgrid([3, 5])\n verify_meshgrid([4, 2], indexing=\"xy\")\n verify_meshgrid([3, 5, 2])\n verify_meshgrid([3, 1, 5], indexing=\"xy\")\n # Length 0 signifies scalar.\n verify_meshgrid([3, 5, 0])\n\[email protected]_gpu\ndef test_tile():\n def verify_tile(dshape, reps):\n x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n z = relay.tile(x, reps=reps)\n\n func = relay.Function([x], z)\n x_data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n ref_res = np.tile(x_data, reps=reps)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_tile((2, 3, 4), (3, 2, 1))\n verify_tile((2, 3, 4), (1, 2))\n verify_tile((2, 3), (3, 2, 1))\n\[email protected]_gpu\ndef test_repeat():\n def verify_repeat(dshape, repeats, axis):\n x = relay.Var(\"x\", relay.TensorType(dshape, \"float32\"))\n func = relay.Function([x], relay.repeat(x, repeats, axis))\n data = np.random.uniform(size=dshape).astype(\"float32\")\n ref_res = np.repeat(data, repeats, axis)\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_repeat((3,), 2, 0)\n verify_repeat((3, 10), 2, -1)\n verify_repeat((3, 2, 4), 3, 1)\n\[email protected]_gpu\ndef test_stack():\n def verify_stack(dshapes, axis):\n y = []\n for shape in dshapes:\n y.append(relay.var(\"input\", relay.TensorType(shape, \"float32\")))\n x = relay.Tuple(y)\n z = relay.stack(x, axis=axis)\n\n func = relay.Function(y, z)\n x_data = [np.random.normal(size=shape).astype(\"float32\") for shape in dshapes]\n ref_res = np.stack(x_data, axis=axis)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(*x_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_stack([(2,), (2,), (2,)], -1)\n verify_stack([(2,), (2,), (2,)], 0)\n verify_stack([(2, 2, 4), (2, 2, 4), (2, 2, 4)], 1)\n verify_stack([(2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4)], -1)\n verify_stack([(2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4), (2, 2, 3, 4)], 4)\n\n\[email protected]_gpu\ndef test_reverse():\n def verify_reverse(dshape, axis):\n x = relay.var(\"x\", relay.TensorType(dshape, \"float32\"))\n z = relay.reverse(x, axis=axis)\n zz = run_infer_type(z)\n\n func = relay.Function([x], z)\n x_data = np.random.uniform(low=-1, high=1, size=dshape).astype(\"float32\")\n ref_res = np.flip(x_data, axis)\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_reverse((2, 3, 4), 1)\n verify_reverse((4, 7), 0)\n verify_reverse((2, 3, 4), -1)\n\n\[email protected]_gpu\ndef test_reverse_sequence():\n def verify_reverse_sequence(x_data, seq_lengths, batch_axis, seq_axis, ref_res):\n seq_lengths_data = np.array(seq_lengths).astype(\"int32\")\n x = relay.var(\"x\", relay.TensorType(x_data.shape, str(x_data.dtype)))\n z = relay.reverse_sequence(x, relay.const(seq_lengths_data), seq_axis, batch_axis)\n zz = run_infer_type(z)\n assert zz.checked_type == x.type_annotation\n func = relay.Function([x], z)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n\n indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n result = [[0, 5, 10, 15],\n [4, 1, 6, 11],\n [8, 9, 2, 7],\n [12, 13, 14, 3]]\n verify_reverse_sequence(indata, [1, 2, 3, 4], 1, 0, np.array(result))\n verify_reverse_sequence(indata, [1, 2, 3, 4], -1, 0, np.array(result))\n verify_reverse_sequence(indata.astype(\"float32\"), [1, 2, 3, 4], 1, 0, np.array(result).astype(\"float32\"))\n\n indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n result = [[0, 1, 2, 3],\n [5, 4, 6, 7],\n [10, 9, 8, 11],\n [15, 14, 13, 12]]\n verify_reverse_sequence(indata, [1, 2, 3, 4], 0, 1, np.array(result))\n verify_reverse_sequence(indata, [1, 2, 3, 4], 0, -1, np.array(result))\n verify_reverse_sequence(indata.astype(\"float32\"), [1, 2, 3, 4], 0, 1, np.array(result).astype(\"float32\"))\n\n indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n result = [[0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [15, 14, 13, 12]]\n verify_reverse_sequence(indata, [-1, 0, 1, 5], 0, 1, np.array(result))\n\n indata = np.array(np.arange(0, 54)).reshape([2, 3, 3, 3]).astype(\"int32\")\n result = [[[[18, 19, 20], [21, 22, 23], [24, 25, 26]],\n [[9, 10, 11], [12, 13, 14], [15, 16, 17]],\n [[0, 1, 2], [3, 4, 5], [6, 7, 8]]],\n [[[45, 46, 47], [48, 49, 50], [51, 52, 53]],\n [[36, 37, 38], [39, 40, 41], [42, 43, 44]],\n [[27, 28, 29], [30, 31, 32], [33, 34, 35]]]]\n verify_reverse_sequence(indata, [3, 3], 0, 1, np.array(result))\n\n indata = np.array(np.arange(0, 54)).reshape([2, 3, 3, 3]).astype(\"int32\")\n result = [[[[9, 10, 11], [21, 22, 23], [15, 16, 17]],\n [[0, 1, 2], [12, 13, 14], [6, 7, 8]],\n [[18, 19, 20], [3, 4, 5], [24, 25, 26]]],\n [[[36, 37, 38], [48, 49, 50], [42, 43, 44]],\n [[27, 28, 29], [39, 40, 41], [33, 34, 35]],\n [[45, 46, 47], [30, 31, 32], [51, 52, 53]]]]\n verify_reverse_sequence(indata, [2, 3, 2], 2, 1, np.array(result))\n\n indata = np.array(np.arange(0, 16)).reshape([4, 4]).astype(\"int32\")\n result = []\n with pytest.raises(Exception) as execinfo:\n verify_reverse_sequence(indata, [2, 3, 2, 4, 5], 1, 0, np.array(result))\n\n assert \"For reverse_sequnece seq_lengths size should match with dimension of batch axis,\" \\\n \" but got dimension of batch_axis = 4, and seq_length size = 5\" in execinfo.value.args[0]\n\n\ndef test_scatter():\n\n def ref_scatter(data, indices, updates, axis=0):\n idx = np.indices(indices.shape).reshape(indices.ndim, -1)\n\n updated_idx = np.copy(idx)\n indices = indices.reshape(-1)\n for i in range(len(indices)):\n updated_idx[axis, i] = indices[i]\n scattered = np.copy(data)\n scattered[tuple(updated_idx)] = updates[tuple(idx)]\n return scattered\n\n def verify_scatter(dshape, ishape, axis=0):\n d = relay.var(\"d\", relay.TensorType(dshape, \"float32\"))\n i = relay.var(\"i\", relay.TensorType(ishape, \"int64\"))\n u = relay.var(\"u\", relay.TensorType(ishape, \"float32\"))\n z = relay.op.scatter(d, i, u, axis)\n\n func = relay.Function([d, i, u], z)\n\n data_np = np.random.uniform(size=dshape).astype(\"float32\")\n updates_np = np.random.uniform(size=ishape).astype(\"float32\")\n indices_np = np.random.randint(-dshape[axis], dshape[axis] - 1, ishape).astype(\"int64\")\n\n ref_res = ref_scatter(data_np, indices_np, updates_np, axis)\n # TODO(mbrookhart): expand testing when adding more backend schedules\n for target, ctx in [(\"llvm\", tvm.cpu())]:\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(data_np, indices_np, updates_np)\n tvm.testing.assert_allclose(\n op_res.asnumpy(), ref_res, rtol=1e-5)\n\n verify_scatter((10, ), (10, ), 0)\n verify_scatter((10, 5), (10, 5), -2)\n verify_scatter((10, 5), (10, 5), -1)\n verify_scatter((10, 5), (3, 5), 0)\n verify_scatter((12, 4), (7, 2), 1)\n verify_scatter((2, 3, 4), (1, 3, 4), 0)\n verify_scatter((2, 3, 4), (2, 1, 4), 1)\n verify_scatter((2, 3, 4), (2, 3, 1), 2)\n verify_scatter((2, 3, 4, 5), (1, 3, 4, 5), 0)\n verify_scatter((6, 3, 4, 5), (2, 3, 4, 5), 1)\n verify_scatter((2, 3, 8, 5), (2, 3, 1, 1), 2)\n verify_scatter((16, 16, 4, 5), (16, 16, 4, 5), 3)\n\n\ndef test_scatter_add():\n\n def ref_scatter_add(data, indices, updates, axis=0):\n output = np.copy(data)\n for index in np.ndindex(*indices.shape):\n new_index = list(index)\n new_index[axis] = indices[index]\n output[tuple(new_index)] += updates[index]\n return output\n\n def verify_scatter_add(dshape, ishape, axis=0):\n d = relay.var(\"d\", relay.TensorType(dshape, \"float32\"))\n i = relay.var(\"i\", relay.TensorType(ishape, \"int64\"))\n u = relay.var(\"u\", relay.TensorType(ishape, \"float32\"))\n z = relay.op.scatter_add(d, i, u, axis)\n\n func = relay.Function([d, i, u], z)\n\n data_np = np.random.uniform(size=dshape).astype(\"float32\")\n updates_np = np.random.uniform(size=ishape).astype(\"float32\")\n indices_np = np.random.randint(-dshape[axis], dshape[axis] - 1, ishape).astype(\"int64\")\n\n ref_res = ref_scatter_add(data_np, indices_np, updates_np, axis)\n # TODO(mbrookhart): expand testing when adding more backend schedules\n for target, ctx in [(\"llvm\", tvm.cpu())]:\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(data_np, indices_np, updates_np)\n tvm.testing.assert_allclose(\n op_res.asnumpy(), ref_res, rtol=1e-5)\n\n verify_scatter_add((10, ), (10, ), 0)\n verify_scatter_add((10, 5), (10, 5), -2)\n verify_scatter_add((10, 5), (10, 5), -1)\n verify_scatter_add((10, 5), (3, 5), 0)\n verify_scatter_add((12, 4), (7, 2), 1)\n verify_scatter_add((2, 3, 4), (1, 3, 4), 0)\n verify_scatter_add((2, 3, 4), (2, 1, 4), 1)\n verify_scatter_add((2, 3, 4), (2, 3, 1), 2)\n verify_scatter_add((2, 3, 4, 5), (1, 3, 4, 5), 0)\n verify_scatter_add((6, 3, 4, 5), (2, 3, 4, 5), 1)\n verify_scatter_add((2, 3, 8, 5), (2, 3, 1, 1), 2)\n verify_scatter_add((16, 16, 4, 5), (16, 16, 4, 5), 3)\n\n\[email protected]_gpu\ndef test_gather():\n def verify_gather(data, axis, indices, ref_res):\n data = np.asarray(data, dtype='float32')\n indices = np.asarray(indices, dtype='int32')\n ref_res = np.asarray(ref_res)\n\n d = relay.var(\"x\", relay.TensorType(data.shape, \"float32\"))\n i = relay.var(\"y\", relay.TensorType(indices.shape, \"int32\"))\n z = relay.gather(d, axis, i)\n\n func = relay.Function([d, i], z)\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(data, indices)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res,\n rtol=1e-5)\n\n verify_gather([[1, 2], [3, 4]],\n 1,\n [[0, 0], [1, 0]],\n [[1, 1], [4, 3]])\n verify_gather([[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]],\n 0,\n [[[1, 0, 1], [1, 1, 0]]],\n [[[6, 1, 8], [9, 10, 5]]])\n verify_gather([[[-0.2321, -0.2024, -1.7624], [-0.3829, -0.4246, 0.2448],\n [0.1822, 0.2360, -0.8965], [0.4497, -0.2224, 0.6103]],\n [[0.0408, -0.7667, -0.4303], [-0.3216, 0.7489, -0.1502],\n [0.0144, -0.4699, -0.0064], [-0.0768, -1.6064, 1.3390]]],\n 1,\n [[[2, 2, 0], [1, 0, 3]], [[3, 2, 0], [1, 0, 0]]],\n [[[0.1822, 0.2360, -1.7624], [-0.3829, -0.2024, 0.6103]],\n [[-0.0768, -0.4699, -0.4303], [-0.3216, -0.7667, -0.4303]]])\n verify_gather([[[0.3050, 1.6986, 1.1034], [0.7020, -0.6960, -2.1818],\n [0.3116, -0.5773, -0.9912], [0.0835, -1.3915, -1.0720]],\n [[0.1694, -0.6091, -0.6539], [-0.5234, -0.1218, 0.5084],\n [0.2374, -1.9537, -2.0078], [-0.5700, -1.0302, 0.1558]]],\n 2,\n [[[1, 1, 0, 1], [0, 0, 2, 2], [1, 2, 1, 2], [2, 2, 1, 0]],\n [[0, 0, 1, 2], [2, 2, 1, 0], [1, 2, 0, 0], [0, 2, 0, 2]]],\n [[[1.6986, 1.6986, 0.3050, 1.6986],\n [0.7020, 0.7020, -2.1818, -2.1818],\n [-0.5773, -0.9912, -0.5773, -0.9912],\n [-1.0720, -1.0720, -1.3915, 0.0835]],\n [[0.1694, 0.1694, -0.6091, -0.6539],\n [0.5084, 0.5084, -0.1218, -0.5234],\n [-1.9537, -2.0078, 0.2374, 0.2374],\n [-0.5700, 0.1558, -0.5700, 0.1558]]])\n\n\[email protected]_gpu\ndef test_gather_nd():\n def verify_gather_nd(xshape, yshape, y_data):\n x = relay.var(\"x\", relay.TensorType(xshape, \"float32\"))\n y = relay.var(\"y\", relay.TensorType(yshape, \"int32\"))\n z = relay.gather_nd(x, y)\n\n func = relay.Function([x, y], z)\n x_data = np.random.uniform(size=xshape).astype(\"float32\")\n ref_res = x_data[tuple(y_data)]\n\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data, y_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n verify_gather_nd((2, 2), (2, 3), [[1, 1, 0], [0, 1, 0]])\n verify_gather_nd((2, 2, 2), (2, 2), [[0, 1], [1, 0]])\n verify_gather_nd((3, 2, 2), (2, 2), [[0, 1], [1, 0]])\n verify_gather_nd((3, 2), (2, 2, 3), [[[0, 1, 2], [2, 0, 1]], [[0, 0, 0], [1, 1, 1]]])\n\n\ndef _verify_infiniteness_ops(relay_op, ref_op):\n for dtype in ['float32', 'float16', 'float16', 'int32', 'int16']:\n shape = (2, 8, 8)\n x = relay.var(\"x\", relay.TensorType(shape, dtype))\n y = relay_op(x)\n yy = run_infer_type(y)\n assert yy.checked_type == relay.TensorType(shape, \"bool\")\n\n data = np.random.uniform(size=shape).astype(dtype)\n if dtype.startswith('float'):\n data.ravel()[np.random.choice(data.size, int(data.size * 0.5), replace=False)] = np.infty\n data.ravel()[np.random.choice(data.size, int(data.size * 0.5), replace=False)] = np.nan\n\n intrp = create_executor()\n op_res = intrp.evaluate(y, {x: data})\n ref_res = ref_op(data)\n np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=0.01)\n\n\ndef test_isfinite():\n _verify_infiniteness_ops(relay.isfinite, np.isfinite)\n\n\ndef test_isinf():\n _verify_infiniteness_ops(relay.isinf, np.isinf)\n\n\[email protected]_gpu\ndef test_unravel_index():\n def verify_unravel_index(indices, shape, dtype):\n x_data = np.array(indices).astype(dtype)\n y_data = np.array(shape).astype(dtype)\n x = relay.var(\"x\", relay.TensorType(x_data.shape, dtype))\n y = relay.var(\"y\", relay.TensorType(y_data.shape, dtype))\n\n z = relay.unravel_index(x, y)\n zz = run_infer_type(z)\n\n if len(x_data.shape) == 1:\n out_shape = [y_data.shape[0], x_data.shape[0]]\n else:\n out_shape = [y_data.shape[0]]\n assert zz.checked_type == relay.ty.TensorType(out_shape, dtype)\n\n func = relay.Function([x, y], z)\n ref_res = np.unravel_index(x_data, y_data)\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n op_res = intrp.evaluate(func)(x_data, y_data)\n tvm.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=1e-5)\n\n for dtype in [\"int64\", \"int32\"]:\n verify_unravel_index([0, 1, 2, 3], [2, 2], dtype)\n verify_unravel_index([144], [5, 5, 5, 2], dtype)\n verify_unravel_index(144, [5, 5, 5, 2], dtype)\n verify_unravel_index([100, 13, 5], [5, 5, 5, 2], dtype)\n\n # In below example, 5 is out of bound for array of size 4.\n # Numpy implementation throws error for it\n # TVM implementation does not throw error instead it produces\n # output which is inline with Tensorflow\n # verify_unravel_index([0, 1, 2, 5], [2, 2], dtype)\n\[email protected]_gpu\ndef test_sparse_to_dense():\n def verify_sparse_to_dense(sparse_indices, sparse_values, default_value, output_shape, xpected):\n sparse_indices_data = np.array(sparse_indices)\n sparse_values_data = np.array(sparse_values)\n default_value_data = np.array(default_value)\n\n a = relay.var(\"a\", relay.TensorType(sparse_indices_data.shape, str(sparse_indices_data.dtype)))\n b = relay.var(\"b\", relay.TensorType(sparse_values_data.shape, str(sparse_values_data.dtype)))\n if default_value is None:\n args = [a, b]\n d = relay.sparse_to_dense(a, output_shape, b)\n else:\n c = relay.var(\"c\", relay.TensorType(default_value_data.shape, str(default_value_data.dtype)))\n args = [a, b, c]\n d = relay.sparse_to_dense(a, output_shape, b, c)\n\n zz = run_infer_type(d)\n assert zz.checked_type == relay.ty.TensorType(output_shape, str(sparse_values_data.dtype))\n\n func = relay.Function(args, d)\n for target, ctx in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n intrp = relay.create_executor(kind, ctx=ctx, target=target)\n if default_value is None:\n op_res = intrp.evaluate(func)(sparse_indices_data, sparse_values_data)\n else:\n op_res = intrp.evaluate(func)(\n sparse_indices_data, sparse_values_data, default_value_data\n )\n tvm.testing.assert_allclose(op_res.asnumpy(), xpected, rtol=1e-5)\n\n\n verify_sparse_to_dense(1, 3, 0, [5], [0, 3, 0, 0, 0]) # scalar\n verify_sparse_to_dense([0, 1, 4], [3, 3, 3], 0, [5], [3, 3, 0, 0, 3]) # vector\n verify_sparse_to_dense([[0, 0], [1, 2]], [1, 2], 0, [3, 4], [[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]) # nXd\n verify_sparse_to_dense(\n [[0, 0, 0], [1, 2, 3]],\n [1, 2],\n 4,\n [2, 3, 4],\n [[[1, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]], [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 2]]]\n ) # nXd\n verify_sparse_to_dense([0, 1, 4], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1]) # floats\n verify_sparse_to_dense(1, 3, None, [5], [0, 3, 0, 0, 0]) # default value not specified\n\n #negative test cases\n #sparse indices should be ints\n #verify_sparse_to_dense([[0.1, 1.1, 4.1], [0,2,4]], [3.1, 3.1, 3.1], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n #sparse_values should be 0d or 1d only\n #verify_sparse_to_dense([[0, 1, 4], [0, 2, 4]], [[[3.1, 3.1, 3.1]]], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n #sparse_indices should not be > 2d tensor\n #verify_sparse_to_dense([[[[0, 1, 4], [0, 2, 4]]]], [[[[3.1, 3.1, 3.1]]]], 3.5, [5], [3.1, 3.1, 3.5, 3.5, 3.1])\n\nif __name__ == \"__main__\":\n test_cast()\n test_zeros_ones()\n test_unary_identity()\n test_clip()\n test_transpose_infer_type()\n test_transpose()\n test_reshape_infer_type()\n test_reshape()\n test_reshape_fail()\n test_reshape_like_infer_type()\n test_reshape_like()\n test_take_infer_type()\n test_take()\n test_full_infer_type()\n test_full()\n test_full_like_infer_type()\n test_full_like()\n test_infer_type_leaky_relu()\n test_infer_type_prelu()\n test_squeeze()\n test_squeeze_infer_type()\n test_squeeze_bad_axes_infer_type()\n test_split_infer_type()\n test_arange()\n test_meshgrid()\n test_reverse()\n test_stack()\n test_tile()\n test_repeat()\n test_gather_nd()\n test_isfinite()\n test_isinf()\n test_unravel_index()\n test_sparse_to_dense()\n test_fixed_point_multiply()\n" ]
[ [ "numpy.ones", "numpy.take", "numpy.asarray", "numpy.copy", "numpy.stack", "numpy.meshgrid", "numpy.tanh", "numpy.ndindex", "numpy.unravel_index", "numpy.full_like", "numpy.transpose", "numpy.reshape", "numpy.random.rand", "numpy.where", "numpy.linspace", "numpy.random.randint", "numpy.random.uniform", "numpy.tile", "numpy.random.normal", "numpy.repeat", "numpy.arange", "numpy.indices", "numpy.random.random_sample", "numpy.squeeze", "numpy.random.randn", "numpy.clip", "numpy.flip", "numpy.array", "numpy.logaddexp", "numpy.full" ] ]
Jhsmit/awesome-panel
[ "53f7754f7c505a2666f6724df26c851ae942ec40" ]
[ "application/pages/training_analysis/services/fit_file_services.py" ]
[ "\"\"\"In this module we provide services for working with fit files.\r\n\r\nResources\r\n\r\n- fitparse package: [GitHub](https://github.com/dtcooper/python-fitparse) and \\\r\n [Docs](http://dtcooper.github.io/python-fitparse/)\r\n- fitdecode pacakge: [GitHub](https://github.com/polyvertex/fitdecode) and \\\r\n [Read the Docs](https://fitdecode.readthedocs.io/en/latest/)\r\n- [FIT on Wikipedia](https://wiki.openstreetmap.org/wiki/FIT)\r\n- [Download FIT SDK](https://www.thisisant.com/resources/fit).\r\n\"\"\"\r\n\r\nfrom typing import Union\r\n\r\nimport fitparse\r\nimport pandas as pd\r\n\r\nUNIT_CONVERSION = {\r\n \"speed\": {\"from\": \"10*6m/s\", \"to\": \"km/h\", \"factor\": 0.0036,},\r\n \"enhanced_speed\": {\"from\": \"10*6m/s\", \"to\": \"km/h\", \"factor\": 3.6,},\r\n \"altitude\": {\"from\": \"unknown\", \"to\": \"m\", \"factor\": 0.03855343881175331,},\r\n \"position_long\": {\"from\": \"semicircles\", \"to\": \"degrees\", \"factor\": (180.0 / 2 ** 31),},\r\n \"position_lat\": {\"from\": \"semicircles\", \"to\": \"degrees\", \"factor\": (180.0 / 2 ** 31),},\r\n}\r\n\r\n\r\ndef parse_fit_file(file: Union[fitparse.base.FitFile, bytes, str,]) -> pd.DataFrame:\r\n \"\"\"Converts a fit_file to a dataframe\r\n\r\n Args:\r\n file (Union[fitparse.base.FitFile, bytes, str]): The fit file to parse\r\n\r\n Raises:\r\n ValueError: If the file is not in a supported format\r\n\r\n Returns:\r\n pd.DataFrame: A DataFrame with the data\r\n \"\"\"\r\n if isinstance(file, (bytes, str,),):\r\n fit_file = fitparse.FitFile(file)\r\n elif isinstance(file, fitparse.base.FitFile,):\r\n fit_file = file\r\n else:\r\n raise ValueError(f\"{type(file)} is not supported!\")\r\n\r\n return _parse_records(fit_file.get_messages(\"record\"))\r\n\r\n\r\ndef _parse_records(records,):\r\n data = [record.get_values() for record in records]\r\n training_data = pd.DataFrame(data)\r\n _convert_units(training_data)\r\n return training_data\r\n\r\n\r\ndef _convert_units(training_data_row: pd.DataFrame,):\r\n columns = set(UNIT_CONVERSION.keys()).intersection(set(training_data_row.columns))\r\n for column in columns:\r\n training_data_row[column] *= UNIT_CONVERSION[column][\"factor\"]\r\n" ]
[ [ "pandas.DataFrame" ] ]
rainwoodman/tensorflow
[ "9b7ff60faa841f0473facf618cb5b66b9cb99b5e" ]
[ "tensorflow/python/kernel_tests/sparse_xent_op_test.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for SparseSoftmaxCrossEntropyWithLogits op.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport time\n\nimport numpy as np\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import backprop as backprop_lib\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops as ops_lib\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.ops import gradient_checker_v2\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import sparse_ops\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import app\nfrom tensorflow.python.platform import test\n\n\nclass SparseXentTest(test.TestCase):\n\n def _npXent(self, features, labels):\n features = np.reshape(features, [-1, features.shape[-1]])\n labels = np.reshape(labels, [-1])\n batch_dim = 0\n class_dim = 1\n batch_size = features.shape[batch_dim]\n e = np.exp(features - np.reshape(\n np.amax(\n features, axis=class_dim), [batch_size, 1]))\n probs = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1])\n labels_mat = np.zeros_like(probs).astype(probs.dtype)\n labels_mat[np.arange(batch_size), labels] = 1.0\n bp = (probs - labels_mat)\n l = -np.sum(labels_mat * np.log(probs + 1.0e-20), axis=1)\n return l, bp\n\n def _testXent(self, np_features, np_labels):\n np_loss, np_backprop = self._npXent(np_features, np_labels)\n with self.cached_session():\n loss, backprop = gen_nn_ops.sparse_softmax_cross_entropy_with_logits(\n np_features, np_labels)\n tf_loss, tf_backprop = self.evaluate([loss, backprop])\n self.assertAllCloseAccordingToType(np_loss, tf_loss)\n self.assertAllCloseAccordingToType(np_backprop, tf_backprop)\n\n def testSingleClass(self):\n for label_dtype in np.int32, np.int64:\n with self.cached_session():\n loss, backprop = gen_nn_ops.sparse_softmax_cross_entropy_with_logits(\n np.array([[1.], [-1.], [0.]]).astype(np.float32),\n np.array([0, 0, 0]).astype(label_dtype))\n tf_loss, tf_backprop = self.evaluate([loss, backprop])\n self.assertAllClose([0.0, 0.0, 0.0], tf_loss)\n self.assertAllClose([[0.0], [0.0], [0.0]], tf_backprop)\n\n @test_util.run_gpu_only()\n def testInvalidLabelGPU(self):\n features = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.],\n [1., 2., 3., 4.]]\n labels = [4, 3, 0, -1]\n loss, backprop = self.evaluate(\n gen_nn_ops.sparse_softmax_cross_entropy_with_logits(features, labels))\n self.assertAllClose([[np.nan] * 4, [0.25, 0.25, 0.25, -0.75],\n [-0.968, 0.087, 0.237, 0.6439], [np.nan] * 4],\n backprop,\n rtol=1e-3,\n atol=1e-3)\n self.assertAllClose([np.nan, 1.3862, 3.4420, np.nan],\n loss,\n rtol=1e-3,\n atol=1e-3)\n\n @test_util.run_in_graph_and_eager_modes(use_gpu=False)\n @test_util.disable_xla(\"XLA cannot assert inside of a kernel.\")\n def testInvalidLabelCPU(self):\n features = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.],\n [1., 2., 3., 4.]]\n labels = [4, 3, 0, -1]\n with self.assertRaisesRegex(\n (errors_impl.InvalidArgumentError, errors_impl.UnknownError),\n \"Received a label value of\"):\n self.evaluate(\n gen_nn_ops.sparse_softmax_cross_entropy_with_logits(features, labels))\n\n def testNpXent(self):\n # We create 2 batches of logits for testing.\n # batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3.\n # batch 1 has a bit of difference: 1, 2, 3, 4, with target 0.\n features = [[1., 1., 1., 1.], [1., 2., 3., 4.]]\n labels = [3, 0]\n\n # For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25\n # With a hard target 3, the backprop is [0.25, 0.25, 0.25, -0.75]\n # The loss for this batch is -log(0.25) = 1.386\n #\n # For batch 1, we have:\n # exp(0) = 1\n # exp(1) = 2.718\n # exp(2) = 7.389\n # exp(3) = 20.085\n # SUM = 31.192\n # So we have as probabilities:\n # exp(0) / SUM = 0.032\n # exp(1) / SUM = 0.087\n # exp(2) / SUM = 0.237\n # exp(3) / SUM = 0.644\n # With a hard 1, the backprop is [0.032 - 1.0 = -0.968, 0.087, 0.237, 0.644]\n # The loss for this batch is [1.0 * -log(0.25), 1.0 * -log(0.032)]\n # = [1.3862, 3.4420]\n np_loss, np_backprop = self._npXent(np.array(features), np.array(labels))\n self.assertAllClose(\n np.array([[0.25, 0.25, 0.25, -0.75], [-0.968, 0.087, 0.237, 0.6439]]),\n np_backprop,\n rtol=1.e-3,\n atol=1.e-3)\n self.assertAllClose(\n np.array([1.3862, 3.4420]), np_loss, rtol=1.e-3, atol=1.e-3)\n\n def testShapeMismatch(self):\n with self.session():\n with self.assertRaisesRegex(ValueError, \".*Rank mismatch:*\"):\n nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=[[0, 2]], logits=[[0., 1.], [2., 3.], [2., 3.]])\n\n def testScalar(self):\n with self.session():\n with self.assertRaisesRegex(ValueError, \".*Logits cannot be scalars*\"):\n nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=constant_op.constant(0), logits=constant_op.constant(1.0))\n\n def testLabelsPlaceholderScalar(self):\n with ops_lib.Graph().as_default(), self.session():\n labels = array_ops.placeholder(np.int32)\n y = nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=labels, logits=[[7.]])\n with self.assertRaisesOpError(\"labels must be 1-D\"):\n y.eval(feed_dict={labels: 0})\n\n def testVector(self):\n with self.session():\n loss = nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=constant_op.constant(0), logits=constant_op.constant([1.0]))\n self.assertAllClose(0.0, self.evaluate(loss))\n\n def testFloat(self):\n for label_dtype in np.int32, np.int64:\n self._testXent(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32),\n np.array([3, 0]).astype(label_dtype))\n\n def testDouble(self):\n for label_dtype in np.int32, np.int64:\n self._testXent(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64),\n np.array([0, 3]).astype(label_dtype))\n\n def testHalf(self):\n for label_dtype in np.int32, np.int64:\n self._testXent(\n np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16),\n np.array([3, 0]).astype(label_dtype))\n\n def testEmpty(self):\n self._testXent(np.zeros((0, 3)), np.zeros((0,), dtype=np.int32))\n\n @test_util.run_in_graph_and_eager_modes(use_gpu=True)\n def testGradient(self):\n with self.session() as sess:\n l = constant_op.constant([3, 0, 1], name=\"l\")\n f = constant_op.constant(\n [0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4],\n shape=[3, 4],\n dtype=dtypes.float64,\n name=\"f\")\n\n def xent(f):\n # gradient_checker_v2.computee_gradient doesn't take int32/int64.\n # labels must be of type int32/int64, so passing them separately here.\n return nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=l, logits=f, name=\"xent\")\n\n theoretical, numerical = gradient_checker_v2.compute_gradient(xent, [f])\n\n if not context.executing_eagerly():\n # Check that no extra computation performed. When only first derivative\n # is requested, second derivative must not be computed. So when there is\n # no second derivative, there is no `BatchMatMul` op in the graph.\n op_names = [\n op.op_def.name for op in sess.graph.get_operations() if op.op_def\n ]\n self.assertNotIn(\"BatchMatMul\", op_names)\n self.assertNotIn(\"BatchMatMulV2\", op_names)\n\n tol = 5e-8\n self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)\n\n def testSecondGradient(self):\n with self.session() as sess:\n l = constant_op.constant([3, 0, 1], name=\"l\")\n f = constant_op.constant(\n [0.3, 0.4, 0.1, 1.2, 0.1, 1.9, 0.1, 0.7, 0.8, 0.2, 1.3, 1.3],\n shape=[3, 4],\n dtype=dtypes.float64,\n name=\"f\")\n\n def xent_grad(f):\n if not context.executing_eagerly():\n return gradients_impl.gradients(\n nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=l, logits=f, name=\"xent\"), [f])[0]\n with backprop_lib.GradientTape() as tape:\n tape.watch(f)\n return tape.gradient(\n nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=l, logits=f, name=\"xent\"), [f])[0]\n\n theoretical, numerical = gradient_checker_v2.compute_gradient(\n xent_grad, [f])\n\n if not context.executing_eagerly():\n # Check that second derivative is calculated.\n # (it is equivalent to being `BatchMatMul` op in the graph because of\n # implementation of xentropy grad)\n op_names = [\n op.op_def.name for op in sess.graph.get_operations() if op.op_def\n ]\n self.assertIn(\"BatchMatMulV2\", op_names)\n\n tol = 5e-8\n self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)\n\n @test_util.run_in_graph_and_eager_modes(use_gpu=True)\n def _testHighDim(self, features, labels):\n np_loss, np_backprop = self._npXent(np.array(features), np.array(labels))\n # manually reshape loss\n np_loss = np.reshape(np_loss, np.array(labels).shape)\n tf_loss = nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=labels, logits=features)\n if not context.executing_eagerly():\n tf_backprop = tf_loss.op.inputs[0].op.outputs[1]\n else:\n with backprop_lib.GradientTape() as tape:\n features = constant_op.constant(features)\n tape.watch(features)\n tf_backprop = tape.gradient(\n nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=labels, logits=features), [features])[0]\n tf_backprop = array_ops.reshape(tf_backprop, np_backprop.shape)\n\n self.assertAllCloseAccordingToType(np_loss, tf_loss)\n self.assertAllCloseAccordingToType(np_backprop, tf_backprop)\n\n def testHighDim(self):\n features = [[[1., 1., 1., 1.]], [[1., 2., 3., 4.]]]\n labels = [[3], [0]]\n self._testHighDim(features, labels)\n\n def testHighDim2(self):\n features = [[[1., 1., 1., 1.], [2., 2., 2., 2.]],\n [[1., 2., 3., 4.], [5., 6., 7., 8.]]]\n labels = [[3, 2], [0, 3]]\n self._testHighDim(features, labels)\n\n def testScalarHandling(self):\n with ops_lib.Graph().as_default(), self.session(use_gpu=False) as sess:\n with self.assertRaisesRegex(errors_impl.InvalidArgumentError,\n \".*labels must be 1-D.*\"):\n labels = array_ops.placeholder(dtypes.int32, shape=[None, 1])\n logits = array_ops.placeholder(dtypes.float32, shape=[None, 3])\n ce = nn_ops.sparse_softmax_cross_entropy_with_logits(\n labels=array_ops.squeeze(labels), logits=logits)\n labels_v2 = np.zeros((1, 1), dtype=np.int32)\n logits_v2 = np.random.randn(1, 3)\n sess.run([ce], feed_dict={labels: labels_v2, logits: logits_v2})\n\n\ndef _sparse_vs_dense_xent_benchmark_dense(labels, logits):\n labels = array_ops.identity(labels)\n logits = array_ops.identity(logits)\n with ops_lib.device(\"/cpu:0\"): # Sparse-to-dense must be on CPU\n batch_size = array_ops.shape(logits)[0]\n num_entries = array_ops.shape(logits)[1]\n length = batch_size * num_entries\n labels += num_entries * math_ops.range(batch_size)\n target = sparse_ops.sparse_to_dense(labels,\n array_ops.stack([length]), 1.0, 0.0)\n target = array_ops.reshape(target, array_ops.stack([-1, num_entries]))\n crossent = nn_ops.softmax_cross_entropy_with_logits(\n labels=target, logits=logits, name=\"SequenceLoss/CrossEntropy\")\n crossent_sum = math_ops.reduce_sum(crossent)\n grads = gradients_impl.gradients([crossent_sum], [logits])[0]\n\n return (crossent_sum, grads)\n\n\ndef _sparse_vs_dense_xent_benchmark_sparse(labels, logits):\n # Using sparse_softmax_cross_entropy_with_logits\n labels = labels.astype(np.int64)\n labels = array_ops.identity(labels)\n logits = array_ops.identity(logits)\n crossent = nn_ops.sparse_softmax_cross_entropy_with_logits(\n logits, labels, name=\"SequenceLoss/CrossEntropy\")\n crossent_sum = math_ops.reduce_sum(crossent)\n grads = gradients_impl.gradients([crossent_sum], [logits])[0]\n\n return (crossent_sum, grads)\n\n\ndef sparse_vs_dense_xent_benchmark(batch_size, num_entries, use_gpu):\n config = config_pb2.ConfigProto()\n config.allow_soft_placement = True\n config.gpu_options.per_process_gpu_memory_fraction = 0.3\n labels = np.random.randint(num_entries, size=batch_size).astype(np.int32)\n logits = np.random.randn(batch_size, num_entries).astype(np.float32)\n\n def _timer(sess, ops):\n # Warm in\n for _ in range(20):\n sess.run(ops)\n\n # Timing run\n start = time.time()\n for _ in range(20):\n sess.run(ops)\n end = time.time()\n\n return (end - start) / 20.0 # Average runtime per iteration\n\n # Using sparse_to_dense and softmax_cross_entropy_with_logits\n with session.Session(config=config) as sess:\n if not use_gpu:\n with ops_lib.device(\"/cpu:0\"):\n ops = _sparse_vs_dense_xent_benchmark_dense(labels, logits)\n else:\n ops = _sparse_vs_dense_xent_benchmark_dense(labels, logits)\n delta_dense = _timer(sess, ops)\n\n # Using sparse_softmax_cross_entropy_with_logits\n with session.Session(config=config) as sess:\n if not use_gpu:\n with test_util.device(\"/cpu:0\"):\n ops = _sparse_vs_dense_xent_benchmark_sparse(labels, logits)\n else:\n ops = _sparse_vs_dense_xent_benchmark_sparse(labels, logits)\n delta_sparse = _timer(sess, ops)\n\n print(\"%d \\t %d \\t %s \\t %f \\t %f \\t %f\" % (batch_size, num_entries, use_gpu,\n delta_dense, delta_sparse,\n delta_sparse / delta_dense))\n\n\ndef main(_):\n print(\"Sparse Xent vs. SparseToDense + Xent\")\n print(\"batch \\t depth \\t gpu \\t dt(dense) \\t dt(sparse) \"\n \"\\t dt(sparse)/dt(dense)\")\n for use_gpu in (False, True):\n for batch_size in (32, 64, 128):\n for num_entries in (100, 1000, 10000):\n sparse_vs_dense_xent_benchmark(batch_size, num_entries, use_gpu)\n sparse_vs_dense_xent_benchmark(32, 100000, use_gpu)\n sparse_vs_dense_xent_benchmark(8, 1000000, use_gpu)\n\n\nif __name__ == \"__main__\":\n if \"--benchmarks\" in sys.argv:\n sys.argv.remove(\"--benchmarks\")\n app.run()\n else:\n test.main()\n" ]
[ [ "tensorflow.python.framework.test_util.run_gpu_only", "numpy.sum", "tensorflow.python.ops.nn_ops.softmax_cross_entropy_with_logits", "tensorflow.python.ops.gradients_impl.gradients", "numpy.log", "numpy.amax", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.platform.app.run", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.eager.backprop.GradientTape", "numpy.reshape", "tensorflow.python.ops.gradient_checker_v2.compute_gradient", "tensorflow.python.ops.math_ops.range", "tensorflow.python.framework.test_util.disable_xla", "tensorflow.python.client.session.Session", "tensorflow.python.ops.gen_nn_ops.sparse_softmax_cross_entropy_with_logits", "tensorflow.python.framework.ops.device", "numpy.zeros", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.framework.test_util.device", "tensorflow.python.ops.array_ops.squeeze", "numpy.arange", "tensorflow.python.ops.nn_ops.sparse_softmax_cross_entropy_with_logits", "numpy.zeros_like", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.framework.test_util.run_in_graph_and_eager_modes", "numpy.random.randn", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.array_ops.reshape", "numpy.array", "tensorflow.python.eager.context.executing_eagerly", "numpy.random.randint" ] ]
stephanefschwarz/EMET
[ "92ab8b0a53bbdfe5618353f0055eba98ae93f53f" ]
[ "emet/hypothesis/generate_dictionary.py" ]
[ "import sys\nimport pandas as pd\nimport requests\nimport nltk\nnltk.download('stopwords')\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\n\nfrom bs4 import BeautifulSoup\n\n# --- open dataset --- #\ndata = pd.read_csv('./dataset/translated_twitter_posts.csv')\n\ndocuments = data['translated_posts']\n\n# --- create an instance of tokenizer --- #\n\npremises = []\n\ntokenizer = RegexpTokenizer(r'\\w+')\n\nprogress = 0\ntotal_posts = documents.shape[0]\n\nfor document in documents:\n sentence = ''\n tokens = tokenizer.tokenize(document)\n for token in tokens:\n\n if not token in stopwords.words('english'):\n try:\n request = requests.get(\"http://www.urbandictionary.com/define.php?term={}\".format(token))\n extract_mening = BeautifulSoup(request.content, 'html.parser')\n meaning = extract_mening.find(\"div\",attrs={\"class\":\"meaning\"})\n if meaning != None:\n meaning = meaning.text\n sentence = sentence + meaning + ' '\n else:\n sentence = sentence + token + ' '\n except Exception as e:\n print('Exception at token ', token, '\\n', e)\n else:\n sentence = sentence + token + ' '\n\n premises.append(sentence)\n\n progress = progress + 1\n percentage = round((progress / total_posts) * 100, 2)\n\n output_print = \"{}% | {}/{}\".format(percentage, progress, total_posts)\n\n # Poor way to show a progress bar :|\n sys.stdout.write(\"\\r {:<70}\".format(output_print))\n sys.stdout.flush()\n\ndata['premises'] = premises\ndata.to_csv('./dataset/premises_twitter_posts.csv')\n" ]
[ [ "pandas.read_csv" ] ]
gujralsanyam22/models
[ "d96f8f043dbe2b5ca8ea1785f57df8faf68d8875", "11ea5237818e791a5717716d5413977f4c4db1e3", "11ea5237818e791a5717716d5413977f4c4db1e3", "11ea5237818e791a5717716d5413977f4c4db1e3" ]
[ "official/nlp/bert/run_squad.py", "official/vision/detection/dataloader/tf_example_decoder.py", "research/object_detection/export_tflite_ssd_graph_lib.py", "research/slim/nets/nasnet/pnasnet.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Run BERT on SQuAD 1.1 and SQuAD 2.0 in TF 2.x.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport time\n\n# Import libraries\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport gin\nimport tensorflow as tf\nfrom official.common import distribute_utils\nfrom official.nlp.bert import configs as bert_configs\nfrom official.nlp.bert import run_squad_helper\nfrom official.nlp.bert import tokenization\nfrom official.nlp.data import squad_lib as squad_lib_wp\nfrom official.utils.misc import keras_utils\n\n\nflags.DEFINE_string('vocab_file', None,\n 'The vocabulary file that the BERT model was trained on.')\n\n# More flags can be found in run_squad_helper.\nrun_squad_helper.define_common_squad_flags()\n\nFLAGS = flags.FLAGS\n\n\ndef train_squad(strategy,\n input_meta_data,\n custom_callbacks=None,\n run_eagerly=False,\n init_checkpoint=None,\n sub_model_export_name=None):\n \"\"\"Run bert squad training.\"\"\"\n bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)\n init_checkpoint = init_checkpoint or FLAGS.init_checkpoint\n run_squad_helper.train_squad(strategy, input_meta_data, bert_config,\n custom_callbacks, run_eagerly, init_checkpoint,\n sub_model_export_name=sub_model_export_name)\n\n\ndef predict_squad(strategy, input_meta_data):\n \"\"\"Makes predictions for the squad dataset.\"\"\"\n bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n run_squad_helper.predict_squad(\n strategy, input_meta_data, tokenizer, bert_config, squad_lib_wp)\n\n\ndef eval_squad(strategy, input_meta_data):\n \"\"\"Evaluate on the squad dataset.\"\"\"\n bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n eval_metrics = run_squad_helper.eval_squad(\n strategy, input_meta_data, tokenizer, bert_config, squad_lib_wp)\n return eval_metrics\n\n\ndef export_squad(model_export_path, input_meta_data):\n \"\"\"Exports a trained model as a `SavedModel` for inference.\n\n Args:\n model_export_path: a string specifying the path to the SavedModel directory.\n input_meta_data: dictionary containing meta data about input and model.\n\n Raises:\n Export path is not specified, got an empty string or None.\n \"\"\"\n bert_config = bert_configs.BertConfig.from_json_file(FLAGS.bert_config_file)\n run_squad_helper.export_squad(model_export_path, input_meta_data, bert_config)\n\n\ndef main(_):\n gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param)\n\n with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader:\n input_meta_data = json.loads(reader.read().decode('utf-8'))\n\n if FLAGS.mode == 'export_only':\n export_squad(FLAGS.model_export_path, input_meta_data)\n return\n\n # Configures cluster spec for multi-worker distribution strategy.\n if FLAGS.num_gpus > 0:\n _ = distribute_utils.configure_cluster(FLAGS.worker_hosts, FLAGS.task_index)\n strategy = distribute_utils.get_distribution_strategy(\n distribution_strategy=FLAGS.distribution_strategy,\n num_gpus=FLAGS.num_gpus,\n all_reduce_alg=FLAGS.all_reduce_alg,\n tpu_address=FLAGS.tpu)\n\n if 'train' in FLAGS.mode:\n if FLAGS.log_steps:\n custom_callbacks = [keras_utils.TimeHistory(\n batch_size=FLAGS.train_batch_size,\n log_steps=FLAGS.log_steps,\n logdir=FLAGS.model_dir,\n )]\n else:\n custom_callbacks = None\n\n train_squad(\n strategy,\n input_meta_data,\n custom_callbacks=custom_callbacks,\n run_eagerly=FLAGS.run_eagerly,\n sub_model_export_name=FLAGS.sub_model_export_name,\n )\n if 'predict' in FLAGS.mode:\n predict_squad(strategy, input_meta_data)\n if 'eval' in FLAGS.mode:\n eval_metrics = eval_squad(strategy, input_meta_data)\n f1_score = eval_metrics['final_f1']\n logging.info('SQuAD eval F1-score: %f', f1_score)\n summary_dir = os.path.join(FLAGS.model_dir, 'summaries', 'eval')\n summary_writer = tf.summary.create_file_writer(summary_dir)\n with summary_writer.as_default():\n # TODO(lehou): write to the correct step number.\n tf.summary.scalar('F1-score', f1_score, step=0)\n summary_writer.flush()\n # Also write eval_metrics to json file.\n squad_lib_wp.write_to_json_files(\n eval_metrics, os.path.join(summary_dir, 'eval_metrics.json'))\n time.sleep(60)\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('bert_config_file')\n flags.mark_flag_as_required('model_dir')\n app.run(main)\n", "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tensorflow Example proto decoder for object detection.\n\nA decoder to decode string tensors containing serialized tensorflow.Example\nprotos for object detection.\n\"\"\"\nimport tensorflow as tf\n\n\nclass TfExampleDecoder(object):\n \"\"\"Tensorflow Example proto decoder.\"\"\"\n\n def __init__(self, include_mask=False):\n self._include_mask = include_mask\n self._keys_to_features = {\n 'image/encoded':\n tf.io.FixedLenFeature((), tf.string),\n 'image/source_id':\n tf.io.FixedLenFeature((), tf.string),\n 'image/height':\n tf.io.FixedLenFeature((), tf.int64),\n 'image/width':\n tf.io.FixedLenFeature((), tf.int64),\n 'image/object/bbox/xmin':\n tf.io.VarLenFeature(tf.float32),\n 'image/object/bbox/xmax':\n tf.io.VarLenFeature(tf.float32),\n 'image/object/bbox/ymin':\n tf.io.VarLenFeature(tf.float32),\n 'image/object/bbox/ymax':\n tf.io.VarLenFeature(tf.float32),\n 'image/object/class/label':\n tf.io.VarLenFeature(tf.int64),\n 'image/object/area':\n tf.io.VarLenFeature(tf.float32),\n 'image/object/is_crowd':\n tf.io.VarLenFeature(tf.int64),\n }\n if include_mask:\n self._keys_to_features.update({\n 'image/object/mask':\n tf.io.VarLenFeature(tf.string),\n })\n\n def _decode_image(self, parsed_tensors):\n \"\"\"Decodes the image and set its static shape.\"\"\"\n image = tf.io.decode_image(parsed_tensors['image/encoded'], channels=3)\n image.set_shape([None, None, 3])\n return image\n\n def _decode_boxes(self, parsed_tensors):\n \"\"\"Concat box coordinates in the format of [ymin, xmin, ymax, xmax].\"\"\"\n xmin = parsed_tensors['image/object/bbox/xmin']\n xmax = parsed_tensors['image/object/bbox/xmax']\n ymin = parsed_tensors['image/object/bbox/ymin']\n ymax = parsed_tensors['image/object/bbox/ymax']\n return tf.stack([ymin, xmin, ymax, xmax], axis=-1)\n\n def _decode_masks(self, parsed_tensors):\n \"\"\"Decode a set of PNG masks to the tf.float32 tensors.\"\"\"\n def _decode_png_mask(png_bytes):\n mask = tf.squeeze(\n tf.io.decode_png(png_bytes, channels=1, dtype=tf.uint8), axis=-1)\n mask = tf.cast(mask, dtype=tf.float32)\n mask.set_shape([None, None])\n return mask\n\n height = parsed_tensors['image/height']\n width = parsed_tensors['image/width']\n masks = parsed_tensors['image/object/mask']\n return tf.cond(\n pred=tf.greater(tf.size(input=masks), 0),\n true_fn=lambda: tf.map_fn(_decode_png_mask, masks, dtype=tf.float32),\n false_fn=lambda: tf.zeros([0, height, width], dtype=tf.float32))\n\n def _decode_areas(self, parsed_tensors):\n xmin = parsed_tensors['image/object/bbox/xmin']\n xmax = parsed_tensors['image/object/bbox/xmax']\n ymin = parsed_tensors['image/object/bbox/ymin']\n ymax = parsed_tensors['image/object/bbox/ymax']\n return tf.cond(\n tf.greater(tf.shape(parsed_tensors['image/object/area'])[0], 0),\n lambda: parsed_tensors['image/object/area'],\n lambda: (xmax - xmin) * (ymax - ymin))\n\n def decode(self, serialized_example):\n \"\"\"Decode the serialized example.\n\n Args:\n serialized_example: a single serialized tf.Example string.\n\n Returns:\n decoded_tensors: a dictionary of tensors with the following fields:\n - image: a uint8 tensor of shape [None, None, 3].\n - source_id: a string scalar tensor.\n - height: an integer scalar tensor.\n - width: an integer scalar tensor.\n - groundtruth_classes: a int64 tensor of shape [None].\n - groundtruth_is_crowd: a bool tensor of shape [None].\n - groundtruth_area: a float32 tensor of shape [None].\n - groundtruth_boxes: a float32 tensor of shape [None, 4].\n - groundtruth_instance_masks: a float32 tensor of shape\n [None, None, None].\n - groundtruth_instance_masks_png: a string tensor of shape [None].\n \"\"\"\n parsed_tensors = tf.io.parse_single_example(\n serialized=serialized_example, features=self._keys_to_features)\n for k in parsed_tensors:\n if isinstance(parsed_tensors[k], tf.SparseTensor):\n if parsed_tensors[k].dtype == tf.string:\n parsed_tensors[k] = tf.sparse.to_dense(\n parsed_tensors[k], default_value='')\n else:\n parsed_tensors[k] = tf.sparse.to_dense(\n parsed_tensors[k], default_value=0)\n\n image = self._decode_image(parsed_tensors)\n boxes = self._decode_boxes(parsed_tensors)\n areas = self._decode_areas(parsed_tensors)\n is_crowds = tf.cond(\n tf.greater(tf.shape(parsed_tensors['image/object/is_crowd'])[0], 0),\n lambda: tf.cast(parsed_tensors['image/object/is_crowd'], dtype=tf.bool),\n lambda: tf.zeros_like(parsed_tensors['image/object/class/label'], dtype=tf.bool)) # pylint: disable=line-too-long\n if self._include_mask:\n masks = self._decode_masks(parsed_tensors)\n\n decoded_tensors = {\n 'image': image,\n 'source_id': parsed_tensors['image/source_id'],\n 'height': parsed_tensors['image/height'],\n 'width': parsed_tensors['image/width'],\n 'groundtruth_classes': parsed_tensors['image/object/class/label'],\n 'groundtruth_is_crowd': is_crowds,\n 'groundtruth_area': areas,\n 'groundtruth_boxes': boxes,\n }\n if self._include_mask:\n decoded_tensors.update({\n 'groundtruth_instance_masks': masks,\n 'groundtruth_instance_masks_png': parsed_tensors['image/object/mask'],\n })\n return decoded_tensors\n", "# Lint as: python2, python3\n# Copyright 2018 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\"\"\"Exports an SSD detection model to use with tf-lite.\n\nSee export_tflite_ssd_graph.py for usage.\n\"\"\"\nimport os\nimport tempfile\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.core.protobuf import saver_pb2\nfrom object_detection import exporter\nfrom object_detection.builders import graph_rewriter_builder\nfrom object_detection.builders import model_builder\nfrom object_detection.builders import post_processing_builder\nfrom object_detection.core import box_list\nfrom object_detection.utils import tf_version\n\n_DEFAULT_NUM_CHANNELS = 3\n_DEFAULT_NUM_COORD_BOX = 4\n\nif tf_version.is_tf1():\n from tensorflow.tools.graph_transforms import TransformGraph # pylint: disable=g-import-not-at-top\n\n\ndef get_const_center_size_encoded_anchors(anchors):\n \"\"\"Exports center-size encoded anchors as a constant tensor.\n\n Args:\n anchors: a float32 tensor of shape [num_anchors, 4] containing the anchor\n boxes\n\n Returns:\n encoded_anchors: a float32 constant tensor of shape [num_anchors, 4]\n containing the anchor boxes.\n \"\"\"\n anchor_boxlist = box_list.BoxList(anchors)\n y, x, h, w = anchor_boxlist.get_center_coordinates_and_sizes()\n num_anchors = y.get_shape().as_list()\n\n with tf.Session() as sess:\n y_out, x_out, h_out, w_out = sess.run([y, x, h, w])\n encoded_anchors = tf.constant(\n np.transpose(np.stack((y_out, x_out, h_out, w_out))),\n dtype=tf.float32,\n shape=[num_anchors[0], _DEFAULT_NUM_COORD_BOX],\n name='anchors')\n return encoded_anchors\n\n\ndef append_postprocessing_op(frozen_graph_def,\n max_detections,\n max_classes_per_detection,\n nms_score_threshold,\n nms_iou_threshold,\n num_classes,\n scale_values,\n detections_per_class=100,\n use_regular_nms=False,\n additional_output_tensors=()):\n \"\"\"Appends postprocessing custom op.\n\n Args:\n frozen_graph_def: Frozen GraphDef for SSD model after freezing the\n checkpoint\n max_detections: Maximum number of detections (boxes) to show\n max_classes_per_detection: Number of classes to display per detection\n nms_score_threshold: Score threshold used in Non-maximal suppression in\n post-processing\n nms_iou_threshold: Intersection-over-union threshold used in Non-maximal\n suppression in post-processing\n num_classes: number of classes in SSD detector\n scale_values: scale values is a dict with following key-value pairs\n {y_scale: 10, x_scale: 10, h_scale: 5, w_scale: 5} that are used in decode\n centersize boxes\n detections_per_class: In regular NonMaxSuppression, number of anchors used\n for NonMaxSuppression per class\n use_regular_nms: Flag to set postprocessing op to use Regular NMS instead of\n Fast NMS.\n additional_output_tensors: Array of additional tensor names to output.\n Tensors are appended after postprocessing output.\n\n Returns:\n transformed_graph_def: Frozen GraphDef with postprocessing custom op\n appended\n TFLite_Detection_PostProcess custom op node has four outputs:\n detection_boxes: a float32 tensor of shape [1, num_boxes, 4] with box\n locations\n detection_classes: a float32 tensor of shape [1, num_boxes]\n with class indices\n detection_scores: a float32 tensor of shape [1, num_boxes]\n with class scores\n num_boxes: a float32 tensor of size 1 containing the number of detected\n boxes\n \"\"\"\n new_output = frozen_graph_def.node.add()\n new_output.op = 'TFLite_Detection_PostProcess'\n new_output.name = 'TFLite_Detection_PostProcess'\n new_output.attr['_output_quantized'].CopyFrom(\n attr_value_pb2.AttrValue(b=True))\n new_output.attr['_output_types'].list.type.extend([\n types_pb2.DT_FLOAT, types_pb2.DT_FLOAT, types_pb2.DT_FLOAT,\n types_pb2.DT_FLOAT\n ])\n new_output.attr['_support_output_type_float_in_quantized_op'].CopyFrom(\n attr_value_pb2.AttrValue(b=True))\n new_output.attr['max_detections'].CopyFrom(\n attr_value_pb2.AttrValue(i=max_detections))\n new_output.attr['max_classes_per_detection'].CopyFrom(\n attr_value_pb2.AttrValue(i=max_classes_per_detection))\n new_output.attr['nms_score_threshold'].CopyFrom(\n attr_value_pb2.AttrValue(f=nms_score_threshold.pop()))\n new_output.attr['nms_iou_threshold'].CopyFrom(\n attr_value_pb2.AttrValue(f=nms_iou_threshold.pop()))\n new_output.attr['num_classes'].CopyFrom(\n attr_value_pb2.AttrValue(i=num_classes))\n\n new_output.attr['y_scale'].CopyFrom(\n attr_value_pb2.AttrValue(f=scale_values['y_scale'].pop()))\n new_output.attr['x_scale'].CopyFrom(\n attr_value_pb2.AttrValue(f=scale_values['x_scale'].pop()))\n new_output.attr['h_scale'].CopyFrom(\n attr_value_pb2.AttrValue(f=scale_values['h_scale'].pop()))\n new_output.attr['w_scale'].CopyFrom(\n attr_value_pb2.AttrValue(f=scale_values['w_scale'].pop()))\n new_output.attr['detections_per_class'].CopyFrom(\n attr_value_pb2.AttrValue(i=detections_per_class))\n new_output.attr['use_regular_nms'].CopyFrom(\n attr_value_pb2.AttrValue(b=use_regular_nms))\n\n new_output.input.extend(\n ['raw_outputs/box_encodings', 'raw_outputs/class_predictions', 'anchors'])\n # Transform the graph to append new postprocessing op\n input_names = []\n output_names = ['TFLite_Detection_PostProcess'\n ] + list(additional_output_tensors)\n transforms = ['strip_unused_nodes']\n transformed_graph_def = TransformGraph(frozen_graph_def, input_names,\n output_names, transforms)\n return transformed_graph_def\n\n\ndef export_tflite_graph(pipeline_config,\n trained_checkpoint_prefix,\n output_dir,\n add_postprocessing_op,\n max_detections,\n max_classes_per_detection,\n detections_per_class=100,\n use_regular_nms=False,\n binary_graph_name='tflite_graph.pb',\n txt_graph_name='tflite_graph.pbtxt',\n additional_output_tensors=()):\n \"\"\"Exports a tflite compatible graph and anchors for ssd detection model.\n\n Anchors are written to a tensor and tflite compatible graph\n is written to output_dir/tflite_graph.pb.\n\n Args:\n pipeline_config: a pipeline.proto object containing the configuration for\n SSD model to export.\n trained_checkpoint_prefix: a file prefix for the checkpoint containing the\n trained parameters of the SSD model.\n output_dir: A directory to write the tflite graph and anchor file to.\n add_postprocessing_op: If add_postprocessing_op is true: frozen graph adds a\n TFLite_Detection_PostProcess custom op\n max_detections: Maximum number of detections (boxes) to show\n max_classes_per_detection: Number of classes to display per detection\n detections_per_class: In regular NonMaxSuppression, number of anchors used\n for NonMaxSuppression per class\n use_regular_nms: Flag to set postprocessing op to use Regular NMS instead of\n Fast NMS.\n binary_graph_name: Name of the exported graph file in binary format.\n txt_graph_name: Name of the exported graph file in text format.\n additional_output_tensors: Array of additional tensor names to output.\n Additional tensors are appended to the end of output tensor list.\n\n Raises:\n ValueError: if the pipeline config contains models other than ssd or uses an\n fixed_shape_resizer and provides a shape as well.\n \"\"\"\n tf.gfile.MakeDirs(output_dir)\n if pipeline_config.model.WhichOneof('model') != 'ssd':\n raise ValueError('Only ssd models are supported in tflite. '\n 'Found {} in config'.format(\n pipeline_config.model.WhichOneof('model')))\n\n num_classes = pipeline_config.model.ssd.num_classes\n nms_score_threshold = {\n pipeline_config.model.ssd.post_processing.batch_non_max_suppression\n .score_threshold\n }\n nms_iou_threshold = {\n pipeline_config.model.ssd.post_processing.batch_non_max_suppression\n .iou_threshold\n }\n scale_values = {}\n scale_values['y_scale'] = {\n pipeline_config.model.ssd.box_coder.faster_rcnn_box_coder.y_scale\n }\n scale_values['x_scale'] = {\n pipeline_config.model.ssd.box_coder.faster_rcnn_box_coder.x_scale\n }\n scale_values['h_scale'] = {\n pipeline_config.model.ssd.box_coder.faster_rcnn_box_coder.height_scale\n }\n scale_values['w_scale'] = {\n pipeline_config.model.ssd.box_coder.faster_rcnn_box_coder.width_scale\n }\n\n image_resizer_config = pipeline_config.model.ssd.image_resizer\n image_resizer = image_resizer_config.WhichOneof('image_resizer_oneof')\n num_channels = _DEFAULT_NUM_CHANNELS\n if image_resizer == 'fixed_shape_resizer':\n height = image_resizer_config.fixed_shape_resizer.height\n width = image_resizer_config.fixed_shape_resizer.width\n if image_resizer_config.fixed_shape_resizer.convert_to_grayscale:\n num_channels = 1\n shape = [1, height, width, num_channels]\n else:\n raise ValueError(\n 'Only fixed_shape_resizer'\n 'is supported with tflite. Found {}'.format(\n image_resizer_config.WhichOneof('image_resizer_oneof')))\n\n image = tf.placeholder(\n tf.float32, shape=shape, name='normalized_input_image_tensor')\n\n detection_model = model_builder.build(\n pipeline_config.model, is_training=False)\n predicted_tensors = detection_model.predict(image, true_image_shapes=None)\n # The score conversion occurs before the post-processing custom op\n _, score_conversion_fn = post_processing_builder.build(\n pipeline_config.model.ssd.post_processing)\n class_predictions = score_conversion_fn(\n predicted_tensors['class_predictions_with_background'])\n\n with tf.name_scope('raw_outputs'):\n # 'raw_outputs/box_encodings': a float32 tensor of shape [1, num_anchors, 4]\n # containing the encoded box predictions. Note that these are raw\n # predictions and no Non-Max suppression is applied on them and\n # no decode center size boxes is applied to them.\n tf.identity(predicted_tensors['box_encodings'], name='box_encodings')\n # 'raw_outputs/class_predictions': a float32 tensor of shape\n # [1, num_anchors, num_classes] containing the class scores for each anchor\n # after applying score conversion.\n tf.identity(class_predictions, name='class_predictions')\n # 'anchors': a float32 tensor of shape\n # [4, num_anchors] containing the anchors as a constant node.\n tf.identity(\n get_const_center_size_encoded_anchors(predicted_tensors['anchors']),\n name='anchors')\n\n # Add global step to the graph, so we know the training step number when we\n # evaluate the model.\n tf.train.get_or_create_global_step()\n\n # graph rewriter\n is_quantized = pipeline_config.HasField('graph_rewriter')\n if is_quantized:\n graph_rewriter_config = pipeline_config.graph_rewriter\n graph_rewriter_fn = graph_rewriter_builder.build(\n graph_rewriter_config, is_training=False)\n graph_rewriter_fn()\n\n if pipeline_config.model.ssd.feature_extractor.HasField('fpn'):\n exporter.rewrite_nn_resize_op(is_quantized)\n\n # freeze the graph\n saver_kwargs = {}\n if pipeline_config.eval_config.use_moving_averages:\n saver_kwargs['write_version'] = saver_pb2.SaverDef.V1\n moving_average_checkpoint = tempfile.NamedTemporaryFile()\n exporter.replace_variable_values_with_moving_averages(\n tf.get_default_graph(), trained_checkpoint_prefix,\n moving_average_checkpoint.name)\n checkpoint_to_use = moving_average_checkpoint.name\n else:\n checkpoint_to_use = trained_checkpoint_prefix\n\n saver = tf.train.Saver(**saver_kwargs)\n input_saver_def = saver.as_saver_def()\n frozen_graph_def = exporter.freeze_graph_with_def_protos(\n input_graph_def=tf.get_default_graph().as_graph_def(),\n input_saver_def=input_saver_def,\n input_checkpoint=checkpoint_to_use,\n output_node_names=','.join([\n 'raw_outputs/box_encodings', 'raw_outputs/class_predictions',\n 'anchors'\n ] + list(additional_output_tensors)),\n restore_op_name='save/restore_all',\n filename_tensor_name='save/Const:0',\n clear_devices=True,\n output_graph='',\n initializer_nodes='')\n\n # Add new operation to do post processing in a custom op (TF Lite only)\n if add_postprocessing_op:\n transformed_graph_def = append_postprocessing_op(\n frozen_graph_def,\n max_detections,\n max_classes_per_detection,\n nms_score_threshold,\n nms_iou_threshold,\n num_classes,\n scale_values,\n detections_per_class,\n use_regular_nms,\n additional_output_tensors=additional_output_tensors)\n else:\n # Return frozen without adding post-processing custom op\n transformed_graph_def = frozen_graph_def\n\n binary_graph = os.path.join(output_dir, binary_graph_name)\n with tf.gfile.GFile(binary_graph, 'wb') as f:\n f.write(transformed_graph_def.SerializeToString())\n txt_graph = os.path.join(output_dir, txt_graph_name)\n with tf.gfile.GFile(txt_graph, 'w') as f:\n f.write(str(transformed_graph_def))\n", "# Copyright 2018 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\"\"\"Contains the definition for the PNASNet classification networks.\n\nPaper: https://arxiv.org/abs/1712.00559\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport tensorflow.compat.v1 as tf\nimport tf_slim as slim\nfrom tensorflow.contrib import training as contrib_training\n\nfrom nets.nasnet import nasnet\nfrom nets.nasnet import nasnet_utils\n\narg_scope = slim.arg_scope\n\n\ndef large_imagenet_config():\n \"\"\"Large ImageNet configuration based on PNASNet-5.\"\"\"\n return contrib_training.HParams(\n stem_multiplier=3.0,\n dense_dropout_keep_prob=0.5,\n num_cells=12,\n filter_scaling_rate=2.0,\n num_conv_filters=216,\n drop_path_keep_prob=0.6,\n use_aux_head=1,\n num_reduction_layers=2,\n data_format='NHWC',\n skip_reduction_layer_input=1,\n total_training_steps=250000,\n use_bounded_activation=False,\n )\n\n\ndef mobile_imagenet_config():\n \"\"\"Mobile ImageNet configuration based on PNASNet-5.\"\"\"\n return contrib_training.HParams(\n stem_multiplier=1.0,\n dense_dropout_keep_prob=0.5,\n num_cells=9,\n filter_scaling_rate=2.0,\n num_conv_filters=54,\n drop_path_keep_prob=1.0,\n use_aux_head=1,\n num_reduction_layers=2,\n data_format='NHWC',\n skip_reduction_layer_input=1,\n total_training_steps=250000,\n use_bounded_activation=False,\n )\n\n\ndef pnasnet_large_arg_scope(weight_decay=4e-5, batch_norm_decay=0.9997,\n batch_norm_epsilon=0.001):\n \"\"\"Default arg scope for the PNASNet Large ImageNet model.\"\"\"\n return nasnet.nasnet_large_arg_scope(\n weight_decay, batch_norm_decay, batch_norm_epsilon)\n\n\ndef pnasnet_mobile_arg_scope(weight_decay=4e-5,\n batch_norm_decay=0.9997,\n batch_norm_epsilon=0.001):\n \"\"\"Default arg scope for the PNASNet Mobile ImageNet model.\"\"\"\n return nasnet.nasnet_mobile_arg_scope(weight_decay, batch_norm_decay,\n batch_norm_epsilon)\n\n\ndef _build_pnasnet_base(images,\n normal_cell,\n num_classes,\n hparams,\n is_training,\n final_endpoint=None):\n \"\"\"Constructs a PNASNet image model.\"\"\"\n\n end_points = {}\n\n def add_and_check_endpoint(endpoint_name, net):\n end_points[endpoint_name] = net\n return final_endpoint and (endpoint_name == final_endpoint)\n\n # Find where to place the reduction cells or stride normal cells\n reduction_indices = nasnet_utils.calc_reduction_layers(\n hparams.num_cells, hparams.num_reduction_layers)\n\n # pylint: disable=protected-access\n stem = lambda: nasnet._imagenet_stem(images, hparams, normal_cell)\n # pylint: enable=protected-access\n net, cell_outputs = stem()\n if add_and_check_endpoint('Stem', net):\n return net, end_points\n\n # Setup for building in the auxiliary head.\n aux_head_cell_idxes = []\n if len(reduction_indices) >= 2:\n aux_head_cell_idxes.append(reduction_indices[1] - 1)\n\n # Run the cells\n filter_scaling = 1.0\n # true_cell_num accounts for the stem cells\n true_cell_num = 2\n activation_fn = tf.nn.relu6 if hparams.use_bounded_activation else tf.nn.relu\n for cell_num in range(hparams.num_cells):\n is_reduction = cell_num in reduction_indices\n stride = 2 if is_reduction else 1\n if is_reduction: filter_scaling *= hparams.filter_scaling_rate\n if hparams.skip_reduction_layer_input or not is_reduction:\n prev_layer = cell_outputs[-2]\n net = normal_cell(\n net,\n scope='cell_{}'.format(cell_num),\n filter_scaling=filter_scaling,\n stride=stride,\n prev_layer=prev_layer,\n cell_num=true_cell_num)\n if add_and_check_endpoint('Cell_{}'.format(cell_num), net):\n return net, end_points\n true_cell_num += 1\n cell_outputs.append(net)\n\n if (hparams.use_aux_head and cell_num in aux_head_cell_idxes and\n num_classes and is_training):\n aux_net = activation_fn(net)\n # pylint: disable=protected-access\n nasnet._build_aux_head(aux_net, end_points, num_classes, hparams,\n scope='aux_{}'.format(cell_num))\n # pylint: enable=protected-access\n\n # Final softmax layer\n with tf.variable_scope('final_layer'):\n net = activation_fn(net)\n net = nasnet_utils.global_avg_pool(net)\n if add_and_check_endpoint('global_pool', net) or not num_classes:\n return net, end_points\n net = slim.dropout(net, hparams.dense_dropout_keep_prob, scope='dropout')\n logits = slim.fully_connected(net, num_classes)\n\n if add_and_check_endpoint('Logits', logits):\n return net, end_points\n\n predictions = tf.nn.softmax(logits, name='predictions')\n if add_and_check_endpoint('Predictions', predictions):\n return net, end_points\n return logits, end_points\n\n\ndef build_pnasnet_large(images,\n num_classes,\n is_training=True,\n final_endpoint=None,\n config=None):\n \"\"\"Build PNASNet Large model for the ImageNet Dataset.\"\"\"\n hparams = copy.deepcopy(config) if config else large_imagenet_config()\n # pylint: disable=protected-access\n nasnet._update_hparams(hparams, is_training)\n # pylint: enable=protected-access\n\n if tf.test.is_gpu_available() and hparams.data_format == 'NHWC':\n tf.logging.info(\n 'A GPU is available on the machine, consider using NCHW '\n 'data format for increased speed on GPU.')\n\n if hparams.data_format == 'NCHW':\n images = tf.transpose(a=images, perm=[0, 3, 1, 2])\n\n # Calculate the total number of cells in the network.\n # There is no distinction between reduction and normal cells in PNAS so the\n # total number of cells is equal to the number normal cells plus the number\n # of stem cells (two by default).\n total_num_cells = hparams.num_cells + 2\n\n normal_cell = PNasNetNormalCell(hparams.num_conv_filters,\n hparams.drop_path_keep_prob, total_num_cells,\n hparams.total_training_steps,\n hparams.use_bounded_activation)\n with arg_scope(\n [slim.dropout, nasnet_utils.drop_path, slim.batch_norm],\n is_training=is_training):\n with arg_scope([slim.avg_pool2d, slim.max_pool2d, slim.conv2d,\n slim.batch_norm, slim.separable_conv2d,\n nasnet_utils.factorized_reduction,\n nasnet_utils.global_avg_pool,\n nasnet_utils.get_channel_index,\n nasnet_utils.get_channel_dim],\n data_format=hparams.data_format):\n return _build_pnasnet_base(\n images,\n normal_cell=normal_cell,\n num_classes=num_classes,\n hparams=hparams,\n is_training=is_training,\n final_endpoint=final_endpoint)\nbuild_pnasnet_large.default_image_size = 331\n\n\ndef build_pnasnet_mobile(images,\n num_classes,\n is_training=True,\n final_endpoint=None,\n config=None):\n \"\"\"Build PNASNet Mobile model for the ImageNet Dataset.\"\"\"\n hparams = copy.deepcopy(config) if config else mobile_imagenet_config()\n # pylint: disable=protected-access\n nasnet._update_hparams(hparams, is_training)\n # pylint: enable=protected-access\n\n if tf.test.is_gpu_available() and hparams.data_format == 'NHWC':\n tf.logging.info(\n 'A GPU is available on the machine, consider using NCHW '\n 'data format for increased speed on GPU.')\n\n if hparams.data_format == 'NCHW':\n images = tf.transpose(a=images, perm=[0, 3, 1, 2])\n\n # Calculate the total number of cells in the network.\n # There is no distinction between reduction and normal cells in PNAS so the\n # total number of cells is equal to the number normal cells plus the number\n # of stem cells (two by default).\n total_num_cells = hparams.num_cells + 2\n\n normal_cell = PNasNetNormalCell(hparams.num_conv_filters,\n hparams.drop_path_keep_prob, total_num_cells,\n hparams.total_training_steps,\n hparams.use_bounded_activation)\n with arg_scope(\n [slim.dropout, nasnet_utils.drop_path, slim.batch_norm],\n is_training=is_training):\n with arg_scope(\n [\n slim.avg_pool2d, slim.max_pool2d, slim.conv2d, slim.batch_norm,\n slim.separable_conv2d, nasnet_utils.factorized_reduction,\n nasnet_utils.global_avg_pool, nasnet_utils.get_channel_index,\n nasnet_utils.get_channel_dim\n ],\n data_format=hparams.data_format):\n return _build_pnasnet_base(\n images,\n normal_cell=normal_cell,\n num_classes=num_classes,\n hparams=hparams,\n is_training=is_training,\n final_endpoint=final_endpoint)\n\n\nbuild_pnasnet_mobile.default_image_size = 224\n\n\nclass PNasNetNormalCell(nasnet_utils.NasNetABaseCell):\n \"\"\"PNASNet Normal Cell.\"\"\"\n\n def __init__(self, num_conv_filters, drop_path_keep_prob, total_num_cells,\n total_training_steps, use_bounded_activation=False):\n # Configuration for the PNASNet-5 model.\n operations = [\n 'separable_5x5_2', 'max_pool_3x3', 'separable_7x7_2', 'max_pool_3x3',\n 'separable_5x5_2', 'separable_3x3_2', 'separable_3x3_2', 'max_pool_3x3',\n 'separable_3x3_2', 'none'\n ]\n used_hiddenstates = [1, 1, 0, 0, 0, 0, 0]\n hiddenstate_indices = [1, 1, 0, 0, 0, 0, 4, 0, 1, 0]\n\n super(PNasNetNormalCell, self).__init__(\n num_conv_filters, operations, used_hiddenstates, hiddenstate_indices,\n drop_path_keep_prob, total_num_cells, total_training_steps,\n use_bounded_activation)\n" ]
[ [ "tensorflow.summary.scalar", "tensorflow.summary.create_file_writer", "tensorflow.io.gfile.GFile" ], [ "tensorflow.size", "tensorflow.io.parse_single_example", "tensorflow.zeros", "tensorflow.stack", "tensorflow.shape", "tensorflow.sparse.to_dense", "tensorflow.map_fn", "tensorflow.io.decode_png", "tensorflow.io.decode_image", "tensorflow.zeros_like", "tensorflow.cast", "tensorflow.io.FixedLenFeature", "tensorflow.io.VarLenFeature" ], [ "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.train.Saver", "tensorflow.compat.v1.Session", "tensorflow.tools.graph_transforms.TransformGraph", "tensorflow.compat.v1.identity", "tensorflow.core.framework.attr_value_pb2.AttrValue", "tensorflow.compat.v1.gfile.GFile", "numpy.stack", "tensorflow.compat.v1.get_default_graph", "tensorflow.compat.v1.train.get_or_create_global_step", "tensorflow.compat.v1.gfile.MakeDirs", "tensorflow.compat.v1.name_scope" ], [ "tensorflow.compat.v1.test.is_gpu_available", "tensorflow.compat.v1.transpose", "tensorflow.compat.v1.nn.softmax", "tensorflow.compat.v1.variable_scope", "tensorflow.contrib.training.HParams", "tensorflow.compat.v1.logging.info" ] ]
cns-iu/ccf-research
[ "e029c8985a249c1caec925e95f5286c505c706ea" ]
[ "hackathon/annotation_compare_viz.py" ]
[ "import json\nfrom re import split\nimport shutil\nimport os\nimport sys\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\nfrom skimage import io\nfrom shapely.geometry import Polygon\n\nImage.MAX_IMAGE_PIXELS = None\n\n\ndef make_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n else:\n shutil.rmtree(path)\n os.makedirs(path)\n\n\ndef dice(a, b):\n return 2 * a.intersection(b).area / (a.area + b.area)\n\n\ndef recall(a, b):\n return a.intersection(b).area / b.area\n\n\ndef precision(a, b):\n return a.intersection(b).area / a.area\n\n\ndef find_diff(dice_thred=0.5, draw_preview=True, log_score=True):\n # A - new json\n with open(file_A_path) as data_file:\n data = json.load(data_file)\n\n average_area = sum(\n [Polygon(item[\"geometry\"][\"coordinates\"][0]).area for item in data]\n ) / len(data)\n area_threshold = average_area / 50\n print(\"average area size: \", average_area)\n print(\"size threshold: \", area_threshold)\n\n coor_list_a = []\n\n for item in data:\n coor = item[\"geometry\"][\"coordinates\"]\n poly = Polygon(coor[0])\n if poly.area > area_threshold:\n coor_list_a.extend(item[\"geometry\"][\"coordinates\"])\n else:\n print(\"A ignore\", poly.area)\n A_x_list = [[xy[0] for xy in coor] for coor in coor_list_a]\n A_y_list = [[xy[1] for xy in coor] for coor in coor_list_a]\n A_id_list = [i for i in range(len(coor_list_a))]\n\n # B - old json\n with open(file_B_path) as data_file:\n data = json.load(data_file)\n\n coor_list_b = []\n\n for item in data:\n coor = item[\"geometry\"][\"coordinates\"]\n coor = [\n [[xy[1], xy[0]] for xy in coor[0]]\n ] # for some json. Comment this line if needed\n poly = Polygon(coor[0])\n if poly.area > area_threshold:\n coor_list_b.extend(coor)\n else:\n print(\"B ignore\", poly.area)\n B_x_list = [[xy[0] for xy in coor] for coor in coor_list_b]\n B_y_list = [[xy[1] for xy in coor] for coor in coor_list_b]\n\n # find difference\n center_list_new = []\n for i in range(len(A_x_list)):\n mean_x = (sum(A_x_list[i]) - A_x_list[i][-1]) / (len(A_x_list[i]) - 1)\n mean_y = (sum(A_y_list[i]) - A_y_list[i][-1]) / (len(A_y_list[i]) - 1)\n center_list_new.append((mean_x, mean_y))\n\n center_list_old = []\n for i in range(len(B_x_list)):\n mean_x = (sum(B_x_list[i]) - B_x_list[i][-1]) / (len(B_x_list[i]) - 1)\n mean_y = (sum(B_y_list[i]) - B_y_list[i][-1]) / (len(B_y_list[i]) - 1)\n center_list_old.append((mean_x, mean_y))\n\n new_added_list = []\n new_added_f1_list = []\n new_same_list = []\n new_revised_list = []\n f1_list = []\n\n positon_threshold = 500\n dice_threshold = dice_thred\n\n ignore_count = 0\n for i in A_id_list:\n x, y = center_list_new[i]\n new_p = Polygon(coor_list_a[i])\n min_f1 = 0\n min_j = -1\n _recall, _precision = -1, -1\n for j in range(len(center_list_old)):\n _x, _y = center_list_old[j]\n old_p = Polygon(coor_list_b[j])\n if (x - _x) ** 2 + (y - _y) ** 2 <= positon_threshold ** 2:\n f1 = dice(new_p, old_p)\n if f1 > min_f1:\n min_f1 = f1\n min_j = j\n _recall = recall(new_p, old_p)\n _precision = precision(new_p, old_p)\n\n if min_f1 >= 0.999:\n _flag = f\"Same\\t{min_f1}\"\n new_same_list.append(i)\n elif min_f1 >= dice_threshold:\n _flag = f\"Revised\\t{min_f1}\"\n new_revised_list.append(i)\n f1_list.append((min_f1, _recall, _precision))\n else:\n _flag = f\"Added\\t{min_f1}\"\n new_added_list.append(i)\n new_added_f1_list.append(min_f1)\n # print(min_f1)\n if _flag.startswith(\"Same\") or _flag.startswith(\"Revised\"):\n if min_j != -1:\n coor_list_b.pop(min_j)\n center_list_old.pop(min_j)\n # print(i, _flag)\n\n removed_count = len(center_list_old)\n print(f\"A\\tB\\tsame\\tmatch\\tadded\\tdeleted\")\n print(\n f\"{len(A_x_list)}\\t{len(B_x_list)}\\t{len(new_same_list)}\\t{len(new_revised_list)}\"\n f\"\\t{len(new_added_list)}\\t{removed_count}\"\n )\n print(f\"[FP: {len(new_added_list)}/{len(A_x_list)}]\")\n print(f\"[FN: {removed_count}/{len(B_x_list)}]\")\n # print(f\"{len(new_same_list)} same\")\n # print(f\"{len(new_revised_list)} revised\")\n # print(f\"{len(new_added_list)} added\")\n # print(f\"{removed_count} deleted\")\n\n # draw visualization\n if draw_preview:\n ref_image = io.imread(image_ref_path)\n background = np.zeros(shape=ref_image.shape, dtype=np.uint8)\n img = Image.fromarray(background, \"L\")\n img = img.convert(\"RGB\")\n font_path = r\"c:\\windows\\fonts\\bahnschrift.ttf\"\n font = ImageFont.truetype(font_path, size=48)\n title_font = ImageFont.truetype(font_path, size=72)\n ImageDraw.Draw(img).text(\n (100, 400),\n text=f\"DICE Threshold = {dice_thred}\",\n font=title_font,\n fill=\"white\",\n )\n ImageDraw.Draw(img).text(\n (100, 480),\n text=f\"PREDICTION [FP: {len(new_added_list)}/{len(A_x_list)}]\",\n font=title_font,\n fill=\"yellow\",\n )\n ImageDraw.Draw(img).text(\n (100, 560),\n text=f\"GROUND TRUTH [FN: {removed_count}/{len(B_x_list)}]\",\n font=title_font,\n fill=\"red\",\n )\n\n for i in new_added_list:\n coor_tuple = [(xy[1], xy[0]) for xy in coor_list_a[i]]\n # print(coor_tuple)\n ImageDraw.Draw(img).line(coor_tuple, fill=\"yellow\", width=6)\n # text\n f1 = new_added_f1_list[new_added_list.index(i)]\n if f1 > 0:\n text = \"{:.3f}\".format(f1) # + f\",{Polygon(coor_list_a[i]).area}\"\n ImageDraw.Draw(img).text(\n (center_list_new[i][1] - 40, center_list_new[i][0] + 60),\n text,\n font=font,\n )\n\n for coor_b in coor_list_b:\n coor_tuple = [(xy[1], xy[0]) for xy in coor_b]\n # print(coor_tuple)\n ImageDraw.Draw(img).line(coor_tuple, fill=\"red\", width=6)\n # text = f\",{Polygon(coor_b).area}\"\n # ImageDraw.Draw(img).text(\n # (coor_tuple[0][0], coor_tuple[0][1]),\n # text,\n # font=font,\n # )\n img = np.array(img).astype(\"uint8\")\n output_path = image_ref_path.replace(\n \".png\", f'_{str(dice_thred).replace(\".\",\"_\")}.png'\n )\n io.imsave(output_path, img)\n print(f\"Image saved to {output_path}\")\n\n # write score\n if log_score:\n txt_path = file_A_path.replace(\"json\", \"txt\")\n with open(txt_path, \"w\") as f:\n for item in f1_list:\n f.write(f\"{item[0]},{item[1]},{item[2]}\\n\")\n\n\nif __name__ == \"__main__\":\n file_A_path = (\n r\"C:\\Users\\yiju\\Desktop\\Copy\\Scripts\\masks\\1-tom-new-kidney\\pred_00a67c839.json\"\n )\n file_B_path = r\"C:\\Users\\yiju\\Desktop\\Copy\\Data\\hubmap-kidney-segmentation\\test\\00a67c839.json\"\n\n if len(sys.argv) >= 3:\n file_A_path = sys.argv[1]\n file_B_path = sys.argv[2]\n image_ref_path = file_A_path.replace(\"json\", \"png\")\n\n A_name = file_A_path.split(\"\\\\\")[-1].split(\".\")[0]\n B_name = file_B_path.split(\"\\\\\")[-1].split(\".\")[0]\n print(\"A: \", A_name)\n print(\"B: \", B_name)\n\n for d in [0.5]: # [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]:\n find_diff(dice_thred=d, draw_preview=True, log_score=True)\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
yizhe-ang/MMSceneGraph
[ "d4daec3d7930d6fe1efe75b9c0a265c8be0b70ba" ]
[ "mmdet/models/relation_heads/imp_head.py" ]
[ "# ---------------------------------------------------------------\r\n# imp_head.py\r\n# Set-up time: 2020/5/21 下午11:22\r\n# Copyright (c) 2020 ICT\r\n# Licensed under The MIT License [see LICENSE for details]\r\n# Written by Kenneth-Wong (Wenbin-Wang) @ VIPL.ICT\r\n# Contact: [email protected] [OR] [email protected]\r\n# ---------------------------------------------------------------\r\n\r\nfrom ..registry import HEADS\r\nimport torch\r\nfrom .relation_head import RelationHead\r\nfrom .approaches import IMPContext\r\nfrom mmdet.core import bbox2roi\r\n\r\n\r\[email protected]_module\r\nclass IMPHead(RelationHead):\r\n def __init__(self, **kwargs):\r\n super(IMPHead, self).__init__(**kwargs)\r\n\r\n self.context_layer = IMPContext(self.head_config, self.obj_classes, self.rel_classes)\r\n\r\n def forward(self,\r\n img,\r\n img_meta,\r\n det_result,\r\n gt_result=None,\r\n is_testing=False,\r\n ignore_classes=None):\r\n \"\"\"\r\n Obtain the relation prediction results based on detection results.\r\n Args:\r\n img (Tensor): of shape (N, C, H, W) encoding input images.\r\n Typically these should be mean centered and std scaled.\r\n\r\n img_meta (list[dict]): list of image info dict where each dict has:\r\n 'img_shape', 'scale_factor', 'flip', and may also contain\r\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\r\n For details on the values of these keys see\r\n `mmdet/datasets/pipelines/formatting.py:Collect`.\r\n det_result: (Result): Result containing bbox, label, mask, point, rels,\r\n etc. According to different mode, all the contents have been\r\n set correctly. Feel free to use it.\r\n gt_result : (Result): The ground truth information.\r\n is_testing:\r\n\r\n Returns:\r\n det_result with the following newly added keys:\r\n refine_scores (list[Tensor]): logits of object\r\n rel_scores (list[Tensor]): logits of relation\r\n rel_pair_idxes (list[Tensor]): (num_rel, 2) index of subject and object\r\n relmaps (list[Tensor]): (num_obj, num_obj):\r\n target_rel_labels (list[Tensor]): the target relation label.\r\n \"\"\"\r\n roi_feats, union_feats, det_result = self.frontend_features(img, img_meta, det_result, gt_result)\r\n if roi_feats.shape[0] == 0:\r\n return det_result\r\n\r\n refine_obj_scores, rel_scores = self.context_layer(roi_feats, union_feats, det_result)\r\n\r\n num_rels = [r.shape[0] for r in det_result.rel_pair_idxes]\r\n num_objs = [len(b) for b in det_result.bboxes]\r\n assert len(num_rels) == len(num_objs)\r\n\r\n if self.use_bias:\r\n obj_preds = refine_obj_scores.max(-1)[1]\r\n obj_preds = obj_preds.split(num_objs, dim=0)\r\n\r\n pair_preds = []\r\n for pair_idx, obj_pred in zip(det_result.rel_pair_idxes, obj_preds):\r\n pair_preds.append(torch.stack((obj_pred[pair_idx[:, 0]], obj_pred[pair_idx[:, 1]]), dim=1))\r\n pair_pred = torch.cat(pair_preds, dim=0)\r\n\r\n rel_scores = rel_scores + self.freq_bias.index_with_labels(pair_pred.long())\r\n\r\n # make some changes: list to tensor or tensor to tuple\r\n if self.training:\r\n det_result.target_labels = torch.cat(det_result.target_labels, dim=-1)\r\n det_result.target_rel_labels = torch.cat(det_result.target_rel_labels, dim=-1)\r\n else:\r\n refine_obj_scores = refine_obj_scores.split(num_objs, dim=0)\r\n rel_scores = rel_scores.split(num_rels, dim=0)\r\n\r\n det_result.refine_scores = refine_obj_scores\r\n det_result.rel_scores = rel_scores\r\n return det_result\r\n\r\n" ]
[ [ "torch.stack", "torch.cat" ] ]
jvel07/ast
[ "600e7cf952ec59ac9cc1bb3170d3da7578e1f384" ]
[ "src/models/ast_models.py" ]
[ "# -*- coding: utf-8 -*-\n# @Time : 6/10/21 5:04 PM\n# @Author : Yuan Gong\n# @Affiliation : Massachusetts Institute of Technology\n# @Email : [email protected]\n# @File : ast_models.py\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1,2,3\"\n\n\nimport torch\nimport torch.nn as nn\nfrom torch.cuda.amp import autocast\nimport wget\n\nos.environ['TORCH_HOME'] = '../../pretrained_models'\nimport timm\nfrom timm.models.layers import to_2tuple, trunc_normal_\n\n\n# override the timm package to relax the input shape constraint.\nclass PatchEmbed(nn.Module):\n def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):\n super().__init__()\n\n img_size = to_2tuple(img_size)\n patch_size = to_2tuple(patch_size)\n num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])\n self.img_size = img_size\n self.patch_size = patch_size\n self.num_patches = num_patches\n\n self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)\n\n def forward(self, x):\n x = self.proj(x).flatten(2).transpose(1, 2)\n return x\n\n\nclass ASTModel(nn.Module):\n \"\"\"\n The AST model.\n :param label_dim: the label dimension, i.e., the number of total classes, it is 527 for AudioSet, 50 for ESC-50, and 35 for speechcommands v2-35\n :param fstride: the stride of patch spliting on the frequency dimension, for 16*16 patchs, fstride=16 means no overlap, fstride=10 means overlap of 6\n :param tstride: the stride of patch spliting on the time dimension, for 16*16 patchs, tstride=16 means no overlap, tstride=10 means overlap of 6\n :param input_fdim: the number of frequency bins of the input spectrogram\n :param input_tdim: the number of time frames of the input spectrogram\n :param imagenet_pretrain: if use ImageNet pretrained model\n :param audioset_pretrain: if use full AudioSet and ImageNet pretrained model\n :param model_size: the model size of AST, should be in [tiny224, small224, base224, base384], base224 and base 384 are same model, but are trained differently during ImageNet pretraining.\n \"\"\"\n\n def __init__(self, label_dim=3, fstride=10, tstride=10, input_fdim=128, input_tdim=1024, imagenet_pretrain=True,\n audioset_pretrain=True, model_size='base384', verbose=True):\n\n super(ASTModel, self).__init__()\n assert timm.__version__ == '0.4.5', 'Please use timm == 0.4.5, the code might not be compatible with newer versions.'\n\n if verbose == True:\n print('---------------AST Model Summary---------------')\n print('ImageNet pretraining: {:s}, AudioSet pretraining: {:s}'.format(str(imagenet_pretrain),\n str(audioset_pretrain)))\n # override timm input shape restriction\n timm.models.vision_transformer.PatchEmbed = PatchEmbed\n\n # if AudioSet pretraining is not used (but ImageNet pretraining may still apply)\n if audioset_pretrain == False:\n if model_size == 'tiny224':\n self.v = timm.create_model('vit_deit_tiny_distilled_patch16_224', pretrained=imagenet_pretrain)\n elif model_size == 'small224':\n self.v = timm.create_model('vit_deit_small_distilled_patch16_224', pretrained=imagenet_pretrain)\n elif model_size == 'base224':\n self.v = timm.create_model('vit_deit_base_distilled_patch16_224', pretrained=imagenet_pretrain)\n elif model_size == 'base384':\n self.v = timm.create_model('vit_deit_base_distilled_patch16_384', pretrained=imagenet_pretrain)\n else:\n raise Exception('Model size must be one of tiny224, small224, base224, base384.')\n self.original_num_patches = self.v.patch_embed.num_patches\n self.oringal_hw = int(self.original_num_patches ** 0.5)\n self.original_embedding_dim = self.v.pos_embed.shape[2]\n self.mlp_head = nn.Sequential(nn.LayerNorm(self.original_embedding_dim),\n nn.Linear(self.original_embedding_dim, label_dim))\n\n # automatcially get the intermediate shape\n f_dim, t_dim = self.get_shape(fstride, tstride, input_fdim, input_tdim)\n num_patches = f_dim * t_dim\n self.v.patch_embed.num_patches = num_patches\n if verbose == True:\n print('frequncey stride={:d}, time stride={:d}'.format(fstride, tstride))\n print('number of patches={:d}'.format(num_patches))\n\n # the linear projection layer\n new_proj = torch.nn.Conv2d(1, self.original_embedding_dim, kernel_size=(16, 16), stride=(fstride, tstride))\n if imagenet_pretrain == True:\n new_proj.weight = torch.nn.Parameter(torch.sum(self.v.patch_embed.proj.weight, dim=1).unsqueeze(1))\n new_proj.bias = self.v.patch_embed.proj.bias\n self.v.patch_embed.proj = new_proj\n\n # the positional embedding\n if imagenet_pretrain == True:\n # get the positional embedding from deit model, skip the first two tokens (cls token and distillation token), reshape it to original 2D shape (24*24).\n new_pos_embed = self.v.pos_embed[:, 2:, :].detach().reshape(1, self.original_num_patches,\n self.original_embedding_dim).transpose(1,\n 2).reshape(\n 1, self.original_embedding_dim, self.oringal_hw, self.oringal_hw)\n # cut (from middle) or interpolate the second dimension of the positional embedding\n if t_dim <= self.oringal_hw:\n new_pos_embed = new_pos_embed[:, :, :,\n int(self.oringal_hw / 2) - int(t_dim / 2): int(self.oringal_hw / 2) - int(\n t_dim / 2) + t_dim]\n else:\n new_pos_embed = torch.nn.functional.interpolate(new_pos_embed, size=(self.oringal_hw, t_dim),\n mode='bilinear')\n # cut (from middle) or interpolate the first dimension of the positional embedding\n if f_dim <= self.oringal_hw:\n new_pos_embed = new_pos_embed[:, :,\n int(self.oringal_hw / 2) - int(f_dim / 2): int(self.oringal_hw / 2) - int(\n f_dim / 2) + f_dim, :]\n else:\n new_pos_embed = torch.nn.functional.interpolate(new_pos_embed, size=(f_dim, t_dim), mode='bilinear')\n # flatten the positional embedding\n new_pos_embed = new_pos_embed.reshape(1, self.original_embedding_dim, num_patches).transpose(1, 2)\n # concatenate the above positional embedding with the cls token and distillation token of the deit model.\n self.v.pos_embed = nn.Parameter(torch.cat([self.v.pos_embed[:, :2, :].detach(), new_pos_embed], dim=1))\n else:\n # if not use imagenet pretrained model, just randomly initialize a learnable positional embedding\n # TODO can use sinusoidal positional embedding instead\n new_pos_embed = nn.Parameter(\n torch.zeros(1, self.v.patch_embed.num_patches + 2, self.original_embedding_dim))\n self.v.pos_embed = new_pos_embed\n trunc_normal_(self.v.pos_embed, std=.02)\n\n # now load a model that is pretrained on both ImageNet and AudioSet\n elif audioset_pretrain == True:\n if audioset_pretrain == True and imagenet_pretrain == False:\n raise ValueError(\n 'currently model pretrained on only audioset is not supported, please set imagenet_pretrain = True to use audioset pretrained model.')\n if model_size != 'base384':\n raise ValueError('currently only has base384 AudioSet pretrained model.')\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n if os.path.exists('../../pretrained_models/audioset_10_10_0.4593.pth') == False:\n # this model performs 0.4593 mAP on the audioset eval set\n audioset_mdl_url = 'https://www.dropbox.com/s/cv4knew8mvbrnvq/audioset_0.4593.pth?dl=1'\n wget.download(audioset_mdl_url, out='../../pretrained_models/audioset_10_10_0.4593.pth')\n sd = torch.load('../../pretrained_models/audioset_10_10_0.4593.pth', map_location=device)\n # sd = torch.load('../../pretrained_models/ast_audioset.pth', map_location=device)\n audio_model = ASTModel(label_dim=527, fstride=10, tstride=10, input_fdim=128, input_tdim=1024,\n imagenet_pretrain=False, audioset_pretrain=False, model_size='base384',\n verbose=False)\n audio_model = torch.nn.DataParallel(audio_model)\n print(\"***************USING=>\", torch.cuda.current_device())\n audio_model.load_state_dict(sd, strict=False)\n self.v = audio_model.module.v\n self.original_embedding_dim = self.v.pos_embed.shape[2]\n self.mlp_head = nn.Sequential(nn.LayerNorm(self.original_embedding_dim),\n nn.Linear(self.original_embedding_dim, label_dim))\n\n f_dim, t_dim = self.get_shape(fstride, tstride, input_fdim, input_tdim)\n num_patches = f_dim * t_dim\n self.v.patch_embed.num_patches = num_patches\n if verbose == True:\n print('frequncey stride={:d}, time stride={:d}'.format(fstride, tstride))\n print('number of patches={:d}'.format(num_patches))\n\n new_pos_embed = self.v.pos_embed[:, 2:, :].detach().reshape(1, 1212, 768).transpose(1, 2).reshape(1, 768,\n 12, 101)\n # if the input sequence length is larger than the original audioset (10s), then cut the positional embedding\n if t_dim < 101:\n new_pos_embed = new_pos_embed[:, :, :, 50 - int(t_dim / 2): 50 - int(t_dim / 2) + t_dim]\n # otherwise interpolate\n else:\n new_pos_embed = torch.nn.functional.interpolate(new_pos_embed, size=(12, t_dim), mode='bilinear')\n print(\"NEW POST EMBED:\", new_pos_embed.shape)\n new_pos_embed = new_pos_embed.reshape(1, 768, num_patches).transpose(1, 2)\n print(\"NEW POST EMBED:\", new_pos_embed.shape)\n self.v.pos_embed = nn.Parameter(torch.cat([self.v.pos_embed[:, :2, :].detach(), new_pos_embed], dim=1))\n\n def get_shape(self, fstride, tstride, input_fdim=128, input_tdim=1024):\n test_input = torch.randn(1, 1, input_fdim, input_tdim)\n test_proj = nn.Conv2d(1, self.original_embedding_dim, kernel_size=(16, 16), stride=(fstride, tstride))\n test_out = test_proj(test_input)\n f_dim = test_out.shape[2]\n t_dim = test_out.shape[3]\n return f_dim, t_dim\n\n @autocast()\n def forward(self, x):\n \"\"\"\n :param x: the input spectrogram, expected shape: (batch_size, time_frame_num, frequency_bins), e.g., (12, 1024, 128)\n :return: prediction\n \"\"\"\n # expect input x = (batch_size, time_frame_num, frequency_bins), e.g., (12, 1024, 128)\n x = x.unsqueeze(1)\n x = x.transpose(2, 3)\n\n B = x.shape[0]\n x = self.v.patch_embed(x)\n cls_tokens = self.v.cls_token.expand(B, -1, -1)\n dist_token = self.v.dist_token.expand(B, -1, -1)\n x = torch.cat((cls_tokens, dist_token, x), dim=1)\n x = x + self.v.pos_embed\n x = self.v.pos_drop(x)\n for blk in self.v.blocks:\n x = blk(x)\n x = self.v.norm(x)\n x = (x[:, 0] + x[:, 1]) / 2\n\n # x = self.mlp_head(x)\n return x\n\n\n# if __name__ == '__main__':\n# input_tdim = 100\n# ast_mdl = ASTModel(input_tdim=input_tdim)\n# # input a batch of 10 spectrogram, each with 100 time frames and 128 frequency bins\n# test_input = torch.rand([10, input_tdim, 128])\n# test_output = ast_mdl(test_input)\n# # output should be in shape [10, 527], i.e., 10 samples, each with prediction of 527 classes.\n# print(test_output.shape)\n#\n# input_tdim = 512\n# ast_mdl = ASTModel(input_tdim=input_tdim, label_dim=50, audioset_pretrain=True)\n# # input a batch of 10 spectrogram, each with 512 time frames and 128 frequency bins\n# test_input = torch.rand([10, input_tdim, 128])\n# test_output = ast_mdl(test_input)\n# # output should be in shape [10, 527], i.e., 10 samples, each with prediction of 527 classes.\n# print(test_output.shape)\n" ]
[ [ "torch.sum", "torch.nn.Linear", "torch.load", "torch.randn", "torch.cuda.current_device", "torch.cuda.amp.autocast", "torch.nn.Conv2d", "torch.nn.LayerNorm", "torch.cuda.is_available", "torch.zeros", "torch.nn.DataParallel", "torch.cat", "torch.nn.functional.interpolate" ] ]
zhaohengyin/irgail_example
[ "89f7661b5ab08bdf79686eaf8933ad7b5badced4" ]
[ "utils.py" ]
[ "from tqdm import tqdm\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\ndef build_mlp(input_dim, output_dim, hidden_units=[64, 64],\n hidden_activation=nn.Tanh(), output_activation=None):\n layers = []\n units = input_dim\n for next_units in hidden_units:\n layers.append(nn.Linear(units, next_units))\n layers.append(hidden_activation)\n units = next_units\n layers.append(nn.Linear(units, output_dim))\n if output_activation is not None:\n layers.append(output_activation)\n return nn.Sequential(*layers)\n\ndef dict_concat(x):\n return torch.cat([value for key, value in x.items()], dim=0)\n\ndef dict_config_concat(x):\n return torch.cat([torch.cat((value, key.repeat(value.size(0),1)), dim=1) for key, value in x.items()], dim=0)\n" ]
[ [ "torch.nn.Sequential", "torch.nn.Linear", "torch.nn.Tanh" ] ]
kyuhoJeong11/GrewRL
[ "a514698df8d38df34de0bd1667d99927f0aa3885" ]
[ "carla/PythonAPI/examples/tutorial4.py" ]
[ "import glob\nimport os\nimport sys\nimport random\nimport time\nimport numpy as np\nimport cv2\nimport math\nfrom collections import deque\nfrom keras.applications.xception import Xception\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.optimizers import Adam\nfrom keras.models import Model\n\n'''\nCarla 패키지가 사용하는 egg파일 탐색\n'''\ntry:\n sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (\n sys.version_info.major,\n sys.version_info.minor,\n 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])\nexcept IndexError:\n pass\nimport carla\n\nSHOW_PREVIEW = False\nIM_WIDTH = 640\nIM_HEIGHT = 480\nSECONDS_PER_EPISODE = 10\nREPLAY_MEMORY_SIZE = 5_000\nMIN_REPLAY_MEMORY_SIZE = 1_000\nMINIBATCH_SIZE = 16\nPREDICTION_BATCH_SIZE = 1\nTRAINING_BATCH_SIZE = MINIBATCH_SIZE // 4\nUPDATE_TARGET_EVERY = 5\nMODEL_NAME = \"Xception\"\n\nMEMORY_FRACTION = 0.8\nMIN_REWARD = -200\n\nEPISODES = 100\n\nDISCOUNT = 0.99\nepsilon = 1\nEPSILON_DECAY = 0.95\nMIN_EPSILON = 0.001\n\nAGGREGATE_STATS_EVERY = 10\n\n'''\n환경 class 세팅\n'''\nclass CarEnv:\n SHOW_CAM = SHOW_PREVIEW # 미리보기 여부\n STEER_AMT = 1.0\n im_width = IM_WIDTH\n im_height = IM_HEIGHT\n front_camera = None\n actor_list = []\n collision_hist = [] # collision 목록\n\n def __init__(self):\n self.client = carla.Client(\"localhost\", 2000)\n self.client.set_timeout(2.0)\n\n # client가 켜져 있다면, world 검색 가능.\n self.world = self.client.get_world()\n\n # world에는 우리가 시뮬레이션에 액터를 새로 추가할 때 사용할 수 있는 bp 목록이 있다.\n self.blueprint_library = self.world.get_blueprint_library()\n\n # 차량 모델 지정\n self.model_3 = self.blueprint_library.filter(\"model3\")[0]\n\n def reset(self):\n self.collision_hist = []\n self.actor_list = []\n\n # 랜덤한 위치에 차량 생성 후 actor list에 추가\n self.transform = random.choice(self.world.get_map().get_spawn_points())\n self.vehicle = self.world.spawn_actor(self.model_3, self.transform)\n self.actor_list.append(self.vehicle)\n\n # rgb Camera 센서의 bp 가져오기\n self.rgb_cam = self.blueprint_library.find('sensor.camera.rgb')\n\n # rgb Camera 센서로 입력 받은 이미지의 크기 조절\n self.rgb_cam.set_attribute(\"image_size_x\", f\"{self.im_width}\")\n self.rgb_cam.set_attribute(\"image_size_y\", f\"{self.im_height}\")\n self.rgb_cam.set_attribute(\"fov\", f\"110\")\n\n # sensor의 위치 조정\n transform = carla.Transform(carla.Location(x=2.5, z=0.7))\n\n # 센서의 생성 및 리스트 추가.\n self.sensor = self.world.spawn_actor(self.rgb_cam, transform, attach_to=self.vehicle)\n self.actor_list.append(self.sensor)\n\n # 센서로 입력 받은 데이터를 활용하기 위해 lambda 함수 사용\n self.sensor.listen(lambda data: self.process_img(data))\n\n self.vehicle.apply_control(carla.VehicleControl(throttle=0.0, brake=0.0))\n\n '''\n 차량 생성 시 차가 지면에 부딪히면 충돌이 발생. \n 또는 센서들이 초기화되고 값을 반환하는 데 시간이 걸릴 수 있음. \n 따라서 4초 정도의 대기시간을 사용.\n '''\n time.sleep(4)\n\n # collision 센서의 bp 가져오기\n colsensor = self.blueprint_library.find(\"sensor.other.collision\")\n\n # 센서의 생성 및 리스트 추가\n self.colsensor = self.world.spawn_actor(colsensor, transform, attach_to=self.vehicle)\n self.actor_list.append(self.colsensor)\n\n # 센서로 입력 받은 데이터를 활용하기 위해 lambda 함수 사용\n self.colsensor.listen(lambda event: self.collision_data(event))\n\n while self.front_camera is None:\n time.sleep(0.01)\n\n '''\n 에피소드의 실제 확인 시간 기록.\n 브레이크와 스로틀이 사용되지 않는지 확인 후\n 첫 번째 관찰 결과 반환. \n '''\n self.episode_start = time.time()\n self.vehicle.apply_control(carla.VehicleControl(throttle=0.0, brake=0.0))\n\n return self.front_camera\n\n # collision data 처리\n def collision_data(self, event):\n self.collision_hist.append(event)\n\n # image data 처리\n def process_img(self, image):\n i = np.array(image.raw_data)\n #print(i.shape)\n i2 = i.reshape((self.im_height, self.im_width, 4))\n i3 = i2[:, :, :3]\n if self.SHOW_CAM:\n cv2.imshow(\"\", i3)\n cv2.waitKey(1)\n self.front_camera = i3\n\n # action, reward, done, any_extra_info 관리\n def step(self, action):\n if action == 0:\n self.vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=-1*self.STEER_AMT))\n elif action == 1:\n self.vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer= 0))\n elif action == 2:\n self.vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=1*self.STEER_AMT))\n\n v = self.vehicle.get_velocity()\n kmh = int(3.6 * math.sqrt(v.x**2 + v.y**2 + v.z**2))\n\n if len(self.collision_hist) != 0:\n done = True\n reward = -200\n elif kmh < 50:\n done = False\n reward = -1\n else:\n done = False\n reward = 1\n\n if self.episode_start + SECONDS_PER_EPISODE < time.time():\n done = True\n\n return self.front_camera, reward, done, None\n\n# 강화 학습\nclass DQNAgent:\n def __init__(self):\n self.model = self.create_model()\n self.target_model = self.create_model()\n self.target_model.set_weights(self.model.get_weights())\n\n self.replay_memory = deque(maxlen=REPLAY_MEMORY_SIZE)\n\n self.tensorboard = ModifiedTensorBoard(log_dir=f\"logs/{MODEL_NAME}-{int(time.time())}\")\n self.target_update_counter = 0\n self.graph = tf.get_default_graph()\n\n self.terminate = False\n self.last_logged_episode = 0\n self.training_initialized = False\n\n # 모델 생성\n def create_model(self):\n base_model = Xception(weights=None, include_top=False, input_shape=(IM_HEIGHT, IM_WIDTH,3))\n\n x = base_model.output\n x = GlobalAveragePooling2D()(x)\n\n predictions = Dense(3, activation=\"linear\")(x)\n model = Model(inputs=base_model.input, outputs=predictions)\n model.compile(loss=\"mse\", optimizer=Adam(lr=0.001), metrics=[\"accuracy\"])\n return model\n\n\n def update_replay_memory(self, transition):\n # transition = (current_state, action, reward, new_state, done)\n self.replay_memory.append(transition)\n\n def train(self):\n if len(self.replay_memory) < MIN_REPLAY_MEMORY_SIZE:\n return\n\n minibatch = random.sample(self.replay_memory, MINIBATCH_SIZE)\n\n current_states = np.array([transition[0] for transition in minibatch])/255\n with self.graph.as_default():\n current_qs_list = self.model.predict(current_states, PREDICTION_BATCH_SIZE)\n\n new_current_states = np.array([transition[3] for transition in minibatch])/255\n with self.graph.as_default():\n future_qs_list = self.target_model.predict(new_current_states, PREDICTION_BATCH_SIZE)\n\n # x = input / y = output\n X = []\n y = []\n\n for index, (current_state, action, reward, new_state, done) in enumerate(minibatch):\n if not done:\n max_future_q = np.max(future_qs_list[index])\n new_q = reward + DISCOUNT * max_future_q\n else:\n new_q = reward\n\n current_qs = current_qs_list[index]\n current_qs[action] = new_q\n\n X.append(current_state)\n y.append(current_qs)\n\n '''\n step 단위가 아니라 episode 단위로 log 기록\n log_this_step이 true일 때만 TensorBoard에 log 기록\n '''\n log_this_step = False\n if self.tensorboard.step > self.last_logged_episode:\n log_this_step = True\n self.last_log_episode = self.tensorboard.step\n\n with self.graph.as_default():\n self.model.fit(np.array(X)/255, np.array(y), batch_size=TRAINING_BATCH_SIZE, verbose=0, shuffle=False, callbacks=[self.tensorboard] if log_this_step else None)\n\n\n if log_this_step:\n self.target_update_counter += 1\n\n # target_model 업데이트 여부 확인\n if self.target_update_counter > UPDATE_TARGET_EVERY:\n self.target_model.set_weights(self.model.get_weights())\n self.target_update_counter = 0\n\n def get_qs(self, state):\n return self.model.predict(np.array(state).reshape(-1 *state.shape)/255)[0]\n\n # train 진행\n def train_in_loop(self):\n X = np.random.uniform(size=(1, IM_HEIGHT, IM_WIDTH, 3)).astype(np.float32)\n y = np.random.uniform(size=(1, 3)).astype(np.float32)\n with self.graph.as_default():\n self.model.fit(X,y, verbose=False, batch_size=1)\n\n self.training_initialized = True\n\n while True:\n if self.terminate:\n return\n self.train()\n time.sleep(0.01)" ]
[ [ "numpy.array", "numpy.random.uniform", "numpy.max" ] ]
vanderhe/fortnet-python
[ "118237f0ce750852d973b213161fc04623fd7f82" ]
[ "test/test_fnetout.py" ]
[ "#!/usr/bin/env python3\n#------------------------------------------------------------------------------#\n# fortnet-python: Python Tools for the Fortnet Software Package #\n# Copyright (C) 2021 - 2022 T. W. van der Heide #\n# #\n# See the LICENSE file for terms of usage and distribution. #\n#------------------------------------------------------------------------------#\n\n\n'''\nRegression tests covering the Fnetout class of Fortformat.\n'''\n\n\nimport os\nimport pytest\nimport numpy as np\n\nfrom common import compare_fnetout_references\n\n\nREFPATH = os.path.join(os.getcwd(), 'test', 'references', 'Fnetout')\n\n\ndef test_predict_atomic():\n '''Test extraction capabilities for a prediction run\n with a network that was trained on atomic targets.\n '''\n\n fname = 'predict_atomic.hdf5'\n\n ref = {}\n ref['mode'] = 'predict'\n ref['ndatapoints'] = 5\n ref['nglobaltargets'] = 0\n ref['natomictargets'] = 2\n ref['tforces'] = False\n ref['forces'] = None\n ref['atomictargets'] = None\n ref['globaltargets'] = None\n ref['globalpredictions'] = None\n ref['globalpredictions_atomic'] = None\n ref['atomicpredictions'] = [\n np.array([[1.961575401201565427e-01, 9.168128808877051839e-01],\n [1.325239781646761206e-01, 7.994346410064820940e-01],\n [1.826092611054506987e-01, 8.918864627286081648e-01],\n [1.951603716977679814e-01, 9.149779051068115399e-01],\n [1.963975544054146483e-01, 9.172546297234291934e-01],\n [1.365085697599923986e-01, 8.068187835637852245e-01],\n [1.937271428648690563e-01, 9.123404738385268997e-01],\n [1.963833753374974733e-01, 9.172283491672438283e-01],\n [-2.963259061179163711e-01, 6.622931487753776381e+00],\n [-3.116645694102148090e-01, 6.341542248977436458e+00],\n [-2.954852994924470622e-01, 6.639489278084699464e+00],\n [-3.046303752343871851e-01, 6.455384967114186523e+00]],\n dtype=float),\n np.array([[1.811418904020697107e-01, 8.890399580545689240e-01],\n [1.286134726005213336e-01, 7.921870956352004001e-01],\n [1.287072680065694807e-01, 7.923610013248644224e-01],\n [1.285878019428332852e-01, 7.921394561667119971e-01],\n [-3.205833278148639831e-01, 6.199868006587744951e+00],\n [-3.205832449473826062e-01, 6.199870243635043465e+00]],\n dtype=float),\n np.array([[1.508316035937055932e-01, 8.333084902706219266e-01],\n [1.963987299989748136e-01, 9.172568038424152581e-01],\n [1.963985352644728455e-01, 9.172564425915140651e-01],\n [1.314458979434688091e-01, 7.974318952109518133e-01],\n [1.959840207934034628e-01, 9.164924149116437935e-01],\n [1.962475111339566924e-01, 9.169785285430018806e-01],\n [1.963735428400687211e-01, 9.172103673056410944e-01],\n [1.692361060177546561e-01, 8.672524620359242098e-01],\n [-2.953595347026437556e-01, 6.642087650077651340e+00],\n [-3.151594350113108844e-01, 6.282255421963240494e+00],\n [-2.991868120084945071e-01, 6.559077847747195378e+00],\n [-3.170787084631181418e-01, 6.252835565560094011e+00]],\n dtype=float),\n np.array([[1.304479687184249281e-01, 7.955871276861898878e-01],\n [1.297462265528342706e-01, 7.942881684589961910e-01],\n [1.298443617239196379e-01, 7.944708584405727470e-01],\n [1.961872820312715870e-01, 9.168651269507970270e-01],\n [-3.205789586106497779e-01, 6.199943703977714549e+00],\n [-3.205781729831197469e-01, 6.199947713843369179e+00]],\n dtype=float),\n np.array([[1.288099388080513885e-01, 7.925517780736619500e-01],\n [1.286199169387698682e-01, 7.921996037242402533e-01],\n [1.286878255987483899e-01, 7.923246429757131448e-01],\n [1.312376406171068266e-01, 7.970445915261700209e-01],\n [-3.205835576648750629e-01, 6.199865084107108792e+00],\n [-3.205822580166140523e-01, 6.199887555086769808e+00]],\n dtype=float)]\n\n equal = compare_fnetout_references(ref, os.path.join(REFPATH, '_' + fname))\n\n assert equal\n\n\ndef test_predict_global():\n '''Test extraction capabilities for a prediction run\n with a network that was trained on global targets.\n '''\n\n fname = 'predict_global.hdf5'\n\n ref = {}\n ref['mode'] = 'predict'\n ref['ndatapoints'] = 5\n ref['nglobaltargets'] = 1\n ref['natomictargets'] = 0\n ref['tforces'] = False\n ref['forces'] = None\n ref['atomictargets'] = None\n ref['globaltargets'] = None\n\n ref['globalpredictions_atomic'] = [\n np.array([-1.526436789762218496e+02], dtype=float),\n np.array([[-4.585193773117663341e+02],\n [-4.585193773117663341e+02]], dtype=float) / 2.0,\n np.array([[-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02]], dtype=float) / 3.0,\n np.array([[-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02]], dtype=float) / 4.0,\n np.array([[-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02]], dtype=float) / 5.0]\n\n ref['globalpredictions'] = [\n np.array([-1.526436789762218496e+02], dtype=float),\n np.array([-4.585193773117663341e+02], dtype=float),\n np.array([-2.290754290677185736e+02], dtype=float),\n np.array([-6.877477714671086915e+02], dtype=float),\n np.array([-5.349057545062817098e+02], dtype=float)]\n\n ref['atomicpredictions'] = None\n\n equal = compare_fnetout_references(ref, os.path.join(REFPATH, '_' + fname))\n\n assert equal\n\n\ndef test_predict_global_singleforces():\n '''Test extraction capabilities for a prediction run with a network\n that was trained on global targets and calculates atomic forces.\n '''\n\n fname = 'predict_global_singleforces.hdf5'\n\n ref = {}\n ref['mode'] = 'predict'\n ref['ndatapoints'] = 2\n ref['nglobaltargets'] = 1\n ref['natomictargets'] = 0\n\n ref['atomictargets'] = None\n ref['globaltargets'] = None\n ref['atomicpredictions'] = None\n\n ref['tforces'] = True\n ref['forces'] = []\n ref['forces'].append([])\n ref['forces'].append([])\n ref['forces'][0].append(np.array([\n [-1.129280561189105470e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [1.129280561189105470e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n ref['forces'][1].append(np.array([\n [-8.464270111301352983e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [8.464270111301352983e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n\n ref['globalpredictions_atomic'] = [\n np.array([[-4.301790810131604914e-01],\n [-4.301790810131604914e-01]], dtype=float) / 2.0,\n np.array([[-5.025593389423121948e-01],\n [-5.025593389423121948e-01]], dtype=float) / 2.0]\n\n ref['globalpredictions'] = [\n np.array([-4.301790810131604914e-01], dtype=float),\n np.array([-5.025593389423121948e-01], dtype=float)]\n\n equal = compare_fnetout_references(ref, os.path.join(REFPATH, '_' + fname))\n\n assert equal\n\n\ndef test_predict_global_multiforces():\n '''Test extraction capabilities for a prediction run with a network\n that was trained on global targets and calculates atomic forces.\n '''\n\n fname = 'predict_global_multiforces.hdf5'\n\n ref = {}\n ref['mode'] = 'predict'\n ref['ndatapoints'] = 2\n ref['nglobaltargets'] = 3\n ref['natomictargets'] = 0\n\n ref['atomictargets'] = None\n ref['globaltargets'] = None\n ref['atomicpredictions'] = None\n\n ref['tforces'] = True\n ref['forces'] = []\n ref['forces'].append([])\n ref['forces'].append([])\n ref['forces'][0].append(np.array([\n [-1.113504383113195217e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [1.113504383113195217e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n ref['forces'][0].append(np.array([\n [-1.117387033151562292e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [1.117387033151562292e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n ref['forces'][0].append(np.array([\n [-1.110108965167277972e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [1.110108965167277972e+00, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n ref['forces'][1].append(np.array([\n [-8.450938994823964379e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [8.450938994823964379e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n ref['forces'][1].append(np.array([\n [-8.465140042623886529e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [8.465140042623886529e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n ref['forces'][1].append(np.array([\n [-8.438788427604926312e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00],\n [8.438788427604926312e-01, 0.000000000000000000e+00,\n 0.000000000000000000e+00]], dtype=float))\n\n ref['globalpredictions_atomic'] = [\n np.array([[-4.304246998683396441e-01, -4.302864774322330277e-01,\n -4.305433861504512905e-01],\n [-4.304246998683396441e-01, -4.302864774322330277e-01,\n -4.305433861504512905e-01]], dtype=float) / 2.0,\n np.array([[-5.022394949529731534e-01, -5.022869347972704901e-01,\n -5.021969559503443037e-01],\n [-5.022394949529731534e-01, -5.022869347972704901e-01,\n -5.021969559503443037e-01]], dtype=float) / 2.0]\n\n ref['globalpredictions'] = [\n np.array([-4.304246998683396441e-01, -4.302864774322330277e-01,\n -4.305433861504512905e-01], dtype=float),\n np.array([-5.022394949529731534e-01, -5.022869347972704901e-01,\n -5.021969559503443037e-01], dtype=float)]\n\n equal = compare_fnetout_references(ref, os.path.join(REFPATH, '_' + fname))\n\n assert equal\n\n\ndef test_validate_atomic():\n '''Test extraction capabilities for a validation run\n with a network that was trained on atomic targets.\n '''\n\n fname = 'validate_atomic.hdf5'\n\n ref = {}\n ref['mode'] = 'validate'\n ref['ndatapoints'] = 5\n ref['nglobaltargets'] = 0\n ref['natomictargets'] = 2\n\n ref['globaltargets'] = None\n ref['globalpredictions'] = None\n ref['globalpredictions_atomic'] = None\n\n ref['tforces'] = False\n ref['forces'] = None\n\n ref['atomictargets'] = [\n np.array([\n [1.540549993515014648e-01, 8.459450006484985352e-01],\n [1.883080005645751953e-01, 8.116919994354248047e-01],\n [1.595949977636337280e-01, 8.404050022363662720e-01],\n [1.432220041751861572e-01, 8.567779958248138428e-01],\n [1.232710033655166626e-01, 8.767289966344833374e-01],\n [1.735100001096725464e-01, 8.264899998903274536e-01],\n [1.588409990072250366e-01, 8.411590009927749634e-01],\n [1.403059959411621094e-01, 8.596940040588378906e-01],\n [-2.634609937667846680e-01, 6.263460993766784668e+00],\n [-3.214380145072937012e-01, 6.321438014507293701e+00],\n [-3.043099939823150635e-01, 6.304309993982315063e+00],\n [-3.519429862499237061e-01, 6.351942986249923706e+00]],\n dtype=float),\n np.array([\n [1.272429972887039185e-01, 8.727570027112960815e-01],\n [1.549790054559707642e-01, 8.450209945440292358e-01],\n [1.774729937314987183e-01, 8.225270062685012817e-01],\n [1.796700060367584229e-01, 8.203299939632415771e-01],\n [-3.525030016899108887e-01, 6.352503001689910889e+00],\n [-2.868520021438598633e-01, 6.286852002143859863e+00]],\n dtype=float),\n np.array([\n [1.852180063724517822e-01, 8.147819936275482178e-01],\n [1.311800032854080200e-01, 8.688199967145919800e-01],\n [1.232030019164085388e-01, 8.767969980835914612e-01],\n [1.774370074272155762e-01, 8.225629925727844238e-01],\n [1.587480008602142334e-01, 8.412519991397857666e-01],\n [1.444180011749267578e-01, 8.555819988250732422e-01],\n [1.365029960870742798e-01, 8.634970039129257202e-01],\n [1.802569925785064697e-01, 8.197430074214935303e-01],\n [-2.689329981803894043e-01, 6.268932998180389404e+00],\n [-3.368290066719055176e-01, 6.336829006671905518e+00],\n [-3.142969906330108643e-01, 6.314296990633010864e+00],\n [-3.169249892234802246e-01, 6.316924989223480225e+00]],\n dtype=float),\n np.array([\n [1.770180016756057739e-01, 8.229819983243942261e-01],\n [1.812230050563812256e-01, 8.187769949436187744e-01],\n [1.482979953289031982e-01, 8.517020046710968018e-01],\n [9.460300207138061523e-02, 9.053969979286193848e-01],\n [-2.429430037736892700e-01, 6.242943003773689270e+00],\n [-3.581880033016204834e-01, 6.358188003301620483e+00]],\n dtype=float),\n np.array([\n [1.596090048551559448e-01, 8.403909951448440552e-01],\n [1.659840047359466553e-01, 8.340159952640533447e-01],\n [1.713179945945739746e-01, 8.286820054054260254e-01],\n [1.658540070056915283e-01, 8.341459929943084717e-01],\n [-3.264440000057220459e-01, 6.326444000005722046e+00],\n [-3.363139927387237549e-01, 6.336313992738723755e+00]],\n dtype=float)]\n ref['atomicpredictions'] = [\n np.array([\n [1.961575401201565427e-01, 9.168128808877051839e-01],\n [1.325239781646761206e-01, 7.994346410064820940e-01],\n [1.826092611054506987e-01, 8.918864627286081648e-01],\n [1.951603716977679814e-01, 9.149779051068115399e-01],\n [1.963975544054146483e-01, 9.172546297234291934e-01],\n [1.365085697599923986e-01, 8.068187835637852245e-01],\n [1.937271428648690563e-01, 9.123404738385268997e-01],\n [1.963833753374974733e-01, 9.172283491672438283e-01],\n [-2.963259061179163711e-01, 6.622931487753776381e+00],\n [-3.116645694102148090e-01, 6.341542248977436458e+00],\n [-2.954852994924470622e-01, 6.639489278084699464e+00],\n [-3.046303752343871851e-01, 6.455384967114186523e+00]],\n dtype=float),\n np.array([\n [1.811418904020697107e-01, 8.890399580545689240e-01],\n [1.286134726005213336e-01, 7.921870956352004001e-01],\n [1.287072680065694807e-01, 7.923610013248644224e-01],\n [1.285878019428332852e-01, 7.921394561667119971e-01],\n [-3.205833278148639831e-01, 6.199868006587744951e+00],\n [-3.205832449473826062e-01, 6.199870243635043465e+00]],\n dtype=float),\n np.array([\n [1.508316035937055932e-01, 8.333084902706219266e-01],\n [1.963987299989748136e-01, 9.172568038424152581e-01],\n [1.963985352644728455e-01, 9.172564425915140651e-01],\n [1.314458979434688091e-01, 7.974318952109518133e-01],\n [1.959840207934034628e-01, 9.164924149116437935e-01],\n [1.962475111339566924e-01, 9.169785285430018806e-01],\n [1.963735428400687211e-01, 9.172103673056410944e-01],\n [1.692361060177546561e-01, 8.672524620359242098e-01],\n [-2.953595347026437556e-01, 6.642087650077651340e+00],\n [-3.151594350113108844e-01, 6.282255421963240494e+00],\n [-2.991868120084945071e-01, 6.559077847747195378e+00],\n [-3.170787084631181418e-01, 6.252835565560094011e+00]],\n dtype=float),\n np.array([\n [1.304479687184249281e-01, 7.955871276861898878e-01],\n [1.297462265528342706e-01, 7.942881684589961910e-01],\n [1.298443617239196379e-01, 7.944708584405727470e-01],\n [1.961872820312715870e-01, 9.168651269507970270e-01],\n [-3.205789586106497779e-01, 6.199943703977714549e+00],\n [-3.205781729831197469e-01, 6.199947713843369179e+00]],\n dtype=float),\n np.array([\n [1.288099388080513885e-01, 7.925517780736619500e-01],\n [1.286199169387698682e-01, 7.921996037242402533e-01],\n [1.286878255987483899e-01, 7.923246429757131448e-01],\n [1.312376406171068266e-01, 7.970445915261700209e-01],\n [-3.205835576648750629e-01, 6.199865084107108792e+00],\n [-3.205822580166140523e-01, 6.199887555086769808e+00]],\n dtype=float)]\n\n equal = compare_fnetout_references(ref, os.path.join(REFPATH, '_' + fname))\n\n assert equal\n\n\ndef test_validate_global():\n '''Test extraction capabilities for a validation run\n with a network that was trained on global targets.\n '''\n\n fname = 'validate_global.hdf5'\n\n ref = {}\n ref['mode'] = 'validate'\n ref['ndatapoints'] = 5\n ref['nglobaltargets'] = 1\n ref['natomictargets'] = 0\n\n ref['tforces'] = False\n ref['forces'] = None\n\n ref['atomictargets'] = None\n ref['atomicpredictions'] = None\n\n ref['globaltargets'] = [\n np.array([-1.527736989418316114e+02], dtype=float),\n np.array([-4.584216715420000128e+02], dtype=float),\n np.array([-2.291870019319999869e+02], dtype=float),\n np.array([-6.876760346160000381e+02], dtype=float),\n np.array([-5.348338707069999600e+02], dtype=float)]\n\n ref['globalpredictions'] = [\n np.array([-1.526436789762218496e+02], dtype=float),\n np.array([-4.585193773117663341e+02], dtype=float),\n np.array([-2.290754290677185736e+02], dtype=float),\n np.array([-6.877477714671086915e+02], dtype=float),\n np.array([-5.349057545062817098e+02], dtype=float)]\n\n ref['globalpredictions_atomic'] = [\n np.array([[-1.526436789762218496e+02]], dtype=float),\n np.array([[-4.585193773117663341e+02],\n [-4.585193773117663341e+02]], dtype=float) / 2.0,\n np.array([[-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02]], dtype=float) / 3.0,\n np.array([[-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02]], dtype=float) / 4.0,\n np.array([[-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02]], dtype=float) / 5.0]\n\n equal = compare_fnetout_references(ref, os.path.join(REFPATH, '_' + fname))\n\n assert equal\n\n\ndef test_validate_atomic_global():\n '''Test extraction capabilities for a validation run with a\n network that was trained on both, atomic and global targets.\n '''\n\n fname = 'validate_atomic_global.hdf5'\n\n ref = {}\n ref['mode'] = 'validate'\n ref['ndatapoints'] = 5\n ref['nglobaltargets'] = 1\n ref['natomictargets'] = 2\n\n ref['targets'] = True\n ref['tforces'] = False\n ref['forces'] = None\n\n ref['atomictargets'] = [\n np.array([\n [1.540549993515014648e-01, 8.459450006484985352e-01],\n [1.883080005645751953e-01, 8.116919994354248047e-01],\n [1.595949977636337280e-01, 8.404050022363662720e-01],\n [1.432220041751861572e-01, 8.567779958248138428e-01],\n [1.232710033655166626e-01, 8.767289966344833374e-01],\n [1.735100001096725464e-01, 8.264899998903274536e-01],\n [1.588409990072250366e-01, 8.411590009927749634e-01],\n [1.403059959411621094e-01, 8.596940040588378906e-01],\n [-2.634609937667846680e-01, 6.263460993766784668e+00],\n [-3.214380145072937012e-01, 6.321438014507293701e+00],\n [-3.043099939823150635e-01, 6.304309993982315063e+00],\n [-3.519429862499237061e-01, 6.351942986249923706e+00]],\n dtype=float),\n np.array([\n [1.272429972887039185e-01, 8.727570027112960815e-01],\n [1.549790054559707642e-01, 8.450209945440292358e-01],\n [1.774729937314987183e-01, 8.225270062685012817e-01],\n [1.796700060367584229e-01, 8.203299939632415771e-01],\n [-3.525030016899108887e-01, 6.352503001689910889e+00],\n [-2.868520021438598633e-01, 6.286852002143859863e+00]],\n dtype=float),\n np.array([\n [1.852180063724517822e-01, 8.147819936275482178e-01],\n [1.311800032854080200e-01, 8.688199967145919800e-01],\n [1.232030019164085388e-01, 8.767969980835914612e-01],\n [1.774370074272155762e-01, 8.225629925727844238e-01],\n [1.587480008602142334e-01, 8.412519991397857666e-01],\n [1.444180011749267578e-01, 8.555819988250732422e-01],\n [1.365029960870742798e-01, 8.634970039129257202e-01],\n [1.802569925785064697e-01, 8.197430074214935303e-01],\n [-2.689329981803894043e-01, 6.268932998180389404e+00],\n [-3.368290066719055176e-01, 6.336829006671905518e+00],\n [-3.142969906330108643e-01, 6.314296990633010864e+00],\n [-3.169249892234802246e-01, 6.316924989223480225e+00]],\n dtype=float),\n np.array([\n [1.770180016756057739e-01, 8.229819983243942261e-01],\n [1.812230050563812256e-01, 8.187769949436187744e-01],\n [1.482979953289031982e-01, 8.517020046710968018e-01],\n [9.460300207138061523e-02, 9.053969979286193848e-01],\n [-2.429430037736892700e-01, 6.242943003773689270e+00],\n [-3.581880033016204834e-01, 6.358188003301620483e+00]],\n dtype=float),\n np.array([\n [1.596090048551559448e-01, 8.403909951448440552e-01],\n [1.659840047359466553e-01, 8.340159952640533447e-01],\n [1.713179945945739746e-01, 8.286820054054260254e-01],\n [1.658540070056915283e-01, 8.341459929943084717e-01],\n [-3.264440000057220459e-01, 6.326444000005722046e+00],\n [-3.363139927387237549e-01, 6.336313992738723755e+00]],\n dtype=float)]\n ref['atomicpredictions'] = [\n np.array([\n [1.961575401201565427e-01, 9.168128808877051839e-01],\n [1.325239781646761206e-01, 7.994346410064820940e-01],\n [1.826092611054506987e-01, 8.918864627286081648e-01],\n [1.951603716977679814e-01, 9.149779051068115399e-01],\n [1.963975544054146483e-01, 9.172546297234291934e-01],\n [1.365085697599923986e-01, 8.068187835637852245e-01],\n [1.937271428648690563e-01, 9.123404738385268997e-01],\n [1.963833753374974733e-01, 9.172283491672438283e-01],\n [-2.963259061179163711e-01, 6.622931487753776381e+00],\n [-3.116645694102148090e-01, 6.341542248977436458e+00],\n [-2.954852994924470622e-01, 6.639489278084699464e+00],\n [-3.046303752343871851e-01, 6.455384967114186523e+00]],\n dtype=float),\n np.array([\n [1.811418904020697107e-01, 8.890399580545689240e-01],\n [1.286134726005213336e-01, 7.921870956352004001e-01],\n [1.287072680065694807e-01, 7.923610013248644224e-01],\n [1.285878019428332852e-01, 7.921394561667119971e-01],\n [-3.205833278148639831e-01, 6.199868006587744951e+00],\n [-3.205832449473826062e-01, 6.199870243635043465e+00]],\n dtype=float),\n np.array([\n [1.508316035937055932e-01, 8.333084902706219266e-01],\n [1.963987299989748136e-01, 9.172568038424152581e-01],\n [1.963985352644728455e-01, 9.172564425915140651e-01],\n [1.314458979434688091e-01, 7.974318952109518133e-01],\n [1.959840207934034628e-01, 9.164924149116437935e-01],\n [1.962475111339566924e-01, 9.169785285430018806e-01],\n [1.963735428400687211e-01, 9.172103673056410944e-01],\n [1.692361060177546561e-01, 8.672524620359242098e-01],\n [-2.953595347026437556e-01, 6.642087650077651340e+00],\n [-3.151594350113108844e-01, 6.282255421963240494e+00],\n [-2.991868120084945071e-01, 6.559077847747195378e+00],\n [-3.170787084631181418e-01, 6.252835565560094011e+00]],\n dtype=float),\n np.array([\n [1.304479687184249281e-01, 7.955871276861898878e-01],\n [1.297462265528342706e-01, 7.942881684589961910e-01],\n [1.298443617239196379e-01, 7.944708584405727470e-01],\n [1.961872820312715870e-01, 9.168651269507970270e-01],\n [-3.205789586106497779e-01, 6.199943703977714549e+00],\n [-3.205781729831197469e-01, 6.199947713843369179e+00]],\n dtype=float),\n np.array([\n [1.288099388080513885e-01, 7.925517780736619500e-01],\n [1.286199169387698682e-01, 7.921996037242402533e-01],\n [1.286878255987483899e-01, 7.923246429757131448e-01],\n [1.312376406171068266e-01, 7.970445915261700209e-01],\n [-3.205835576648750629e-01, 6.199865084107108792e+00],\n [-3.205822580166140523e-01, 6.199887555086769808e+00]],\n dtype=float)]\n\n ref['globaltargets'] = [\n np.array([-1.527736989418316114e+02], dtype=float),\n np.array([-4.584216715420000128e+02], dtype=float),\n np.array([-2.291870019319999869e+02], dtype=float),\n np.array([-6.876760346160000381e+02], dtype=float),\n np.array([-5.348338707069999600e+02], dtype=float)]\n\n ref['globalpredictions'] = [\n np.array([-1.526436789762218496e+02], dtype=float) * 12.0,\n np.array([-4.585193773117663341e+02], dtype=float) * 6.0,\n np.array([-2.290754290677185736e+02], dtype=float) * 12.0,\n np.array([-6.877477714671086915e+02], dtype=float) * 6.0,\n np.array([-5.349057545062817098e+02], dtype=float) * 6.0]\n\n ref['globalpredictions_atomic'] = [\n np.array([[-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02],\n [-1.526436789762218496e+02]], dtype=float),\n np.array([[-4.585193773117663341e+02],\n [-4.585193773117663341e+02],\n [-4.585193773117663341e+02],\n [-4.585193773117663341e+02],\n [-4.585193773117663341e+02],\n [-4.585193773117663341e+02]], dtype=float),\n np.array([[-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02],\n [-2.290754290677185736e+02]], dtype=float),\n np.array([[-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02],\n [-6.877477714671086915e+02]], dtype=float),\n np.array([[-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02],\n [-5.349057545062817098e+02]], dtype=float)]\n\n equal = compare_fnetout_references(ref, os.path.join(REFPATH, '_' + fname))\n\n assert equal\n\n\nif __name__ == '__main__':\n pytest.main()\n" ]
[ [ "numpy.array" ] ]
iamfaith/DeepLearning
[ "467c73e2d0435f0a05255e5b5e00454260d01f27" ]
[ "books/PRML/PRML-master-Python/prml/nn/optimizer/ada_delta.py" ]
[ "import numpy as np\nfrom prml.nn.optimizer.optimizer import Optimizer\n\n\nclass AdaDelta(Optimizer):\n \"\"\"\n AdaDelta optimizer\n \"\"\"\n\n def __init__(self, parameter, rho=0.95, epsilon=1e-8):\n super().__init__(parameter, None)\n self.rho = rho\n self.epsilon = epsilon\n self.mean_squared_deriv = []\n self.mean_squared_update = []\n for p in self.parameter:\n self.mean_squared_deriv.append(np.zeros(p.shape))\n self.mean_squared_update.append(np.zeros(p.shape))\n\n def update(self):\n self.increment_iteration()\n for p, msd, msu in zip(self.parameter, self.mean_squared_deriv, self.mean_squared_update):\n if p.grad is None:\n continue\n grad = p.grad\n msd *= self.rho\n msd += (1 - self.rho) * grad ** 2\n delta = np.sqrt((msu + self.epsilon) / (msd + self.epsilon)) * grad\n msu *= self.rho\n msu *= (1 - self.rho) * delta ** 2\n p.value += delta\n" ]
[ [ "numpy.sqrt", "numpy.zeros" ] ]
laenan8466/DeerLab
[ "94f1942da1b506e0661a8e7e4901bb5ba6d69143" ]
[ "deerlab/utils/utils.py" ]
[ "import warnings\r\nimport numpy as np\r\nimport cmath as math\r\nimport scipy as scp\r\nimport scipy.optimize as opt\r\n\r\nfrom types import FunctionType \r\n\r\n\r\ndef parse_multidatasets(V,K,weights,precondition=False):\r\n#===============================================================================\r\n \r\n # Identify if the signals have already been processed by this function\r\n if type(V) is not list:\r\n if V.size == np.atleast_1d(weights).size:\r\n # If so, just return without doing anything\r\n if precondition:\r\n return V,K,weights,[np.arange(0,len(V))],[1]\r\n else:\r\n return V,K,weights,[np.arange(0,len(V))]\r\n\r\n # If multiple signals are specified as a list...\r\n if type(V) is list and all([type(Vs) is np.ndarray for Vs in V]):\r\n nSignals = len(V)\r\n prescales = np.zeros(nSignals)\r\n Vlist = []\r\n # Pre-scale the signals, important for fitregmodel when using global fits with arbitrary scales\r\n for i in range(nSignals):\r\n if precondition:\r\n prescales[i] = max(V[i])\r\n Vlist.append(V[i]/prescales[i])\r\n else:\r\n Vlist.append(V[i])\r\n V = np.concatenate(Vlist, axis=0) # ...concatenate them along the list \r\n elif type(V) is np.ndarray:\r\n nSignals = 1\r\n prescales = [1]\r\n Vlist = [V]\r\n else:\r\n raise TypeError('The input signal(s) must be numpy array or a list of numpy arrays.')\r\n \r\n def prepareKernel(K,nSignals):\r\n # If multiple kernels are specified as a list...\r\n if type(K) is tuple:\r\n K = [Ks for Ks in K]\r\n if type(K) is list and all([type(Ks) is np.ndarray for Ks in K]):\r\n nKernels = len(K)\r\n K = np.concatenate(K, axis=0) # ...concatenate them along the list \r\n elif type(K) is np.ndarray:\r\n nKernels = 1\r\n else:\r\n raise TypeError('The input kernel(s) must be numpy array or a list of numpy arrays.')\r\n # Check that the same number of signals and kernel have been passed\r\n if nSignals!=nKernels:\r\n raise KeyError('The same number of kernels and signals must be specified as lists.')\r\n return K\r\n\r\n if type(K) is FunctionType:\r\n Kmulti = lambda p: prepareKernel(K(p),nSignals)\r\n else:\r\n Kmulti = prepareKernel(K,nSignals)\r\n\r\n # If multiple weights are specified as a list...\r\n if type(weights) is list or not hasattr(weights, \"__len__\"):\r\n weights = np.atleast_1d(weights)\r\n if len(weights)==1:\r\n weights = np.repeat(weights,nSignals)\r\n weights = weights/sum(weights)\r\n if len(weights)!=nSignals:\r\n raise KeyError('If multiple signals are passed, the same number of weights are required.')\r\n weights_ = []\r\n for i in range(len(weights)):\r\n weights_ = np.concatenate((weights_,weights[i]*np.ones(len(Vlist[i]))))\r\n weights = weights_\r\n else:\r\n raise TypeError('The input weights(s) must be numpy array or a list of numpy arrays.')\r\n\r\n # Get the indices to extract the subsets again\r\n Ns = [len(V) for V in Vlist]\r\n subset = [None]*nSignals\r\n for i in range(nSignals):\r\n if i==0:\r\n prev = 0\r\n else:\r\n prev = subset[i-1][-1]+1\r\n subset[i] = np.arange(prev,prev+Ns[i])\r\n\r\n if precondition:\r\n return V,Kmulti,weights,subset,prescales\r\n else:\r\n return V,Kmulti,weights,subset\r\n#===============================================================================\r\n\r\n\r\ndef hccm(J,*args):\r\n \"\"\"\r\n Heteroscedasticity Consistent Covariance Matrix (HCCM)\r\n ======================================================\r\n\r\n Computes the heteroscedasticity consistent covariance matrix (HCCM) of\r\n a given LSQ problem given by the Jacobian matrix (J) and the covariance\r\n matrix of the data (V). If the residual (res) is specified, the\r\n covariance matrix is estimated using some of the methods specified in\r\n (mode). The HCCM are valid for both heteroscedasticit and\r\n homoscedasticit residual vectors. \r\n\r\n Usage:\r\n ------\r\n C = hccm(J,V)\r\n C = hccm(J,res,mode)\r\n\r\n Arguments:\r\n ----------\r\n J (NxM-element array)\r\n Jacobian matrix of the residual vector\r\n res (N-element array)\r\n Vector of residuals\r\n mode (string)\r\n HCCM estimator, options are:\r\n 'HC0' - White, H. (1980)\r\n 'HC1' - MacKinnon and White, (1985)\r\n 'HC2' - MacKinnon and White, (1985)\r\n 'HC3' - Davidson and MacKinnon, (1993)\r\n 'HC4' - Cribari-Neto, (2004)\r\n 'HC5' - Cribari-Neto, (2007)\r\n\r\n Returns:\r\n --------\r\n C (MxM-element array) \r\n Heteroscedasticity consistent covariance matrix \r\n\r\n References:\r\n ------------ \r\n [1] \r\n White, H. (1980). A heteroskedasticity-consistent covariance matrix\r\n estimator and a direct test for heteroskedasticity. Econometrica, 48(4), 817-838\r\n DOI: 10.2307/1912934\r\n\r\n [2] \r\n MacKinnon and White, (1985). Some heteroskedasticity-consistent covariance\r\n matrix estimators with improved finite sample properties. Journal of Econometrics, 29 (1985), \r\n pp. 305-325. DOI: 10.1016/0304-4076(85)90158-7\r\n\r\n [3] \r\n Davidson and MacKinnon, (1993). Estimation and Inference in Econometrics\r\n Oxford University Press, New York. \r\n\r\n [4] \r\n Cribari-Neto, F. (2004). Asymptotic inference under heteroskedasticity of\r\n unknown form. Computational Statistics & Data Analysis, 45(1), 215-233\r\n DOI: 10.1016/s0167-9473(02)00366-3\r\n\r\n [5] \r\n Cribari-Neto, F., Souza, T. C., & Vasconcellos, K. L. P. (2007). Inference\r\n under heteroskedasticity and leveraged data. Communications in Statistics –\r\n Theory and Methods, 36(10), 1877-1888. DOI: 10.1080/03610920601126589\r\n \"\"\"\r\n\r\n # Unpack inputs\r\n if len(args)==2:\r\n res,mode = args\r\n V = []\r\n elif len(args)==1:\r\n V = args[0]\r\n\r\n # Hat matrix\r\n H = [email protected](J.T@J)@J.T\r\n # Get leverage\r\n h = np.diag(H)\r\n # Number of parameters (k) & Number of variables (n)\r\n n,k = np.shape(J)\r\n\r\n if isempty(V):\r\n # Select estimation method using established nomenclature\r\n if mode.upper() == 'HC0': # White,(1980),[1]\r\n # Estimate the data covariance matrix\r\n V = np.diag(res**2)\r\n \r\n elif mode.upper() == 'HC1': # MacKinnon and White,(1985),[2]\r\n # Estimate the data covariance matrix\r\n V = n/(n-k)*np.diag(res**2)\r\n \r\n elif mode.upper() == 'HC2': # MacKinnon and White,(1985),[2]\r\n # Estimate the data covariance matrix\r\n V = np.diag(res**2/(1-h))\r\n \r\n elif mode.upper() == 'HC3': # Davidson and MacKinnon,(1993),[3]\r\n # Estimate the data covariance matrix\r\n V = np.diag(res/(1-h))**2\r\n \r\n elif mode.upper() == 'HC4': # Cribari-Neto,(2004),[4]\r\n # Compute discount factor\r\n delta = np.minimum(4,n*h/k)\r\n # Estimate the data covariance matrix\r\n V = np.diag(res**2./((1 - h)**delta))\r\n \r\n elif mode.upper() == 'HC5': # Cribari-Neto,(2007),[5]\r\n # Compute inflation factor\r\n k = 0.7\r\n alpha = np.minimum(np.maximum(4,k*max(h)/np.mean(h)),h/np.mean(h))\r\n # Estimate the data covariance matrix\r\n V = np.diag(res**2./(np.sqrt((1 - h)**alpha)))\r\n \r\n else:\r\n raise KeyError('HCCM estimation mode not found.')\r\n\r\n\r\n # Heteroscedasticity Consistent Covariance Matrix (HCCM) estimator\r\n C = np.linalg.pinv(J.T@J)@J.T@V@[email protected](J.T@J)\r\n\r\n return C\r\n#===============================================================================\r\n\r\n\r\n# =================================================================\r\ndef metadata(**kwargs):\r\n \"\"\"\r\n Decorator: Set model metadata as function attributes \r\n \"\"\"\r\n attributes = list(kwargs.keys())\r\n metadata = list(kwargs.values())\r\n\r\n def _setmetadata(func):\r\n for attribute,data in zip(attributes,metadata):\r\n setattr(func,attribute,data)\r\n return func\r\n return _setmetadata\r\n# =================================================================\r\n\r\ndef gsvd(A,B):\r\n#===============================================================================\r\n m,p = A.shape\r\n n = B.shape[0]\r\n\r\n # Economy-sized.\r\n useQA = m > p\r\n useQB = n > p\r\n if useQA:\r\n QA,A = scp.linalg.qr(A)\r\n A = A[0:p,0:p]\r\n QA = QA[:,0:p]\r\n m = p\r\n\r\n if useQB:\r\n QB,B = scp.linalg.qr(B)\r\n B = B[0:p,0:p]\r\n QB = QB[:,0:p]\r\n n = p\r\n\r\n Q,_ = np.linalg.qr(np.vstack((A,B)), mode='reduced')\r\n Q1 = Q[0:m,0:p]\r\n Q2 = Q[m:m+n,0:p]\r\n C,S = csd(Q1,Q2)\r\n\r\n # Vector of generalized singular values.\r\n q = min(m+n,p)\r\n # Supress divide by 0 warning \r\n with warnings.catch_warnings():\r\n warnings.simplefilter('ignore')\r\n U = np.vstack((np.zeros((q-m,1),'double'), np.diag(C,max(0,q-m)).reshape(len(np.diag(C,max(0,q-m))),1)))/np.vstack((np.diag(S,0).reshape(len(np.diag(S,0)),1), np.zeros((q-n,1),'double') ))\r\n\r\n\r\n return U\r\n#===============================================================================\r\n\r\n\r\ndef csd(Q1,Q2):\r\n#===============================================================================\r\n \"\"\"\r\n Cosine-Sine Decomposition\r\n -------------------------\r\n \r\n Given Q1 and Q2 such that Q1'* Q1 + Q2'* Q2 = I, the\r\n C-S Decomposition is a joint factorization of the form\r\n Q1 = U1*C*V' and Q2=U2*S*V'\r\n where U1,U2,V are orthogonal matrices and C and S are diagonal\r\n matrices (not necessarily square) satisfying\r\n C'* C + S'* S = I\r\n The diagonal entries of C and S are nonnegative and the\r\n diagonal elements of C are in nondecreasing order.\r\n The matrix Q1 cannot have more columns than rows.\r\n\r\n Based on the Octave code by Artiste (submitted by S.J.Leon): \r\n http://www.ar-tiste.com/m-fun/m-fun-index.html\r\n\r\n \"\"\"\r\n m,n = Q1.shape\r\n p,_ = Q2.shape\r\n if m < p:\r\n s,c = csd(Q2,Q1)\r\n j = np.flip(np.arange(n)) \r\n c = c[:,j] \r\n s = s[:,j] \r\n m = np.minimum(m,p) \r\n i = np.flip(np.arange(m)) \r\n c[np.arange(m),:] = c[i,:] \r\n n = np.minimum(n,p) \r\n i = np.flip(np.arange(n)) \r\n s[np.arange(n),:] = s[i,:] \r\n return c,s\r\n\r\n _,sdiag,v = np.linalg.svd(Q1)\r\n c = np.zeros((m, n))\r\n np.fill_diagonal(c, sdiag)\r\n v = v.T.conj()\r\n z = np.eye(n,n)\r\n z = scp.linalg.hankel(z[:,n-1])\r\n c[0:n,:] = z@c[0:n,:]@z\r\n v = v@z\r\n Q2 = Q2@v\r\n k=0\r\n for j in range(1,n):\r\n if c[j,j] <= 1/np.sqrt(2): k=j\r\n b = Q2[:,0:k]\r\n u2,r = np.linalg.qr(b,mode='complete')\r\n s = u2.T@Q2\r\n t = np.minimum(p,n)\r\n tt = np.minimum(m,p)\r\n if k<t:\r\n r2 = s[np.ix_(range(k,p),range(k,t))]\r\n _,sdiag,vt = np.linalg.svd(r2)\r\n ss= np.zeros(r2.shape)\r\n np.fill_diagonal(ss, sdiag)\r\n vt = vt.T.conj()\r\n s[k:p,k:t] = ss\r\n c[:,k:t] = c[:,k:t]@vt\r\n w = c[k:tt,k:t]\r\n z,r = np.linalg.qr(w,mode='complete')\r\n c[k:tt,k:t] = r\r\n for j in range(n):\r\n if c[j,j]<0:\r\n c[j,j] = -c[j,j]\r\n for j in range(t):\r\n if s[j,j]<0:\r\n s[j,j] = -s[j,j]\r\n\r\n return c,s\r\n#===============================================================================\r\n\r\n#===============================================================================\r\ndef diagf(X):\r\n \"\"\"\r\n Diagonal force\r\n\r\n X = diagf(X) zeros all the elements off the main diagonal of X.\r\n \"\"\"\r\n X = np.triu(np.tril(X))\r\n return X\r\n#===============================================================================\r\n\r\n#===============================================================================\r\ndef diagp(Y,X,k):\r\n \"\"\"\r\n DIAGP Diagonal positive.\r\n Y,X = diagp(Y,X,k) scales the columns of Y and the rows of X by\r\n unimodular factors to make the k-th diagonal of X real and positive.\r\n \"\"\"\r\n D = np.diag(X,k)\r\n j = np.where((D.real < 0) | (D.imag != 0))\r\n D = np.diag(np.conj(D[j])/abs(D[j]))\r\n Y[:,j] = Y[:,j]@D.T\r\n X[j,:] = D@X[j,:]\r\n X = X+0 # use \"+0\" to set possible -0 elements to 0\r\n return Y,X\r\n#===============================================================================\r\n\r\n#===============================================================================\r\ndef Jacobian(fcn, x0, lb, ub):\r\n \"\"\" \r\n Finite difference Jacobian estimation \r\n Estimates the Jacobian matrix of a vector-valued function ``fcn`` at the \r\n point ``x0`` taking into consideration box-constraints defined by the lower\r\n and upper bounds ``lb`` and ``ub``.\r\n\r\n This is a wrapper around the ``scipy.optimize._numdiff.approx_derivative`` function.\r\n\r\n \"\"\"\r\n J = opt._numdiff.approx_derivative(fcn,x0,method='2-point',bounds=(lb,ub))\r\n J = np.atleast_2d(J)\r\n return J\r\n#===============================================================================\r\n\r\n#===============================================================================\r\ndef movmean(x, N):\r\n \"\"\"\r\n Moving mean\r\n ===========\r\n\r\n Returns an array of local N-point mean values, where each mean is calculated over a sliding window of length k across neighboring elements of x.\r\n\r\n Usage:\r\n ------\r\n xfilt = movmean(x,N)\r\n\r\n Arguments:\r\n ----------\r\n x (array)\r\n Array to be filtered\r\n N (scalar)\r\n Window size\r\n \r\n Returns:\r\n --------\r\n xfilt (array)\r\n Filtered array\r\n \r\n \"\"\"\r\n xfilt = np.convolve(x, np.ones(N)/N, mode='same')\r\n return xfilt\r\n#===============================================================================\r\n\r\n#===============================================================================\r\ndef ovl(A,B):\r\n \"\"\"\r\n Overlap metric\r\n ==============\r\n\r\n Returns the overlap between two vectors A and B.\r\n\r\n Usage:\r\n ------\r\n metric = ovl(A,B)\r\n\r\n Arguments:\r\n ----------\r\n A (N-element array)\r\n First vector\r\n B (N-element array)\r\n Second vector\r\n \r\n Returns:\r\n --------\r\n metric (array)\r\n Overlap metric\r\n\r\n \"\"\"\r\n A /= np.sum(A)\r\n B /= np.sum(B)\r\n metric = np.sum(np.minimum(A,B))\r\n return metric\r\n#===============================================================================\r\n\r\n\r\ndef isempty(A):\r\n#===============================================================================Q\r\n A = np.atleast_1d(A)\r\n boolean = np.size(A)==0\r\n return boolean\r\n#===============================================================================\r\n\r\n\r\ndef multistarts(n,x0,lb,ub):\r\n#===============================================================================\r\n\r\n if n<0:\r\n raise ValueError('The number of requested starting points must be n>0.') \r\n\r\n if len(x0) != len(lb) or len(x0) != len(ub):\r\n raise ValueError('The lower/upper bound size(s) are not compatible with the initial guess vector x0.') \r\n\r\n # Generate n-1 new starting points within the bounds\r\n if n>1:\r\n x0 = np.linspace(lb,ub,n-1)\r\n else:\r\n x0 = [x0]\r\n return x0\r\n#===============================================================================\r\n" ]
[ [ "numpy.sum", "numpy.ones", "numpy.diag", "numpy.size", "scipy.linalg.hankel", "numpy.fill_diagonal", "numpy.tril", "scipy.optimize._numdiff.approx_derivative", "numpy.vstack", "numpy.where", "numpy.linspace", "numpy.mean", "numpy.minimum", "numpy.eye", "numpy.atleast_2d", "numpy.zeros", "numpy.repeat", "numpy.arange", "numpy.linalg.pinv", "numpy.linalg.qr", "numpy.conj", "numpy.linalg.svd", "numpy.atleast_1d", "scipy.linalg.qr", "numpy.shape", "numpy.sqrt", "numpy.concatenate" ] ]
linxi1158/iMIX
[ "99898de97ef8b45462ca1d6bf2542e423a73d769" ]
[ "imix/data/infocomp/ocrvqa_infocpler.py" ]
[ "import torch\n\nfrom ..utils.stream import ItemFeature\nfrom .base_infocpler import BaseInfoCpler\n\n\nclass OCRVQAInfoCpler(BaseInfoCpler):\n\n def __init__(self, cfg):\n super().__init__(cfg)\n\n def complete_info(self, item_feature: ItemFeature):\n tokens = self.tokenizer.tokenize(item_feature.question.strip())\n tokens = self.tokenizer.get_limited_tokens(tokens, self.max_seq_length - 2)\n tokens, input_lm_label_ids = self.tokenizer.random_mask_tokens(tokens, self.word_mask_ratio)\n tokens = [self._CLS_TOKEN] + tokens + [self._SEP_TOEKN]\n\n input_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(tokens)\n input_segment = [0] * len(tokens)\n input_lm_label_ids = [-1] * len(tokens)\n # while len(input_ids) < self.max_seq_length:\n # input_ids.append(int(self.pad_idx))\n # input_mask.append(0)\n # input_segment.append(0)\n # input_lm_label_ids.append(-1)\n to_extd_length = self.max_seq_length - len(input_ids)\n self.info_extend(to_extd_length, (input_ids, int(self.pad_idx)), (input_mask, 0), (input_segment, 0),\n (input_lm_label_ids, -1))\n # ocr vectors\n ocr_tokens = self.tokenizer.get_limited_tokens(item_feature.ocr_tokens, self.max_ocr_length)\n item_feature.ocr_vectors_glove = self.get_tokens_glove_vectors(ocr_tokens)\n item_feature.ocr_vectors_order = self.get_tokens_order_vectors(ocr_tokens)\n item_feature.ocr_vectors_phoc = self.get_tokens_phoc_vectors(ocr_tokens)\n item_feature.ocr_vectors_fasttext = self.get_tokens_fasttext_vectors(ocr_tokens)\n\n # ocr features and bboxes\n features_ocr = torch.zeros(\n (self.max_ocr_length,\n item_feature.features_ocr.shape[1] if item_feature.features_ocr is not None else 2048),\n dtype=torch.float)\n bbox_ocr_normalized = torch.zeros(\n (self.max_ocr_length,\n item_feature.ocr_normalized_boxes.shape[1] if item_feature.ocr_normalized_boxes is not None else 4),\n dtype=torch.float)\n if item_feature.features_ocr is not None:\n limit = min(self.max_ocr_length, len(item_feature.features_ocr))\n features_ocr[:limit] = torch.tensor(item_feature.features_ocr[:limit])\n bbox_ocr_normalized[:limit] = torch.tensor(item_feature.ocr_normalized_boxes[:limit])\n item_feature.features_ocr = features_ocr\n item_feature.ocr_normalized_boxes = bbox_ocr_normalized\n\n # features and bboxes\n img_h = item_feature.image_height\n img_w = item_feature.image_width\n item_feature.bbox = self._get_bbox_from_normalized(item_feature.obj_normalized_boxes, img_h, img_w)\n item_feature.bbox_normalized = item_feature.obj_normalized_boxes\n item_feature.bbox_ocr = self._get_bbox_from_normalized(item_feature.ocr_normalized_boxes, img_h, img_w)\n item_feature.bbox_ocr_normalized = item_feature.ocr_normalized_boxes\n\n item_feature.input_ids = torch.tensor(input_ids, dtype=torch.long)\n item_feature.input_mask = torch.tensor(input_mask, dtype=torch.int)\n item_feature.input_segment = torch.tensor(input_segment, dtype=torch.int)\n item_feature.input_lm_label_ids = torch.tensor(input_lm_label_ids, dtype=torch.long)\n item_feature.qa_ids = [self.qa_ans2id[ans] for ans in item_feature.answers if ans in self.qa_ans2id]\n # item_feature.qa_allids = [self.qa_ans2id[ans] for ans in item_feature.all_answers if ans in self.qa_ans2id]\n item_feature.answers_scores = self.compute_answers_scores(torch.Tensor(item_feature.qa_ids))\n return item_feature\n" ]
[ [ "torch.zeros", "torch.tensor", "torch.Tensor" ] ]
CatrionaMarr/OnlineMCMCTest
[ "92899d082c1bdfc2d61128ced453ac59812ae03a" ]
[ "results/8112a5333cb1bb472ee14fa5342f6422/pyfile.py" ]
[ "#!/usr/bin/env python\n\n# import required packages\nimport emcee\nimport numpy as np\nfrom numpy import exp, log\n\n# import model function from separate file\nfrom mymodel import mymodel\n\n# import post-processing function from theonlinemcmc package\nfrom theonlinemcmc import *\n\n# initialise error code value\nerrval = 0\n\n# define the log posterior function\ndef lnprob(theta, x, sigma_gauss, data):\n lp = lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n\n return lp + lnlike(theta, x, sigma_gauss, data)\n\n\n# define the log prior function\ndef lnprior(theta):\n lp = 0.\n m,c = theta\n\n if -10 < m < 10:\n lp = 0.\n else:\n return -np.inf\n\n if -10 < c < 10:\n lp = 0.\n else:\n return -np.inf\n\n return lp\n\n\n# define log likelihood function\ndef lnlike(theta, x, sigma_gauss, data):\n m,c = theta\n md = mymodel(m,c,x)\n return -0.5*np.sum(((md - data)/sigma_gauss)**2)\n\n\n# set number of MCMC points\nNmcmc = 1000\nNburnin = 1000\nNens = 100\nndim = 2\n\n# initialise the start ensemble points\ntry:\n mini = -10 + np.random.rand(Nens)*20\n cini = -10 + np.random.rand(Nens)*20\n pos = np.array([mini, cini]).T\nexcept:\n errval = PRIOR_INIT_ERR\n\n# read in the data\nif errval == 0:\n try:\n data = np.loadtxt(\"data_file.txt\")\n except:\n try:\n data = np.loadtxt(\"data_file.txt\", delimiter=\",\")\n except:\n errval = DATA_READ_ERR\n\n\n# read in the abscissa values\nif errval == 0:\n try:\n x = np.loadtxt(\"abscissa_file.txt\")\n except:\n try:\n x = np.loadtxt(\"abscissa_file.txt\", delimiter=\",\")\n except:\n errval = ABSCISSA_READ_ERR\n\n\n# read in sigma (standard deviation) values (there may be nothing here if it not applicable to your likelihood)\n\n# run the MCMC\nif errval == 0:\n if len(data) != len(x):\n errval = DATA_LENGTH_ERR\n\n argslist = (x, 0.65, data)\n\nif errval == 0:\n # set up sampler\n try:\n sampler = emcee.EnsembleSampler(Nens, ndim, lnprob, args=argslist)\n except:\n errval = MCMC_INIT_ERR\n\n # run sampler\n try:\n sampler.run_mcmc(pos, Nmcmc+Nburnin)\n # remove burn-in and flatten\n samples = sampler.chain[:, Nburnin:, :].reshape((-1, ndim))\n lnp = np.reshape(sampler.lnprobability[:, Nburnin:].flatten(), (-1,1))\n samples = np.hstack((samples, lnp))\n except:\n errval = MCMC_RUN_ERR\n\n # output the posterior samples, likelihood and variables\n try:\n np.savetxt('posterior_samples.txt.gz', samples)\n fv = open('variables.txt', 'w')\n fv.write(\"m,c\")\n fv.close()\n except:\n errval = POST_OUTPUT_ERR\n\n # run post-processing script\n try:\n postprocessing(samples, \"m,c\", x, \"x\", data, \"[email protected]\", \"http://localhost/results/8112a5333cb1bb472ee14fa5342f6422\")\n except:\n errval = POST_PROCESS_ERR\n\nsuccess = True\nif errval != 0:\n # run different script in case error codes are encountered\n errorpage(errval, \"[email protected]\", \"http://localhost/results/8112a5333cb1bb472ee14fa5342f6422\")\n success = False\n\n\n" ]
[ [ "numpy.sum", "numpy.savetxt", "numpy.hstack", "numpy.isfinite", "numpy.random.rand", "numpy.array", "numpy.loadtxt" ] ]
zjutcv/mmhid
[ "faeaf4fb5c634037c6e482f63ef73e7f2144c7b5" ]
[ "mmhid/datasets/builder.py" ]
[ "# Copyright (c) OpenMMLab. All rights reserved.\nimport copy\nimport platform\nimport random\nfrom functools import partial\n\nimport numpy as np\nfrom mmcv.parallel import collate\nfrom mmcv.runner import get_dist_info\nfrom mmcv.utils import Registry, build_from_cfg\nfrom torch.utils.data import DataLoader\n\nfrom .samplers import DistributedGroupSampler, DistributedSampler, GroupSampler\n\nDATA_ROOT = {\n 'BIT': './data/BIT',\n 'UT': './data/ut120',\n 'highfive': './data/highfive'\n}\n\nFRAMES_ROOT = {\n 'BIT': 'Bit-frames',\n}\n\nANNO_ROOT = {\n 'BIT': 'BIT-anno/tidy_anno'\n}\n\nif platform.system() != 'Windows':\n # https://github.com/pytorch/pytorch/issues/973\n import resource\n\n rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\n base_soft_limit = rlimit[0]\n hard_limit = rlimit[1]\n soft_limit = min(max(4096, base_soft_limit), hard_limit)\n resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit))\n\nHID_DATASETS = Registry('hid_dataset')\nHID_PIPELINES = Registry('hid_pipeline')\n\n\ndef build_dataset(cfg, default_args=None):\n dataset = build_from_cfg(cfg, HID_DATASETS, default_args)\n return dataset\n\n\ndef build_dataloader(dataset,\n samples_per_gpu,\n workers_per_gpu,\n num_gpus=1,\n dist=True,\n shuffle=True,\n seed=None,\n **kwargs):\n \"\"\"Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed training, there is only one dataloader for all GPUs.\n\n Args:\n dataset (Dataset): A PyTorch dataset.\n samples_per_gpu (int): Number of training samples on each GPU, i.e.,\n batch size of each GPU.\n workers_per_gpu (int): How many subprocesses to use for data loading\n for each GPU.\n num_gpus (int): Number of GPUs. Only used in non-distributed training.\n dist (bool): Distributed training/test or not. Default: True.\n shuffle (bool): Whether to shuffle the data at every epoch.\n Default: True.\n kwargs: any keyword argument to be used to initialize DataLoader\n\n Returns:\n DataLoader: A PyTorch dataloader.\n \"\"\"\n rank, world_size = get_dist_info()\n if dist:\n # DistributedGroupSampler will definitely shuffle the data to satisfy\n # that images on each GPU are in the same group\n if shuffle:\n sampler = DistributedGroupSampler(\n dataset, samples_per_gpu, world_size, rank, seed=seed)\n else:\n sampler = DistributedSampler(\n dataset, world_size, rank, shuffle=False, seed=seed)\n batch_size = samples_per_gpu\n num_workers = workers_per_gpu\n else:\n sampler = GroupSampler(dataset, samples_per_gpu) if shuffle else None\n batch_size = num_gpus * samples_per_gpu\n num_workers = num_gpus * workers_per_gpu\n\n init_fn = partial(\n worker_init_fn, num_workers=num_workers, rank=rank,\n seed=seed) if seed is not None else None\n\n data_loader = DataLoader(\n dataset,\n batch_size=batch_size,\n sampler=sampler,\n num_workers=num_workers,\n collate_fn=partial(collate, samples_per_gpu=samples_per_gpu),\n pin_memory=False,\n worker_init_fn=init_fn,\n **kwargs)\n\n return data_loader\n\n\ndef worker_init_fn(worker_id, num_workers, rank, seed):\n # The seed of each worker equals to\n # num_worker * rank + worker_id + user_seed\n worker_seed = num_workers * rank + worker_id + seed\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n" ]
[ [ "numpy.random.seed" ] ]
amelliaaas/tugastkc4
[ "f442382c72379e911f3780543b95345a3b1c9407", "f442382c72379e911f3780543b95345a3b1c9407" ]
[ "venv/Lib/site-packages/skimage/transform/tests/test_radon_transform.py", "venv/Lib/site-packages/skimage/segmentation/tests/test_slic.py" ]
[ "import itertools\nimport pytest\n\nimport numpy as np\nfrom skimage.data import shepp_logan_phantom\nfrom skimage.transform import radon, iradon, iradon_sart, rescale\n\nfrom skimage._shared.utils import convert_to_float\nfrom skimage._shared import testing\nfrom skimage._shared.testing import test_parallel\nfrom skimage._shared._warnings import expected_warnings\n\n\nPHANTOM = shepp_logan_phantom()[::2, ::2]\nPHANTOM = rescale(PHANTOM, 0.5, order=1,\n mode='constant', anti_aliasing=False, multichannel=False)\n\n\ndef _debug_plot(original, result, sinogram=None):\n from matplotlib import pyplot as plt\n imkwargs = dict(cmap='gray', interpolation='nearest')\n if sinogram is None:\n plt.figure(figsize=(15, 6))\n sp = 130\n else:\n plt.figure(figsize=(11, 11))\n sp = 221\n plt.subplot(sp + 0)\n plt.imshow(sinogram, aspect='auto', **imkwargs)\n plt.subplot(sp + 1)\n plt.imshow(original, **imkwargs)\n plt.subplot(sp + 2)\n plt.imshow(result, vmin=original.min(), vmax=original.max(), **imkwargs)\n plt.subplot(sp + 3)\n plt.imshow(result - original, **imkwargs)\n plt.colorbar()\n plt.show()\n\n\ndef _rescale_intensity(x):\n x = x.astype(float)\n x -= x.min()\n x /= x.max()\n return x\n\n\ndef test_iradon_bias_circular_phantom():\n \"\"\"\n test that a uniform circular phantom has a small reconstruction bias\n \"\"\"\n pixels = 128\n xy = np.arange(-pixels / 2, pixels / 2) + 0.5\n x, y = np.meshgrid(xy, xy)\n image = x**2 + y**2 <= (pixels/4)**2\n\n theta = np.linspace(0., 180., max(image.shape), endpoint=False)\n sinogram = radon(image, theta=theta)\n\n reconstruction_fbp = iradon(sinogram, theta=theta)\n error = reconstruction_fbp - image\n\n tol = 5e-5\n roi_err = np.abs(np.mean(error))\n assert roi_err < tol\n\n\ndef check_radon_center(shape, circle, dtype, preserve_range):\n # Create a test image with only a single non-zero pixel at the origin\n image = np.zeros(shape, dtype=dtype)\n image[(shape[0] // 2, shape[1] // 2)] = 1.\n # Calculate the sinogram\n theta = np.linspace(0., 180., max(shape), endpoint=False)\n sinogram = radon(image, theta=theta, circle=circle,\n preserve_range=preserve_range)\n # The sinogram should be a straight, horizontal line\n sinogram_max = np.argmax(sinogram, axis=0)\n print(sinogram_max)\n assert np.std(sinogram_max) < 1e-6\n\n\[email protected](\"shape\", [(16, 16), (17, 17)])\[email protected](\"circle\", [False, True])\[email protected](\"dtype\", [np.float64, np.float32, np.uint8, bool])\[email protected](\"preserve_range\", [False, True])\ndef test_radon_center(shape, circle, dtype, preserve_range):\n check_radon_center(shape, circle, dtype, preserve_range)\n\n\[email protected](\"shape\", [(32, 16), (33, 17)])\[email protected](\"circle\", [False])\[email protected](\"dtype\", [np.float64, np.float32, np.uint8, bool])\[email protected](\"preserve_range\", [False, True])\ndef test_radon_center_rectangular(shape, circle, dtype, preserve_range):\n check_radon_center(shape, circle, dtype, preserve_range)\n\n\ndef check_iradon_center(size, theta, circle):\n debug = False\n # Create a test sinogram corresponding to a single projection\n # with a single non-zero pixel at the rotation center\n if circle:\n sinogram = np.zeros((size, 1), dtype=float)\n sinogram[size // 2, 0] = 1.\n else:\n diagonal = int(np.ceil(np.sqrt(2) * size))\n sinogram = np.zeros((diagonal, 1), dtype=float)\n sinogram[sinogram.shape[0] // 2, 0] = 1.\n maxpoint = np.unravel_index(np.argmax(sinogram), sinogram.shape)\n print('shape of generated sinogram', sinogram.shape)\n print('maximum in generated sinogram', maxpoint)\n # Compare reconstructions for theta=angle and theta=angle + 180;\n # these should be exactly equal\n reconstruction = iradon(sinogram, theta=[theta], circle=circle)\n reconstruction_opposite = iradon(sinogram, theta=[theta + 180],\n circle=circle)\n print('rms deviance:',\n np.sqrt(np.mean((reconstruction_opposite - reconstruction)**2)))\n if debug:\n import matplotlib.pyplot as plt\n imkwargs = dict(cmap='gray', interpolation='nearest')\n plt.figure()\n plt.subplot(221)\n plt.imshow(sinogram, **imkwargs)\n plt.subplot(222)\n plt.imshow(reconstruction_opposite - reconstruction, **imkwargs)\n plt.subplot(223)\n plt.imshow(reconstruction, **imkwargs)\n plt.subplot(224)\n plt.imshow(reconstruction_opposite, **imkwargs)\n plt.show()\n\n assert np.allclose(reconstruction, reconstruction_opposite)\n\n\nsizes_for_test_iradon_center = [16, 17]\nthetas_for_test_iradon_center = [0, 90]\ncircles_for_test_iradon_center = [False, True]\n\n\[email protected](\"size, theta, circle\",\n itertools.product(sizes_for_test_iradon_center,\n thetas_for_test_iradon_center,\n circles_for_test_iradon_center))\ndef test_iradon_center(size, theta, circle):\n check_iradon_center(size, theta, circle)\n\n\ndef check_radon_iradon(interpolation_type, filter_type):\n debug = False\n image = PHANTOM\n reconstructed = iradon(radon(image, circle=False), filter_name=filter_type,\n interpolation=interpolation_type, circle=False)\n delta = np.mean(np.abs(image - reconstructed))\n print('\\n\\tmean error:', delta)\n if debug:\n _debug_plot(image, reconstructed)\n if filter_type in ('ramp', 'shepp-logan'):\n if interpolation_type == 'nearest':\n allowed_delta = 0.03\n else:\n allowed_delta = 0.025\n else:\n allowed_delta = 0.05\n assert delta < allowed_delta\n\n\nfilter_types = [\"ramp\", \"shepp-logan\", \"cosine\", \"hamming\", \"hann\"]\ninterpolation_types = ['linear', 'nearest']\nradon_iradon_inputs = list(itertools.product(interpolation_types,\n filter_types))\n# cubic interpolation is slow; only run one test for it\nradon_iradon_inputs.append(('cubic', 'shepp-logan'))\n\n\[email protected](\"interpolation_type, filter_type\",\n radon_iradon_inputs)\ndef test_radon_iradon(interpolation_type, filter_type):\n check_radon_iradon(interpolation_type, filter_type)\n\n\[email protected](\"filter_type\", filter_types)\ndef test_iradon_new_signature(filter_type):\n image = PHANTOM\n sinogram = radon(image, circle=False)\n with pytest.warns(FutureWarning):\n assert np.array_equal(iradon(sinogram, filter=filter_type),\n iradon(sinogram, filter_name=filter_type))\n\n\ndef test_iradon_angles():\n \"\"\"\n Test with different number of projections\n \"\"\"\n size = 100\n # Synthetic data\n image = np.tri(size) + np.tri(size)[::-1]\n # Large number of projections: a good quality is expected\n nb_angles = 200\n theta = np.linspace(0, 180, nb_angles, endpoint=False)\n radon_image_200 = radon(image, theta=theta, circle=False)\n reconstructed = iradon(radon_image_200, circle=False)\n delta_200 = np.mean(abs(_rescale_intensity(image) -\n _rescale_intensity(reconstructed)))\n assert delta_200 < 0.03\n # Lower number of projections\n nb_angles = 80\n radon_image_80 = radon(image, theta=theta, circle=False)\n # Test whether the sum of all projections is approximately the same\n s = radon_image_80.sum(axis=0)\n assert np.allclose(s, s[0], rtol=0.01)\n reconstructed = iradon(radon_image_80, circle=False)\n delta_80 = np.mean(abs(image / np.max(image) -\n reconstructed / np.max(reconstructed)))\n # Loss of quality when the number of projections is reduced\n assert delta_80 > delta_200\n\n\ndef check_radon_iradon_minimal(shape, slices):\n debug = False\n theta = np.arange(180)\n image = np.zeros(shape, dtype=float)\n image[slices] = 1.\n sinogram = radon(image, theta, circle=False)\n reconstructed = iradon(sinogram, theta, circle=False)\n print('\\n\\tMaximum deviation:', np.max(np.abs(image - reconstructed)))\n if debug:\n _debug_plot(image, reconstructed, sinogram)\n if image.sum() == 1:\n assert (np.unravel_index(np.argmax(reconstructed), image.shape)\n == np.unravel_index(np.argmax(image), image.shape))\n\n\nshapes = [(3, 3), (4, 4), (5, 5)]\n\n\ndef generate_test_data_for_radon_iradon_minimal(shapes):\n def shape2coordinates(shape):\n c0, c1 = shape[0] // 2, shape[1] // 2\n coordinates = itertools.product((c0 - 1, c0, c0 + 1),\n (c1 - 1, c1, c1 + 1))\n return coordinates\n\n def shape2shapeandcoordinates(shape):\n return itertools.product([shape], shape2coordinates(shape))\n\n return itertools.chain.from_iterable([shape2shapeandcoordinates(shape)\n for shape in shapes])\n\n\[email protected](\"shape, coordinate\",\n generate_test_data_for_radon_iradon_minimal(shapes))\ndef test_radon_iradon_minimal(shape, coordinate):\n check_radon_iradon_minimal(shape, coordinate)\n\n\ndef test_reconstruct_with_wrong_angles():\n a = np.zeros((3, 3))\n p = radon(a, theta=[0, 1, 2], circle=False)\n iradon(p, theta=[0, 1, 2], circle=False)\n with testing.raises(ValueError):\n iradon(p, theta=[0, 1, 2, 3])\n\n\ndef _random_circle(shape):\n # Synthetic random data, zero outside reconstruction circle\n np.random.seed(98312871)\n image = np.random.rand(*shape)\n c0, c1 = np.ogrid[0:shape[0], 0:shape[1]]\n r = np.sqrt((c0 - shape[0] // 2)**2 + (c1 - shape[1] // 2)**2)\n radius = min(shape) // 2\n image[r > radius] = 0.\n return image\n\n\ndef test_radon_circle():\n a = np.ones((10, 10))\n with expected_warnings(['reconstruction circle']):\n radon(a, circle=True)\n\n # Synthetic data, circular symmetry\n shape = (61, 79)\n c0, c1 = np.ogrid[0:shape[0], 0:shape[1]]\n r = np.sqrt((c0 - shape[0] // 2)**2 + (c1 - shape[1] // 2)**2)\n radius = min(shape) // 2\n image = np.clip(radius - r, 0, np.inf)\n image = _rescale_intensity(image)\n angles = np.linspace(0, 180, min(shape), endpoint=False)\n sinogram = radon(image, theta=angles, circle=True)\n assert np.all(sinogram.std(axis=1) < 1e-2)\n\n # Synthetic data, random\n image = _random_circle(shape)\n sinogram = radon(image, theta=angles, circle=True)\n mass = sinogram.sum(axis=0)\n average_mass = mass.mean()\n relative_error = np.abs(mass - average_mass) / average_mass\n print(relative_error.max(), relative_error.mean())\n assert np.all(relative_error < 3.2e-3)\n\n\ndef check_sinogram_circle_to_square(size):\n from skimage.transform.radon_transform import _sinogram_circle_to_square\n image = _random_circle((size, size))\n theta = np.linspace(0., 180., size, False)\n sinogram_circle = radon(image, theta, circle=True)\n\n def argmax_shape(a):\n return np.unravel_index(np.argmax(a), a.shape)\n\n print('\\n\\targmax of circle:', argmax_shape(sinogram_circle))\n sinogram_square = radon(image, theta, circle=False)\n print('\\targmax of square:', argmax_shape(sinogram_square))\n sinogram_circle_to_square = _sinogram_circle_to_square(sinogram_circle)\n print('\\targmax of circle to square:',\n argmax_shape(sinogram_circle_to_square))\n error = abs(sinogram_square - sinogram_circle_to_square)\n print(np.mean(error), np.max(error))\n assert (argmax_shape(sinogram_square) ==\n argmax_shape(sinogram_circle_to_square))\n\n\[email protected](\"size\", (50, 51))\ndef test_sinogram_circle_to_square(size):\n check_sinogram_circle_to_square(size)\n\n\ndef check_radon_iradon_circle(interpolation, shape, output_size):\n # Forward and inverse radon on synthetic data\n image = _random_circle(shape)\n radius = min(shape) // 2\n sinogram_rectangle = radon(image, circle=False)\n reconstruction_rectangle = iradon(sinogram_rectangle,\n output_size=output_size,\n interpolation=interpolation,\n circle=False)\n sinogram_circle = radon(image, circle=True)\n reconstruction_circle = iradon(sinogram_circle,\n output_size=output_size,\n interpolation=interpolation,\n circle=True)\n # Crop rectangular reconstruction to match circle=True reconstruction\n width = reconstruction_circle.shape[0]\n excess = int(np.ceil((reconstruction_rectangle.shape[0] - width) / 2))\n s = np.s_[excess:width + excess, excess:width + excess]\n reconstruction_rectangle = reconstruction_rectangle[s]\n # Find the reconstruction circle, set reconstruction to zero outside\n c0, c1 = np.ogrid[0:width, 0:width]\n r = np.sqrt((c0 - width // 2)**2 + (c1 - width // 2)**2)\n reconstruction_rectangle[r > radius] = 0.\n print(reconstruction_circle.shape)\n print(reconstruction_rectangle.shape)\n np.allclose(reconstruction_rectangle, reconstruction_circle)\n\n\n# if adding more shapes to test data, you might want to look at commit d0f2bac3f\nshapes_radon_iradon_circle = ((61, 79), )\ninterpolations = ('nearest', 'linear')\noutput_sizes = (None,\n min(shapes_radon_iradon_circle[0]),\n max(shapes_radon_iradon_circle[0]),\n 97)\n\n\[email protected](\"shape, interpolation, output_size\",\n itertools.product(shapes_radon_iradon_circle,\n interpolations, output_sizes))\ndef test_radon_iradon_circle(shape, interpolation, output_size):\n check_radon_iradon_circle(interpolation, shape, output_size)\n\n\ndef test_order_angles_golden_ratio():\n from skimage.transform.radon_transform import order_angles_golden_ratio\n np.random.seed(1231)\n lengths = [1, 4, 10, 180]\n for l in lengths:\n theta_ordered = np.linspace(0, 180, l, endpoint=False)\n theta_random = np.random.uniform(0, 180, l)\n for theta in (theta_random, theta_ordered):\n indices = [x for x in order_angles_golden_ratio(theta)]\n # no duplicate indices allowed\n assert len(indices) == len(set(indices))\n\n\n@test_parallel()\ndef test_iradon_sart():\n debug = False\n\n image = rescale(PHANTOM, 0.8, mode='reflect',\n multichannel=False, anti_aliasing=False)\n theta_ordered = np.linspace(0., 180., image.shape[0], endpoint=False)\n theta_missing_wedge = np.linspace(0., 150., image.shape[0], endpoint=True)\n for theta, error_factor in ((theta_ordered, 1.),\n (theta_missing_wedge, 2.)):\n sinogram = radon(image, theta, circle=True)\n reconstructed = iradon_sart(sinogram, theta)\n\n if debug:\n from matplotlib import pyplot as plt\n plt.figure()\n plt.subplot(221)\n plt.imshow(image, interpolation='nearest')\n plt.subplot(222)\n plt.imshow(sinogram, interpolation='nearest')\n plt.subplot(223)\n plt.imshow(reconstructed, interpolation='nearest')\n plt.subplot(224)\n plt.imshow(reconstructed - image, interpolation='nearest')\n plt.show()\n\n delta = np.mean(np.abs(reconstructed - image))\n print('delta (1 iteration) =', delta)\n assert delta < 0.02 * error_factor\n reconstructed = iradon_sart(sinogram, theta, reconstructed)\n delta = np.mean(np.abs(reconstructed - image))\n print('delta (2 iterations) =', delta)\n assert delta < 0.014 * error_factor\n reconstructed = iradon_sart(sinogram, theta, clip=(0, 1))\n delta = np.mean(np.abs(reconstructed - image))\n print('delta (1 iteration, clip) =', delta)\n assert delta < 0.018 * error_factor\n\n np.random.seed(1239867)\n shifts = np.random.uniform(-3, 3, sinogram.shape[1])\n x = np.arange(sinogram.shape[0])\n sinogram_shifted = np.vstack([np.interp(x + shifts[i], x,\n sinogram[:, i])\n for i in range(sinogram.shape[1])]).T\n reconstructed = iradon_sart(sinogram_shifted, theta,\n projection_shifts=shifts)\n if debug:\n from matplotlib import pyplot as plt\n plt.figure()\n plt.subplot(221)\n plt.imshow(image, interpolation='nearest')\n plt.subplot(222)\n plt.imshow(sinogram_shifted, interpolation='nearest')\n plt.subplot(223)\n plt.imshow(reconstructed, interpolation='nearest')\n plt.subplot(224)\n plt.imshow(reconstructed - image, interpolation='nearest')\n plt.show()\n\n delta = np.mean(np.abs(reconstructed - image))\n print('delta (1 iteration, shifted sinogram) =', delta)\n assert delta < 0.022 * error_factor\n\n\[email protected](\"preserve_range\", [True, False])\ndef test_iradon_dtype(preserve_range):\n sinogram = np.zeros((16, 1), dtype=int)\n sinogram[8, 0] = 1.\n sinogram64 = sinogram.astype('float64')\n sinogram32 = sinogram.astype('float32')\n\n assert iradon(sinogram, theta=[0],\n preserve_range=preserve_range).dtype == 'float64'\n assert iradon(sinogram64, theta=[0],\n preserve_range=preserve_range).dtype == sinogram64.dtype\n assert iradon(sinogram32, theta=[0],\n preserve_range=preserve_range).dtype == sinogram32.dtype\n\n\ndef test_radon_dtype():\n img = convert_to_float(PHANTOM, False)\n img32 = img.astype(np.float32)\n\n assert radon(img).dtype == img.dtype\n assert radon(img32).dtype == img32.dtype\n\n\[email protected](\"dtype\", [np.float32, np.float64])\ndef test_iradon_sart_dtype(dtype):\n sinogram = np.zeros((16, 1), dtype=int)\n sinogram[8, 0] = 1.\n sinogram64 = sinogram.astype('float64')\n sinogram32 = sinogram.astype('float32')\n\n with expected_warnings(['Input data is cast to float']):\n assert iradon_sart(sinogram, theta=[0]).dtype == 'float64'\n\n assert iradon_sart(sinogram64, theta=[0]).dtype == sinogram64.dtype\n assert iradon_sart(sinogram32, theta=[0]).dtype == sinogram32.dtype\n\n assert iradon_sart(sinogram, theta=[0], dtype=dtype).dtype == dtype\n assert iradon_sart(sinogram32, theta=[0], dtype=dtype).dtype == dtype\n assert iradon_sart(sinogram64, theta=[0], dtype=dtype).dtype == dtype\n\n\ndef test_iradon_sart_wrong_dtype():\n sinogram = np.zeros((16, 1))\n\n with testing.raises(ValueError):\n iradon_sart(sinogram, dtype=int)\n", "from itertools import product\n\nimport pytest\nimport numpy as np\nfrom skimage.segmentation import slic\n\nfrom skimage._shared import testing\nfrom skimage._shared.testing import test_parallel, assert_equal\n\n\n@test_parallel()\ndef test_color_2d():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21, 3))\n img[:10, :10, 0] = 1\n img[10:, :10, 1] = 1\n img[10:, 10:, 2] = 1\n img += 0.01 * rnd.normal(size=img.shape)\n img[img > 1] = 1\n img[img < 0] = 0\n seg = slic(img, n_segments=4, sigma=0, enforce_connectivity=False,\n start_label=0)\n\n # we expect 4 segments\n assert_equal(len(np.unique(seg)), 4)\n assert_equal(seg.shape, img.shape[:-1])\n assert_equal(seg[:10, :10], 0)\n assert_equal(seg[10:, :10], 2)\n assert_equal(seg[:10, 10:], 1)\n assert_equal(seg[10:, 10:], 3)\n\n\ndef test_multichannel_2d():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 20, 8))\n img[:10, :10, 0:2] = 1\n img[:10, 10:, 2:4] = 1\n img[10:, :10, 4:6] = 1\n img[10:, 10:, 6:8] = 1\n img += 0.01 * rnd.normal(size=img.shape)\n img = np.clip(img, 0, 1, out=img)\n seg = slic(img, n_segments=4, enforce_connectivity=False, start_label=0)\n\n # we expect 4 segments\n assert_equal(len(np.unique(seg)), 4)\n assert_equal(seg.shape, img.shape[:-1])\n assert_equal(seg[:10, :10], 0)\n assert_equal(seg[10:, :10], 2)\n assert_equal(seg[:10, 10:], 1)\n assert_equal(seg[10:, 10:], 3)\n\n\ndef test_gray_2d():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21))\n img[:10, :10] = 0.33\n img[10:, :10] = 0.67\n img[10:, 10:] = 1.00\n img += 0.0033 * rnd.normal(size=img.shape)\n img[img > 1] = 1\n img[img < 0] = 0\n seg = slic(img, sigma=0, n_segments=4, compactness=1,\n multichannel=False, convert2lab=False, start_label=0)\n\n assert_equal(len(np.unique(seg)), 4)\n assert_equal(seg.shape, img.shape)\n assert_equal(seg[:10, :10], 0)\n assert_equal(seg[10:, :10], 2)\n assert_equal(seg[:10, 10:], 1)\n assert_equal(seg[10:, 10:], 3)\n\n\ndef test_color_3d():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21, 22, 3))\n slices = []\n for dim_size in img.shape[:-1]:\n midpoint = dim_size // 2\n slices.append((slice(None, midpoint), slice(midpoint, None)))\n slices = list(product(*slices))\n colors = list(product(*(([0, 1],) * 3)))\n for s, c in zip(slices, colors):\n img[s] = c\n img += 0.01 * rnd.normal(size=img.shape)\n img[img > 1] = 1\n img[img < 0] = 0\n seg = slic(img, sigma=0, n_segments=8, start_label=0)\n\n assert_equal(len(np.unique(seg)), 8)\n for s, c in zip(slices, range(8)):\n assert_equal(seg[s], c)\n\n\ndef test_gray_3d():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21, 22))\n slices = []\n for dim_size in img.shape:\n midpoint = dim_size // 2\n slices.append((slice(None, midpoint), slice(midpoint, None)))\n slices = list(product(*slices))\n shades = np.arange(0, 1.000001, 1.0 / 7)\n for s, sh in zip(slices, shades):\n img[s] = sh\n img += 0.001 * rnd.normal(size=img.shape)\n img[img > 1] = 1\n img[img < 0] = 0\n seg = slic(img, sigma=0, n_segments=8, compactness=1,\n multichannel=False, convert2lab=False, start_label=0)\n\n assert_equal(len(np.unique(seg)), 8)\n for s, c in zip(slices, range(8)):\n assert_equal(seg[s], c)\n\n\ndef test_list_sigma():\n rnd = np.random.RandomState(0)\n img = np.array([[1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1]], float)\n img += 0.1 * rnd.normal(size=img.shape)\n result_sigma = np.array([[0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1]], int)\n seg_sigma = slic(img, n_segments=2, sigma=[1, 50, 1],\n multichannel=False, start_label=0)\n assert_equal(seg_sigma, result_sigma)\n\n\ndef test_spacing():\n rnd = np.random.RandomState(0)\n img = np.array([[1, 1, 1, 0, 0],\n [1, 1, 0, 0, 0]], float)\n result_non_spaced = np.array([[0, 0, 0, 1, 1],\n [0, 0, 1, 1, 1]], int)\n result_spaced = np.array([[0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1]], int)\n img += 0.1 * rnd.normal(size=img.shape)\n seg_non_spaced = slic(img, n_segments=2, sigma=0, multichannel=False,\n compactness=1.0, start_label=0)\n seg_spaced = slic(img, n_segments=2, sigma=0, spacing=[1, 500, 1],\n compactness=1.0, multichannel=False, start_label=0)\n assert_equal(seg_non_spaced, result_non_spaced)\n assert_equal(seg_spaced, result_spaced)\n\n\ndef test_invalid_lab_conversion():\n img = np.array([[1, 1, 1, 0, 0],\n [1, 1, 0, 0, 0]], float) + 1\n with testing.raises(ValueError):\n slic(img, multichannel=True, convert2lab=True, start_label=0)\n\n\ndef test_enforce_connectivity():\n img = np.array([[0, 0, 0, 1, 1, 1],\n [1, 0, 0, 1, 1, 0],\n [0, 0, 0, 1, 1, 0]], float)\n\n segments_connected = slic(img, 2, compactness=0.0001,\n enforce_connectivity=True,\n convert2lab=False, start_label=0)\n segments_disconnected = slic(img, 2, compactness=0.0001,\n enforce_connectivity=False,\n convert2lab=False, start_label=0)\n\n # Make sure nothing fatal occurs (e.g. buffer overflow) at low values of\n # max_size_factor\n segments_connected_low_max = slic(img, 2, compactness=0.0001,\n enforce_connectivity=True,\n convert2lab=False,\n max_size_factor=0.8,\n start_label=0)\n\n result_connected = np.array([[0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1],\n [0, 0, 0, 1, 1, 1]], float)\n\n result_disconnected = np.array([[0, 0, 0, 1, 1, 1],\n [1, 0, 0, 1, 1, 0],\n [0, 0, 0, 1, 1, 0]], float)\n\n assert_equal(segments_connected, result_connected)\n assert_equal(segments_disconnected, result_disconnected)\n assert_equal(segments_connected_low_max, result_connected)\n\n\ndef test_slic_zero():\n # Same as test_color_2d but with slic_zero=True\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21, 3))\n img[:10, :10, 0] = 1\n img[10:, :10, 1] = 1\n img[10:, 10:, 2] = 1\n img += 0.01 * rnd.normal(size=img.shape)\n img[img > 1] = 1\n img[img < 0] = 0\n seg = slic(img, n_segments=4, sigma=0, slic_zero=True, start_label=0)\n\n # we expect 4 segments\n assert_equal(len(np.unique(seg)), 4)\n assert_equal(seg.shape, img.shape[:-1])\n assert_equal(seg[:10, :10], 0)\n assert_equal(seg[10:, :10], 2)\n assert_equal(seg[:10, 10:], 1)\n assert_equal(seg[10:, 10:], 3)\n\n\ndef test_more_segments_than_pixels():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21))\n img[:10, :10] = 0.33\n img[10:, :10] = 0.67\n img[10:, 10:] = 1.00\n img += 0.0033 * rnd.normal(size=img.shape)\n img[img > 1] = 1\n img[img < 0] = 0\n seg = slic(img, sigma=0, n_segments=500, compactness=1,\n multichannel=False, convert2lab=False, start_label=0)\n assert np.all(seg.ravel() == np.arange(seg.size))\n\n\ndef test_color_2d_mask():\n rnd = np.random.RandomState(0)\n msk = np.zeros((20, 21))\n msk[2:-2, 2:-2] = 1\n img = np.zeros((20, 21, 3))\n img[:10, :10, 0] = 1\n img[10:, :10, 1] = 1\n img[10:, 10:, 2] = 1\n img += 0.01 * rnd.normal(size=img.shape)\n np.clip(img, 0, 1, out=img)\n seg = slic(img, n_segments=4, sigma=0, enforce_connectivity=False,\n mask=msk)\n\n # we expect 4 segments + masked area\n assert_equal(len(np.unique(seg)), 5)\n assert_equal(seg.shape, img.shape[:-1])\n # segments\n assert_equal(seg[2:10, 2:10], 1)\n assert_equal(seg[10:-2, 2:10], 4)\n assert_equal(seg[2:10, 10:-2], 2)\n assert_equal(seg[10:-2, 10:-2], 3)\n # non masked area\n assert_equal(seg[:2, :], 0)\n assert_equal(seg[-2:, :], 0)\n assert_equal(seg[:, :2], 0)\n assert_equal(seg[:, -2:], 0)\n\n\ndef test_multichannel_2d_mask():\n rnd = np.random.RandomState(0)\n msk = np.zeros((20, 20))\n msk[2:-2, 2:-2] = 1\n img = np.zeros((20, 20, 8))\n img[:10, :10, 0:2] = 1\n img[:10, 10:, 2:4] = 1\n img[10:, :10, 4:6] = 1\n img[10:, 10:, 6:8] = 1\n img += 0.01 * rnd.normal(size=img.shape)\n np.clip(img, 0, 1, out=img)\n seg = slic(img, n_segments=4, enforce_connectivity=False,\n mask=msk)\n\n # we expect 4 segments + masked area\n assert_equal(len(np.unique(seg)), 5)\n assert_equal(seg.shape, img.shape[:-1])\n # segments\n assert_equal(seg[2:10, 2:10], 2)\n assert_equal(seg[2:10, 10:-2], 1)\n assert_equal(seg[10:-2, 2:10], 4)\n assert_equal(seg[10:-2, 10:-2], 3)\n # non masked area\n assert_equal(seg[:2, :], 0)\n assert_equal(seg[-2:, :], 0)\n assert_equal(seg[:, :2], 0)\n assert_equal(seg[:, -2:], 0)\n\n\ndef test_gray_2d_mask():\n rnd = np.random.RandomState(0)\n msk = np.zeros((20, 21))\n msk[2:-2, 2:-2] = 1\n img = np.zeros((20, 21))\n img[:10, :10] = 0.33\n img[10:, :10] = 0.67\n img[10:, 10:] = 1.00\n img += 0.0033 * rnd.normal(size=img.shape)\n np.clip(img, 0, 1, out=img)\n seg = slic(img, sigma=0, n_segments=4, compactness=1,\n multichannel=False, convert2lab=False, mask=msk)\n\n assert_equal(len(np.unique(seg)), 5)\n assert_equal(seg.shape, img.shape)\n # segments\n assert_equal(seg[2:10, 2:10], 1)\n assert_equal(seg[2:10, 10:-2], 2)\n assert_equal(seg[10:-2, 2:10], 3)\n assert_equal(seg[10:-2, 10:-2], 4)\n # non masked area\n assert_equal(seg[:2, :], 0)\n assert_equal(seg[-2:, :], 0)\n assert_equal(seg[:, :2], 0)\n assert_equal(seg[:, -2:], 0)\n\n\ndef test_list_sigma_mask():\n rnd = np.random.RandomState(0)\n msk = np.zeros((2, 6))\n msk[:, 1:-1] = 1\n img = np.array([[1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1]], float)\n img += 0.1 * rnd.normal(size=img.shape)\n result_sigma = np.array([[0, 1, 1, 2, 2, 0],\n [0, 1, 1, 2, 2, 0]], int)\n seg_sigma = slic(img, n_segments=2, sigma=[1, 50, 1],\n multichannel=False, mask=msk)\n assert_equal(seg_sigma, result_sigma)\n\n\ndef test_spacing_mask():\n rnd = np.random.RandomState(0)\n msk = np.zeros((2, 5))\n msk[:, 1:-1] = 1\n img = np.array([[1, 1, 1, 0, 0],\n [1, 1, 0, 0, 0]], float)\n result_non_spaced = np.array([[0, 1, 1, 2, 0],\n [0, 1, 2, 2, 0]], int)\n result_spaced = np.array([[0, 1, 1, 1, 0],\n [0, 2, 2, 2, 0]], int)\n img += 0.1 * rnd.normal(size=img.shape)\n seg_non_spaced = slic(img, n_segments=2, sigma=0, multichannel=False,\n compactness=1.0, mask=msk)\n seg_spaced = slic(img, n_segments=2, sigma=0, spacing=[1, 50, 1],\n compactness=1.0, multichannel=False, mask=msk)\n assert_equal(seg_non_spaced, result_non_spaced)\n assert_equal(seg_spaced, result_spaced)\n\n\ndef test_enforce_connectivity_mask():\n msk = np.zeros((3, 6))\n msk[:, 1:-1] = 1\n img = np.array([[0, 0, 0, 1, 1, 1],\n [1, 0, 0, 1, 1, 0],\n [0, 0, 0, 1, 1, 0]], float)\n\n segments_connected = slic(img, 2, compactness=0.0001,\n enforce_connectivity=True,\n convert2lab=False, mask=msk)\n segments_disconnected = slic(img, 2, compactness=0.0001,\n enforce_connectivity=False,\n convert2lab=False, mask=msk)\n\n # Make sure nothing fatal occurs (e.g. buffer overflow) at low values of\n # max_size_factor\n segments_connected_low_max = slic(img, 2, compactness=0.0001,\n enforce_connectivity=True,\n convert2lab=False,\n max_size_factor=0.8, mask=msk)\n\n result_connected = np.array([[0, 1, 1, 2, 2, 0],\n [0, 1, 1, 2, 2, 0],\n [0, 1, 1, 2, 2, 0]], float)\n\n result_disconnected = np.array([[0, 1, 1, 2, 2, 0],\n [0, 1, 1, 2, 2, 0],\n [0, 1, 1, 2, 2, 0]], float)\n\n assert_equal(segments_connected, result_connected)\n assert_equal(segments_disconnected, result_disconnected)\n assert_equal(segments_connected_low_max, result_connected)\n\n\ndef test_slic_zero_mask():\n\n rnd = np.random.RandomState(0)\n msk = np.zeros((20, 21))\n msk[2:-2, 2:-2] = 1\n img = np.zeros((20, 21, 3))\n img[:10, :10, 0] = 1\n img[10:, :10, 1] = 1\n img[10:, 10:, 2] = 1\n img += 0.01 * rnd.normal(size=img.shape)\n np.clip(img, 0, 1, out=img)\n seg = slic(img, n_segments=4, sigma=0, slic_zero=True,\n mask=msk)\n\n # we expect 4 segments + masked area\n assert_equal(len(np.unique(seg)), 5)\n assert_equal(seg.shape, img.shape[:-1])\n # segments\n assert_equal(seg[2:10, 2:10], 1)\n assert_equal(seg[2:10, 10:-2], 2)\n assert_equal(seg[10:-2, 2:10], 3)\n assert_equal(seg[10:-2, 10:-2], 4)\n # non masked area\n assert_equal(seg[:2, :], 0)\n assert_equal(seg[-2:, :], 0)\n assert_equal(seg[:, :2], 0)\n assert_equal(seg[:, -2:], 0)\n\n\ndef test_more_segments_than_pixels_mask():\n rnd = np.random.RandomState(0)\n msk = np.zeros((20, 21))\n msk[2:-2, 2:-2] = 1\n img = np.zeros((20, 21))\n img[:10, :10] = 0.33\n img[10:, :10] = 0.67\n img[10:, 10:] = 1.00\n img += 0.0033 * rnd.normal(size=img.shape)\n np.clip(img, 0, 1, out=img)\n seg = slic(img, sigma=0, n_segments=500, compactness=1,\n multichannel=False, convert2lab=False, mask=msk)\n\n expected = np.arange(seg[2:-2, 2:-2].size) + 1\n assert np.all(seg[2:-2, 2:-2].ravel() == expected)\n\n\ndef test_color_3d_mask():\n\n msk = np.zeros((20, 21, 22))\n msk[2:-2, 2:-2, 2:-2] = 1\n\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21, 22, 3))\n slices = []\n for dim_size in msk.shape:\n midpoint = dim_size // 2\n slices.append((slice(None, midpoint), slice(midpoint, None)))\n slices = list(product(*slices))\n colors = list(product(*(([0, 1],) * 3)))\n for s, c in zip(slices, colors):\n img[s] = c\n img += 0.01 * rnd.normal(size=img.shape)\n np.clip(img, 0, 1, out=img)\n\n seg = slic(img, sigma=0, n_segments=8, mask=msk)\n\n # we expect 8 segments + masked area\n assert_equal(len(np.unique(seg)), 9)\n for s, c in zip(slices, range(1, 9)):\n assert_equal(seg[s][2:-2, 2:-2, 2:-2], c)\n\n\ndef test_gray_3d_mask():\n\n msk = np.zeros((20, 21, 22))\n msk[2:-2, 2:-2, 2:-2] = 1\n\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21, 22))\n slices = []\n for dim_size in img.shape:\n midpoint = dim_size // 2\n slices.append((slice(None, midpoint), slice(midpoint, None)))\n slices = list(product(*slices))\n shades = np.linspace(0, 1, 8)\n for s, sh in zip(slices, shades):\n img[s] = sh\n img += 0.001 * rnd.normal(size=img.shape)\n np.clip(img, 0, 1, out=img)\n seg = slic(img, sigma=0, n_segments=8, multichannel=False,\n convert2lab=False, mask=msk)\n\n # we expect 8 segments + masked area\n assert_equal(len(np.unique(seg)), 9)\n for s, c in zip(slices, range(1, 9)):\n assert_equal(seg[s][2:-2, 2:-2, 2:-2], c)\n\n\[email protected](\"dtype\", ['float32', 'float64', 'uint8', 'int'])\ndef test_dtype_support(dtype):\n img = np.random.rand(28, 28).astype(dtype)\n\n # Simply run the function to assert that it runs without error\n slic(img, start_label=1)\n" ]
[ [ "numpy.ones", "numpy.random.seed", "matplotlib.pyplot.imshow", "numpy.meshgrid", "numpy.allclose", "matplotlib.pyplot.figure", "numpy.abs", "numpy.random.rand", "numpy.linspace", "numpy.mean", "numpy.random.uniform", "numpy.tri", "numpy.ceil", "numpy.zeros", "numpy.argmax", "numpy.arange", "numpy.all", "numpy.max", "numpy.std", "matplotlib.pyplot.colorbar", "numpy.interp", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "numpy.clip", "numpy.sqrt" ], [ "numpy.zeros", "numpy.random.RandomState", "numpy.arange", "numpy.clip", "numpy.random.rand", "numpy.array", "numpy.linspace", "numpy.unique" ] ]
NickyBar/QIP
[ "11747b40beb38d41faa297fb2b53f28c6519c753" ]
[ "qiskit/basicplotter.py" ]
[ "# -*- coding: utf-8 -*-\n\n# Copyright 2017 IBM RESEARCH. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\n\"\"\"\nBasic plotting methods using matplotlib.\n\nThese include methods to plot Bloch vectors, histograms, and quantum spheres.\n\nAuthor: Andrew Cross, Jay Gambetta\n\"\"\"\nfrom mpl_toolkits.mplot3d import proj3d\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import FancyArrowPatch\nimport numpy as np\nfrom collections import Counter\nfrom functools import reduce\n\n\ndef plot_histogram(data, number_to_keep=None):\n \"\"\"Plot a histogram of data.\n\n data is a dictionary of {'000': 5, '010': 113, ...}\n number_to_keep is the number of terms to plot and rest is made into a\n single bar called other values\n \"\"\"\n if number_to_keep is not None:\n data_temp = dict(Counter(data).most_common(number_to_keep))\n data_temp[\"rest\"] = sum(data.values()) - sum(data_temp.values())\n data = data_temp\n\n labels = sorted(data)\n values = np.array([data[key] for key in labels], dtype=float)\n pvalues = values / sum(values)\n numelem = len(values)\n ind = np.arange(numelem) # the x locations for the groups\n width = 0.35 # the width of the bars\n fig, ax = plt.subplots()\n rects = ax.bar(ind, pvalues, width, color='seagreen')\n # add some text for labels, title, and axes ticks\n ax.set_ylabel('Probabilities', fontsize=12)\n ax.set_xticks(ind)\n ax.set_xticklabels(labels, fontsize=12)\n ax.set_ylim([0., min([1.2, max([1.2 * val for val in pvalues])])])\n # attach some text labels\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,\n '%f' % float(height),\n ha='center', va='bottom')\n plt.show()\n\n\n# Functions used for plotting on the qsphere.\n#\n# See:\n# lex_index:\n# https://msdn.microsoft.com/en-us/library/aa289166%28v=vs.71%29.aspx\n# n_choose_k: http://stackoverflow.com/questions/\n# 2096573/counting-combinations-and-permutations-efficiently\n\n\nclass Arrow3D(FancyArrowPatch):\n \"\"\"Standard 3D arrow.\"\"\"\n\n def __init__(self, xs, ys, zs, *args, **kwargs):\n \"\"\"Create arrow.\"\"\"\n FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n \"\"\"Draw the arrow.\"\"\"\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\n\ndef compliment(value):\n \"\"\"Swap 1 and 0 in a vector.\"\"\"\n return ''.join(COMPLEMENT[x] for x in value)\n\n\nCOMPLEMENT = {'1': '0', '0': '1'}\n\n\ndef n_choose_k(n, k):\n \"\"\"Return the number of combinations.\"\"\"\n if n == 0:\n return 0.0\n else:\n return reduce(lambda x, y: x * y[0] / y[1],\n zip(range(n - k + 1, n + 1),\n range(1, k + 1)), 1)\n\n\ndef lex_index(n, k, lst):\n \"\"\"Return the index of a combination.\"\"\"\n assert len(lst) == k, \"list should have length k\"\n comb = list(map(lambda x: n - 1 - x, lst))\n dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])\n m = dualm\n return int(m)\n\n\ndef bit_string_index(s):\n \"\"\"Return the index of a string of 0s and 1s.\"\"\"\n n = len(s)\n k = s.count(\"1\")\n assert s.count(\"0\") == n - k, \"s must be a string of 0 and 1\"\n ones = [pos for pos, char in enumerate(s) if char == \"1\"]\n return lex_index(n, k, ones)\n\n\ndef plot_qsphere(data, number_to_keep, number_of_qubits):\n \"\"\"Plot the qsphere of data.\"\"\"\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111, projection='3d')\n ax.axes.set_xlim3d(-1.0, 1.0)\n ax.axes.set_ylim3d(-1.0, 1.0)\n ax.axes.set_zlim3d(-1.0, 1.0)\n ax.set_aspect(\"equal\")\n ax.axes.grid(False)\n # Plot semi-transparent sphere\n u = np.linspace(0, 2 * np.pi, 25)\n v = np.linspace(0, np.pi, 25)\n x = np.outer(np.cos(u), np.sin(v))\n y = np.outer(np.sin(u), np.sin(v))\n z = np.outer(np.ones(np.size(u)), np.cos(v))\n ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k', alpha=0.05,\n linewidth=0)\n # wireframe\n # Get rid of the panes\n # ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n # ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n # ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n\n # Get rid of the spines\n # ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n # ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n # ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n # Get rid of the ticks\n # ax.set_xticks([])\n # ax.set_yticks([])\n # ax.set_zticks([])\n d = number_of_qubits\n total_values = sum(data.values())\n for key in data:\n weight = key.count(\"1\")\n zvalue = -2 * weight / d + 1\n number_of_divisions = n_choose_k(d, weight)\n weight_order = bit_string_index(key)\n if weight_order >= number_of_divisions / 2:\n com_key = compliment(key)\n weight_order_temp = bit_string_index(com_key)\n weight_order = np.floor(\n number_of_divisions / 2) + weight_order_temp + 1\n print(key + \" \" + str(weight_order))\n angle = (weight_order) * 2 * np.pi / number_of_divisions\n xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)\n yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)\n linewidth = 5 * data.get(key) / total_values\n print([xvalue, yvalue, zvalue])\n a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue], mutation_scale=20,\n lw=linewidth, arrowstyle=\"->\", color=\"k\")\n ax.add_artist(a)\n for weight in range(d + 1):\n theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)\n z = -2 * weight / d + 1\n if weight == 0:\n z = z - 0.001\n if weight == d:\n z = z + 0.001\n r = np.sqrt(1 - z**2)\n x = r * np.cos(theta)\n y = r * np.sin(theta)\n ax.plot(x, y, z, 'k')\n plt.show()\n\n\n# Functions used for plotting tomography.\n\n\ndef plot_bloch_vector(bloch, title=\"\"):\n \"\"\"Plot a Bloch vector.\n\n Plot a sphere, axes, the Bloch vector, and its projections onto each axis.\n bloch is a 3-tuple (x, y, z)\n title is a string, the plot title\n \"\"\"\n # Set arrow lengths\n arlen = 1.3\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.set_aspect(\"equal\")\n\n # Plot semi-transparent sphere\n u = np.linspace(0, 2 * np.pi, 100)\n v = np.linspace(0, np.pi, 100)\n x = np.outer(np.cos(u), np.sin(v))\n y = np.outer(np.sin(u), np.sin(v))\n z = np.outer(np.ones(np.size(u)), np.cos(v))\n ax.plot_surface(x, y, z, color=\"b\", alpha=0.1)\n\n # Plot arrows (axes, Bloch vector, its projections)\n xa = Arrow3D([0, arlen], [0, 0], [0, 0], mutation_scale=20, lw=1,\n arrowstyle=\"-|>\", color=\"k\")\n ya = Arrow3D([0, 0], [0, arlen], [0, 0], mutation_scale=20, lw=1,\n arrowstyle=\"-|>\", color=\"k\")\n za = Arrow3D([0, 0], [0, 0], [0, arlen], mutation_scale=20, lw=1,\n arrowstyle=\"-|>\", color=\"k\")\n a = Arrow3D([0, bloch[0]], [0, bloch[1]], [0, bloch[2]], mutation_scale=20,\n lw=2, arrowstyle=\"simple\", color=\"k\")\n bax = Arrow3D([0, bloch[0]], [0, 0], [0, 0], mutation_scale=20, lw=2,\n arrowstyle=\"-\", color=\"r\")\n bay = Arrow3D([0, 0], [0, bloch[1]], [0, 0], mutation_scale=20, lw=2,\n arrowstyle=\"-\", color=\"g\")\n baz = Arrow3D([0, 0], [0, 0], [0, bloch[2]], mutation_scale=20, lw=2,\n arrowstyle=\"-\", color=\"b\")\n arrowlist = [xa, ya, za, a, bax, bay, baz]\n for arr in arrowlist:\n ax.add_artist(arr)\n\n # Rotate the view\n ax.view_init(30, 30)\n\n # Annotate the axes, shifts are ad-hoc for this (30, 30) view\n xp, yp, _ = proj3d.proj_transform(arlen, 0, 0, ax.get_proj())\n plt.annotate(\"x\", xy=(xp, yp), xytext=(-3, -8),\n textcoords='offset points', ha='right', va='bottom')\n xp, yp, _ = proj3d.proj_transform(0, arlen, 0, ax.get_proj())\n plt.annotate(\"y\", xy=(xp, yp), xytext=(6, -5),\n textcoords='offset points', ha='right', va='bottom')\n xp, yp, _ = proj3d.proj_transform(0, 0, arlen, ax.get_proj())\n plt.annotate(\"z\", xy=(xp, yp), xytext=(2, 0),\n textcoords='offset points', ha='right', va='bottom')\n\n plt.title(title)\n plt.show()\n\n\n# Functions used by randomized benchmarking.\n\n\ndef plot_rb_data(xdata, ydatas, yavg, fit, survival_prob):\n \"\"\"Plot randomized benchmarking data.\n\n xdata = list of subsequence lengths\n ydatas = list of lists of survival probabilities for each sequence\n yavg = mean of the survival probabilities at each sequence length\n fit = list of fitting parameters [a, b, alpha]\n survival_prob = function that computes survival probability\n \"\"\"\n # Plot the result for each sequence\n for ydata in ydatas:\n plt.plot(xdata, ydata, 'rx')\n # Plot the mean\n plt.plot(xdata, yavg, 'bo')\n # Plot the fit\n plt.plot(xdata, survival_prob(xdata, *fit), 'b-')\n plt.show()\n" ]
[ [ "numpy.sqrt", "numpy.sin", "matplotlib.pyplot.figure", "matplotlib.pyplot.annotate", "matplotlib.patches.FancyArrowPatch.draw", "numpy.cos", "matplotlib.pyplot.subplots", "numpy.size", "numpy.arange", "matplotlib.pyplot.title", "numpy.floor", "matplotlib.pyplot.show", "matplotlib.patches.FancyArrowPatch.__init__", "numpy.array", "matplotlib.pyplot.plot", "numpy.linspace" ] ]
wfarah/frbpoppy
[ "e575c49e6b4a69015a66d3f38a3459e0ffe4eb05" ]
[ "tests/int_pro_surveys.py" ]
[ "\"\"\"Plot intensity profile of theoretical beam patterns.\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.stats import binned_statistic as bstat\n\nfrom frbpoppy.survey import Survey\n\nOBSERVATORIES = [('parkes', 'htru'),\n ('apertif', 'apertif')]\n\nn = int(1e6)\n\nfor obs in OBSERVATORIES:\n\n survey = obs[1]\n pattern = obs[0]\n\n s = Survey(survey, gain_pattern=pattern)\n int_pro, offset = s.intensity_profile(n_gen=n)\n\n # Sort the values\n sorted_int = np.argsort(offset)\n int_pro = int_pro[sorted_int]\n offset = offset[sorted_int]\n\n # Offset in degrees\n offset = offset/60.\n\n bins = 1e2\n\n bin_means, bin_edges, bin_numbers = bstat(offset,\n int_pro,\n statistic='mean',\n bins=bins)\n\n bin_mins, _, _ = bstat(offset, int_pro, statistic='min', bins=bins)\n bin_maxs, _, _ = bstat(offset, int_pro, statistic='max', bins=bins)\n\n center = (bin_edges[:-1] + bin_edges[1:]) / 2\n\n plt.plot(center, bin_means, label=pattern)\n plt.fill_between(center, bin_mins, bin_maxs, alpha=0.2)\n\n\nplt.xlabel(f'Offset ($\\degree$)')\nplt.ylabel('Intensity Profile')\nplt.yscale('log')\nplt.legend()\nplt.tight_layout()\nplt.savefig('plots/int_pro_surveys.pdf')\n" ]
[ [ "matplotlib.pyplot.legend", "scipy.stats.binned_statistic", "matplotlib.pyplot.savefig", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.yscale", "numpy.argsort", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.xlabel" ] ]
feature-engineer/glymur
[ "660b593ab7bfbb3036de5d15c3ecb43bef3bf919" ]
[ "tests/test_colour_specification_box.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nTest suite specifically targeting ICC profiles\n\"\"\"\n\n# Standard library imports ...\nfrom datetime import datetime\ntry:\n import importlib.resources as ir\nexcept ImportError: # pragma: no cover\n # before 3.7\n import importlib_resources as ir\nimport struct\nimport tempfile\nimport unittest\nimport warnings\n\n# Third party library imports\nimport numpy as np\n\n# Local imports\nimport glymur\nfrom glymur import Jp2k\nfrom glymur._iccprofile import _ICCProfile\nfrom glymur.jp2box import (\n ColourSpecificationBox, ContiguousCodestreamBox, FileTypeBox,\n ImageHeaderBox, JP2HeaderBox, JPEG2000SignatureBox, InvalidJp2kError\n)\nfrom glymur.core import SRGB\nfrom . import fixtures, data\n\n\nclass TestColourSpecificationBox(fixtures.TestCommon):\n \"\"\"Test suite for colr box instantiation.\"\"\"\n\n def setUp(self):\n super(TestColourSpecificationBox, self).setUp()\n\n j2k = Jp2k(self.j2kfile)\n codestream = j2k.get_codestream()\n height = codestream.segment[1].ysiz\n width = codestream.segment[1].xsiz\n num_components = len(codestream.segment[1].xrsiz)\n\n self.jp2b = JPEG2000SignatureBox()\n self.ftyp = FileTypeBox()\n self.jp2h = JP2HeaderBox()\n self.jp2c = ContiguousCodestreamBox()\n self.ihdr = ImageHeaderBox(height=height, width=width,\n num_components=num_components)\n\n self.icc_profile = ir.read_binary(data, 'sgray.icc')\n\n def test_bad_method_printing(self):\n \"\"\"\n SCENARIO: An ICC profile is both too short and has an invalid method\n value.\n\n EXPECTED RESULT: Warnings are issued. Printing the string\n representation should not error out.\n \"\"\"\n with ir.path(data, 'issue405.dat') as path:\n with path.open('rb') as f:\n f.seek(8)\n with warnings.catch_warnings():\n # Lots of things wrong with this file.\n warnings.simplefilter('ignore')\n box = ColourSpecificationBox.parse(f, length=80, offset=0)\n str(box)\n\n def test_colr_with_out_enum_cspace(self):\n \"\"\"must supply an enumerated colorspace when writing\"\"\"\n j2k = Jp2k(self.j2kfile)\n\n boxes = [self.jp2b, self.ftyp, self.jp2h, self.jp2c]\n boxes[2].box = [self.ihdr, ColourSpecificationBox(colorspace=None)]\n with open(self.temp_jp2_filename, mode='wb') as tfile:\n with self.assertRaises(InvalidJp2kError):\n j2k.wrap(tfile.name, boxes=boxes)\n\n def test_missing_colr_box(self):\n \"\"\"jp2h must have a colr box\"\"\"\n j2k = Jp2k(self.j2kfile)\n boxes = [self.jp2b, self.ftyp, self.jp2h, self.jp2c]\n boxes[2].box = [self.ihdr]\n with open(self.temp_jp2_filename, mode='wb') as tfile:\n with self.assertRaises(InvalidJp2kError):\n j2k.wrap(tfile.name, boxes=boxes)\n\n def test_bad_approx_jp2_field(self):\n \"\"\"JP2 has requirements for approx field\"\"\"\n j2k = Jp2k(self.j2kfile)\n boxes = [self.jp2b, self.ftyp, self.jp2h, self.jp2c]\n colr = ColourSpecificationBox(colorspace=SRGB, approximation=1)\n boxes[2].box = [self.ihdr, colr]\n with open(self.temp_jp2_filename, mode='wb') as tfile:\n with self.assertRaises(InvalidJp2kError):\n j2k.wrap(tfile.name, boxes=boxes)\n\n def test_default_colr(self):\n \"\"\"basic colr instantiation\"\"\"\n colr = ColourSpecificationBox(colorspace=SRGB)\n self.assertEqual(colr.method, glymur.core.ENUMERATED_COLORSPACE)\n self.assertEqual(colr.precedence, 0)\n self.assertEqual(colr.approximation, 0)\n self.assertEqual(colr.colorspace, SRGB)\n self.assertIsNone(colr.icc_profile)\n\n def test_icc_profile(self):\n \"\"\"basic colr box with ICC profile\"\"\"\n colr = ColourSpecificationBox(icc_profile=self.icc_profile)\n self.assertEqual(colr.method, glymur.core.ENUMERATED_COLORSPACE)\n self.assertEqual(colr.precedence, 0)\n self.assertEqual(colr.approximation, 0)\n\n icc_profile = _ICCProfile(colr.icc_profile)\n self.assertEqual(icc_profile.header['Version'], '2.1.0')\n self.assertEqual(icc_profile.header['Color Space'], 'gray')\n self.assertIsNone(icc_profile.header['Datetime'])\n\n # Only True for version4\n self.assertFalse('Profile Id' in icc_profile.header.keys())\n\n def test_colr_with_bad_color(self):\n \"\"\"\n SCENARIO: A colr box has an invalid colorspace.\n\n EXPECTED RESULT: An InvalidJp2kError is raised when attempting to\n write the box.\n \"\"\"\n with self.assertWarns(UserWarning):\n # A warning is issued due to the bad colorspace.\n colr = ColourSpecificationBox(colorspace=-1, approximation=0)\n\n with tempfile.TemporaryFile() as tfile:\n with self.assertRaises(InvalidJp2kError):\n colr.write(tfile)\n\n def test_write_colr_with_bad_method(self):\n \"\"\"\n SCENARIO: A colr box has an invalid method value.\n\n EXPECTED RESULT: InvalidJp2kError\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n colr = ColourSpecificationBox(colorspace=SRGB, method=5)\n with tempfile.TemporaryFile() as tfile:\n with self.assertRaises(InvalidJp2kError):\n colr.write(tfile)\n\n\nclass TestSuite(unittest.TestCase):\n \"\"\"Test suite for ICC Profile code.\"\"\"\n\n def setUp(self):\n self.buffer = ir.read_binary(data, 'sgray.icc')\n\n def test_bad_rendering_intent(self):\n \"\"\"\n The rendering intent is not in the range 0-4.\n\n It should be classified as 'unknown'\n \"\"\"\n intent = struct.pack('>I', 10)\n self.buffer = self.buffer[:64] + intent + self.buffer[68:]\n\n icc_profile = _ICCProfile(self.buffer)\n self.assertEqual(icc_profile.header['Rendering Intent'], 'unknown')\n\n def test_version4(self):\n \"\"\"\n ICC profile is version 4\n \"\"\"\n leadoff = struct.pack('>IIBB', 416, 0, 4, 0)\n self.buffer = leadoff + self.buffer[10:]\n\n icc_profile = _ICCProfile(self.buffer)\n self.assertEqual(icc_profile.header['Version'], '4.0.0')\n self.assertTrue('Profile Id' in icc_profile.header.keys())\n\n def test_icc_profile(self):\n \"\"\"\n SCENARIO: The ColourDefinitionBox has an ICC profile.\n\n EXPECTED RESULT: Verify the ICC profile metadata.\n \"\"\"\n with ir.path(data, 'text_GBR.jp2') as path:\n with self.assertWarns(UserWarning):\n # The brand is wrong, this is JPX, not JP2.\n j = Jp2k(path)\n box = j.box[3].box[1]\n\n self.assertEqual(box.icc_profile_header['Size'], 1328)\n self.assertEqual(box.icc_profile_header['Color Space'], 'RGB')\n self.assertEqual(box.icc_profile_header['Connection Space'], 'XYZ')\n self.assertEqual(box.icc_profile_header['Datetime'],\n datetime(2009, 2, 25, 11, 26, 11))\n self.assertEqual(box.icc_profile_header['File Signature'], 'acsp')\n self.assertEqual(box.icc_profile_header['Platform'], 'APPL')\n self.assertEqual(box.icc_profile_header['Flags'],\n 'not embedded, can be used independently')\n self.assertEqual(box.icc_profile_header['Device Manufacturer'], 'appl')\n self.assertEqual(box.icc_profile_header['Device Model'], '')\n self.assertEqual(box.icc_profile_header['Device Attributes'],\n ('reflective, glossy, positive media polarity, '\n 'color media'))\n self.assertEqual(box.icc_profile_header['Rendering Intent'],\n 'perceptual')\n np.testing.assert_almost_equal(box.icc_profile_header['Illuminant'],\n np.array([0.9642023, 1.0, 0.824905]),\n decimal=6)\n self.assertEqual(box.icc_profile_header['Creator'], 'appl')\n" ]
[ [ "numpy.array" ] ]
LiRunyi2001/cnSoftBei
[ "72b90033ade1e926d3fb23621f5c67fa8eec9bb4" ]
[ "roberta/scripts/convert_bert_text_classification_from_huggingface_to_uer.py" ]
[ "import sys\nimport os\nimport torch\nimport argparse\nimport collections\n\nuer_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\"))\nsys.path.insert(0, uer_dir)\n\nfrom scripts.convert_bert_from_huggingface_to_uer import convert_bert_transformer_encoder_from_huggingface_to_uer\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"--input_model_path\", type=str, default=\"huggingface_model.bin\",\n help=\".\")\nparser.add_argument(\"--output_model_path\", type=str, default=\"pytorch_model.bin\",\n help=\".\")\nparser.add_argument(\"--layers_num\", type=int, default=12, help=\".\")\n\nargs = parser.parse_args()\npath = args.input_model_path\n\ninput_model = torch.load(args.input_model_path, map_location='cpu')\n\noutput_model = collections.OrderedDict()\n\noutput_model[\"embedding.word_embedding.weight\"] = input_model[\"bert.embeddings.word_embeddings.weight\"]\noutput_model[\"embedding.position_embedding.weight\"] = input_model[\"bert.embeddings.position_embeddings.weight\"]\noutput_model[\"embedding.segment_embedding.weight\"] = torch.cat((torch.Tensor([[0]*input_model[\"bert.embeddings.token_type_embeddings.weight\"].size()[1]]), input_model[\"bert.embeddings.token_type_embeddings.weight\"]), dim=0)\noutput_model[\"embedding.layer_norm.gamma\"] = input_model[\"bert.embeddings.LayerNorm.weight\"]\noutput_model[\"embedding.layer_norm.beta\"] = input_model[\"bert.embeddings.LayerNorm.bias\"]\n\nconvert_bert_transformer_encoder_from_huggingface_to_uer(input_model, output_model, args.layers_num)\n\noutput_model[\"output_layer_1.weight\"] = input_model[\"bert.pooler.dense.weight\"]\noutput_model[\"output_layer_1.bias\"] = input_model[\"bert.pooler.dense.bias\"]\noutput_model[\"output_layer_2.weight\"] = input_model[\"classifier.weight\"]\noutput_model[\"output_layer_2.bias\"] = input_model[\"classifier.bias\"]\n\ntorch.save(output_model, args.output_model_path)\n" ]
[ [ "torch.save", "torch.load" ] ]
zjplab/Pedestron
[ "07e1a2cee82b57e1584b0c744f5b44f1ae92be73" ]
[ "mmdet/models/bbox_heads/mgan_head.py" ]
[ "import torch.nn as nn\n\nfrom ..registry import HEADS\nfrom ..utils import ConvModule\nfrom mmdetection.core import auto_fp16\n\n\[email protected]_module\nclass MGANHead(nn.Module):\n\n def __init__(self,\n num_convs=2,\n roi_feat_size=7,\n in_channels=512,\n conv_out_channels=512,\n conv_cfg=None,\n norm_cfg=None):\n super(MGANHead, self).__init__()\n self.num_convs = num_convs\n self.roi_feat_size = roi_feat_size\n self.in_channels = in_channels\n self.conv_out_channels = conv_out_channels\n\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n self.fp16_enabled = False\n\n self.convs = nn.ModuleList()\n for i in range(self.num_convs):\n in_channels = (\n self.in_channels if i == 0 else self.conv_out_channels)\n self.convs.append(\n ConvModule(\n in_channels,\n self.conv_out_channels,\n 3,\n padding=1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg))\n logits_in_channel = self.conv_out_channels\n self.conv_logits = nn.Conv2d(logits_in_channel, 1, 1)\n self.relu = nn.ReLU(inplace=True)\n self.debug_imgs = None\n\n @auto_fp16()\n def forward(self, x):\n for conv in self.convs:\n x = conv(x)\n x = self.conv_logits(x).sigmoid() * x\n return x\n\n\n" ]
[ [ "torch.nn.ReLU", "torch.nn.ModuleList", "torch.nn.Conv2d" ] ]
bucaps/HotSpotMap
[ "655d83d98316acbf9328519850268f548ae44af4" ]
[ "HotSpotMap.py" ]
[ "# HotSpotMap: A python based temperature (thermal) map generation\n# tool for HotSpot-6.0 (http://lava.cs.virginia.edu/HotSpot/)\n# This tool uses python's turtle library\n#\n# Author: Gaurav Kothari ([email protected]) Copyright 2021\n#\n# This tool generates:\n# 1) Floor-plan image (using floor-plan file)\n# 2) Thermal map (using floor-plan file and steady temperature file)\n# 3) Fine grained thermal map (using floor-plan file and grid steady temperature file)\n#\n# Supports 2D and 3D stacked systems\n# Supports output formats: '.eps' and '.pdf'\nimport os\nimport time\nimport subprocess\nimport tkinter\nimport turtle\nimport tempfile\nimport numpy as np\nimport matplotlib\nfrom matplotlib import cm\nfrom matplotlib.colors import LinearSegmentedColormap\nimport argparse\nfrom sys import argv\n\n\n# To represent each floor-plan unit\nclass FloorplanUnit():\n def __init__(self, name, width, height, xpos, ypos, temp=0):\n self.name = name\n self.width = width\n self.height = height\n self.xpos = xpos\n self.ypos = ypos\n self.temp = temp # temperature\n\n\nmsg_prefix = \" HotSpotMap:\"\n\n# Home co-ordinates for drawing the chip floor-plan\n# Note: turtle's default home co-ordinates are (0,0)\n# For drawing the floor-plan, we will start from (-w/2,-h/2), where\n# w = width of the chip, h = height of the chip\nchip_home_xpos = 0\nchip_home_ypos = 0\n\n\n# Inspired from HotSpot 6.0\ndef get_chip_width(flp_units):\n min_x = flp_units[0].xpos\n max_x = flp_units[0].xpos + flp_units[0].width\n\n for i in range(1, len(flp_units)):\n if flp_units[i].xpos < min_x:\n min_x = flp_units[i].xpos\n if (flp_units[i].xpos + flp_units[i].width) > max_x:\n max_x = flp_units[i].xpos + flp_units[i].width\n\n return (max_x - min_x) * 1e3\n\n\n# Inspired from HotSpot 6.0\ndef get_chip_height(flp_units):\n min_y = flp_units[0].ypos\n max_y = flp_units[0].ypos + flp_units[0].height\n\n for i in range(1, len(flp_units)):\n if flp_units[i].ypos < min_y:\n min_y = flp_units[i].ypos\n if (flp_units[i].ypos + flp_units[i].height) > max_y:\n max_y = flp_units[i].ypos + flp_units[i].height\n\n return (max_y - min_y) * 1e3\n\n\ndef get_pos_from_chip_home(xpos, ypos):\n return (chip_home_xpos + xpos, chip_home_ypos + ypos)\n\n\n# Only for 3D systems, collect all the output files\n# (for every layer) to combine them later as a single PDF\noutput_3d_files = []\n\n\n#\n# Functions related to Turtle\n#\ndef turtle_setup(config):\n # setup screen\n ts = turtle.Screen()\n cw = (config.chip_width * 1e-3 * config.zoom_by)\n ch = (config.chip_height * 1e-3 * config.zoom_by)\n ts.reset()\n ts.colormode(255)\n ts.tracer(0, 0)\n global chip_home_xpos\n chip_home_xpos = -(cw / 2)\n global chip_home_ypos\n chip_home_ypos = -(ch / 2)\n\n # create turtle cursor\n t = turtle.Turtle()\n t.pen(shown=False)\n t.pensize(0.5)\n t.hideturtle()\n t.penup()\n t.setpos(chip_home_xpos, chip_home_ypos)\n return t\n\n\ndef turtle_save_image(config):\n ts = turtle.getscreen()\n eps_file = os.path.join(\n config.output_dir, \"{f}-{a}.eps\".format(f=config.output_file,\n a=config.action))\n pdf_file = os.path.join(\n config.output_dir, \"{f}-{a}.pdf\".format(f=config.output_file,\n a=config.action))\n\n canvas = ts.getcanvas()\n canvas.config(width=config.chip_width * 1e-3 * config.zoom_by,\n height=config.chip_height * 1e-3 * config.zoom_by)\n canvas.postscript(file=eps_file)\n print(\"{p} Generated eps file: {f}\".format(p=msg_prefix, f=eps_file))\n cmd = \"ps2pdf {i} {o}\".format(i=eps_file, o=pdf_file)\n process = subprocess.Popen(cmd, shell=True)\n process.wait()\n print(\"{p} Generated pdf file: {f}\".format(p=msg_prefix, f=pdf_file))\n\n if config.model_3d:\n output_3d_files.append(pdf_file)\n\n\ndef turtle_draw_unit(t,\n xpos,\n ypos,\n width,\n height,\n config,\n name,\n border_color=\"\",\n fill_color=\"\",\n hide_names=True):\n xpos *= config.zoom_by\n ypos *= config.zoom_by\n pos = get_pos_from_chip_home(xpos, ypos)\n xpos = pos[0]\n ypos = pos[1]\n width *= config.zoom_by\n height *= config.zoom_by\n t.penup()\n t.setpos(xpos, ypos)\n t.color(border_color, fill_color)\n if fill_color:\n t.begin_fill()\n t.pendown()\n t.forward(width)\n t.left(90)\n t.forward(height)\n t.left(90)\n t.forward(width)\n t.left(90)\n t.forward(height)\n t.left(90)\n if fill_color:\n t.end_fill()\n t.penup()\n\n if name and (hide_names == False):\n t.setpos(xpos + (width / 2), ypos + (height / 2))\n t.pendown()\n t.color(\"black\")\n print_name = name\n if config.print_area:\n area = (width / config.zoom_by) * (height /\n config.zoom_by) * 1e6 # mm2\n area = round(area, 3)\n print_name += \" ({a})\".format(a=area)\n t.write(print_name,\n align=\"center\",\n font=(config.font, config.font_size, config.font_weight))\n t.penup()\n\n\ndef draw_chip_dimensions(t, config):\n # draw height scale on left of the floor-plan\n arrow_height = 15\n xpos = -30\n ypos = 0\n t.penup()\n t.color(\"black\")\n t.setpos(get_pos_from_chip_home(xpos, ypos))\n t.left(90)\n t.pendown()\n t.forward(config.chip_height * 1e-3 * config.zoom_by)\n temp = t.pos()\n t.left(135)\n t.forward(arrow_height)\n t.setpos(temp)\n t.right(270)\n t.forward(arrow_height)\n t.penup()\n t.setpos(get_pos_from_chip_home(xpos, ypos))\n t.pendown()\n t.left(90)\n t.forward(arrow_height)\n t.penup()\n t.setpos(get_pos_from_chip_home(xpos, ypos))\n t.right(270)\n t.pendown()\n t.forward(arrow_height)\n t.right(135) # reset\n t.penup()\n\n canvas = turtle.getcanvas()\n xpos = -45\n ypos = (config.chip_height * 1e-3 * config.zoom_by) / 2\n pos = get_pos_from_chip_home(xpos, ypos)\n canvas.create_text(pos[0],\n pos[1],\n text=\"Height {h} mm\".format(h=config.chip_height),\n angle=90,\n font=(config.font, config.font_size,\n config.font_weight))\n\n # draw width scale on top of the floor-plan\n xpos = 0\n ypos = (config.chip_height * 1e-3 * config.zoom_by) + 30\n t.penup()\n t.setpos(get_pos_from_chip_home(xpos, ypos))\n t.pendown()\n t.forward(config.chip_width * 1e-3 * config.zoom_by)\n temp = t.pos()\n t.left(135)\n t.forward(arrow_height)\n t.setpos(temp)\n t.right(270)\n t.forward(arrow_height)\n t.penup()\n t.setpos(get_pos_from_chip_home(xpos, ypos))\n t.pendown()\n t.left(90)\n t.forward(arrow_height)\n t.penup()\n t.setpos(get_pos_from_chip_home(xpos, ypos))\n t.right(270)\n t.pendown()\n t.forward(arrow_height)\n t.penup()\n\n canvas = turtle.getcanvas()\n xpos = (config.chip_width * 1e-3 * config.zoom_by) / 2\n ypos = -45\n pos = get_pos_from_chip_home(xpos, ypos)\n canvas.create_text(pos[0],\n pos[1],\n text=\"Width {w} mm\".format(w=config.chip_width),\n angle=0,\n font=(config.font, config.font_size,\n config.font_weight))\n\n\n#\n# Function related to temperature color bar\n#\n\n# Colors used for temperature map\ncolors = [\n \"#ff0000\",\n \"#ff3300\",\n \"#ff6600\",\n \"#ff9900\",\n \"#ffcc00\",\n \"#ffff00\",\n \"#ccff00\",\n \"#99ff00\",\n \"#66ff00\",\n \"#33ff00\",\n \"#00ff00\",\n \"#00ff33\",\n \"#00ff66\",\n \"#00ff99\",\n \"#00ffcc\",\n \"#00ffff\",\n \"#00ccff\",\n \"#0099ff\",\n \"#0066ff\",\n \"#0033ff\",\n \"#0000ff\",\n]\n\n\n# Color map for temperatures\ndef get_chip_temp_cmap():\n global colors\n colors.reverse()\n cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\n \"chipTemp\", colors)\n return cmap\n\n\ndef draw_color_bar(t, config, colors, temp_min, temp_max):\n xpos = ((config.chip_width + 0.05) * 1e-3)\n ypos = 0\n color_bar_max_height = config.chip_height * 1e-3\n color_cell_width = color_bar_max_height / len(colors)\n color_cell_height = color_cell_width\n\n temp_cell_width = color_cell_width * 3\n temp_cell_height = color_cell_height\n\n interval = len(colors)\n temp_values = np.linspace(temp_min,\n temp_max,\n num=int(interval),\n endpoint=True)\n temp_values = [round(val, 2) for val in temp_values]\n\n i = 0\n for color in colors:\n # draw the temperature value\n turtle_draw_unit(t,\n xpos,\n ypos,\n temp_cell_width,\n temp_cell_height,\n config,\n name=\"{f}K\".format(f=temp_values[i]),\n border_color=\"\",\n fill_color=\"\",\n hide_names=False)\n # color cell\n turtle_draw_unit(t,\n xpos + temp_cell_width,\n ypos,\n color_cell_width,\n color_cell_height,\n config,\n name=\"\",\n border_color=\"black\",\n fill_color=color)\n ypos += color_cell_height\n i += 1\n\n\n#\n# Functions related to drawing chip floor-plan\n#\n\n\n# Checks if floor-plan has duplicated units\ndef check_duplicated_flp_units(flp_units_names):\n flp_units_namesSet = set(flp_units_names)\n\n if len(flp_units_namesSet) != len(flp_units_names):\n print(\"{p} warning! duplicated floor-plan units detected\".format(\n p=msg_prefix))\n\n\ndef draw_floorplan(config, t):\n start = time.time()\n file = open(config.floor_plan, \"r\")\n flp = file.readlines()\n flp_units = []\n flp_units_names = []\n\n for line in flp:\n if \"#\" in line or line == \"\\n\" or not line:\n continue\n line = line.split(\"\\t\")\n flp_units_names.append(line[0])\n flp_units.append(\n FloorplanUnit(line[0], float(line[1]), float(line[2]),\n float(line[3]), float(line[4])))\n\n check_duplicated_flp_units(flp_units_names)\n\n print(\"{p} Drawing floor-plan\".format(p=msg_prefix))\n print(\n \"{p} Reading floor-plan file {f}: found {u} units, {w} mm chip-width, {h} mm chip-height\"\n .format(f=config.floor_plan,\n p=msg_prefix,\n u=len(flp_units),\n w=config.chip_width,\n h=config.chip_height))\n\n file.close()\n\n for unit in flp_units:\n turtle_draw_unit(turtle,\n unit.xpos,\n unit.ypos,\n unit.width,\n unit.height,\n config,\n name=unit.name,\n border_color=\"black\",\n fill_color=\"\",\n hide_names=config.hide_names)\n\n end = time.time()\n print(\"{p} Finished drawing floor-plan in {t} seconds\".format(\n p=msg_prefix, t=round((end - start), 2)))\n\n\n#\n# Functions related to draw the temperature maps\n#\n\n\n# This parses the given temperature file and extracts\n# min and max temperatures (for steady and grid steady file)\ndef get_temperature_file_config(temperature_file, grid_steady_file_3d=\"\"):\n file = open(temperature_file, \"r\")\n lines = file.readlines()\n\n temperatures = []\n for line in lines:\n if line == \"\\n\" or not line:\n continue\n line = line.split(\"\\t\")\n if len(line) == 1:\n continue # for 3D grid steady file, skip layer header\n temperatures.append(float(line[1]))\n\n file.close()\n\n grid_steady_config = []\n grid_steady_config.append(str(min(temperatures)))\n grid_steady_config.append(str(max(temperatures)))\n return grid_steady_config\n\n\ndef draw_grid_steady_thermal_map(config, turtle, grid_steady_file_3d=\"\"):\n start = time.time()\n\n temperature_limit_file = config.temperature_file\n\n if config.model_3d:\n # for 3D systems, use the original grid-steady file containing\n # the temperature data for all the layers to extract min and max\n # temperatures, because all the layers must use the same color range\n temperature_limit_file = grid_steady_file_3d\n\n # find min and max temperatures reported in grid steady file\n grid_steady_config = get_temperature_file_config(temperature_limit_file)\n\n rows = config.grid_rows\n cols = config.grid_cols\n temp_min = float(grid_steady_config[0])\n temp_max = float(grid_steady_config[1])\n print(\n \"{p} Reading grid steady file {f}, with {r} rows, {c} cols, {min} min-temp, {max} max-temp\"\n .format(p=msg_prefix,\n f=config.temperature_file,\n r=rows,\n c=cols,\n min=temp_min,\n max=temp_max))\n\n # normalize temperature range between 0 and 1, which will be used to fetch color from color map\n norm_temp_range = matplotlib.colors.Normalize(vmin=temp_min, vmax=temp_max)\n\n # generate color map\n cmap = get_chip_temp_cmap()\n\n global colors\n draw_color_bar(turtle, config, colors, temp_min, temp_max)\n\n grid_cell_width = (config.chip_width * 1e-3) / cols\n grid_cell_height = (config.chip_height * 1e-3) / rows\n\n file = open(config.temperature_file, \"r\")\n lines = file.readlines()\n\n xpos = 0\n ypos = (config.chip_height * 1e-3) - grid_cell_height\n print(\"{p} Drawing temperature grid\".format(p=msg_prefix))\n\n next_col = 0\n for line in lines:\n if line == \"\\n\" or not line:\n continue\n else:\n line = line.split(\"\\t\")\n col = line[0] # column number\n temp = float(\n line[1]) # temperature of the cell at current row and column\n\n color = matplotlib.colors.rgb2hex(cmap(norm_temp_range(temp)))\n turtle_draw_unit(turtle,\n xpos,\n ypos,\n grid_cell_width,\n grid_cell_height,\n config,\n name=\"\",\n border_color=color,\n fill_color=color)\n xpos += grid_cell_width\n next_col += 1\n\n if next_col == config.grid_cols:\n # one complete row is finished\n xpos = 0\n next_col = 0\n ypos -= grid_cell_height\n\n file.close()\n end = time.time()\n print(\"{p} Finished drawing temperature grid in {t} seconds\".format(\n p=msg_prefix, t=round((end - start), 2)))\n\n\ndef draw_steady_thermal_map(config, turtle):\n start = time.time()\n # find min and max temperatures reported in steady file\n steady_config = get_temperature_file_config(config.temperature_file)\n\n temp_min = float(steady_config[0])\n temp_max = float(steady_config[1])\n print(\"{p} Reading steady file {f}, found {min} min-temp, {max} max-temp\".\n format(p=msg_prefix,\n f=config.temperature_file,\n min=temp_min,\n max=temp_max))\n\n # normalize temperature range between 0 and 1, which will be used to fetch color from color map\n norm_temp_range = matplotlib.colors.Normalize(vmin=temp_min, vmax=temp_max)\n\n # generate color map\n cmap = get_chip_temp_cmap()\n\n draw_color_bar(turtle, config, colors, temp_min, temp_max)\n\n # read all the floor-plan units\n file = open(config.floor_plan, \"r\")\n flp = file.readlines()\n flp_units = []\n\n for line in flp:\n if \"#\" in line or line == \"\\n\":\n continue\n line = line.split(\"\\t\")\n flp_units.append(\n FloorplanUnit(line[0], float(line[1]), float(line[2]),\n float(line[3]), float(line[4])))\n\n file.close()\n\n file = open(config.temperature_file, \"r\")\n lines = file.readlines()\n\n for line in lines:\n line = line.split(\"\\t\")\n name = line[0]\n temp = float(line[1])\n\n # for 3D steady temperature file, each unit is appended with prefix layer_<layer>_\n # we need to remove that prefix\n if config.model_3d and \"layer_\" in name:\n name = name[name.find(\"_\") + 1:]\n name = name[name.find(\"_\") + 1:]\n\n for unit in flp_units:\n if unit.name == name:\n color = matplotlib.colors.rgb2hex(cmap(norm_temp_range(temp)))\n turtle_draw_unit(turtle,\n unit.xpos,\n unit.ypos,\n unit.width,\n unit.height,\n config,\n name=unit.name,\n border_color=\"black\",\n fill_color=color,\n hide_names=config.hide_names)\n\n file.close()\n end = time.time()\n print(\"{p} Finished steady temperature map in {t} seconds\".format(\n p=msg_prefix, t=round((end - start), 2)))\n\n\n#\n# Function related to parse file for 3D system (such as LCF and grid-steady file)\n#\n\n\n# Parse HotSpot's layer configuration file (lcf) for 3D systems\n# For 3D systems, config.floor_plan is the lCF\ndef read_lcf(config):\n file = open(config.floor_plan, \"r\")\n lines = file.readlines()\n\n config_lines = [\n ] # To store lcf after removing all the comments and blank lines\n\n for line in lines:\n if \"#\" in line or not line or line == \"\\n\":\n continue\n config_lines.append(line)\n\n file.close()\n\n layer_num_pos = 0 # pos of layer number for the corresponding layer\n has_power_pos = 2 # pos of power dissipation flag for the corresponding layer\n floor_plan_file_pos = 6 # pos of floor plan file for the corresponding layer\n\n current_line = 0\n current_layer = []\n\n lcf_home_dir = os.path.dirname(config.floor_plan)\n lcf_breakdown_list = []\n\n while current_line < len(config_lines):\n if current_line and ((current_line % 7) == 0):\n temp = []\n temp.append(current_layer[layer_num_pos].rstrip())\n temp.append(current_layer[has_power_pos].rstrip())\n temp.append(\n os.path.join(lcf_home_dir,\n current_layer[floor_plan_file_pos].rstrip()))\n lcf_breakdown_list.append(temp)\n current_layer.clear()\n\n current_layer.append(config_lines[current_line])\n current_line += 1\n\n print(\"{p} Finished reading lcf file: {f}, found {flp} floor-plan files\".\n format(p=msg_prefix,\n f=config.floor_plan,\n flp=len(lcf_breakdown_list)))\n\n return lcf_breakdown_list\n\n\ndef extract_grid_temperatures_for_layer(config, temperature_file, layer):\n file = open(temperature_file, \"r\")\n lines = file.readlines()\n file.close()\n\n # remove all the empty lines\n cleaned_lines = []\n for line in lines:\n if line == \"\\n\" or not line:\n continue\n cleaned_lines.append(line)\n\n line_num = 0\n look_for_layer = \"layer_{l}\".format(l=layer)\n\n while cleaned_lines[line_num].rstrip() != look_for_layer:\n line_num += 1\n\n print(\n \"{p} Grid temperature data for layer {l} starts at line {n} in file: {f}\"\n .format(p=msg_prefix, l=layer, n=line_num, f=temperature_file))\n\n # grid temperatures for current layer start at line_num\n line_num += 1 # skip the header line for this layer\n file = open(\"temp.grid.steady\", \"w\")\n\n # we will read grid_rows x grid_cols line from this line onwards\n lines_read = line_num\n lines_to_read = line_num + (config.grid_rows * config.grid_cols)\n\n while lines_read < lines_to_read:\n current_line = cleaned_lines[lines_read]\n file.write(\"{l}\\n\".format(l=current_line.rstrip()))\n lines_read += 1\n\n file.close()\n\n\n# For 2D systems\ndef main_2d(config):\n turtle = turtle_setup(config)\n if config.action == \"flp\":\n draw_floorplan(config, turtle)\n else:\n if config.action == \"grid-steady\":\n draw_grid_steady_thermal_map(config, turtle)\n draw_floorplan(\n config, turtle\n ) # This will superimpose floor-plan onto temperature grid\n else:\n draw_steady_thermal_map(config, turtle)\n\n if config.print_chip_dim:\n draw_chip_dimensions(turtle, config)\n turtle_save_image(config)\n\n\n# For 3D stacked systems\ndef main_3d(config):\n lcf_breakdown_list = read_lcf(config)\n\n output_file_bkp = config.output_file\n temperature_file_bkp = config.temperature_file\n\n for lcf_layer in lcf_breakdown_list:\n layer = int(lcf_layer[0]) # layer number\n\n # override the config parameters\n config.floor_plan = lcf_layer[2]\n config.output_file = output_file_bkp\n config.output_file += \"-layer-{l}\".format(l=layer)\n\n turtle = turtle_setup(config)\n\n print(\"{s} Processing layer {l} with floor-plan: {f}\".format(\n s=msg_prefix, l=layer, f=config.floor_plan))\n\n if config.action == \"flp\":\n draw_floorplan(config, turtle)\n else:\n if config.action == \"grid-steady\":\n extract_grid_temperatures_for_layer(config,\n temperature_file_bkp,\n layer)\n\n # this file has extracted grid temperatures for current layer\n config.temperature_file = \"temp.grid.steady\"\n draw_grid_steady_thermal_map(config, turtle,\n temperature_file_bkp)\n draw_floorplan(\n config, turtle\n ) # this will superimpose floor-plan onto temperature grid\n os.remove(\"temp.grid.steady\")\n else:\n draw_steady_thermal_map(config, turtle)\n\n if config.print_chip_dim:\n draw_chip_dimensions(turtle, config)\n\n\n turtle_save_image(config)\n\n print(\"\")\n\n if config.concat:\n # this code block combines all the files\n # generated for each layer into a single PDF\n output_file_list_str = \"\"\n\n for file in output_3d_files:\n output_file_list_str += \"{f} \".format(f=file)\n\n final_concat_output = os.path.join(\n config.output_dir, \"{p}-{a}-concat.pdf\".format(p=output_file_bkp,a=config.action))\n\n pdfjam = \"pdfjam --nup {n}x1 --landscape {files} -o {output}\".format(\n n=len(output_3d_files),\n files=output_file_list_str,\n output=final_concat_output)\n\n print(\"{p} Executing {c}\".format(p=msg_prefix, c=pdfjam))\n process = subprocess.Popen(pdfjam, shell=True)\n process.wait()\n stdout, stderr = process.communicate()\n\n if stdout:\n print(stdout)\n\n if stderr:\n print(stderr)\n\n\ndef setup_chip_dimensions(config):\n floor_plan_file = config.floor_plan\n\n if config.model_3d:\n lcf_breakdown_list = read_lcf(config)\n # index 0 in lcf_breakdown_list is the 1st layer in 3D system\n # index 2 in 1st layer is the floor-plan file for that layer\n # for stacked 3D system, all layers must have equal dimensions, so pick any 1 layer\n floor_plan_file = lcf_breakdown_list[0][2]\n\n file = open(floor_plan_file, \"r\")\n flp = file.readlines()\n flp_units = []\n file.close()\n\n for line in flp:\n if \"#\" in line or line == \"\\n\" or not line:\n continue\n line = line.split(\"\\t\")\n flp_units.append(\n FloorplanUnit(line[0], float(line[1]), float(line[2]),\n float(line[3]), float(line[4])))\n\n config.chip_height = round(get_chip_height(flp_units), 5)\n config.chip_width = round(get_chip_width(flp_units), 5)\n\n print(\"{p} Calculated chip's width as {w} mm and chip's height as {h} mm\".\n format(p=msg_prefix, w=config.chip_width, h=config.chip_height))\n\n\ndef parse_command_line():\n version = 2.0\n description = \"A python based temperature (thermal) map generation tool for HotSpot-6.0 (http://lava.cs.virginia.edu/HotSpot/), Author: Gaurav Kothari ([email protected]) v{v}\".format(\n v=version)\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument(\"-a\",\n \"--action\",\n action=\"store\",\n dest=\"action\",\n required=True,\n choices=[\"flp\", \"steady\", \"grid-steady\"],\n help=\"Action type\")\n parser.add_argument(\"-3D\",\n \"--model-3D\",\n action=\"store_true\",\n dest=\"model_3d\",\n required=False,\n default=False,\n help=\"To indicate a 3D system\")\n parser.add_argument(\"-f\",\n \"--flp\",\n action=\"store\",\n dest=\"floor_plan\",\n required=True,\n help=\"Floor-plan file\")\n parser.add_argument(\n \"-t\",\n \"--temperature\",\n action=\"store\",\n dest=\"temperature_file\",\n required=(\"steady\" in argv) or (\"grid-steady\" in argv),\n help=\n \"Steady temperature file or Grid steady temperature file based on action\"\n )\n parser.add_argument(\"-r\",\n \"--row\",\n action=\"store\",\n dest=\"grid_rows\",\n type=int,\n required=(\"grid-steady\" in argv),\n help=\"Number of rows in grid-steady model\")\n parser.add_argument(\"-c\",\n \"--col\",\n action=\"store\",\n dest=\"grid_cols\",\n type=int,\n required=(\"grid-steady\" in argv),\n help=\"Number of columns in grid-steady model\")\n parser.add_argument(\"-ft\",\n \"--font\",\n action=\"store\",\n dest=\"font\",\n required=False,\n default=\"Ubuntu\",\n help=\"Font family\")\n parser.add_argument(\"-fts\",\n \"--font-size\",\n action=\"store\",\n dest=\"font_size\",\n required=False,\n default=9,\n type=int,\n help=\"Font size\")\n parser.add_argument(\"-ftw\",\n \"--font-weight\",\n action=\"store\",\n dest=\"font_weight\",\n required=False,\n default=\"normal\",\n help=\"Font weight\")\n parser.add_argument(\"-o\",\n \"--output-file\",\n action=\"store\",\n dest=\"output_file\",\n required=True,\n help=\"Output file name prefix\")\n parser.add_argument(\"-d\",\n \"--output-directory\",\n action=\"store\",\n dest=\"output_dir\",\n required=False,\n default=os.getcwd(),\n help=\"Output directory\")\n parser.add_argument(\"-hn\",\n \"--hide-names\",\n action=\"store_true\",\n dest=\"hide_names\",\n required=False,\n default=False,\n help=\"Hide names on floor-plan\")\n parser.add_argument(\"-z\",\n \"--zoom-by\",\n action=\"store\",\n dest=\"zoom_by\",\n type=int,\n required=False,\n default=75000,\n help=\"Zoom factor\")\n parser.add_argument(\"-pcd\",\n \"--print-chip-dim\",\n action=\"store_true\",\n dest=\"print_chip_dim\",\n required=False,\n default=False,\n help=\"Draw chip' width and height scale\")\n parser.add_argument(\"-concat\",\n \"--concat-3D\",\n action=\"store_true\",\n dest=\"concat\",\n required=False,\n default=False,\n help=\"Combines the images generated for all layer into a single PDF\")\n parser.add_argument(\n \"-pa\",\n \"--print-area\",\n action=\"store_true\",\n dest=\"print_area\",\n required=False,\n default=False,\n help=\n \"Print unit's area (mm2) alongside its name, rounded to three decimal places\"\n )\n args = parser.parse_args()\n print(\"{p} {d}\".format(p=msg_prefix, d=description))\n print(\"\")\n return args\n\n\ndef main():\n config = parse_command_line()\n\n # before we start drawing images, first quickly read floor-plan file\n # and calculate the chip's width and height\n setup_chip_dimensions(config)\n\n if config.model_3d:\n main_3d(config)\n else:\n main_2d(config)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "matplotlib.colors.Normalize", "matplotlib.colors.LinearSegmentedColormap.from_list" ] ]
Xiaoying-Tian/selective-inference
[ "a20c5ad3f527beb709d5b8d7301016640738b092" ]
[ "selection/truncated/chi.py" ]
[ "\"\"\"\nThis module implements the class `truncated_chi2` which \nperforms (conditional) UMPU tests for Gaussians\nrestricted to a set of intervals.\n\n\"\"\"\nimport numpy as np\nimport mpmath as mp\nfrom scipy.stats import chi, chi2\n\nfrom .base import truncated, find_root\n\nclass truncated_chi(truncated):\n\n \"\"\"\n >>> from intervals import intervals\n >>> I = intervals.intersection(intervals((-1, 6)), \\\n intervals(( 0, 7)), \\\n ~intervals((1, 4)))\n >>> distr = trunc_chi(I, 3, 2.)\n >>> print distr.cdf(0)\n 0.0\n >>> z = distr.quantile(distr.cdf(5.))\n >>> np.abs(z - 5) < 1e-2\n True\n \"\"\"\n def __init__(self, I, k, scale = 1.):\n \"\"\"\n Create a new object for a truncated_chi distribution\n\n Parameters\n ----------\n I : intervals\n The intervals the distribution is truncated to\n\n k : int\n Number of degree of freedom of the distribution\n\n scale : float\n The distribution is \\sim scale * \\chi_k\n\n \n \"\"\"\n\n self._k = k\n self._scale = scale\n truncated.__init__(self, I)\n\n def _cdf_notTruncated(self, a, b, dps):\n \"\"\"\n Compute the probability of being in the interval (a, b)\n for a variable with a chi distribution (not truncated)\n \n Parameters\n ----------\n a, b : float\n Bounds of the interval. Can be infinite.\n\n dps : int\n Decimal precision (decimal places). Used in mpmath\n\n Returns\n -------\n p : float\n The probability of being in the intervals (a, b)\n P( a < X < b)\n for a non truncated variable\n\n \"\"\"\n scale = self._scale\n k = self._k\n\n dps_temp = mp.mp.dps\n mp.mp.dps = dps\n\n a = max(0, a)\n b = max(0, b)\n\n sf = mp.gammainc(1./2 * k, \n 1./2*((a/scale)**2), \n 1./2*((b/scale)**2), \n regularized=True)\n mp.mp.dps = dps_temp\n return sf\n\n def _pdf_notTruncated(self, z, dps):\n scale = self._scale\n k = self._k\n dps = self._dps\n\n return chi.pdf(z/scale, k)\n\n def _quantile_notTruncated(self, q, tol=1.e-6):\n \"\"\"\n Compute the quantile for the non truncated distribution\n\n Parameters\n ----------\n q : float\n quantile you want to compute. Between 0 and 1\n\n tol : float\n precision for the output\n\n Returns\n -------\n x : float\n x such that P(X < x) = q\n\n \"\"\"\n scale = self._scale\n k = self._k\n dps = self._dps\n \n z_approx = scale * chi.ppf(q, k)\n \n epsilon = scale * 0.001\n lb = z_approx - epsilon\n ub = z_approx + epsilon\n\n f = lambda z: self._cdf_notTruncated(-np.inf, z, dps)\n\n z = find_root(f, q, lb, ub, tol)\n\n return z \n \n\nclass truncated_chi2(truncated):\n\n \"\"\"\n\n >>> from intervals import intervals\n >>> I = intervals.intersection(intervals((-1, 6)), \\\n intervals(( 0, 7)), \\\n ~intervals((1, 4)))\n >>> distr = trunc_chi(I, 3, 2.)\n >>> print distr.cdf(0)\n 0.0\n >>> z = distr.quantile(distr.cdf(5.))\n >>> np.abs(z - 5) < 1e-2\n True\n \"\"\"\n def __init__(self, I, k, scale = 1.):\n \"\"\"\n Create a new object for a truncated_chi distribution\n\n Parameters\n ----------\n I : intervals\n The intervals the distribution is truncated to\n\n k : int\n Number of degree of freedom of the distribution\n\n scale : float\n The distribution is \\sim scale * \\chi_k\n\n \n \"\"\"\n\n self._k = k\n self._scale = scale\n truncated.__init__(self, I)\n\n def _cdf_notTruncated(self, a, b, dps):\n \"\"\"\n Compute the probability of being in the interval (a, b)\n for a variable with a chi distribution (not truncated)\n \n Parameters\n ----------\n a, b : float\n Bounds of the interval. Can be infinite.\n\n dps : int\n Decimal precision (decimal places). Used in mpmath\n\n Returns\n -------\n p : float\n The probability of being in the intervals (a, b)\n P( a < X < b)\n for a non truncated variable\n\n \"\"\"\n scale = self._scale\n k = self._k\n\n dps_temp = mp.mp.dps\n mp.mp.dps = dps\n\n a = max(0, a)\n b = max(0, b)\n\n cdf = mp.gammainc(1./2 * k, \n 1./2*(a/scale), \n 1./2*(b/scale), \n regularized=True)\n mp.mp.dps = dps_temp\n return cdf\n\n def _pdf_notTruncated(self, z, dps):\n scale = self._scale\n k = self._k\n dps = self._dps\n\n return chi2.pdf(z/scale, k)\n\n def _quantile_notTruncated(self, q, tol=1.e-6):\n \"\"\"\n Compute the quantile for the non truncated distribution\n\n Parameters\n ----------\n q : float\n quantile you want to compute. Between 0 and 1\n\n tol : float\n precision for the output\n\n Returns\n -------\n x : float\n x such that P(X < x) = q\n\n \"\"\"\n scale = self._scale\n k = self._k\n dps = self._dps\n \n z_approx = scale * chi.ppf(q, k)\n \n epsilon = scale * 0.001\n lb = z_approx - epsilon\n ub = z_approx + epsilon\n\n f = lambda z: self._cdf_notTruncated(-np.inf, z, dps)\n\n z = find_root(f, q, lb, ub, tol)\n\n return z \n\n def _pdf_notTruncated(self, z, dps):\n scale = self._scale\n k = self._k\n #dps = self._dps\n\n return chi2.pdf(z/scale, k)\n\n def _quantile_notTruncated(self, q, tol=1.e-6):\n \"\"\"\n Compute the quantile for the non truncated distribution\n\n Parameters\n ----------\n q : float\n quantile you want to compute. Between 0 and 1\n\n tol : float\n precision for the output\n\n Returns\n -------\n x : float\n x such that P(X < x) = q\n\n \"\"\"\n scale = self._scale\n k = self._k\n dps = self._dps\n \n z_approx = scale * chi2.ppf(q, k)\n \n epsilon = scale * 0.001\n lb = z_approx - epsilon\n ub = z_approx + epsilon\n\n f = lambda z: self._cdf_notTruncated(-np.inf, z, dps)\n\n z = find_root(f, q, lb, ub, tol)\n\n return z \n \n \n\nimport doctest\ndoctest.testmod()\n\n" ]
[ [ "scipy.stats.chi2.ppf", "scipy.stats.chi2.pdf", "scipy.stats.chi.ppf", "scipy.stats.chi.pdf" ] ]
lujiammy/coronavirus-machine-learning
[ "4af16b1c51a89a81206262b50a9bcf4d9b679853" ]
[ "mlp_uk_learning.py" ]
[ "import numpy as np\nnp.random.seed(1337)\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport matplotlib.pyplot as plt\n\n\nmodel = Sequential()\nmodel.add(Dense(units=50, input_dim=1, activation='relu'))\nmodel.add(Dense(units=50, activation='relu'))\nmodel.add(Dense(units=1, activation='sigmoid'))\nmodel.add(Dense(units=1, activation='linear'))\nmodel.compile(optimizer='adam', loss='mean_squared_error')\nmodel.summary()\n\n# uk corona\nimport json\n\nurl = 'https://api.covid19uk.live/historyfigures'\n\n\ndef read_url_to_json(url):\n import urllib.request as request\n webpage = request.urlopen(url)\n get_data = webpage.read()\n data = json.loads(get_data)\n return data\n\n\nread_data = read_url_to_json(url)\neach_data = read_data['data']\nuk_comfirmed_data = []\n\nfor each in each_data:\n uk_comfirmed_data.append(each['confirmed'])\n\nuk_date_length = len(uk_comfirmed_data)\nuk_dates = list(range(1, uk_date_length + 1))\n\nuk_comfirmed_data = np.array(uk_comfirmed_data)\nuk_dates = np.array(uk_dates)\n\nuk_absorb_amount = uk_comfirmed_data[uk_date_length-1]\n\nuk_comfirmed_data_norm = uk_comfirmed_data / uk_absorb_amount\n\n# fit model\nmodel.fit(uk_dates, uk_comfirmed_data_norm, epochs=10000, shuffle=False)\n\nuk_comfirmed_data_predict = model.predict(uk_dates)\nuk_comfirmed_data_predict = uk_comfirmed_data_predict * uk_absorb_amount\nfig2 = plt.figure(figsize=(7, 5))\nplt.scatter(uk_dates, uk_comfirmed_data, label='Real Confirmed')\nplt.plot(uk_dates, uk_comfirmed_data_predict, label='Predict Result')\nplt.title('UK Confirmed VS Dates')\nplt.xlabel('Dates')\nplt.ylabel('Amount')\nplt.legend()\nplt.show()" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "numpy.random.seed", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.array", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.scatter" ] ]
CrackedSTone/algorithm-detects-liver-pathology
[ "d52d08e4e6931b3502f083f20d6332f7b6839a3b" ]
[ "diplom_test/main.py" ]
[ "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom PyQt5.uic import loadUi\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\n#from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)\nimport matplotlib.image as mpimg\n\nimport sys\n\nimport radiomics_single as rs\n\nqtCreatorFile = \"design/diplom.ui\" # Enter file here.\n\nclass MatplotlibWidget(QMainWindow):\n\n def __init__(self):\n QMainWindow.__init__(self)\n loadUi(qtCreatorFile, self)\n self.FlagLoaded = False\n self.setWindowTitle(\"Texture Analysis for Diffuse Liver Diseases\")\n self.buttonLoader.clicked.connect(self.choose_file)\n self.buttonAnalyze.clicked.connect(self.analyze)\n #self.addToolBar(NavigationToolbar(self.MplWidget.canvas, self))\n self.setWindowIcon(QIcon(\"app.ico\"))\n\n mainMenu = self.menuBar()\n fileMenu = mainMenu.addMenu('File')\n helpMenu = mainMenu.addMenu('Help')\n\n buttonLoaderMenu = QAction('Download', self)\n buttonLoaderMenu.setShortcut('Ctrl+D')\n buttonLoaderMenu.setStatusTip('Download the region of the interest')\n buttonLoaderMenu.triggered.connect(self.choose_file)\n fileMenu.addAction(buttonLoaderMenu)\n\n buttonAnalyzeMenu = QAction('Analysis', self)\n buttonAnalyzeMenu.setShortcut('Ctrl+A')\n buttonAnalyzeMenu.setStatusTip('Analyse the loaded region of the interest')\n buttonAnalyzeMenu.triggered.connect(self.analyze)\n fileMenu.addAction(buttonAnalyzeMenu)\n\n buttonExit = QAction('Quit', self)\n buttonExit.setShortcut('Ctrl+Q')\n buttonExit.setStatusTip('Quit out of application')\n buttonExit.triggered.connect(sys.exit)\n fileMenu.addAction(buttonExit)\n\n buttonLaunch = QAction('How to run', self)\n buttonLaunch.setStatusTip('Get info about how to run the application')\n self.msgBox1 = QMessageBox(self)\n self.msgBox1.setIcon(QMessageBox.Information)\n self.msgBox1.setWindowTitle(\"How to run\")\n self.msgBox1.setText(\"To run the classifier:\\n1) push the button <Choose an image>\\n2) push the button <Analyse>\")\n buttonLaunch.triggered.connect(self.msgBox1.exec_)\n helpMenu.addAction(buttonLaunch)\n\n\n\n buttonInfo = QAction('Application', self)\n buttonInfo.setStatusTip('Get info about the application')\n self.msgBox2 = QMessageBox(self)\n self.msgBox2.setIcon(QMessageBox.Information)\n self.msgBox2.setWindowTitle(\"Application\")\n self.msgBox2.setText(\"This application give an ability to load ROI and predict a probable presence of diffuse liver diseases.\")\n buttonInfo.triggered.connect(self.msgBox2.exec_)\n helpMenu.addAction(buttonInfo)\n\n buttonInfo = QAction('Developer', self)\n buttonInfo.setStatusTip('Get info about the developer')\n self.msgBox3 = QMessageBox(self)\n self.msgBox3.setIcon(QMessageBox.Information)\n self.msgBox3.setWindowTitle(\"Developer\")\n self.msgBox3.setText(\"This application was developed by Illia Yankovyi, the student of the 4th year\"\n \"\\nNTUU Igor Sikorsky Kyiv Polytechnic Institute:\"\n \"\\nFaculty of Biomedical Engineering (FBME)\\n\"\n \"\\nAcademic unit:BS-52 group\\n\"\n \"\\nSupervisor: Nastenko I., M.D., Candidate of Engineering Sciences, Senior Research Fellow.\")\n buttonInfo.triggered.connect(self.msgBox3.exec_)\n helpMenu.addAction(buttonInfo)\n\n self.labelTitle.setText('Classifier of Diffuse Liver Diseases')\n font = QFont()\n font.setPointSize(20)\n font.setBold(True)\n self.labelTitle.setFont(font)\n self.labelTitle.setAlignment(Qt.AlignCenter)\n self.buttonAnalyze.setText('Analyze Image')\n self.buttonLoader.setText('Download Image')\n self.labelResult.setText('To get a prediction:\\n\\n1) Download the region of interest;\\n2) Run the analysis.')\n\n def analyze(self):\n if (self.FlagLoaded):\n self.labelResult.setText(rs.signle_prediction(self.path))\n else:\n self.labelResult.setText(\"Image was not chosen!\\n\\nPlease choose the image\\nbefore running the Analysis\")\n self.msgBox4 = QMessageBox(self)\n self.msgBox4.setIcon(QMessageBox.Warning)\n self.msgBox4.setWindowTitle(\"Error! Image was not chosen.\")\n self.msgBox4.setText(\n \"Image was not chosen! Please choose the image before running the Analysis.\")\n self.msgBox4.exec_()\n\n\n def choose_file(self):\n options = QFileDialog.Options()\n fileName, _ = QFileDialog.getOpenFileName(self, \"Choose an image\", \"\",\n \"Image (*.bmp *.png *.jpeg *.jpg)\", options=options)\n extensions = ['png', 'jpg', 'jpeg', 'bmp']\n fileExtension = (fileName.split('.'))[-1].lower()\n if fileName:\n if fileExtension in extensions:\n self.path = fileName\n self.img = mpimg.imread(self.path)\n self.MplWidget.canvas.axes.clear()\n self.MplWidget.canvas.axes.imshow(self.img)\n self.MplWidget.canvas.axes.set_title('Chosen image')\n self.MplWidget.canvas.draw()\n self.FlagLoaded = True\n else:\n self.labelResult.setText(\"Chosen filetype is not supported.\\nSupported filetypes:\\nBMP, PNG, JPEG, JPG\")\n self.msgBox5 = QMessageBox(self)\n self.msgBox5.setIcon(QMessageBox.Warning)\n self.msgBox5.setWindowTitle(\"Error! Chosen filetype is not supported.\")\n self.msgBox5.setText(\n \"Chosen filetype is not supported.\\nSupported filetypes:\\nBMP, PNG, JPEG, JPG.\")\n self.msgBox5.exec_()\n\nif __name__ == \"__main__\":\n app = QApplication([])\n window = MatplotlibWidget()\n window.show()\n sys.exit(app.exec_())" ]
[ [ "matplotlib.image.imread" ] ]
Jbuxofplenty/quant
[ "2ef24012963e9ead6193e0f421c63fb009c78f80" ]
[ "strategies/hitoshi.py" ]
[ "from zipline.pipeline import Pipeline\nfrom zipline.api import attach_pipeline, pipeline_output\nfrom zipline.pipeline.data.equity_pricing import USEquityPricing\nfrom zipline.pipeline.data import morningstar\nfrom zipline.pipeline.factors import SimpleMovingAverage, AverageDollarVolume\nfrom zipline.pipeline.filters.morningstar import IsPrimaryShare\n\nimport numpy as np # needed for NaN handling\nimport math # ceil and floor are useful for rounding\n\nfrom itertools import cycle\n\n\ndef initialize(context):\n # set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.50))\n set_slippage(\n slippage.VolumeShareSlippage(\n volume_limit=.20,\n price_impact=0.0))\n # set_slippage(slippage.FixedSlippage(spread=0.00))\n set_commission(commission.PerTrade(cost=0.00))\n # set_slippage(slippage.FixedSlippage(spread=0.00))\n set_long_only()\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 # over simplistic tracking of position age\n context.age = {}\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 xrange(\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 # Equities listed as common stock (as opposed to, say, preferred stock).\n # 'ST00000001' indicates common stock.\n common_stock = morningstar.share_class_reference.security_type.latest.eq(\n 'ST00000001')\n\n # Non-depositary receipts. Recall that the ~ operator inverts filters,\n # turning Trues into Falses and vice versa\n not_depositary = ~morningstar.share_class_reference.is_depositary_receipt.latest\n\n # Equities not trading over-the-counter.\n not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith(\n 'OTC')\n\n # Not when-issued equities.\n not_wi = ~morningstar.share_class_reference.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 = ~morningstar.company_reference.standard_name.latest.matches(\n '.* L[. ]?P.?$')\n\n # Equities with a null value in the limited_partnership Morningstar\n # fundamental field.\n not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()\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 = morningstar.valuation.market_cap.latest.notnull()\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 & common_stock\n & not_depositary\n & not_otc\n & not_wi\n & not_lp_name\n & not_lp_balance_sheet\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 # 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(message.format(symbol=stock.symbol, age=context.age[stock]))\n\n pass\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 = context.MyCandidate.next()\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 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.iteritems():\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.iteritems():\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.iteritems():\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.iteritems():\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\n" ]
[ [ "numpy.isnan" ] ]
Codelegant92/STC-ProtoNet
[ "f3e77bb1b363b0338cda6f1701bfabe0cd3accbe" ]
[ "save_features.py" ]
[ "import numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport os\nimport glob\nimport h5py\n\nimport configs\nimport backbone\nfrom data.datamgr import SimpleDataManager\nfrom methods.baselinetrain import BaselineTrain\nfrom methods.baselinefinetune import BaselineFinetune\nfrom methods.protonet import ProtoNet\nfrom methods.matchingnet import MatchingNet\nfrom methods.relationnet import RelationNet\nfrom methods.maml import MAML\nfrom io_utils import model_dict, parse_args, get_resume_file, get_best_file, get_assigned_file \n\n\ndef save_features(model, data_loader, outfile ):\n f = h5py.File(outfile, 'w')\n max_count = len(data_loader)*data_loader.batch_size\n all_labels = f.create_dataset('all_labels',(max_count,), dtype='i')\n all_feats=None\n count=0\n for i, (x,y) in enumerate(data_loader):\n if i%10 == 0:\n print('{:d}/{:d}'.format(i, len(data_loader)))\n x = x.cuda()\n x_var = Variable(x)\n feats = model(x_var)\n if all_feats is None:\n all_feats = f.create_dataset('all_feats', [max_count] + list( feats.size()[1:]) , dtype='f')\n all_feats[count:count+feats.size(0)] = feats.data.cpu().numpy()\n all_labels[count:count+feats.size(0)] = y.cpu().numpy()\n count = count + feats.size(0)\n\n count_var = f.create_dataset('count', (1,), dtype='i')\n count_var[0] = count\n\n f.close()\n\nif __name__ == '__main__':\n params = parse_args('save_features')\n assert params.method != 'maml' and params.method != 'maml_approx', 'maml do not support save_feature and run'\n\n if 'Conv' in params.model:\n image_size = 40\n\n split = params.split\n loadfile = configs.data_dir[params.dataset] + split + '.json'\n loadfile_unk = configs.data_dir[params.dataset] + split + '_unk.json'\n loadfile_sil = configs.data_dir[params.dataset] + split + '_sil.json'\n\n checkpoint_dir = '%s/checkpoints/%s/%s_%s_regularizer' %(configs.save_dir, params.dataset, params.model, params.method)\n #checkpoint_dir = '%s/checkpoints/%s/%s_%s' %(configs.save_dir, params.dataset, params.model, params.method)\n \n if params.train_aug:\n checkpoint_dir += '_aug'\n if not params.method in ['baseline', 'baseline++'] :\n if params.train_n_way != -1:\n checkpoint_dir += '_%d-way_' %( params.train_n_way )\n else:\n checkpoint_dir += '_random-way_'\n if params.train_n_shot != -1:\n checkpoint_dir += '%d-shot' % ( params.train_n_shot )\n else:\n checkpoint_dir += 'random-shot'\n\n if params.save_iter != -1:\n modelfile = get_assigned_file(checkpoint_dir,params.save_iter)\n# elif params.method in ['baseline', 'baseline++'] :\n# modelfile = get_resume_file(checkpoint_dir) #comment in 2019/08/03 updates as the validation of baseline/baseline++ is added\n else:\n modelfile = get_best_file(checkpoint_dir, params.test_n_way)\n\n if params.save_iter != -1:\n outfile = os.path.join( checkpoint_dir.replace(\"checkpoints\",\"features\"), split + \"_\" + str(params.save_iter)+ \".hdf5\") \n else:\n outfile = os.path.join( checkpoint_dir.replace(\"checkpoints\",\"features\"), split + \".hdf5\") \n #outfile = os.path.join( checkpoint_dir.replace(\"checkpoints\",\"features\"), split + \"_test_random-way.hdf5\") \n\n datamgr = SimpleDataManager(image_size, batch_size = 64)\n data_loader = datamgr.get_data_loader(loadfile, [loadfile_unk, loadfile_sil], aug = False)\n\n if params.method in ['relationnet', 'relationnet_softmax']:\n if params.model == 'Conv4': \n model = backbone.Conv4NP()\n elif params.model == 'Conv6': \n model = backbone.Conv6NP()\n elif params.model == 'Conv4S': \n model = backbone.Conv4SNP()\n else:\n model = model_dict[params.model]( flatten = False )\n elif params.method in ['maml' , 'maml_approx']: \n raise ValueError('MAML do not support save feature')\n else:\n model = model_dict[params.model]()\n\n model = model.cuda()\n tmp = torch.load(modelfile)\n state = tmp['state']\n state_keys = list(state.keys())\n for i, key in enumerate(state_keys):\n if \"feature.\" in key:\n newkey = key.replace(\"feature.\",\"\") # an architecture model has attribute 'feature', load architecture feature to backbone by casting name from 'feature.trunk.xx' to 'trunk.xx' \n state[newkey] = state.pop(key)\n else:\n state.pop(key)\n \n model.load_state_dict(state)\n model.eval()\n\n dirname = os.path.dirname(outfile)\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n save_features(model, data_loader, outfile)\n" ]
[ [ "torch.autograd.Variable", "torch.load" ] ]
LSSTDESC/skyportal
[ "1a433aae67b26ffd3516e65e0fdbf866b4751486" ]
[ "skyportal/tests/api/test_photometry.py" ]
[ "import math\n\nimport numpy as np\nimport sncosmo\n\nfrom baselayer.app.env import load_env\nfrom skyportal.models import DBSession, Token\nfrom skyportal.tests import api\n\n_, cfg = load_env()\nPHOT_DETECTION_THRESHOLD = cfg[\"misc.photometry_detection_threshold_nsigma\"]\n\n\ndef test_token_user_post_get_photometry_data(\n upload_data_token, public_source, public_group, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n assert data['data']['ra'] is None\n assert data['data']['dec'] is None\n assert data['data']['ra_unc'] is None\n assert data['data']['dec_unc'] is None\n\n np.testing.assert_allclose(\n data['data']['flux'], 12.24 * 10 ** (-0.4 * (25.0 - 23.9))\n )\n\n\ndef test_token_user_post_put_photometry_data(\n upload_data_token, public_source, public_group, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'instrument_id': ztf_camera.id,\n \"mjd\": [59400, 59401, 59402],\n \"mag\": [19.2, 19.3, np.random.uniform(19, 20)],\n \"magerr\": [0.05, 0.06, np.random.uniform(0.01, 0.1)],\n \"limiting_mag\": [20.0, 20.1, 20.2],\n \"magsys\": [\"ab\", \"ab\", \"ab\"],\n \"filter\": [\"ztfr\", \"ztfg\", \"ztfr\"],\n \"ra\": [42.01, 42.01, 42.02],\n \"dec\": [42.02, 42.01, 42.03],\n \"origin\": [None, \"lol\", \"lol\"],\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n ids = data[\"data\"][\"ids\"]\n assert len(ids) == 3\n\n # POSTing photometry that contains the same first two points should fail:\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'instrument_id': ztf_camera.id,\n \"mjd\": [59400, 59401, 59402],\n \"mag\": [19.2, 19.3, np.random.uniform(19, 20)],\n \"magerr\": [0.05, 0.06, np.random.uniform(0.01, 0.1)],\n \"limiting_mag\": [20.0, 20.1, 20.2],\n \"magsys\": [\"ab\", \"ab\", \"ab\"],\n \"filter\": [\"ztfr\", \"ztfg\", \"ztfr\"],\n \"ra\": [42.01, 42.01, 42.02],\n \"dec\": [42.02, 42.01, 42.03],\n \"origin\": [None, \"lol\", \"lol\"],\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n\n # PUTing photometry that contains\n # the same first point, the second point with a different origin, and a new third point should succeed\n # only the last two points will be ingested\n status, data = api(\n 'PUT',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'instrument_id': ztf_camera.id,\n \"mjd\": [59400, 59401, 59402],\n \"mag\": [19.2, 19.3, np.random.uniform(19, 20)],\n \"magerr\": [0.05, 0.06, np.random.uniform(0.01, 0.1)],\n \"limiting_mag\": [20.0, 20.1, 20.2],\n \"magsys\": [\"ab\", \"ab\", \"ab\"],\n \"filter\": [\"ztfr\", \"ztfg\", \"ztfr\"],\n \"ra\": [42.01, 42.01, 42.02],\n \"dec\": [42.02, 42.01, 42.03],\n \"origin\": [None, \"omg\", \"lol\"],\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n new_ids = data[\"data\"][\"ids\"]\n assert len(new_ids) == 3\n assert len(set(new_ids).intersection(set(ids))) == 1\n\n\ndef test_token_user_post_put_get_photometry_data(\n upload_data_token_two_groups, public_source, public_group, public_group2, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'instrument_id': ztf_camera.id,\n \"mjd\": [59400, 59401, 59402],\n \"mag\": [19.2, 19.3, np.random.uniform(19, 20)],\n \"magerr\": [0.05, 0.06, np.random.uniform(0.01, 0.1)],\n \"limiting_mag\": [20.0, 20.1, 20.2],\n \"magsys\": [\"ab\", \"ab\", \"ab\"],\n \"filter\": [\"ztfr\", \"ztfg\", \"ztfr\"],\n \"ra\": [42.01, 42.01, 42.02],\n \"dec\": [42.02, 42.01, 42.03],\n \"origin\": [None, \"lol\", \"lol\"],\n 'group_ids': [public_group.id],\n },\n token=upload_data_token_two_groups,\n )\n assert status == 200\n assert data['status'] == 'success'\n ids = data[\"data\"][\"ids\"]\n assert len(ids) == 3\n\n status, data = api(\n 'GET', f'photometry/{ids[0]}?format=flux', token=upload_data_token_two_groups\n )\n assert status == 200\n assert data['status'] == 'success'\n group_ids = [g[\"id\"] for g in data['data']['groups']]\n assert len(group_ids) == 2\n assert public_group.id in group_ids\n\n # PUTing photometry that contains\n # the same first point, the second point with a different origin, and a new third point should succeed\n # only the last two points will be ingested\n status, data = api(\n 'PUT',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'instrument_id': ztf_camera.id,\n \"mjd\": [59400, 59401],\n \"mag\": [19.2, 19.3],\n \"magerr\": [0.05, 0.06],\n \"limiting_mag\": [20.0, 20.1],\n \"magsys\": [\"ab\", \"ab\"],\n \"filter\": [\"ztfr\", \"ztfg\"],\n \"ra\": [42.01, 42.01],\n \"dec\": [42.02, 42.01],\n \"origin\": [None, \"lol\"],\n 'group_ids': [public_group.id, public_group2.id],\n },\n token=upload_data_token_two_groups,\n )\n assert status == 200\n assert data['status'] == 'success'\n new_ids = data[\"data\"][\"ids\"]\n assert len(new_ids) == 2\n assert len(set(new_ids).intersection(set(ids))) == 2\n\n status, data = api(\n 'GET', f'photometry/{ids[0]}?format=flux', token=upload_data_token_two_groups\n )\n assert status == 200\n assert data['status'] == 'success'\n group_ids = [g[\"id\"] for g in data['data']['groups']]\n assert len(group_ids) == 3\n\n token_object = (\n DBSession()\n .query(Token)\n .filter(Token.id == upload_data_token_two_groups)\n .first()\n )\n\n assert sorted(group_ids) == sorted(\n [\n public_group.id,\n public_group2.id,\n token_object.created_by.single_user_group.id,\n ]\n )\n\n\ndef test_post_photometry_multiple_groups(\n upload_data_token_two_groups,\n public_source_two_groups,\n public_group,\n public_group2,\n ztf_camera,\n):\n upload_data_token = upload_data_token_two_groups\n public_source = public_source_two_groups\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id, public_group2.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n assert data['data']['ra'] is None\n assert data['data']['dec'] is None\n assert data['data']['ra_unc'] is None\n assert data['data']['dec_unc'] is None\n\n assert len(data['data']['groups']) == 3\n\n np.testing.assert_allclose(\n data['data']['flux'], 12.24 * 10 ** (-0.4 * (25.0 - 23.9))\n )\n\n\ndef test_post_photometry_all_groups(\n upload_data_token_two_groups,\n super_admin_token,\n public_source_two_groups,\n public_group,\n public_group2,\n ztf_camera,\n):\n upload_data_token = upload_data_token_two_groups\n public_source = public_source_two_groups\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': \"all\",\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET',\n f'photometry/{photometry_id}?format=flux',\n token=super_admin_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n assert data['data']['ra'] is None\n assert data['data']['dec'] is None\n assert data['data']['ra_unc'] is None\n assert data['data']['dec_unc'] is None\n\n assert len(data['data']['groups']) == 2\n assert data['data']['groups'][0]['name'] == cfg['misc']['public_group_name']\n\n np.testing.assert_allclose(\n data['data']['flux'], 12.24 * 10 ** (-0.4 * (25.0 - 23.9))\n )\n\n\ndef test_retrieve_photometry_group_membership_posted_by_other(\n upload_data_token_two_groups,\n view_only_token,\n public_source_two_groups,\n public_group,\n public_group2,\n ztf_camera,\n):\n upload_data_token = upload_data_token_two_groups\n public_source = public_source_two_groups\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id, public_group2.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=view_only_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n assert data['data']['ra'] is None\n assert data['data']['dec'] is None\n assert data['data']['ra_unc'] is None\n assert data['data']['dec_unc'] is None\n\n np.testing.assert_allclose(\n data['data']['flux'], 12.24 * 10 ** (-0.4 * (25.0 - 23.9))\n )\n\n\ndef test_retrieve_photometry_error_group_membership_posted_by_other(\n upload_data_token_two_groups,\n view_only_token,\n public_source_two_groups,\n public_group,\n public_group2,\n ztf_camera,\n):\n upload_data_token = upload_data_token_two_groups\n public_source = public_source_two_groups\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group2.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=view_only_token\n )\n # `view_only_token only` belongs to `public_group`, not `public_group2`\n assert status == 400\n assert data['status'] == 'error'\n assert \"Insufficient permissions\" in data['message']\n\n\ndef test_can_post_photometry_no_groups(\n upload_data_token, public_source, public_group, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n assert len(data['data']['groups']) == 1\n\n\ndef test_can_post_photometry_empty_groups_list(\n upload_data_token, public_source, public_group, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [],\n },\n token=upload_data_token,\n )\n\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n assert len(data['data']['groups']) == 1\n\n\ndef test_token_user_post_mag_photometry_data_and_convert(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': 21.0,\n 'magerr': 0.2,\n 'limiting_mag': 22.3,\n 'magsys': 'vega',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n ab = sncosmo.get_magsystem('ab')\n vega = sncosmo.get_magsystem('vega')\n correction = 2.5 * np.log10(vega.zpbandflux('ztfg') / ab.zpbandflux('ztfg'))\n\n np.testing.assert_allclose(\n data['data']['flux'], 10 ** (-0.4 * (21.0 - correction - 23.9))\n )\n\n np.testing.assert_allclose(\n data['data']['fluxerr'], 0.2 / (2.5 / np.log(10)) * data['data']['flux']\n )\n\n status, data = api('GET', f'photometry/{photometry_id}', token=upload_data_token)\n assert status == 200\n assert data['status'] == 'success'\n\n np.testing.assert_allclose(data['data']['mag'], 21.0 - correction)\n\n np.testing.assert_allclose(data['data']['magerr'], 0.2)\n\n\ndef test_token_user_post_and_get_different_systems_mag(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': 21.0,\n 'magerr': 0.2,\n 'limiting_mag': 22.3,\n 'magsys': 'vega',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET',\n f'photometry/{photometry_id}?format=mag&magsys=vega',\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n assert data['data']['magsys'] == 'vega'\n\n ab = sncosmo.get_magsystem('ab')\n vega = sncosmo.get_magsystem('vega')\n correction = 2.5 * np.log10(vega.zpbandflux('ztfg') / ab.zpbandflux('ztfg'))\n\n np.testing.assert_allclose(data['data']['mag'], 21.0)\n np.testing.assert_allclose(data['data']['magerr'], 0.2)\n np.testing.assert_allclose(data['data']['limiting_mag'], 22.3)\n\n status, data = api(\n 'GET',\n f'photometry/{photometry_id}?format=mag&magsys=ab',\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n np.testing.assert_allclose(data['data']['mag'], 21.0 - correction)\n np.testing.assert_allclose(data['data']['magerr'], 0.2)\n np.testing.assert_allclose(data['data']['limiting_mag'], 22.3 - correction)\n\n\ndef test_token_user_post_and_get_different_systems_flux(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': 21.0,\n 'magerr': 0.2,\n 'limiting_mag': 22.3,\n 'magsys': 'vega',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET',\n f'photometry/{photometry_id}?format=flux&magsys=vega',\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n ab = sncosmo.get_magsystem('ab')\n vega = sncosmo.get_magsystem('vega')\n correction = 2.5 * np.log10(vega.zpbandflux('ztfg') / ab.zpbandflux('ztfg'))\n\n np.testing.assert_allclose(\n data['data']['flux'], 10 ** (-0.4 * (21 - correction - 23.9))\n )\n np.testing.assert_allclose(\n data['data']['fluxerr'], 0.2 / (2.5 / np.log(10)) * data['data']['flux']\n )\n np.testing.assert_allclose(data['data']['zp'], 23.9 + correction)\n\n status, data = api(\n 'GET',\n f'photometry/{photometry_id}?format=flux&magsys=ab',\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n np.testing.assert_allclose(\n data['data']['flux'], 10 ** (-0.4 * (21 - correction - 23.9))\n )\n np.testing.assert_allclose(\n data['data']['fluxerr'], 0.2 / (2.5 / np.log(10)) * data['data']['flux']\n )\n np.testing.assert_allclose(data['data']['zp'], 23.9)\n\n\ndef test_token_user_mixed_photometry_post(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': 21.0,\n 'magerr': [0.2, 0.1],\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][1]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n np.testing.assert_allclose(data['data']['flux'], 10 ** (-0.4 * (21.0 - 23.9)))\n\n np.testing.assert_allclose(\n data['data']['fluxerr'], 0.1 / (2.5 / np.log(10)) * data['data']['flux']\n )\n\n # should fail as len(mag) != len(magerr)\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': [21.0],\n 'magerr': [0.2, 0.1],\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n\n\ndef test_token_user_mixed_mag_none_photometry_post(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': None,\n 'magerr': [0.2, 0.1],\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': [21.3, None],\n 'magerr': [0.2, 0.1],\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': [21.3, None],\n 'magerr': [None, 0.1],\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n\n\ndef test_token_user_post_photometry_limits(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': None,\n 'magerr': None,\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n assert data['data']['flux'] is None\n np.testing.assert_allclose(\n data['data']['fluxerr'], 10 ** (-0.4 * (22.3 - 23.9)) / PHOT_DETECTION_THRESHOLD\n )\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': None,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n assert data['data']['flux'] is None\n np.testing.assert_allclose(\n data['data']['fluxerr'], 0.031 * 10 ** (-0.4 * (25.0 - 23.9))\n )\n\n\ndef test_token_user_post_invalid_filter(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': None,\n 'magerr': None,\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'bessellv',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n\n\ndef test_token_user_post_photometry_data_series(\n upload_data_token, public_source, ztf_camera, public_group\n):\n # valid request\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': [58000.0, 58001.0, 58002.0],\n 'instrument_id': ztf_camera.id,\n 'flux': [12.24, 15.24, 12.24],\n 'fluxerr': [0.031, 0.029, 0.030],\n 'filter': ['ztfg', 'ztfg', 'ztfg'],\n 'zp': [25.0, 30.0, 21.2],\n 'magsys': ['ab', 'ab', 'ab'],\n 'ra': 264.1947917,\n 'dec': [50.5478333, 50.5478333 + 0.00001, 50.5478333],\n 'dec_unc': 0.2,\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n assert len(data['data']['ids']) == 3\n\n photometry_id = data['data']['ids'][1]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n assert np.allclose(data['data']['flux'], 15.24 * 10 ** (-0.4 * (30 - 23.9)))\n\n assert np.allclose(data['data']['dec'], 50.5478333 + 0.00001)\n\n assert np.allclose(data['data']['dec_unc'], 0.2)\n assert data['data']['ra_unc'] is None\n\n # invalid request\n status, data = api(\n 'POST',\n 'photometry',\n data=[\n {\n 'obj_id': str(public_source.id),\n 'mjd': 58000,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'filter': 'ztfg',\n 'zp': 25.0,\n 'magsys': 'ab',\n 'group_ids': [public_group.id],\n },\n {\n 'obj_id': str(public_source.id),\n 'mjd': 58001,\n 'instrument_id': ztf_camera.id,\n 'flux': 15.24,\n 'fluxerr': 0.031,\n 'filter': 'ztfg',\n 'zp': 30.0,\n 'magsys': 'ab',\n 'group_ids': [public_group.id],\n },\n {\n 'obj_id': str(public_source.id),\n 'mjd': 58002,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'filter': 'ztfg',\n 'zp': 21.2,\n 'magsys': 'vega',\n 'group_ids': [public_group.id],\n },\n ],\n token=upload_data_token,\n )\n\n assert status == 400\n assert data['status'] == 'error'\n\n\ndef test_post_photometry_no_access_token(\n view_only_token, public_source, ztf_camera, public_group\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=view_only_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n\n\ndef test_token_user_update_photometry(\n upload_data_token, public_source, ztf_camera, public_group\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n np.testing.assert_allclose(data['data']['flux'], 12.24 * 10 ** (-0.4 * (25 - 23.9)))\n\n status, data = api(\n 'PATCH',\n f'photometry/{photometry_id}',\n data={\n 'obj_id': str(public_source.id),\n 'flux': 11.0,\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n np.testing.assert_allclose(data['data']['flux'], 11.0 * 10 ** (-0.4 * (25 - 23.9)))\n\n\ndef test_token_user_cannot_update_unowned_photometry(\n upload_data_token, manage_sources_token, public_source, ztf_camera, public_group\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n np.testing.assert_allclose(data['data']['flux'], 12.24 * 10 ** (-0.4 * (25 - 23.9)))\n\n status, data = api(\n 'PATCH',\n f'photometry/{photometry_id}',\n data={\n 'obj_id': str(public_source.id),\n 'flux': 11.0,\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n },\n token=manage_sources_token,\n )\n assert status == 400\n\n\ndef test_token_user_update_photometry_groups(\n upload_data_token_two_groups,\n manage_sources_token_two_groups,\n public_source_two_groups,\n ztf_camera,\n public_group,\n public_group2,\n view_only_token,\n):\n upload_data_token = upload_data_token_two_groups\n public_source = public_source_two_groups\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n 'group_ids': [public_group.id, public_group2.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=view_only_token\n )\n assert status == 200\n assert data['status'] == 'success'\n\n status, data = api(\n 'PATCH',\n f'photometry/{photometry_id}',\n data={\n 'obj_id': str(public_source.id),\n 'flux': 11.0,\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n 'group_ids': [public_group2.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=view_only_token\n )\n assert status == 400\n assert data['status'] == 'error'\n assert \"Insufficient permissions\" in data[\"message\"]\n\n\ndef test_user_can_delete_owned_photometry_data(\n upload_data_token, public_source, ztf_camera, public_group\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n np.testing.assert_allclose(data['data']['flux'], 12.24 * 10 ** (-0.4 * (25 - 23.9)))\n\n status, data = api('DELETE', f'photometry/{photometry_id}', token=upload_data_token)\n assert status == 200\n\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 400\n\n\ndef test_user_cannot_delete_unowned_photometry_data(\n upload_data_token, manage_sources_token, public_source, ztf_camera, public_group\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n np.testing.assert_allclose(data['data']['flux'], 12.24 * 10 ** (-0.4 * (25 - 23.9)))\n\n status, data = api(\n 'DELETE', f'photometry/{photometry_id}', token=manage_sources_token\n )\n\n assert status == 400\n\n\ndef test_admin_can_delete_unowned_photometry_data(\n upload_data_token, super_admin_token, public_source, ztf_camera, public_group\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfi',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n np.testing.assert_allclose(data['data']['flux'], 12.24 * 10 ** (-0.4 * (25 - 23.9)))\n\n status, data = api('DELETE', f'photometry/{photometry_id}', token=super_admin_token)\n assert status == 200\n\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 400\n\n\ndef test_token_user_retrieving_source_photometry_and_convert(\n view_only_token, public_source\n):\n status, data = api(\n 'GET',\n f'sources/{public_source.id}/photometry?format=flux&magsys=ab',\n token=view_only_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n assert isinstance(data['data'], list)\n assert 'mjd' in data['data'][0]\n assert 'ra_unc' in data['data'][0]\n\n data['data'] = sorted(data['data'], key=lambda d: d['mjd'])\n mag1_ab = -2.5 * np.log10(data['data'][0]['flux']) + data['data'][0]['zp']\n magerr1_ab = 2.5 / np.log(10) * data['data'][0]['fluxerr'] / data['data'][0]['flux']\n\n maglast_ab = -2.5 * np.log10(data['data'][-1]['flux']) + data['data'][-1]['zp']\n magerrlast_ab = (\n 2.5 / np.log(10) * data['data'][-1]['fluxerr'] / data['data'][-1]['flux']\n )\n\n status, data = api(\n 'GET',\n f'sources/{public_source.id}/photometry?format=mag&magsys=ab',\n token=view_only_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n data['data'] = sorted(data['data'], key=lambda d: d['mjd'])\n assert np.allclose(mag1_ab, data['data'][0]['mag'])\n assert np.allclose(magerr1_ab, data['data'][0]['magerr'])\n\n assert np.allclose(maglast_ab, data['data'][-1]['mag'])\n assert np.allclose(magerrlast_ab, data['data'][-1]['magerr'])\n\n status, data = api(\n 'GET',\n f'sources/{public_source.id}/photometry?format=flux&magsys=vega',\n token=view_only_token,\n )\n\n data['data'] = sorted(data['data'], key=lambda d: d['mjd'])\n mag1_vega = -2.5 * np.log10(data['data'][0]['flux']) + data['data'][0]['zp']\n magerr1_vega = (\n 2.5 / np.log(10) * data['data'][0]['fluxerr'] / data['data'][0]['flux']\n )\n\n maglast_vega = -2.5 * np.log10(data['data'][-1]['flux']) + data['data'][-1]['zp']\n magerrlast_vega = (\n 2.5 / np.log(10) * data['data'][-1]['fluxerr'] / data['data'][-1]['flux']\n )\n\n assert status == 200\n assert data['status'] == 'success'\n\n ab = sncosmo.get_magsystem('ab')\n vega = sncosmo.get_magsystem('vega')\n vega_to_ab = {\n filter: 2.5 * np.log10(ab.zpbandflux(filter) / vega.zpbandflux(filter))\n for filter in ['ztfg', 'ztfr', 'ztfi']\n }\n\n assert np.allclose(mag1_ab, mag1_vega + vega_to_ab[data['data'][0]['filter']])\n assert np.allclose(magerr1_ab, magerr1_vega)\n\n assert np.allclose(\n maglast_ab, maglast_vega + vega_to_ab[data['data'][-1]['filter']]\n )\n assert np.allclose(magerrlast_ab, magerrlast_vega)\n\n\ndef test_token_user_retrieve_null_photometry(\n upload_data_token, public_source, ztf_camera, public_group\n):\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': None,\n 'magerr': None,\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n assert data['data']['flux'] is None\n\n np.testing.assert_allclose(\n data['data']['fluxerr'], 10 ** (-0.4 * (22.3 - 23.9)) / PHOT_DETECTION_THRESHOLD\n )\n\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=mag', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n assert data['data']['mag'] is None\n assert data['data']['magerr'] is None\n\n\ndef test_token_user_big_post(\n upload_data_token, public_source, ztf_camera, public_group\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': [58000 + i for i in range(50000)],\n 'instrument_id': ztf_camera.id,\n 'mag': np.random.uniform(low=18, high=22, size=50000).tolist(),\n 'magerr': np.random.uniform(low=0.1, high=0.3, size=50000).tolist(),\n 'limiting_mag': 22.3,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n\ndef test_token_user_get_range_photometry(\n upload_data_token, public_source, public_group, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': [58000.0, 58500.0, 59000.0],\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n status, data = api(\n 'GET',\n 'photometry/range',\n token=upload_data_token,\n data={'instrument_ids': [ztf_camera.id], 'max_date': '2018-05-15T00:00:00'},\n )\n assert status == 200\n assert data['status'] == 'success'\n assert len(data['data']) == 1\n\n status, data = api(\n 'GET',\n 'photometry/range?format=flux&magsys=vega',\n token=upload_data_token,\n data={'instrument_ids': [ztf_camera.id], 'max_date': '2019-02-01T00:00:00'},\n )\n assert status == 200\n assert data['status'] == 'success'\n assert len(data['data']) == 2\n\n\ndef test_reject_photometry_inf(\n upload_data_token, public_source, public_group, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': [58000.0, 58500.0, 59000.0],\n 'instrument_id': ztf_camera.id,\n 'flux': math.inf,\n 'fluxerr': math.inf,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n\n assert status == 400\n assert data['status'] == 'error'\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': math.inf,\n 'magerr': math.inf,\n 'limiting_mag': 22.3,\n 'magsys': 'vega',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n\n assert status == 400\n assert data['status'] == 'error'\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': 2.0,\n 'magerr': 23.0,\n 'limiting_mag': math.inf,\n 'magsys': 'vega',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n\n assert status == 400\n assert data['status'] == 'error'\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': 58000.0,\n 'instrument_id': ztf_camera.id,\n 'mag': None,\n 'magerr': None,\n 'limiting_mag': -math.inf,\n 'magsys': 'vega',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n\n assert status == 400\n assert data['status'] == 'error'\n\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source.id),\n 'mjd': [58000.0, 58500.0, 59000.0],\n 'instrument_id': ztf_camera.id,\n 'flux': None,\n 'fluxerr': math.inf,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group.id],\n },\n token=upload_data_token,\n )\n\n assert status == 400\n assert data['status'] == 'error'\n\n\ndef test_token_user_post_to_foreign_group_and_retrieve(\n upload_data_token, public_source_two_groups, public_group2, ztf_camera\n):\n status, data = api(\n 'POST',\n 'photometry',\n data={\n 'obj_id': str(public_source_two_groups.id),\n 'mjd': [58000.0, 58500.0, 59000.0],\n 'instrument_id': ztf_camera.id,\n 'flux': 12.24,\n 'fluxerr': 0.031,\n 'zp': 25.0,\n 'magsys': 'ab',\n 'filter': 'ztfg',\n 'group_ids': [public_group2.id],\n },\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n photometry_id = data['data']['ids'][0]\n status, data = api(\n 'GET', f'photometry/{photometry_id}?format=flux', token=upload_data_token\n )\n assert status == 200\n\n\ndef test_problematic_photometry_1263(\n upload_data_token, public_source, public_group, ztf_camera, public_group2\n):\n\n payload = {\n \"obj_id\": public_source.id,\n \"group_ids\": [public_group.id, public_group2.id],\n \"magsys\": \"ab\",\n \"zp\": 23.9,\n \"instrument_id\": ztf_camera.id,\n 'mjd': [\n 59145.46447,\n 59149.50347,\n 59149.50347,\n 59150.50872,\n 59150.50872,\n 59152.51631,\n 59155.50801,\n 59152.51631,\n 59155.50801,\n 59156.48479,\n 59156.48479,\n 59126.48693,\n 59128.46834,\n 59130.50257,\n 59135.47329,\n 59137.4758,\n 59139.45454,\n 59141.47449,\n 59143.50987,\n 59143.50987,\n 59145.46447,\n 59145.50556,\n 59150.52806,\n 59150.52806,\n 59151.52116,\n 59151.52116,\n 59152.48332,\n 59152.48332,\n 59155.50022,\n 59155.50022,\n 59156.5383,\n 59126.53144,\n 59128.51928,\n 59130.53196,\n 59135.51196,\n 59137.51334,\n 59139.51507,\n 59141.51422,\n 59143.48529,\n 59143.48529,\n 59145.50556,\n ],\n 'filter': [\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfg',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n 'ztfr',\n ],\n 'flux': [\n 105.4095462,\n 100.4989583,\n 100.4986052,\n 97.45052422,\n 97.45411937,\n 91.71425204,\n 81.08011148,\n 91.71489652,\n 81.08110854,\n 59.37327478,\n 59.37452643,\n None,\n None,\n None,\n 73.17457336,\n 82.20150344,\n 89.14970986,\n 102.1692537,\n 98.6103674,\n 98.60984771,\n 105.4086204,\n 100.8602976,\n 94.84847105,\n 94.85063718,\n 104.8945366,\n 104.8961951,\n 101.6093671,\n 101.6061542,\n 82.34545782,\n 82.34560248,\n 72.48165796,\n None,\n None,\n None,\n 61.60270207,\n 72.73101786,\n 83.83015488,\n 98.70066264,\n 99.85275375,\n 99.84977174,\n 100.8608292,\n ],\n 'fluxerr': [\n 8.416851743,\n 10.10817406,\n 10.10811785,\n 11.74314252,\n 11.74356103,\n 11.40505647,\n 10.61680918,\n 11.40514417,\n 10.61696199,\n 10.6736128,\n 10.67382477,\n 13.51668635,\n 18.71327665,\n 9.509339593,\n 9.374956127,\n 9.638764985,\n 11.98599464,\n 10.42671307,\n 9.666542673,\n 9.666476165,\n 8.41682049,\n 8.680180822,\n 9.926401394,\n 9.926617677,\n 8.494021784,\n 8.494115051,\n 9.984017125,\n 9.983686084,\n 7.964270439,\n 7.964306468,\n 8.499519049,\n 12.65289244,\n 11.39803573,\n 9.771246706,\n 7.839855173,\n 7.592658663,\n 8.674127848,\n 8.965488502,\n 7.69135795,\n 7.691126885,\n 8.680212034,\n ],\n }\n\n status, data = api(\n 'POST',\n 'photometry',\n data=payload,\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n payload = {\n \"obj_id\": public_source.id,\n \"group_ids\": \"all\",\n \"magsys\": \"ab\",\n \"instrument_id\": ztf_camera.id,\n \"filter\": [\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n \"ztfr\",\n \"ztfg\",\n \"ztfg\",\n \"ztfr\",\n \"ztfg\",\n \"ztfg\",\n \"ztfr\",\n \"ztfr\",\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n \"ztfg\",\n \"ztfg\",\n \"ztfr\",\n ],\n \"mjd\": [\n 59130.53195599979,\n 59135.473286999855,\n 59135.51195599977,\n 59137.47579859989,\n 59137.51334490022,\n 59139.45453700004,\n 59139.51506939996,\n 59141.474490699824,\n 59141.51422449993,\n 59143.48528939998,\n 59143.50987270009,\n 59145.46446759999,\n 59145.50555559993,\n 59149.50347220013,\n 59150.50871529989,\n 59150.52805559989,\n 59151.52115740022,\n 59152.4833217999,\n 59152.516307900194,\n 59155.50021990016,\n 59155.5080093001,\n 59156.4847916998,\n 59156.53829859989,\n ],\n \"limiting_mag\": [\n 19.67770004272461,\n 20.11709976196289,\n 20.059200286865234,\n 20.281099319458008,\n 20.224000930786133,\n 19.809099197387695,\n 20.236799240112305,\n 20.57659912109375,\n 20.31290054321289,\n 20.414499282836914,\n 20.680700302124023,\n 20.57069969177246,\n 20.48349952697754,\n 20.242000579833984,\n 20.642900466918945,\n 20.029699325561523,\n 20.11090087890625,\n 19.808948516845703,\n 19.819171905517578,\n 19.9112606048584,\n 19.913991928100586,\n 19.600677490234375,\n 20.005773544311523,\n ],\n \"mag\": [\n None,\n 19.239099502563477,\n 19.426000595092773,\n 19.11280059814453,\n 19.24570083618164,\n 19.024700164794922,\n 19.09149932861328,\n 18.876699447631836,\n 18.914199829101562,\n 18.901599884033203,\n 18.915199279785156,\n 18.84280014038086,\n 18.89069938659668,\n 18.89459991455078,\n 18.92799949645996,\n 18.957399368286133,\n 18.848100662231445,\n 18.882665634155273,\n 18.993907928466797,\n 19.110898971557617,\n 19.127714157104492,\n 19.466022491455078,\n 19.24942970275879,\n ],\n \"magerr\": [\n None,\n 0.1391019970178604,\n 0.13817599415779114,\n 0.12731100618839264,\n 0.11334399878978729,\n 0.1459749937057495,\n 0.11234399676322937,\n 0.11080300062894821,\n 0.09862300008535385,\n 0.0836310014128685,\n 0.1064319983124733,\n 0.08669500052928925,\n 0.09344000369310379,\n 0.10920300334692001,\n 0.13083499670028687,\n 0.11362800002098083,\n 0.08791899681091309,\n 0.1066831648349762,\n 0.13501590490341187,\n 0.10501029342412949,\n 0.14216870069503784,\n 0.19518424570560455,\n 0.12731821835041046,\n ],\n \"ra\": [\n None,\n 134.5934039,\n 134.5934169,\n 134.5933773,\n 134.593404,\n 134.593372,\n 134.5933825,\n 134.5933984,\n 134.5933945,\n 134.5933917,\n 134.5933988,\n 134.5933848,\n 134.5933991,\n 134.5933909,\n 134.5934048,\n 134.5934296,\n 134.5934341,\n 134.593388,\n 134.5933606,\n 134.5933857,\n 134.5933939,\n 134.5933847,\n 134.5933954,\n ],\n \"dec\": [\n None,\n 15.0412865,\n 15.041256,\n 15.0412686,\n 15.0412482,\n 15.0412709,\n 15.0412572,\n 15.0412656,\n 15.0412765,\n 15.0412744,\n 15.0412673,\n 15.041271,\n 15.0412726,\n 15.0413061,\n 15.0412751,\n 15.041267,\n 15.0412856,\n 15.0412655,\n 15.0412913,\n 15.0412952,\n 15.0412737,\n 15.0411913,\n 15.0412605,\n ],\n }\n\n status, data = api(\n 'POST',\n 'photometry',\n data=payload,\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n payload['group_ids'] = 'all'\n\n status, data = api(\n 'PUT',\n 'photometry',\n data=payload,\n token=upload_data_token,\n )\n assert status == 200\n assert data['status'] == 'success'\n\n for id in data['data']['ids']:\n status, data = api(\n 'GET', f'photometry/{id}?format=flux', token=upload_data_token\n )\n assert status == 200\n assert data['status'] == 'success'\n assert len(data['data']['groups']) == 2\n\n\ndef test_problematic_photometry_1276(\n public_source, public_group, super_admin_token, ztf_camera\n):\n payload = {\n \"obj_id\": public_source.id,\n \"group_ids\": [public_group.id],\n \"magsys\": \"ab\",\n \"instrument_id\": ztf_camera.id,\n \"filter\": [\n \"ztfg\",\n \"ztfr\",\n \"ztfr\",\n \"ztfr\",\n \"ztfr\",\n \"ztfr\",\n \"ztfr\",\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n \"ztfr\",\n \"ztfg\",\n \"ztfg\",\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n \"ztfr\",\n \"ztfr\",\n \"ztfg\",\n \"ztfg\",\n \"ztfg\",\n \"ztfg\",\n \"ztfr\",\n \"ztfr\",\n \"ztfg\",\n \"ztfg\",\n \"ztfr\",\n \"ztfg\",\n \"ztfr\",\n ],\n \"mjd\": [\n 59123.41299769981,\n 59129.472291700076,\n 59134.451203700155,\n 59136.46903940011,\n 59136.46903940011,\n 59139.295057899784,\n 59139.295057899784,\n 59139.295057899784,\n 59139.389629600104,\n 59141.36341439979,\n 59141.36341439979,\n 59141.414189800154,\n 59141.414189800154,\n 59143.318460599985,\n 59143.39145829994,\n 59145.34545140015,\n 59145.34545140015,\n 59145.34545140015,\n 59145.41583329998,\n 59145.41583329998,\n 59149.4703819002,\n 59151.32671299996,\n 59151.33918979997,\n 59153.33692129981,\n 59153.404351899866,\n 59155.220972199924,\n 59155.290161999874,\n 59157.360347200185,\n 59157.433634299785,\n ],\n \"limiting_mag\": [\n 19.396099090576172,\n 20.23240089416504,\n 20.129100799560547,\n 20.493600845336914,\n 20.493600845336914,\n 20.422000885009766,\n 20.422000885009766,\n 20.422000885009766,\n 20.272199630737305,\n 20.18910026550293,\n 20.18910026550293,\n 20.846799850463867,\n 20.846799850463867,\n 20.624300003051758,\n 20.854000091552734,\n 20.628799438476562,\n 20.628799438476562,\n 20.628799438476562,\n 20.840900421142578,\n 20.840900421142578,\n 20.32859992980957,\n 19.60849952697754,\n 19.705799102783203,\n 19.47800064086914,\n 19.409400939941406,\n 19.462600708007812,\n 19.77630043029785,\n 19.678672790527344,\n 19.754121780395508,\n ],\n \"mag\": [\n 18.43560028076172,\n 17.338199615478516,\n 16.25189971923828,\n 16.011999130249023,\n 16.09589958190918,\n 15.974100112915039,\n 15.891500473022461,\n 15.891500473022461,\n None,\n 15.753999710083008,\n 15.819600105285645,\n 18.528499603271484,\n 18.57939910888672,\n 15.781000137329102,\n 18.309499740600586,\n 15.692399978637695,\n 15.692399978637695,\n 15.790599822998047,\n 18.305700302124023,\n 18.31529998779297,\n 18.13994026184082,\n 18.040000915527344,\n 15.505499839782715,\n 15.569299697875977,\n 17.812599182128906,\n 18.046100616455078,\n None,\n 17.95865249633789,\n 15.475956916809082,\n ],\n \"magerr\": [\n 0.18098600208759308,\n 0.12704600393772125,\n 0.03412500023841858,\n 0.018530000001192093,\n 0.09321600198745728,\n 0.1358170062303543,\n 0.017785999923944473,\n 0.017785999923944473,\n None,\n 0.017010999843478203,\n 0.0650859996676445,\n 0.1969199925661087,\n 0.08772700279951096,\n 0.05595200136303902,\n 0.17250700294971466,\n 0.0137339998036623,\n 0.0137339998036623,\n 0.06520400196313858,\n 0.06727799773216248,\n 0.13235700130462646,\n 0.12975013256072998,\n 0.11010699719190598,\n 0.04597700014710426,\n 0.049855999648571014,\n 0.10752200335264206,\n 0.13239599764347076,\n None,\n 0.139614999294281,\n 0.042450759559869766,\n ],\n \"ra\": [\n 56.0478815,\n 56.0468989,\n 56.0478,\n 56.0478343,\n 56.0480658,\n 56.0475873,\n 56.047908,\n 56.0480877,\n None,\n 56.0476469,\n 56.0477499,\n 56.047177,\n 56.0469751,\n 56.0480999,\n 56.0470656,\n 56.0477652,\n 56.0476761,\n 56.0476218,\n 56.0469908,\n 56.0472491,\n 56.0467978,\n 56.0472009,\n 56.0478524,\n 56.0476997,\n 56.0471999,\n 56.0476057,\n None,\n 56.0473734,\n 56.0477336,\n ],\n \"dec\": [\n 71.6368125,\n 71.6367721,\n 71.6367167,\n 71.6367615,\n 71.6367048,\n 71.6368681,\n 71.6368457,\n 71.6368389,\n None,\n 71.6367596,\n 71.6365229,\n 71.6367611,\n 71.6368439,\n 71.6367764,\n 71.6368222,\n 71.6367943,\n 71.6368108,\n 71.6367366,\n 71.6368412,\n 71.6367895,\n 71.6368039,\n 71.6367984,\n 71.6367866,\n 71.6367788,\n 71.6368348,\n 71.6367571,\n None,\n 71.6367753,\n 71.6367119,\n ],\n }\n\n status, data = api(\n 'PUT',\n 'photometry',\n data=payload,\n token=super_admin_token,\n )\n assert status == 400\n assert data['status'] == 'error'\n" ]
[ [ "numpy.random.uniform", "numpy.allclose", "numpy.log", "numpy.log10", "numpy.testing.assert_allclose" ] ]
smolendawid/ubaar-competition
[ "28de972d6beb13343c537fc030101be672a852a3" ]
[ "feature_extraction/other_features.py" ]
[ "import pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\n\n\ndef categorical_features(data, features):\n features['vehicleType'] = data['vehicleType']\n features['vehicleOption'] = data['vehicleOption']\n\n features['vehicleTypeOption'] = [a + '_' + b for a, b in zip(data['vehicleType'].values,\n data['vehicleOption'].values)]\n\n cat_columns_clusters = ['cluster_dest_db', 'cluster_src_db', 'cluster_src_km', 'cluster_dest_km']\n cat_columns_date = ['day', 'month']\n cat_columns = ['vehicleType', 'vehicleOption', 'vehicleTypeOption']\n # cat_columns += cat_columns_clusters\n # cat_columns += cat_columns_date\n\n features = pd.get_dummies(features, columns=cat_columns, drop_first=True)\n\n features['day'] = LabelEncoder().fit_transform(features['day'])\n features['month'] = LabelEncoder().fit_transform(features['month'])\n\n return features\n\n\ndef raw_features(data, features):\n features['weight'] = data['weight']\n features['distanceKM'] = data['distanceKM']\n features['taxiDurationMin'] = data['taxiDurationMin']\n\n features['sourceLatitude'] = data['sourceLatitude']\n features['sourceLongitude'] = data['sourceLongitude']\n features['destinationLatitude'] = data['destinationLatitude']\n features['destinationLongitude'] = data['destinationLongitude']\n\n features['src_dest'] = (data['SourceState'] == data['destinationState'])\n features['ave_speed'] = data['distanceKM'] / data['taxiDurationMin']\n\n import numpy as np\n features['weight_dur'] = np.log((data['taxiDurationMin'] + 30 * data['weight']))\n features['weight_dist_dur'] = np.log(1. + (10. + data['weight']) * (100. + data['distanceKM']) *\n (1000. + data['taxiDurationMin']))\n\n features['price'] = data['price']\n\n return features\n" ]
[ [ "sklearn.preprocessing.LabelEncoder", "numpy.log", "pandas.get_dummies" ] ]
nicolasoyharcabal/tensorflow
[ "0d3b58cfe91c6b865a14701345d7a84ce949c0e3" ]
[ "tensorflow/python/data/experimental/ops/batching.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\"\"\"Batching dataset transformations.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.data.experimental.ops import get_single_element\nfrom tensorflow.python.data.experimental.ops import grouping\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.util import convert\nfrom tensorflow.python.data.util import nest\nfrom tensorflow.python.data.util import sparse\nfrom tensorflow.python.data.util import structure\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.util.tf_export import tf_export\n\n\ndef batch_window(dataset):\n \"\"\"Batches a window of tensors.\n\n Args:\n dataset: the input dataset.\n\n Returns:\n A `Tensor` representing the batch of the entire input dataset.\n \"\"\"\n if isinstance(dataset.output_classes, tuple):\n raise TypeError(\"Input dataset expected to have a single component\")\n if dataset.output_classes is ops.Tensor:\n return _batch_dense_window(dataset)\n elif dataset.output_classes is sparse_tensor.SparseTensor:\n return _batch_sparse_window(dataset)\n else:\n raise TypeError(\"Unsupported dataset type: %s\" % dataset.output_classes)\n\n\ndef _batch_dense_window(dataset):\n \"\"\"Batches a window of dense tensors.\"\"\"\n\n def key_fn(_):\n return np.int64(0)\n\n def shape_init_fn(_):\n return array_ops.shape(first_element)\n\n def shape_reduce_fn(state, value):\n check_ops.assert_equal(state, array_ops.shape(value))\n return state\n\n def finalize_fn(state):\n return state\n\n if dataset.output_shapes.is_fully_defined():\n shape = dataset.output_shapes\n else:\n first_element = get_single_element.get_single_element(dataset.take(1))\n shape_reducer = grouping.Reducer(shape_init_fn, shape_reduce_fn,\n finalize_fn)\n shape = get_single_element.get_single_element(\n dataset.apply(grouping.group_by_reducer(key_fn, shape_reducer)))\n\n def batch_init_fn(_):\n batch_shape = array_ops.concat([[0], shape], 0)\n return gen_array_ops.empty(batch_shape, dtype=dataset.output_types)\n\n def batch_reduce_fn(state, value):\n return array_ops.concat([state, [value]], 0)\n\n batch_reducer = grouping.Reducer(batch_init_fn, batch_reduce_fn, finalize_fn)\n return get_single_element.get_single_element(\n dataset.apply(grouping.group_by_reducer(key_fn, batch_reducer)))\n\n\ndef _batch_sparse_window(dataset):\n \"\"\"Batches a window of sparse tensors.\"\"\"\n\n def key_fn(_):\n return np.int64(0)\n\n def shape_init_fn(_):\n return first_element.dense_shape\n\n def shape_reduce_fn(state, value):\n check_ops.assert_equal(state, value.dense_shape)\n return state\n\n def finalize_fn(state):\n return state\n\n if dataset.output_shapes.is_fully_defined():\n shape = dataset.output_shapes\n else:\n first_element = get_single_element.get_single_element(dataset.take(1))\n shape_reducer = grouping.Reducer(shape_init_fn, shape_reduce_fn,\n finalize_fn)\n shape = get_single_element.get_single_element(\n dataset.apply(grouping.group_by_reducer(key_fn, shape_reducer)))\n\n def batch_init_fn(_):\n indices_shape = array_ops.concat([[0], [array_ops.size(shape) + 1]], 0)\n return sparse_tensor.SparseTensor(\n indices=gen_array_ops.empty(indices_shape, dtype=dtypes.int64),\n values=constant_op.constant([], shape=[0], dtype=dataset.output_types),\n dense_shape=array_ops.concat(\n [np.array([0], dtype=np.int64),\n math_ops.cast(shape, dtypes.int64)], 0))\n\n def batch_reduce_fn(state, value):\n return sparse_ops.sparse_concat(0, [state, value])\n\n def reshape_fn(value):\n return sparse_ops.sparse_reshape(\n value,\n array_ops.concat([np.array([1], dtype=np.int64), value.dense_shape], 0))\n\n batch_reducer = grouping.Reducer(batch_init_fn, batch_reduce_fn, finalize_fn)\n return get_single_element.get_single_element(\n dataset.map(reshape_fn).apply(\n grouping.group_by_reducer(key_fn, batch_reducer)))\n\n\n@tf_export(\"data.experimental.dense_to_sparse_batch\")\ndef dense_to_sparse_batch(batch_size, row_shape):\n \"\"\"A transformation that batches ragged elements into `tf.SparseTensor`s.\n\n Like `Dataset.padded_batch()`, this transformation combines multiple\n consecutive elements of the dataset, which might have different\n shapes, into a single element. The resulting element has three\n components (`indices`, `values`, and `dense_shape`), which\n comprise a `tf.SparseTensor` that represents the same data. The\n `row_shape` represents the dense shape of each row in the\n resulting `tf.SparseTensor`, to which the effective batch size is\n prepended. For example:\n\n ```python\n # NOTE: The following examples use `{ ... }` to represent the\n # contents of a dataset.\n a = { ['a', 'b', 'c'], ['a', 'b'], ['a', 'b', 'c', 'd'] }\n\n a.apply(tf.data.experimental.dense_to_sparse_batch(\n batch_size=2, row_shape=[6])) ==\n {\n ([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], # indices\n ['a', 'b', 'c', 'a', 'b'], # values\n [2, 6]), # dense_shape\n ([[0, 0], [0, 1], [0, 2], [0, 3]],\n ['a', 'b', 'c', 'd'],\n [1, 6])\n }\n ```\n\n Args:\n batch_size: A `tf.int64` scalar `tf.Tensor`, representing the\n number of consecutive elements of this dataset to combine in a\n single batch.\n row_shape: A `tf.TensorShape` or `tf.int64` vector tensor-like\n object representing the equivalent dense shape of a row in the\n resulting `tf.SparseTensor`. Each element of this dataset must\n have the same rank as `row_shape`, and must have size less\n than or equal to `row_shape` in each dimension.\n\n Returns:\n A `Dataset` transformation function, which can be passed to\n `tf.data.Dataset.apply`.\n \"\"\"\n\n def _apply_fn(dataset):\n return _DenseToSparseBatchDataset(dataset, batch_size, row_shape)\n\n return _apply_fn\n\n\ndef padded_batch_window(dataset, padded_shape, padding_value=None):\n \"\"\"Batches a window of tensors with padding.\n\n Args:\n dataset: the input dataset.\n padded_shape: (Optional.) `tf.TensorShape` or `tf.int64` vector tensor-like\n object representing the shape to which the input elements should be padded\n prior to batching. Any unknown dimensions (e.g. `tf.Dimension(None)` in a\n `tf.TensorShape` or `-1` in a tensor-like object) will be padded to the\n maximum size of that dimension in each batch.\n padding_value: (Optional.) A scalar-shaped `tf.Tensor`, representing the\n padding value to use. Defaults are `0` for numeric types and the empty\n string for string types. If `dataset` contains `tf.SparseTensor`, this\n value is ignored.\n\n Returns:\n A `Tensor` representing the batch of the entire input dataset.\n\n Raises:\n ValueError: if invalid arguments are provided.\n \"\"\"\n if not issubclass(dataset.output_classes,\n (ops.Tensor, sparse_tensor.SparseTensor)):\n raise TypeError(\"Input dataset expected to have a single tensor component\")\n if issubclass(dataset.output_classes, (ops.Tensor)):\n return _padded_batch_dense_window(dataset, padded_shape, padding_value)\n elif issubclass(dataset.output_classes, (sparse_tensor.SparseTensor)):\n if padding_value is not None:\n raise ValueError(\"Padding value not allowed for sparse tensors\")\n return _padded_batch_sparse_window(dataset, padded_shape)\n else:\n raise TypeError(\"Unsupported dataset type: %s\" % dataset.output_classes)\n\n\ndef _padded_batch_dense_window(dataset, padded_shape, padding_value=None):\n \"\"\"Batches a window of dense tensors with padding.\"\"\"\n\n padded_shape = math_ops.cast(\n convert.partial_shape_to_tensor(padded_shape), dtypes.int32)\n\n def key_fn(_):\n return np.int64(0)\n\n def max_init_fn(_):\n return padded_shape\n\n def max_reduce_fn(state, value):\n \"\"\"Computes the maximum shape to pad to.\"\"\"\n condition = math_ops.reduce_all(\n math_ops.logical_or(\n math_ops.less_equal(array_ops.shape(value), padded_shape),\n math_ops.equal(padded_shape, -1)))\n assert_op = control_flow_ops.Assert(condition, [\n \"Actual shape greater than padded shape: \",\n array_ops.shape(value), padded_shape\n ])\n with ops.control_dependencies([assert_op]):\n return math_ops.maximum(state, array_ops.shape(value))\n\n def finalize_fn(state):\n return state\n\n # Compute the padded shape.\n max_reducer = grouping.Reducer(max_init_fn, max_reduce_fn, finalize_fn)\n padded_shape = get_single_element.get_single_element(\n dataset.apply(grouping.group_by_reducer(key_fn, max_reducer)))\n\n if padding_value is None:\n if dataset.output_types == dtypes.string:\n padding_value = \"\"\n elif dataset.output_types == dtypes.bool:\n padding_value = False\n elif dataset.output_types == dtypes.variant:\n raise TypeError(\"Unable to create padding for field of type 'variant'\")\n else:\n padding_value = 0\n\n def batch_init_fn(_):\n batch_shape = array_ops.concat(\n [np.array([0], dtype=np.int32), padded_shape], 0)\n return gen_array_ops.empty(batch_shape, dtype=dataset.output_types)\n\n def batch_reduce_fn(state, value):\n return array_ops.concat([state, [value]], 0)\n\n def pad_fn(value):\n shape = array_ops.shape(value)\n left = array_ops.zeros_like(shape)\n right = padded_shape - shape\n return array_ops.pad(\n value, array_ops.stack([left, right], 1), constant_values=padding_value)\n\n batch_reducer = grouping.Reducer(batch_init_fn, batch_reduce_fn, finalize_fn)\n return get_single_element.get_single_element(\n dataset.map(pad_fn).apply(\n grouping.group_by_reducer(key_fn, batch_reducer)))\n\n\ndef _padded_batch_sparse_window(dataset, padded_shape):\n \"\"\"Batches a window of sparse tensors with padding.\"\"\"\n\n def key_fn(_):\n return np.int64(0)\n\n def max_init_fn(_):\n return convert.partial_shape_to_tensor(padded_shape)\n\n def max_reduce_fn(state, value):\n \"\"\"Computes the maximum shape to pad to.\"\"\"\n condition = math_ops.reduce_all(\n math_ops.logical_or(\n math_ops.less_equal(value.dense_shape, padded_shape),\n math_ops.equal(padded_shape, -1)))\n assert_op = control_flow_ops.Assert(condition, [\n \"Actual shape greater than padded shape: \", value.dense_shape,\n padded_shape\n ])\n with ops.control_dependencies([assert_op]):\n return math_ops.maximum(state, value.dense_shape)\n\n def finalize_fn(state):\n return state\n\n # Compute the padded shape.\n max_reducer = grouping.Reducer(max_init_fn, max_reduce_fn, finalize_fn)\n padded_shape = get_single_element.get_single_element(\n dataset.apply(grouping.group_by_reducer(key_fn, max_reducer)))\n\n def batch_init_fn(_):\n indices_shape = array_ops.concat([[0], [array_ops.size(padded_shape) + 1]],\n 0)\n return sparse_tensor.SparseTensor(\n indices=gen_array_ops.empty(indices_shape, dtype=dtypes.int64),\n values=constant_op.constant([], shape=[0], dtype=dataset.output_types),\n dense_shape=array_ops.concat(\n [np.array([0], dtype=np.int64), padded_shape], 0))\n\n def batch_reduce_fn(state, value):\n padded_value = sparse_tensor.SparseTensor(\n indices=value.indices, values=value.values, dense_shape=padded_shape)\n reshaped_value = sparse_ops.sparse_reshape(\n padded_value,\n array_ops.concat(\n [np.array([1], dtype=np.int64), padded_value.dense_shape], 0))\n return sparse_ops.sparse_concat(0, [state, reshaped_value])\n\n reducer = grouping.Reducer(batch_init_fn, batch_reduce_fn, finalize_fn)\n return get_single_element.get_single_element(\n dataset.apply(grouping.group_by_reducer(key_fn, reducer)))\n\n\nclass _UnbatchDataset(dataset_ops.UnaryDataset):\n \"\"\"A dataset that splits the elements of its input into multiple elements.\"\"\"\n\n def __init__(self, input_dataset):\n \"\"\"See `unbatch()` for more details.\"\"\"\n super(_UnbatchDataset, self).__init__(input_dataset)\n flat_shapes = nest.flatten(input_dataset.output_shapes)\n if any(s.ndims == 0 for s in flat_shapes):\n raise ValueError(\"Cannot unbatch an input with scalar components.\")\n known_batch_dim = tensor_shape.Dimension(None)\n for s in flat_shapes:\n try:\n known_batch_dim = known_batch_dim.merge_with(s[0])\n except ValueError:\n raise ValueError(\"Cannot unbatch an input whose components have \"\n \"different batch sizes.\")\n self._input_dataset = input_dataset\n\n self._structure = structure.convert_legacy_structure(\n input_dataset.output_types,\n nest.map_structure(lambda s: s[1:], input_dataset.output_shapes),\n input_dataset.output_classes)\n\n def _as_variant_tensor(self):\n return ged_ops.experimental_unbatch_dataset(\n self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access\n **dataset_ops.flat_structure(self))\n\n @property\n def _element_structure(self):\n return self._structure\n\n\n@tf_export(\"data.experimental.unbatch\")\ndef unbatch():\n \"\"\"Splits elements of a dataset into multiple elements on the batch dimension.\n\n For example, if elements of the dataset are shaped `[B, a0, a1, ...]`,\n where `B` may vary for each input element, then for each element in the\n dataset, the unbatched dataset will contain `B` consecutive elements\n of shape `[a0, a1, ...]`.\n\n ```python\n # NOTE: The following example uses `{ ... }` to represent the contents\n # of a dataset.\n a = { ['a', 'b', 'c'], ['a', 'b'], ['a', 'b', 'c', 'd'] }\n\n a.apply(tf.data.experimental.unbatch()) == {\n 'a', 'b', 'c', 'a', 'b', 'a', 'b', 'c', 'd'}\n ```\n\n Returns:\n A `Dataset` transformation function, which can be passed to\n `tf.data.Dataset.apply`.\n \"\"\"\n\n def _apply_fn(dataset):\n \"\"\"Function from `Dataset` to `Dataset` that applies the transformation.\"\"\"\n if not sparse.any_sparse(dataset.output_classes):\n return _UnbatchDataset(dataset)\n\n # NOTE(mrry): We must ensure that any SparseTensors in `dataset`\n # are normalized to the rank-1 dense representation, so that the\n # sparse-oblivious unbatching logic will slice them\n # appropriately. This leads to a somewhat inefficient re-encoding step\n # for all SparseTensor components.\n # TODO(mrry): Consider optimizing this in future\n # if it turns out to be a bottleneck.\n def normalize(arg, *rest):\n if rest:\n return sparse.serialize_many_sparse_tensors((arg,) + rest)\n else:\n return sparse.serialize_many_sparse_tensors(arg)\n\n normalized_dataset = dataset.map(normalize)\n\n # NOTE(mrry): Our `map()` has lost information about the sparseness\n # of any SparseTensor components, so re-apply the structure of the\n # original dataset.\n restructured_dataset = _RestructuredDataset(\n normalized_dataset,\n dataset.output_types,\n dataset.output_shapes,\n dataset.output_classes,\n allow_unsafe_cast=True)\n return _UnbatchDataset(restructured_dataset)\n\n return _apply_fn\n\n\nclass _DenseToSparseBatchDataset(dataset_ops.UnaryDataset):\n \"\"\"A `Dataset` that batches ragged dense elements into `tf.SparseTensor`s.\"\"\"\n\n def __init__(self, input_dataset, batch_size, row_shape):\n \"\"\"See `Dataset.dense_to_sparse_batch()` for more details.\"\"\"\n super(_DenseToSparseBatchDataset, self).__init__(input_dataset)\n if not isinstance(input_dataset.output_types, dtypes.DType):\n raise TypeError(\"DenseToSparseDataset requires an input whose elements \"\n \"have a single component, whereas the input has %r.\" %\n input_dataset.output_types)\n self._input_dataset = input_dataset\n self._batch_size = batch_size\n self._row_shape = row_shape\n self._structure = structure.SparseTensorStructure(\n input_dataset.output_types,\n tensor_shape.vector(None).concatenate(self._row_shape))\n\n def _as_variant_tensor(self):\n return ged_ops.experimental_dense_to_sparse_batch_dataset(\n self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access\n self._batch_size,\n row_shape=convert.partial_shape_to_tensor(self._row_shape),\n **dataset_ops.flat_structure(self))\n\n @property\n def _element_structure(self):\n return self._structure\n\n\nclass _RestructuredDataset(dataset_ops.UnaryDataset):\n \"\"\"An internal helper for changing the structure and shape of a dataset.\"\"\"\n\n def __init__(self,\n dataset,\n output_types,\n output_shapes=None,\n output_classes=None,\n allow_unsafe_cast=False):\n \"\"\"Creates a new dataset with the given output types and shapes.\n\n The given `dataset` must have a structure that is convertible:\n * `dataset.output_types` must be the same as `output_types` module nesting.\n * Each shape in `dataset.output_shapes` must be compatible with each shape\n in `output_shapes` (if given).\n\n Note: This helper permits \"unsafe casts\" for shapes, equivalent to using\n `tf.Tensor.set_shape()` where domain-specific knowledge is available.\n\n Args:\n dataset: A `Dataset` object.\n output_types: A nested structure of `tf.DType` objects.\n output_shapes: (Optional.) A nested structure of `tf.TensorShape` objects.\n If omitted, the shapes will be inherited from `dataset`.\n output_classes: (Optional.) A nested structure of class types.\n If omitted, the class types will be inherited from `dataset`.\n allow_unsafe_cast: (Optional.) If `True`, the caller may switch the\n reported output types and shapes of the restructured dataset, e.g. to\n switch a sparse tensor represented as `tf.variant` to its user-visible\n type and shape.\n\n Raises:\n ValueError: If either `output_types` or `output_shapes` is not compatible\n with the structure of `dataset`.\n \"\"\"\n super(_RestructuredDataset, self).__init__(dataset)\n self._input_dataset = dataset\n\n if not allow_unsafe_cast:\n # Validate that the types are compatible.\n output_types = nest.map_structure(dtypes.as_dtype, output_types)\n flat_original_types = nest.flatten(dataset.output_types)\n flat_new_types = nest.flatten(output_types)\n if flat_original_types != flat_new_types:\n raise ValueError(\n \"Dataset with output types %r cannot be restructured to have \"\n \"output types %r\" % (dataset.output_types, output_types))\n\n if output_shapes is None:\n # Inherit shapes from the original `dataset`.\n output_shapes = nest.pack_sequence_as(\n output_types, nest.flatten(dataset.output_shapes))\n else:\n if not allow_unsafe_cast:\n # Validate that the shapes are compatible.\n nest.assert_same_structure(output_types, output_shapes)\n flat_original_shapes = nest.flatten(dataset.output_shapes)\n flat_new_shapes = nest.flatten_up_to(output_types, output_shapes)\n\n for original_shape, new_shape in zip(flat_original_shapes,\n flat_new_shapes):\n if not original_shape.is_compatible_with(new_shape):\n raise ValueError(\n \"Dataset with output shapes %r cannot be restructured to have \"\n \"incompatible output shapes %r\" % (dataset.output_shapes,\n output_shapes))\n output_shapes = nest.map_structure_up_to(\n output_types, tensor_shape.as_shape, output_shapes)\n if output_classes is None:\n # Inherit class types from the original `dataset`.\n output_classes = nest.pack_sequence_as(\n output_types, nest.flatten(dataset.output_classes))\n\n self._structure = structure.convert_legacy_structure(\n output_types, output_shapes, output_classes)\n\n def _as_variant_tensor(self):\n return self._input_dataset._as_variant_tensor() # pylint: disable=protected-access\n\n @property\n def _element_structure(self):\n return self._structure\n\n\nclass _MapAndBatchDataset(dataset_ops.UnaryDataset):\n \"\"\"A `Dataset` that maps a function over a batch of elements.\"\"\"\n\n def __init__(self, input_dataset, map_func, batch_size, num_parallel_calls,\n drop_remainder):\n \"\"\"See `Dataset.map()` for details.\"\"\"\n super(_MapAndBatchDataset, self).__init__(input_dataset)\n self._input_dataset = input_dataset\n self._map_func = dataset_ops.StructuredFunctionWrapper(\n map_func, \"tf.data.experimental.map_and_batch()\", dataset=input_dataset)\n self._batch_size_t = ops.convert_to_tensor(\n batch_size, dtype=dtypes.int64, name=\"batch_size\")\n self._num_parallel_calls_t = ops.convert_to_tensor(\n num_parallel_calls, dtype=dtypes.int64, name=\"num_parallel_calls\")\n self._drop_remainder_t = ops.convert_to_tensor(\n drop_remainder, dtype=dtypes.bool, name=\"drop_remainder\")\n\n constant_drop_remainder = tensor_util.constant_value(self._drop_remainder_t)\n if constant_drop_remainder:\n # NOTE(mrry): `constant_drop_remainder` may be `None` (unknown statically)\n # or `False` (explicitly retaining the remainder).\n self._structure = self._map_func.output_structure._batch( # pylint: disable=protected-access\n tensor_util.constant_value(self._batch_size_t))\n else:\n self._structure = self._map_func.output_structure._batch(None) # pylint: disable=protected-access\n\n def _functions(self):\n return [self._map_func]\n\n def _as_variant_tensor(self):\n # pylint: disable=protected-access\n return ged_ops.experimental_map_and_batch_dataset(\n self._input_dataset._as_variant_tensor(),\n self._map_func.function.captured_inputs,\n f=self._map_func.function,\n batch_size=self._batch_size_t,\n num_parallel_calls=self._num_parallel_calls_t,\n drop_remainder=self._drop_remainder_t,\n preserve_cardinality=True,\n **dataset_ops.flat_structure(self))\n\n @property\n def _element_structure(self):\n return self._structure\n\n\n@tf_export(\"data.experimental.map_and_batch\")\ndef map_and_batch(map_func,\n batch_size,\n num_parallel_batches=None,\n drop_remainder=False,\n num_parallel_calls=None):\n \"\"\"Fused implementation of `map` and `batch`.\n\n Maps `map_func` across `batch_size` consecutive elements of this dataset\n and then combines them into a batch. Functionally, it is equivalent to `map`\n followed by `batch`. However, by fusing the two transformations together, the\n implementation can be more efficient. Surfacing this transformation in the API\n is temporary. Once automatic input pipeline optimization is implemented,\n the fusing of `map` and `batch` will happen automatically and this API will be\n deprecated.\n\n Args:\n map_func: A function mapping a nested structure of tensors to another\n nested structure of tensors.\n batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of\n consecutive elements of this dataset to combine in a single batch.\n num_parallel_batches: (Optional.) A `tf.int64` scalar `tf.Tensor`,\n representing the number of batches to create in parallel. On one hand,\n higher values can help mitigate the effect of stragglers. On the other\n hand, higher values can increase contention if CPU is scarce.\n drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing\n whether the last batch should be dropped in case its size is smaller than\n desired; the default behavior is not to drop the smaller batch.\n num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`,\n representing the number of elements to process in parallel. If not\n specified, `batch_size * num_parallel_batches` elements will be processed\n in parallel. If the value `tf.data.experimental.AUTOTUNE` is used, then\n the number of parallel calls is set dynamically based on available CPU.\n\n Returns:\n A `Dataset` transformation function, which can be passed to\n `tf.data.Dataset.apply`.\n\n Raises:\n ValueError: If both `num_parallel_batches` and `num_parallel_calls` are\n specified.\n \"\"\"\n\n if num_parallel_batches is None and num_parallel_calls is None:\n num_parallel_calls = batch_size\n elif num_parallel_batches is not None and num_parallel_calls is None:\n num_parallel_calls = batch_size * num_parallel_batches\n elif num_parallel_batches is not None and num_parallel_calls is not None:\n raise ValueError(\"The `num_parallel_batches` and `num_parallel_calls` \"\n \"arguments are mutually exclusive.\")\n\n def _apply_fn(dataset):\n return _MapAndBatchDataset(dataset, map_func, batch_size,\n num_parallel_calls, drop_remainder)\n\n return _apply_fn\n" ]
[ [ "tensorflow.python.ops.math_ops.equal", "tensorflow.python.data.util.sparse.serialize_many_sparse_tensors", "tensorflow.python.data.util.nest.flatten_up_to", "tensorflow.python.ops.math_ops.maximum", "numpy.int64", "tensorflow.python.data.util.nest.flatten", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.data.ops.dataset_ops.flat_structure", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.data.ops.dataset_ops.StructuredFunctionWrapper", "tensorflow.python.data.experimental.ops.grouping.group_by_reducer", "tensorflow.python.ops.sparse_ops.sparse_concat", "tensorflow.python.data.util.structure.convert_legacy_structure", "tensorflow.python.ops.gen_array_ops.empty", "tensorflow.python.ops.array_ops.size", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.data.util.nest.map_structure_up_to", "tensorflow.python.ops.control_flow_ops.Assert", "tensorflow.python.framework.tensor_shape.Dimension", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.data.util.sparse.any_sparse", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.data.util.nest.map_structure", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.data.util.convert.partial_shape_to_tensor", "tensorflow.python.ops.check_ops.assert_equal", "tensorflow.python.data.util.nest.assert_same_structure", "tensorflow.python.data.experimental.ops.grouping.Reducer", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.math_ops.less_equal", "numpy.array", "tensorflow.python.framework.tensor_shape.vector" ] ]
jsonbruce/MTSAnomalyDetection
[ "94e1b3177f8260804a4f9079ce7358f984521471" ]
[ "test/prophet_model.py" ]
[ "#!/usr/bin/env python\n# coding=utf-8\n\n# Created by max on 17-5-4.\n\nimport os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom fbprophet import Prophet\nfrom pandas import Series, DataFrame\n\n\nDATA_FILE = \"dataset/data0.csv\"\n\ndef main(args):\n data = pd.read_csv(DATA_FILE, parse_dates=True, index_col='timestamp')\n\n # Re-group data to fit for Prophet data format\n data['ds'] = data.index\n data = data.reindex(columns=['ds', 'v0', 'v1', 'result'])\n data = data.rename(columns={\"v0\": 'y'})\n\n model = Prophet()\n model.fit(data.ix[data.index[0:500]])\n\n future = model.make_future_dataframe(120, 'H')\n forecast = model.predict(future)\n\n model.plot(forecast)\n model.plot_components(forecast)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main(sys.argv)" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.show" ] ]
FeryET/pytorch-lightning
[ "b1f8b111b5085373599758a4e155a482259cdbf0" ]
[ "tests/lite/test_wrappers.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom unittest.mock import ANY, Mock\n\nimport pytest\nimport torch\nfrom torch.utils.data.dataloader import DataLoader\n\nfrom pytorch_lightning.core.mixins import DeviceDtypeModuleMixin\nfrom pytorch_lightning.lite import LightningLite\nfrom pytorch_lightning.lite.wrappers import _LiteDataLoader, _LiteModule, _LiteOptimizer\nfrom tests.helpers.runif import RunIf\n\n\nclass EmptyLite(LightningLite):\n def run(self):\n pass\n\n\ndef test_lite_module_wraps():\n \"\"\"Test that the wrapped module is accessible via the property.\"\"\"\n module = Mock()\n assert _LiteModule(module, Mock()).module is module\n\n\n@RunIf(min_gpus=1)\[email protected](\n \"precision, input_type, expected_type\",\n [\n (32, torch.float16, torch.float32),\n (32, torch.float32, torch.float32),\n (32, torch.float64, torch.float32),\n (32, torch.int, torch.int),\n (16, torch.float32, torch.float16),\n (16, torch.float64, torch.float16),\n (16, torch.long, torch.long),\n pytest.param(\"bf16\", torch.float32, torch.bfloat16, marks=RunIf(min_torch=\"1.10\")),\n pytest.param(\"bf16\", torch.float64, torch.bfloat16, marks=RunIf(min_torch=\"1.10\")),\n pytest.param(\"bf16\", torch.bool, torch.bool, marks=RunIf(min_torch=\"1.10\")),\n ],\n)\ndef test_lite_module_forward_conversion(precision, input_type, expected_type):\n \"\"\"Test that the LiteModule performs autocasting on the input tensors and during forward().\"\"\"\n lite = EmptyLite(precision=precision, accelerator=\"gpu\", devices=1)\n device = torch.device(\"cuda\", 0)\n\n def check_autocast(forward_input):\n assert precision != 16 or torch.is_autocast_enabled()\n return forward_input\n\n module = Mock(wraps=torch.nn.Identity(), side_effect=check_autocast)\n lite_module = _LiteModule(module, lite._precision_plugin).to(device)\n out = lite_module(torch.tensor([1, 2, 3], dtype=input_type, device=device))\n assert module.call_args[0][0].dtype == expected_type\n assert out.dtype == input_type or out.dtype == torch.get_default_dtype()\n\n\[email protected](\n \"device\", [torch.device(\"cpu\"), pytest.param(torch.device(\"cuda\", 0), marks=RunIf(min_gpus=1))]\n)\[email protected](\"dtype\", [torch.float32, torch.float16])\ndef test_lite_module_device_dtype_propagation(device, dtype):\n \"\"\"Test that the LiteModule propagates device and dtype properties to its submodules (e.g. torchmetrics).\"\"\"\n\n class DeviceModule(DeviceDtypeModuleMixin):\n pass\n\n device_module = DeviceModule()\n lite_module = _LiteModule(device_module, Mock())\n lite_module.to(device)\n assert device_module.device == device\n assert lite_module.device == device\n\n lite_module.to(dtype)\n assert device_module.dtype == dtype\n assert lite_module.dtype == dtype\n\n\ndef test_lite_dataloader_iterator():\n \"\"\"Test that the iteration over a LiteDataLoader wraps the iterator of the underlying dataloader (no automatic\n device placement).\"\"\"\n dataloader = DataLoader(range(5), batch_size=2)\n lite_dataloader = _LiteDataLoader(dataloader)\n assert len(lite_dataloader) == len(dataloader) == 3\n\n iterator = iter(dataloader)\n lite_iterator = iter(lite_dataloader)\n\n assert torch.equal(next(iterator), next(lite_iterator))\n assert torch.equal(next(iterator), next(lite_iterator))\n assert torch.equal(next(iterator), next(lite_iterator))\n\n with pytest.raises(StopIteration):\n next(iterator)\n\n with pytest.raises(StopIteration):\n next(lite_iterator)\n\n\[email protected](\n \"src_device, dest_device\",\n [\n (torch.device(\"cpu\"), torch.device(\"cpu\")),\n pytest.param(torch.device(\"cpu\"), torch.device(\"cuda\", 0), marks=RunIf(min_gpus=1)),\n pytest.param(torch.device(\"cuda\", 0), torch.device(\"cpu\"), marks=RunIf(min_gpus=1)),\n ],\n)\ndef test_lite_dataloader_device_placement(src_device, dest_device):\n \"\"\"Test that the LiteDataLoader moves data to the device in its iterator.\"\"\"\n sample0 = torch.tensor(0, device=src_device)\n sample1 = torch.tensor(1, device=src_device)\n sample2 = {\"data\": torch.tensor(2, device=src_device)}\n sample3 = {\"data\": torch.tensor(3, device=src_device)}\n dataloader = DataLoader([sample0, sample1, sample2, sample3], batch_size=2)\n lite_dataloader = _LiteDataLoader(dataloader=dataloader, device=dest_device)\n iterator = iter(lite_dataloader)\n\n batch0 = next(iterator)\n assert torch.equal(batch0, torch.tensor([0, 1], device=dest_device))\n\n batch1 = next(iterator)\n assert torch.equal(batch1[\"data\"], torch.tensor([2, 3], device=dest_device))\n\n\ndef test_lite_optimizer_wraps():\n \"\"\"Test that the LiteOptimizer fully wraps the optimizer.\"\"\"\n optimizer_cls = torch.optim.SGD\n optimizer = Mock(spec=optimizer_cls)\n lite_optimizer = _LiteOptimizer(optimizer, Mock())\n assert lite_optimizer.optimizer is optimizer\n assert isinstance(lite_optimizer, optimizer_cls)\n\n\ndef test_lite_optimizer_state_dict():\n \"\"\"Test that the LiteOptimizer calls into the strategy to collect the state.\"\"\"\n optimizer = Mock()\n strategy = Mock()\n lite_optimizer = _LiteOptimizer(optimizer=optimizer, strategy=strategy)\n lite_optimizer.state_dict()\n strategy.optimizer_state.assert_called_with(optimizer)\n\n\ndef test_lite_optimizer_steps():\n \"\"\"Test that the LiteOptimizer forwards the step() and zero_grad() calls to the wrapped optimizer.\"\"\"\n optimizer = Mock()\n strategy = Mock()\n strategy.optimizer_step.return_value = 123\n lite_optimizer = _LiteOptimizer(optimizer=optimizer, strategy=strategy)\n step_output = lite_optimizer.step()\n assert step_output == 123\n strategy.optimizer_step.assert_called_once()\n strategy.optimizer_step.assert_called_with(optimizer, opt_idx=0, closure=ANY, model=strategy.model)\n" ]
[ [ "torch.get_default_dtype", "torch.is_autocast_enabled", "torch.tensor", "torch.utils.data.dataloader.DataLoader", "torch.nn.Identity", "torch.device" ] ]
zjzh/jax
[ "8372b98c4856b6b2363b7bb28abdb4579440a656" ]
[ "jax/_src/device_array.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# On-device arrays.\n\nfrom functools import partial, partialmethod\nimport operator\nfrom typing import (Any, List, Optional, Union)\nimport weakref\n\nimport numpy as np\n\nfrom jax import core\nfrom jax._src.config import config\nfrom jax._src import abstract_arrays\nfrom jax._src import dtypes\nfrom jax._src import profiler\nfrom jax._src.lib import xla_client as xc\nimport jax._src.util as util\n\n### device-persistent data\n\nxe = xc._xla\n\nDevice = xc.Device\nBuffer = xe.Buffer\n\n\ndef _forward_method(attrname, self, fun, *args):\n return fun(getattr(self, attrname), *args)\n_forward_to_value = partial(_forward_method, \"_value\")\n\n\n# The following is used for the type xc.Buffer or _DeviceArray.\nDeviceArrayProtocol = Any\nDeviceArray = xc.DeviceArrayBase\n\n\ndef make_device_array(\n aval: core.ShapedArray,\n device: Optional[Device],\n device_buffer: Buffer,\n) -> Union[Buffer, \"_DeviceArray\"]:\n \"\"\"Returns a DeviceArray implementation based on arguments.\n\n This is to be used only within JAX. It will return either a PythonDeviceArray\n or a C++ equivalent implementation.\n \"\"\"\n if isinstance(device_buffer, xc.Buffer):\n\n if device_buffer.aval == aval and device_buffer._device == device:\n return device_buffer\n device_buffer = device_buffer.clone()\n device_buffer._device = device\n device_buffer.aval = aval\n device_buffer.weak_type = aval.weak_type\n return device_buffer\n\n return _DeviceArray(aval, device, device_buffer)\n\n\ndef type_is_device_array(x):\n \"\"\"Returns `True` if `x` is a non-sharded DeviceArray.\n\n Use this function instead of `type(x) is Devicearray`.\n \"\"\"\n type_x = type(x)\n return type_x is _DeviceArray or type_x is xc.Buffer\n\n\ndef device_array_supports_weakrefs():\n try:\n weakref.ref(DeviceArray())\n return True\n except TypeError:\n return False\n\n\nclass _DeviceArray(DeviceArray): # type: ignore\n \"\"\"A DeviceArray is an ndarray backed by a single device memory buffer.\"\"\"\n # We don't subclass ndarray because that would open up a host of issues,\n # but lax_numpy.py overrides isinstance behavior and attaches ndarray methods.\n __slots__ = [\n \"aval\", \"device_buffer\", \"_npy_value\", \"_device\", \"__weakref__\"\n ]\n __array_priority__ = 100\n\n # DeviceArray has methods that are dynamically populated in lax_numpy.py,\n # and this annotation is needed to make pytype happy.\n _HAS_DYNAMIC_ATTRIBUTES = True\n\n def __init__(self, aval: core.ShapedArray, device: Optional[Device],\n device_buffer: Buffer):\n \"\"\"Initializer.\n\n Args:\n aval: The abstract value associated to this array (shape+dtype+weak_type).\n device: The optional sticky device. See\n https://jax.readthedocs.io/en/latest/faq.html#controlling-data-and-computation-placement-on-devices\n device_buffer: The underlying buffer owning the on-device data.\n \"\"\"\n DeviceArray.__init__(self)\n self.aval = aval\n self.device_buffer = device_buffer\n self._device = device\n\n self._npy_value = None\n if config.jax_enable_checks:\n assert type(aval) is core.ShapedArray\n npy_value = self._value\n assert npy_value.dtype == aval.dtype and npy_value.shape == aval.shape, (\n aval, npy_value.shape, npy_value.dtype)\n assert (device is None) or device is device_buffer.device()\n\n def _check_if_deleted(self):\n if self.device_buffer is deleted_buffer:\n raise RuntimeError(\"DeviceArray has been deleted.\")\n\n @profiler.annotate_function\n def block_until_ready(self):\n \"\"\"Blocks the caller until the buffer's value has been computed on device.\n\n This method is mostly useful for timing microbenchmarks that wish to\n time how long a computation takes, without transferring the result back\n to the host.\n\n Returns the buffer object (`self`).\n \"\"\"\n self._check_if_deleted()\n self.device_buffer.block_host_until_ready() # pytype: disable=attribute-error\n return self\n\n @property\n def _value(self):\n self._check_if_deleted()\n if self._npy_value is None:\n self._npy_value = self.device_buffer.to_py() # pytype: disable=attribute-error # bind-properties\n self._npy_value.flags.writeable = False\n return self._npy_value\n\n @property\n def shape(self):\n return self.aval.shape\n\n @property\n def dtype(self):\n return self.aval.dtype\n\n @property\n def size(self):\n return util.prod(self.aval.shape)\n\n @property\n def ndim(self):\n return len(self.aval.shape)\n\n def device(self):\n self._check_if_deleted()\n return self.device_buffer.device() # pytype: disable=attribute-error\n\n def copy_to_host_async(self):\n \"\"\"Requests a copy of the buffer to the host.\"\"\"\n self._check_if_deleted()\n if self._npy_value is None:\n self.device_buffer.copy_to_host_async() # pytype: disable=attribute-error\n\n def delete(self):\n \"\"\"Deletes the device array and any cached copy on the host.\n\n It is an error to access the contents of a `DeviceArray` after it has\n been deleted.\n\n Use of this method is optional; device buffers will be reclaimed\n automatically by Python when a DeviceArray object is garbage collected.\n However, it is sometimes useful to have more explicit control over the\n time of deletion.\n \"\"\"\n self.device_buffer.delete() # pytype: disable=attribute-error\n self.device_buffer = deleted_buffer\n self._npy_value = None\n\n @property\n def __cuda_array_interface__(self):\n return self.device_buffer.__cuda_array_interface__ # pytype: disable=attribute-error # bind-properties\n\n\n# Adding methods dynamically to both _DeviceArray and xc.Buffer\n# pylint: disable=protected-access\nfor device_array in [DeviceArray]:\n\n\n def copy(self):\n \"\"\"Returns an ndarray (backed by host memory, not device memory).\"\"\"\n return np.asarray(self)\n setattr(device_array, \"copy\", copy)\n\n def __repr__(self):\n line_width = np.get_printoptions()[\"linewidth\"]\n prefix = '{}('.format(self.__class__.__name__.lstrip('_'))\n s = np.array2string(self._value, prefix=prefix, suffix=',',\n separator=', ', max_line_width=line_width)\n if self.aval is not None and self.aval.weak_type:\n dtype_str = f'dtype={self.dtype.name}, weak_type=True)'\n else:\n dtype_str = f'dtype={self.dtype.name})'\n last_line_len = len(s) - s.rfind('\\n') + 1\n sep = ' '\n if last_line_len + len(dtype_str) + 1 > line_width:\n sep = ' ' * len(prefix)\n return \"{}{},{}{}\".format(prefix, s, sep, dtype_str)\n\n setattr(device_array, \"__repr__\", __repr__)\n\n def item(self):\n if dtypes.issubdtype(self.dtype, np.complexfloating):\n return complex(self)\n elif dtypes.issubdtype(self.dtype, np.floating):\n return float(self)\n elif dtypes.issubdtype(self.dtype, np.integer):\n return int(self)\n elif dtypes.issubdtype(self.dtype, np.bool_):\n return bool(self)\n else:\n raise TypeError(self.dtype)\n\n setattr(device_array, \"item\", item)\n\n def __len__(self):\n try:\n return self.aval.shape[0]\n except IndexError as err:\n raise TypeError(\"len() of unsized object\") from err # same as numpy error\n\n setattr(device_array, \"__len__\", __len__)\n\n def __iter__(self):\n if self.ndim == 0:\n raise TypeError(\"iteration over a 0-d array\") # same as numpy error\n else:\n return (sl for chunk in self._chunk_iter(100) for sl in chunk._unstack())\n\n setattr(device_array, \"__iter__\", __iter__)\n\n def __reversed__(self):\n return iter(self[::-1])\n\n setattr(device_array, \"__reversed__\", __reversed__)\n\n def __format__(self, format_spec):\n # Simulates behavior of https://github.com/numpy/numpy/pull/9883\n if self.ndim == 0:\n return format(self._value[()], format_spec)\n else:\n return format(self._value, format_spec)\n\n setattr(device_array, \"__format__\", __format__)\n\n def __array__(self, dtype=None, context=None):\n return np.asarray(self._value, dtype=dtype)\n\n setattr(device_array, \"__array__\", __array__)\n\n setattr(device_array, \"__str__\", partialmethod(_forward_to_value, str))\n setattr(device_array, \"__bool__\", partialmethod(_forward_to_value, bool))\n setattr(device_array, \"__nonzero__\", partialmethod(_forward_to_value, bool))\n setattr(device_array, \"__float__\", lambda self: self._value.__float__())\n setattr(device_array, \"__int__\", lambda self: self._value.__int__())\n setattr(device_array, \"__complex__\", lambda self: self._value.__complex__())\n setattr(device_array, \"__hex__\", partialmethod(_forward_to_value, hex))\n setattr(device_array, \"__oct__\", partialmethod(_forward_to_value, oct))\n setattr(device_array, \"__index__\", partialmethod(_forward_to_value,\n operator.index))\n to_bytes = lambda self, order=\"C\": self._value.tobytes(order)\n setattr(device_array, \"tobytes\", to_bytes)\n del to_bytes\n setattr(device_array, \"tolist\", lambda self: self._value.tolist())\n\n # pickle saves and loads just like an ndarray\n setattr(device_array, \"__reduce__\",\n partialmethod(_forward_to_value, operator.methodcaller(\"__reduce__\")))\n\n # explicitly set to be unhashable.\n setattr(device_array, \"__hash__\", None)\n\n # clobbered when jax.numpy is imported, but useful in tests\n setattr(device_array, \"__eq__\", lambda self, other: self._value == other)\n\n # The following methods are dynamically overridden in lax_numpy.py.\n def raise_not_implemented():\n raise NotImplementedError\n\n setattr(device_array, \"__getitem__\", lambda self, i: raise_not_implemented())\n# pylint: enable=protected-access\n\n\nclass DeletedBuffer(object): pass\ndeleted_buffer = DeletedBuffer()\n\n\ndevice_array_types: List[type] = [xc.Buffer, _DeviceArray]\nfor _device_array in device_array_types:\n core.literalable_types.add(_device_array)\n core.pytype_aval_mappings[device_array] = abstract_arrays.canonical_concrete_aval\n" ]
[ [ "numpy.get_printoptions", "numpy.asarray", "numpy.array2string" ] ]
983632847/video_analyst
[ "01b7ad278b828a3f7ff7a0488c5ca8f055240192" ]
[ "videoanalyst/model/task_model/taskmodel_impl/siamese_track.py" ]
[ "# -*- coding: utf-8 -*\n\nimport numpy as np\nfrom loguru import logger\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom videoanalyst.model.common_opr.common_block import (conv_bn_relu,\n xcorr_depthwise)\nfrom videoanalyst.model.module_base import ModuleBase\nfrom videoanalyst.model.task_model.taskmodel_base import (TRACK_TASKMODELS,\n VOS_TASKMODELS)\n\ntorch.set_printoptions(precision=8)\n\n\n@TRACK_TASKMODELS.register\n@VOS_TASKMODELS.register\nclass SiamTrack(ModuleBase):\n r\"\"\"\n SiamTrack model for tracking\n\n Hyper-Parameters\n ----------------\n pretrain_model_path: string\n path to parameter to be loaded into module\n head_width: int\n feature width in head structure\n \"\"\"\n\n default_hyper_params = dict(pretrain_model_path=\"\",\n head_width=256,\n conv_weight_std=0.01,\n neck_conv_bias=[True, True, True, True],\n corr_fea_output=False,\n trt_mode=False,\n trt_fea_model_path=\"\",\n trt_track_model_path=\"\")\n\n support_phases = [\"train\", \"feature\", \"track\", \"freeze_track_fea\"]\n\n def __init__(self, backbone, head, loss=None):\n super(SiamTrack, self).__init__()\n self.basemodel = backbone\n self.head = head\n self.loss = loss\n self.trt_fea_model = None\n self.trt_track_model = None\n self._phase = \"train\"\n\n @property\n def phase(self):\n return self._phase\n\n @phase.setter\n def phase(self, p):\n assert p in self.support_phases\n self._phase = p\n\n def forward(self, *args, phase=None):\n r\"\"\"\n Perform tracking process for different phases (e.g. train / init / track)\n\n Arguments\n ---------\n target_img: torch.Tensor\n target template image patch\n search_img: torch.Tensor\n search region image patch\n\n Returns\n -------\n fcos_score_final: torch.Tensor\n predicted score for bboxes, shape=(B, HW, 1)\n fcos_bbox_final: torch.Tensor\n predicted bbox in the crop, shape=(B, HW, 4)\n fcos_cls_prob_final: torch.Tensor\n classification score, shape=(B, HW, 1)\n fcos_ctr_prob_final: torch.Tensor\n center-ness score, shape=(B, HW, 1)\n \"\"\"\n if phase is None:\n phase = self._phase\n # used during training\n if phase == 'train':\n # resolve training data\n training_data = args[0]\n target_img = training_data[\"im_z\"]\n search_img = training_data[\"im_x\"]\n # backbone feature\n f_z = self.basemodel(target_img)\n f_x = self.basemodel(search_img)\n # feature adjustment\n c_z_k = self.c_z_k(f_z)\n r_z_k = self.r_z_k(f_z)\n c_x = self.c_x(f_x)\n r_x = self.r_x(f_x)\n # feature matching\n r_out = xcorr_depthwise(r_x, r_z_k)\n c_out = xcorr_depthwise(c_x, c_z_k)\n # head\n fcos_cls_score_final, fcos_ctr_score_final, fcos_bbox_final, corr_fea = self.head(\n c_out, r_out)\n predict_data = dict(\n cls_pred=fcos_cls_score_final,\n ctr_pred=fcos_ctr_score_final,\n box_pred=fcos_bbox_final,\n )\n if self._hyper_params[\"corr_fea_output\"]:\n predict_data[\"corr_fea\"] = corr_fea\n return predict_data\n # used for template feature extraction (normal mode)\n elif phase == 'feature':\n target_img, = args\n if self._hyper_params[\"trt_mode\"]:\n # extract feature with trt model\n out_list = self.trt_fea_model(target_img)\n else:\n # backbone feature\n f_z = self.basemodel(target_img)\n # template as kernel\n c_z_k = self.c_z_k(f_z)\n r_z_k = self.r_z_k(f_z)\n # output\n out_list = [c_z_k, r_z_k]\n # used for template feature extraction (trt mode)\n elif phase == \"freeze_track_fea\":\n search_img, = args\n # backbone feature\n f_x = self.basemodel(search_img)\n # feature adjustment\n c_x = self.c_x(f_x)\n r_x = self.r_x(f_x)\n # head\n return [c_x, r_x]\n # [Broken] used for template feature extraction (trt mode)\n # currently broken due to following issue of \"torch2trt\" package\n # c.f. https://github.com/NVIDIA-AI-IOT/torch2trt/issues/251\n elif phase == \"freeze_track_head\":\n c_out, r_out = args\n # head\n outputs = self.head(c_out, r_out, 0, True)\n return outputs\n # used for tracking one frame during test\n elif phase == 'track':\n if len(args) == 3:\n search_img, c_z_k, r_z_k = args\n if self._hyper_params[\"trt_mode\"]:\n c_x, r_x = self.trt_track_model(search_img)\n else:\n # backbone feature\n f_x = self.basemodel(search_img)\n # feature adjustment\n c_x = self.c_x(f_x)\n r_x = self.r_x(f_x)\n elif len(args) == 4:\n # c_x, r_x already computed\n c_z_k, r_z_k, c_x, r_x = args\n else:\n raise ValueError(\"Illegal args length: %d\" % len(args))\n\n # feature matching\n r_out = xcorr_depthwise(r_x, r_z_k)\n c_out = xcorr_depthwise(c_x, c_z_k)\n # head\n fcos_cls_score_final, fcos_ctr_score_final, fcos_bbox_final, corr_fea = self.head(\n c_out, r_out, search_img.size(-1))\n # apply sigmoid\n fcos_cls_prob_final = torch.sigmoid(fcos_cls_score_final)\n fcos_ctr_prob_final = torch.sigmoid(fcos_ctr_score_final)\n # apply centerness correction\n fcos_score_final = fcos_cls_prob_final * fcos_ctr_prob_final\n # register extra output\n extra = dict(c_x=c_x, r_x=r_x, corr_fea=corr_fea)\n # output\n out_list = fcos_score_final, fcos_bbox_final, fcos_cls_prob_final, fcos_ctr_prob_final, extra\n else:\n raise ValueError(\"Phase non-implemented.\")\n\n return out_list\n\n def update_params(self):\n r\"\"\"\n Load model parameters\n \"\"\"\n self._make_convs()\n self._initialize_conv()\n super().update_params()\n if self._hyper_params[\"trt_mode\"]:\n logger.info(\"trt mode enable\")\n from torch2trt import TRTModule\n self.trt_fea_model = TRTModule()\n self.trt_fea_model.load_state_dict(\n torch.load(self._hyper_params[\"trt_fea_model_path\"]))\n self.trt_track_model = TRTModule()\n self.trt_track_model.load_state_dict(\n torch.load(self._hyper_params[\"trt_track_model_path\"]))\n logger.info(\"loading trt model succefully\")\n\n def _make_convs(self):\n head_width = self._hyper_params['head_width']\n\n # feature adjustment\n self.r_z_k = conv_bn_relu(head_width,\n head_width,\n 1,\n 3,\n 0,\n has_relu=False)\n self.c_z_k = conv_bn_relu(head_width,\n head_width,\n 1,\n 3,\n 0,\n has_relu=False)\n self.r_x = conv_bn_relu(head_width, head_width, 1, 3, 0, has_relu=False)\n self.c_x = conv_bn_relu(head_width, head_width, 1, 3, 0, has_relu=False)\n\n def _initialize_conv(self, ):\n conv_weight_std = self._hyper_params['conv_weight_std']\n conv_list = [\n self.r_z_k.conv, self.c_z_k.conv, self.r_x.conv, self.c_x.conv\n ]\n for ith in range(len(conv_list)):\n conv = conv_list[ith]\n torch.nn.init.normal_(conv.weight,\n std=conv_weight_std) # conv_weight_std=0.01\n\n def set_device(self, dev):\n if not isinstance(dev, torch.device):\n dev = torch.device(dev)\n self.to(dev)\n if self.loss is not None:\n for loss_name in self.loss:\n self.loss[loss_name].to(dev)\n" ]
[ [ "torch.load", "torch.set_printoptions", "torch.nn.init.normal_", "torch.sigmoid", "torch.device" ] ]
ysglh/DeepVideoAnalytics
[ "e401b3273782409b2604657514bec293d6aa75b0" ]
[ "repos/tf_ctpn_cpu/lib/utils/setup.py" ]
[ "from Cython.Build import cythonize\nimport numpy as np\nfrom distutils.core import setup\n\n\nsetup(ext_modules=cythonize([\"bbox.pyx\",\"cython_nms.pyx\"],include_path=[np.get_include()]\n ))\n\n" ]
[ [ "numpy.get_include" ] ]
constracktor/testing-python-exercise
[ "70b15a9d8e193fc518e46996cbc3e9f52cb1336d" ]
[ "tests/unit/test_diffusion2d_functions.py" ]
[ "\"\"\"\nTests for functions in class SolveDiffusion2D\n\"\"\"\nimport numpy as np\n#import pytest\nfrom diffusion2d import SolveDiffusion2D\n\nfrom unittest import TestCase\n\n\nclass TestOperations(TestCase):\n \"\"\"\n Test suite for mathematical operations functions.\n \"\"\"\n def setUp(self):\n # Fixture\n self.w = 12.\n self.h = 20.\n self.dx = 0.4\n self.dy = 0.2\n self.D = 0.5\n self.T_cold = 300.\n self.T_hot = 700.\n\n def test_initialize_domain(self):\n \"\"\"\n Check function SolveDiffusion2D.initialize_domain\n \"\"\"\n solver = SolveDiffusion2D()\n\n expected_nx = 30 #int(self.w / self.dx)\n expected_ny = 100 #int(self.h / self.dy)\n\n solver.initialize_domain(self.w,self.h,self.dx,self.dy)\n\n self.assertEqual(solver.nx, expected_nx)\n self.assertEqual(solver.ny, expected_ny)\n\n def test_initialize_physical_parameters(self):\n \"\"\"\n Checks function SolveDiffusion2D.initialize_domain\n \"\"\"\n solver = SolveDiffusion2D()\n solver.dx = self.dx\n solver.dy = self.dy\n\n #dx**2 * dy**2 / (2 * d * (dx**2 + dy**2))\n expected_dt = 0.032\n\n solver.initialize_physical_parameters(self.D)\n\n self.assertAlmostEqual(solver.dt, expected_dt, 6)\n\n def test_get_initial_condition(self):\n \"\"\"\n Checks function SolveDiffusion2D.get_initial_function\n \"\"\"\n solver = SolveDiffusion2D()\n solver.T_cold = self.T_cold\n solver.T_hot = self.T_hot\n solver.initialize_domain(self.w,self.h,self.dx,self.dy)\n\n expected_u = self.T_cold * np.ones((solver.nx, solver.ny))\n\n # Initial conditions - circle of radius r centred at (cx,cy) (mm)\n r, cx, cy = 2, 5, 5\n r2 = r ** 2\n for i in range(solver.nx):\n for j in range(solver.ny):\n p2 = (i * solver.dx - cx) ** 2 + (j * solver.dy - cy) ** 2\n if p2 < r2:\n expected_u[i, j] = self.T_hot\n\n actual_u = solver.get_initial_condition()\n\n for i in range(solver.nx):\n for j in range(solver.ny):\n self.assertEqual(actual_u[i,j], expected_u[i,j])\n\n# def test_initialize_domain():\n# \"\"\"\n# Check function SolveDiffusion2D.initialize_domain\n# \"\"\"\n# solver = SolveDiffusion2D()\n#\n# w = 12.\n# h = 20.\n# dx = 0.4\n# dy = 0.2\n# expected_nx = 30 #int(w / dx)\n# expected_ny = 100 #int(h / dy)\n#\n# solver.initialize_domain(w,h,dx,dy)\n#\n# assert solver.nx == expected_nx\n# assert solver.ny == expected_ny\n#\n# def test_initialize_physical_parameters():\n# \"\"\"\n# Checks function SolveDiffusion2D.initialize_domain\n# \"\"\"\n# solver = SolveDiffusion2D()\n# solver.dx = 0.2\n# solver.dy = 0.4\n# d=5.\n#\n# #dx**2 * dy**2 / (2 * d * (dx**2 + dy**2))\n# expected_dt = pytest.approx(0.0032, abs=0.000001)\n#\n# solver.initialize_physical_parameters(d)\n#\n# assert solver.dt == expected_dt\n#\n# def test_get_initial_condition():\n# \"\"\"\n# Checks function SolveDiffusion2D.get_initial_function\n# \"\"\"\n# solver = SolveDiffusion2D()\n# solver.T_cold = 300.\n# solver.T_hot = 700.\n# solver.dx = 0.1\n# solver.dy = 0.2\n# solver.nx = 100\n# solver.ny = 50\n#\n# expected_u = solver.T_cold * np.ones((solver.nx, solver.ny))\n#\n# # Initial conditions - circle of radius r centred at (cx,cy) (mm)\n# r, cx, cy = 2, 5, 5\n# r2 = r ** 2\n# for i in range(solver.nx):\n# for j in range(solver.ny):\n# p2 = (i * solver.dx - cx) ** 2 + (j * solver.dy - cy) ** 2\n# if p2 < r2:\n# expected_u[i, j] = solver.T_hot\n#\n# actual_u = solver.get_initial_condition()\n#\n# assert np.all(actual_u == expected_u)\n" ]
[ [ "numpy.ones" ] ]
nmardirossian/pyscf
[ "57c8912dcfcc1157a822feede63df54ed1067115", "57c8912dcfcc1157a822feede63df54ed1067115" ]
[ "examples/gto/20-ao_integrals.py", "pyscf/gto/moleintor.py" ]
[ "#!/usr/bin/env python\n#\n# Author: Qiming Sun <[email protected]>\n#\n\n'''\nAccess AO integrals\n\nMole.intor and Mole.intor_by_shell functions can generate AO integrals.\nCalling Mole.intor with the integral function name returns a integral matrix\nfor all basis functions defined in Mole. If the integral operator has many\ncompenents eg gradients, keyword argument comp=* needs to be specified to\ntell the function how many components the integrals have.\nMole.intor_by_shell function generates the integrals for the given shell\nindices. Keyword argument comp=* is also required when the integral operator\nhas multiple components.\n\nSee pyscf/gto/moleintor.py file for the complete list of supported integrals.\n'''\n\nimport numpy\nfrom pyscf import gto, scf\n\nmol = gto.M(\n verbose = 0,\n atom = 'C 0 0 0; O 0 0 1.5',\n basis = 'ccpvdz'\n)\nmf = scf.RHF(mol)\nmf.kernel()\ndm = mf.make_rdm1()\n\n# Overlap, kinetic, nuclear attraction\ns = mol.intor('cint1e_ovlp_sph')\nt = mol.intor('cint1e_kin_sph')\nv = mol.intor('cint1e_nuc_sph')\n# Overlap, kinetic, nuclear attraction gradients (against electron coordinates)\ns1 = mol.intor('cint1e_ipovlp_sph', comp=3)\nt1 = mol.intor('cint1e_ipkin_sph' , comp=3)\nv1 = mol.intor('cint1e_ipnuc_sph' , comp=3)\n\nprint('Dipole %s' % numpy.einsum('xij,ij->x',\n mol.intor('cint1e_r_sph', comp=3), dm))\n\n#\n# AO overlap between two molecules\n#\nmol1 = gto.M(\n verbose = 0,\n atom = 'H 0 1 0; H 1 0 0',\n basis = 'ccpvdz'\n)\ns = gto.intor_cross('cint1e_ovlp_sph', mol, mol1)\nprint('overlap shape (%d, %d)' % s.shape)\n\n#\n# 2e integrals. Keyword aosym is to specify the permutation symmetry in the\n# AO integral matrix. s8 means 8-fold symmetry, s2kl means 2-fold symmetry\n# for the symmetry between kl in (ij|kl)\n#\neri = mol.intor('cint2e_sph', aosym='s8')\n#\n# 2e gradient integrals on first atom only\n#\neri = mol.intor('cint2e_ip1_sph', aosym='s2kl')\n\n#\n# 2e integral gradients on certain atom\n#\natm_id = 1 # second atom\nbas_start, bas_end, ao_start, ao_end = mol.aoslice_by_atom()[atm_id]\ntot_bra = ao_end - ao_start\nnao = mol.nao_nr()\neri1 = numpy.empty((3,tot_bra,nao,nao,nao))\npi = 0\nfor i in range(mol.nbas):\n if mol.bas_atom(i) == atm_id:\n pj = 0\n for j in range(mol.nbas):\n pk = 0\n for k in range(mol.nbas):\n pl = 0\n for l in range(mol.nbas):\n shls = (i, j, k, l)\n buf = mol.intor_by_shell('cint2e_ip1_sph', shls, comp=3)\n di, dj, dk, dl = buf.shape[1:]\n eri1[:,pi:pi+di,pj:pj+dj,pk:pk+dk,pl:pl+dl] = buf\n pl += dl\n pk += dk\n pj += dj\n pi += di\nprint('integral shape %s' % str(eri1.shape))\n\n#\n# Generate a sub-block of AO integrals. The sub-block (ij|kl) contains the\n# shells 2:5 for basis i, 0:2 for j, 0:4 for k and 1:3 for l\n#\nsub_eri = mol.intor('int2e_sph', shls_slice=(2,5,0,2,0,4,1,3))\n# This statement is equivalent to\ndims = []\nfor i in range(mol.nbas):\n l = mol.bas_angular(i)\n nc = mol.bas_nctr(i)\n dims.append((l * 2 + 1) * nc)\nnao_i = sum(dims[2:5])\nnao_j = sum(dims[0:2])\nnao_k = sum(dims[0:4])\nnao_l = sum(dims[1:3])\nsub_eri = numpy.empty((nao_i,nao_j,nao_k,nao_l))\npi = 0\nfor i in range(2,5):\n pj = 0\n for j in range(0,2):\n pk = 0\n for k in range(0,4):\n pl = 0\n for l in range(1,3):\n shls = (i, j, k, l)\n buf = mol.intor_by_shell('int2e_sph', shls)\n di, dj, dk, dl = buf.shape\n sub_eri[pi:pi+di,pj:pj+dj,pk:pk+dk,pl:pl+dl] = buf\n pl += dl\n pk += dk\n pj += dj\n pi += di\nsub_eri = sub_eri.reshape(nao_i*nao_j,nao_k*nao_l)\n\n#\n# Generate all AO integrals for a sub-system.\n#\nmol = gto.M(atom=[['H', 0,0,i] for i in range(10)])\natom_idx = [0,2,4] # The disjoint atoms\nsub_mol = mol.copy()\nsub_mol._bas = mol._bas[atom_idx]\nsub_eri = sub_mol.intor('int2e_sph', aosym='s1')\n\n# This statement is equivalent to\nsub_nao = 0\nfor i in range(mol.nbas):\n if mol.bas_atom(i) in atom_idx:\n l = mol.bas_angular(i)\n nc = mol.bas_nctr(i)\n sub_nao += (l * 2 + 1) * nc\nsub_eri = numpy.empty((sub_nao,sub_nao,sub_nao,sub_nao))\npi = 0\nfor i in range(mol.nbas):\n if mol.bas_atom(i) in atom_idx:\n pj = 0\n for j in range(mol.nbas):\n if mol.bas_atom(j) in atom_idx:\n pk = 0\n for k in range(mol.nbas):\n if mol.bas_atom(k) in atom_idx:\n pl = 0\n for l in range(mol.nbas):\n if mol.bas_atom(l) in atom_idx:\n shls = (i, j, k, l)\n buf = mol.intor_by_shell('int2e_sph', shls)\n di, dj, dk, dl = buf.shape\n sub_eri[pi:pi+di,pj:pj+dj,pk:pk+dk,pl:pl+dl] = buf\n pl += dl\n pk += dk\n pj += dj\n pi += di\nsub_eri = sub_eri.reshape(sub_nao**2,sub_nao**2)\n", "#!/usr/bin/env python\n#\n# Author: Qiming Sun <[email protected]>\n#\n\nimport ctypes\nimport numpy\nfrom pyscf import lib\n\nlibcgto = lib.load_library('libcgto')\n\nANG_OF = 1\nNPRIM_OF = 2\nNCTR_OF = 3\nKAPPA_OF = 4\nPTR_EXP = 5\nPTR_COEFF = 6\nBAS_SLOTS = 8\n\ndef getints(intor_name, atm, bas, env, shls_slice=None, comp=1, hermi=0,\n aosym='s1', ao_loc=None, cintopt=None, out=None):\n r'''1e and 2e integral generator.\n\n Args:\n intor_name : str\n\n ================================ =============\n Function Expression\n ================================ =============\n \"int1e_ovlp_sph\" ( \\| \\)\n \"int1e_nuc_sph\" ( \\| nuc \\| \\)\n \"int1e_kin_sph\" (.5 \\| p dot p\\)\n \"int1e_ia01p_sph\" (#C(0 1) \\| nabla-rinv \\| cross p\\)\n \"int1e_giao_irjxp_sph\" (#C(0 1) \\| r cross p\\)\n \"int1e_cg_irxp_sph\" (#C(0 1) \\| rc cross p\\)\n \"int1e_giao_a11part_sph\" (-.5 \\| nabla-rinv \\| r\\)\n \"int1e_cg_a11part_sph\" (-.5 \\| nabla-rinv \\| rc\\)\n \"int1e_a01gp_sph\" (g \\| nabla-rinv cross p \\|\\)\n \"int1e_igkin_sph\" (#C(0 .5) g \\| p dot p\\)\n \"int1e_igovlp_sph\" (#C(0 1) g \\|\\)\n \"int1e_ignuc_sph\" (#C(0 1) g \\| nuc \\|\\)\n \"int1e_z_sph\" ( \\| zc \\| \\)\n \"int1e_zz_sph\" ( \\| zc zc \\| \\)\n \"int1e_r_sph\" ( \\| rc \\| \\)\n \"int1e_r2_sph\" ( \\| rc dot rc \\| \\)\n \"int1e_rr_sph\" ( \\| rc rc \\| \\)\n \"int1e_pnucp_sph\" (p* \\| nuc dot p \\| \\)\n \"int1e_prinvxp_sph\" (p* \\| rinv cross p \\| \\)\n \"int1e_ovlp_spinor\" ( \\| \\)\n \"int1e_nuc_spinor\" ( \\| nuc \\|\\)\n \"int1e_srsr_spinor\" (sigma dot r \\| sigma dot r\\)\n \"int1e_sr_spinor\" (sigma dot r \\|\\)\n \"int1e_srsp_spinor\" (sigma dot r \\| sigma dot p\\)\n \"int1e_spsp_spinor\" (sigma dot p \\| sigma dot p\\)\n \"int1e_sp_spinor\" (sigma dot p \\|\\)\n \"int1e_spnucsp_spinor\" (sigma dot p \\| nuc \\| sigma dot p\\)\n \"int1e_srnucsr_spinor\" (sigma dot r \\| nuc \\| sigma dot r\\)\n \"int1e_govlp_spinor\" (g \\|\\)\n \"int1e_gnuc_spinor\" (g \\| nuc \\|\\)\n \"int1e_cg_sa10sa01_spinor\" (.5 sigma cross rc \\| sigma cross nabla-rinv \\|\\)\n \"int1e_cg_sa10sp_spinor\" (.5 rc cross sigma \\| sigma dot p\\)\n \"int1e_cg_sa10nucsp_spinor\" (.5 rc cross sigma \\| nuc \\| sigma dot p\\)\n \"int1e_giao_sa10sa01_spinor\" (.5 sigma cross r \\| sigma cross nabla-rinv \\|\\)\n \"int1e_giao_sa10sp_spinor\" (.5 r cross sigma \\| sigma dot p\\)\n \"int1e_giao_sa10nucsp_spinor\" (.5 r cross sigma \\| nuc \\| sigma dot p\\)\n \"int1e_sa01sp_spinor\" (\\| nabla-rinv cross sigma \\| sigma dot p\\)\n \"int1e_spgsp_spinor\" (g sigma dot p \\| sigma dot p\\)\n \"int1e_spgnucsp_spinor\" (g sigma dot p \\| nuc \\| sigma dot p\\)\n \"int1e_spgsa01_spinor\" (g sigma dot p \\| nabla-rinv cross sigma \\|\\)\n \"int1e_spspsp_spinor\" (sigma dot p \\| sigma dot p sigma dot p\\)\n \"int1e_spnuc_spinor\" (sigma dot p \\| nuc \\|\\)\n \"int1e_ovlp_cart\" ( \\| \\)\n \"int1e_nuc_cart\" ( \\| nuc \\| \\)\n \"int1e_kin_cart\" (.5 \\| p dot p\\)\n \"int1e_ia01p_cart\" (#C(0 1) \\| nabla-rinv \\| cross p\\)\n \"int1e_giao_irjxp_cart\" (#C(0 1) \\| r cross p\\)\n \"int1e_cg_irxp_cart\" (#C(0 1) \\| rc cross p\\)\n \"int1e_giao_a11part_cart\" (-.5 \\| nabla-rinv \\| r\\)\n \"int1e_cg_a11part_cart\" (-.5 \\| nabla-rinv \\| rc\\)\n \"int1e_a01gp_cart\" (g \\| nabla-rinv cross p \\|\\)\n \"int1e_igkin_cart\" (#C(0 .5) g \\| p dot p\\)\n \"int1e_igovlp_cart\" (#C(0 1) g \\|\\)\n \"int1e_ignuc_cart\" (#C(0 1) g \\| nuc \\|\\)\n \"int1e_ipovlp_sph\" (nabla \\|\\)\n \"int1e_ipkin_sph\" (.5 nabla \\| p dot p\\)\n \"int1e_ipnuc_sph\" (nabla \\| nuc \\|\\)\n \"int1e_iprinv_sph\" (nabla \\| rinv \\|\\)\n \"int1e_rinv_sph\" (\\| rinv \\|\\)\n \"int1e_ipovlp_spinor\" (nabla \\|\\)\n \"int1e_ipkin_spinor\" (.5 nabla \\| p dot p\\)\n \"int1e_ipnuc_spinor\" (nabla \\| nuc \\|\\)\n \"int1e_iprinv_spinor\" (nabla \\| rinv \\|\\)\n \"int1e_ipspnucsp_spinor\" (nabla sigma dot p \\| nuc \\| sigma dot p\\)\n \"int1e_ipsprinvsp_spinor\" (nabla sigma dot p \\| rinv \\| sigma dot p\\)\n \"int1e_ipovlp_cart\" (nabla \\|\\)\n \"int1e_ipkin_cart\" (.5 nabla \\| p dot p\\)\n \"int1e_ipnuc_cart\" (nabla \\| nuc \\|\\)\n \"int1e_iprinv_cart\" (nabla \\| rinv \\|\\)\n \"int1e_rinv_cart\" (\\| rinv \\|\\)\n \"int2e_p1vxp1_sph\" ( p* \\, cross p \\| \\, \\) ; SSO\n \"int2e_sph\" ( \\, \\| \\, \\)\n \"int2e_ig1_sph\" (#C(0 1) g \\, \\| \\, \\)\n \"int2e_spinor\" (, \\| \\, \\)\n \"int2e_spsp1_spinor\" (sigma dot p \\, sigma dot p \\| \\, \\)\n \"int2e_spsp1spsp2_spinor\" (sigma dot p \\, sigma dot p \\| sigma dot p \\, sigma dot p \\)\n \"int2e_srsr1_spinor\" (sigma dot r \\, sigma dot r \\| \\,\\)\n \"int2e_srsr1srsr2_spinor\" (sigma dot r \\, sigma dot r \\| sigma dot r \\, sigma dot r\\)\n \"int2e_cg_sa10sp1_spinor\" (.5 rc cross sigma \\, sigma dot p \\| \\,\\)\n \"int2e_cg_sa10sp1spsp2_spinor\" (.5 rc cross sigma \\, sigma dot p \\| sigma dot p \\, sigma dot p \\)\n \"int2e_giao_sa10sp1_spinor\" (.5 r cross sigma \\, sigma dot p \\| \\,\\)\n \"int2e_giao_sa10sp1spsp2_spinor\" (.5 r cross sigma \\, sigma dot p \\| sigma dot p \\, sigma dot p \\)\n \"int2e_g1_spinor\" (g \\, \\| \\,\\)\n \"int2e_spgsp1_spinor\" (g sigma dot p \\, sigma dot p \\| \\,\\)\n \"int2e_g1spsp2_spinor\" (g \\, \\| sigma dot p \\, sigma dot p\\)\n \"int2e_spgsp1spsp2_spinor\" (g sigma dot p \\, sigma dot p \\| sigma dot p \\, sigma dot p\\)\n \"int2e_spv1_spinor\" (sigma dot p \\, \\| \\,\\)\n \"int2e_vsp1_spinor\" (\\, sigma dot p \\| \\,\\)\n \"int2e_spsp2_spinor\" (\\, \\| sigma dot p \\, sigma dot p\\)\n \"int2e_spv1spv2_spinor\" (sigma dot p \\, \\| sigma dot p \\,\\)\n \"int2e_vsp1spv2_spinor\" (\\, sigma dot p \\| sigma dot p \\,\\)\n \"int2e_spv1vsp2_spinor\" (sigma dot p \\, \\| \\, sigma dot p\\)\n \"int2e_vsp1vsp2_spinor\" (\\, sigma dot p \\| \\, sigma dot p\\)\n \"int2e_spv1spsp2_spinor\" (sigma dot p \\, \\| sigma dot p \\, sigma dot p\\)\n \"int2e_vsp1spsp2_spinor\" (\\, sigma dot p \\| sigma dot p \\, sigma dot p\\)\n \"int2e_ig1_cart\" (#C(0 1) g \\, \\| \\, \\)\n \"int2e_ip1_sph\" (nabla \\, \\| \\,\\)\n \"int2e_ip1_spinor\" (nabla \\, \\| \\,\\)\n \"int2e_ipspsp1_spinor\" (nabla sigma dot p \\, sigma dot p \\| \\,\\)\n \"int2e_ip1spsp2_spinor\" (nabla \\, \\| sigma dot p \\, sigma dot p\\)\n \"int2e_ipspsp1spsp2_spinor\" (nabla sigma dot p \\, sigma dot p \\| sigma dot p \\, sigma dot p\\)\n \"int2e_ipsrsr1_spinor\" (nabla sigma dot r \\, sigma dot r \\| \\,\\)\n \"int2e_ip1srsr2_spinor\" (nabla \\, \\| sigma dot r \\, sigma dot r\\)\n \"int2e_ipsrsr1srsr2_spinor\" (nabla sigma dot r \\, sigma dot r \\| sigma dot r \\, sigma dot r\\)\n \"int2e_ip1_cart\" (nabla \\, \\| \\,\\)\n \"int2e_ssp1ssp2_spinor\" ( \\, sigma dot p \\| gaunt \\| \\, sigma dot p\\)\n \"int2e_cg_ssa10ssp2_spinor\" (rc cross sigma \\, \\| gaunt \\| \\, sigma dot p\\)\n \"int2e_giao_ssa10ssp2_spinor\" (r cross sigma \\, \\| gaunt \\| \\, sigma dot p\\)\n \"int2e_gssp1ssp2_spinor\" (g \\, sigma dot p \\| gaunt \\| \\, sigma dot p\\)\n \"int2e_ipip1_sph\" ( nabla nabla \\, \\| \\, \\)\n \"int2e_ipvip1_sph\" ( nabla \\, nabla \\| \\, \\)\n \"int2e_ip1ip2_sph\" ( nabla \\, \\| nabla \\, \\)\n \"int3c2e_ip1_sph\" (nabla \\, \\| \\)\n \"int3c2e_ip2_sph\" ( \\, \\| nabla\\)\n \"int2c2e_ip1_sph\" (nabla \\| r12 \\| \\)\n \"int3c2e_spinor\" (nabla \\, \\| \\)\n \"int3c2e_spsp1_spinor\" (nabla \\, \\| \\)\n \"int3c2e_ip1_spinor\" (nabla \\, \\| \\)\n \"int3c2e_ip2_spinor\" ( \\, \\| nabla\\)\n \"int3c2e_ipspsp1_spinor\" (nabla sigma dot p \\, sigma dot p \\| \\)\n \"int3c2e_spsp1ip2_spinor\" (sigma dot p \\, sigma dot p \\| nabla \\)\n ================================ =============\n\n atm : int32 ndarray\n libcint integral function argument\n bas : int32 ndarray\n libcint integral function argument\n env : float64 ndarray\n libcint integral function argument\n\n Kwargs:\n shls_slice : 8-element list\n (ish_start, ish_end, jsh_start, jsh_end, ksh_start, ksh_end, lsh_start, lsh_end)\n comp : int\n Components of the integrals, e.g. int1e_ipovlp has 3 components.\n hermi : int (1e integral only)\n Symmetry of the 1e integrals\n\n | 0 : no symmetry assumed (default)\n | 1 : hermitian\n | 2 : anti-hermitian\n\n aosym : str (2e integral only)\n Symmetry of the 2e integrals\n\n | 4 or '4' or 's4': 4-fold symmetry (default)\n | '2ij' or 's2ij' : symmetry between i, j in (ij|kl)\n | '2kl' or 's2kl' : symmetry between k, l in (ij|kl)\n | 1 or '1' or 's1': no symmetry\n\n out : ndarray (2e integral only)\n array to store the 2e AO integrals\n\n Returns:\n ndarray of 1-electron integrals, can be either 2-dim or 3-dim, depending on comp\n\n Examples:\n\n >>> mol.build(atom='H 0 0 0; H 0 0 1.1', basis='sto-3g')\n >>> gto.getints('int1e_ipnuc_sph', mol._atm, mol._bas, mol._env, comp=3) # <nabla i | V_nuc | j>\n [[[ 0. 0. ]\n [ 0. 0. ]]\n [[ 0. 0. ]\n [ 0. 0. ]]\n [[ 0.10289944 0.48176097]\n [-0.48176097 -0.10289944]]]\n '''\n intor_name = ascint3(intor_name)\n if (intor_name.startswith('int1e') or\n intor_name.startswith('ECP') or\n intor_name.startswith('int2c2e')):\n return getints2c(intor_name, atm, bas, env, shls_slice, comp,\n hermi, ao_loc, cintopt, out)\n elif intor_name.startswith('int2e') or intor_name.startswith('int4c1e'):\n return getints4c(intor_name, atm, bas, env, shls_slice, comp,\n aosym, ao_loc, cintopt, out)\n elif intor_name.startswith('int3c'):\n return getints3c(intor_name, atm, bas, env, shls_slice, comp,\n aosym, ao_loc, cintopt, out)\n else:\n raise RuntimeError('Unknown intor %s' % intor_name)\n\ndef getints2c(intor_name, atm, bas, env, shls_slice=None, comp=1, hermi=0,\n ao_loc=None, cintopt=None, out=None):\n atm = numpy.asarray(atm, dtype=numpy.int32, order='C')\n bas = numpy.asarray(bas, dtype=numpy.int32, order='C')\n env = numpy.asarray(env, dtype=numpy.double, order='C')\n natm = atm.shape[0]\n nbas = bas.shape[0]\n if shls_slice is None:\n shls_slice = (0, nbas, 0, nbas)\n else:\n assert(shls_slice[1] <= nbas and shls_slice[3] <= nbas)\n if ao_loc is None:\n ao_loc = make_loc(bas, intor_name)\n\n i0, i1, j0, j1 = shls_slice[:4]\n naoi = ao_loc[i1] - ao_loc[i0]\n naoj = ao_loc[j1] - ao_loc[j0]\n if intor_name.endswith('_cart') or intor_name.endswith('_sph'):\n mat = numpy.ndarray((naoi,naoj,comp), numpy.double, out, order='F')\n drv_name = 'GTOint2c'\n else:\n mat = numpy.ndarray((naoi,naoj,comp), numpy.complex, out, order='F')\n if '2c2e' in intor_name:\n assert(hermi != lib.HERMITIAN and\n hermi != lib.ANTIHERMI)\n drv_name = 'GTOint2c_spinor'\n\n if cintopt is None:\n cintopt = make_cintopt(atm, bas, env, intor_name)\n# cintopt = lib.c_null_ptr()\n\n fn = getattr(libcgto, drv_name)\n fn(getattr(libcgto, intor_name), mat.ctypes.data_as(ctypes.c_void_p),\n ctypes.c_int(comp), ctypes.c_int(hermi),\n (ctypes.c_int*4)(*(shls_slice[:4])),\n ao_loc.ctypes.data_as(ctypes.c_void_p), cintopt,\n atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),\n bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),\n env.ctypes.data_as(ctypes.c_void_p))\n\n mat = mat.transpose(2,0,1)\n if comp == 1:\n mat = mat[0]\n return mat\n\ndef getints3c(intor_name, atm, bas, env, shls_slice=None, comp=1,\n aosym='s1', ao_loc=None, cintopt=None, out=None):\n atm = numpy.asarray(atm, dtype=numpy.int32, order='C')\n bas = numpy.asarray(bas, dtype=numpy.int32, order='C')\n env = numpy.asarray(env, dtype=numpy.double, order='C')\n natm = atm.shape[0]\n nbas = bas.shape[0]\n if shls_slice is None:\n shls_slice = (0, nbas, 0, nbas, 0, nbas)\n else:\n assert(shls_slice[1] <= nbas and\n shls_slice[3] <= nbas and\n shls_slice[5] <= nbas)\n\n i0, i1, j0, j1, k0, k1 = shls_slice[:6]\n if ao_loc is None:\n ao_loc = make_loc(bas, intor_name)\n if k0 > j1 and k0 > i1:\n if 'ssc' in intor_name:\n ao_loc[k0-1:] = ao_loc[k0] + make_loc(bas[k0:], 'cart')\n elif 'spinor' in intor_name:\n ao_loc[k0-1:] = ao_loc[k0] + make_loc(bas[k0:], intor_name)\n\n naok = ao_loc[k1] - ao_loc[k0]\n\n if aosym in ('s1',):\n naoi = ao_loc[i1] - ao_loc[i0]\n naoj = ao_loc[j1] - ao_loc[j0]\n shape = (naoi, naoj, naok, comp)\n else:\n aosym = 's2ij'\n nij = ao_loc[i1]*(ao_loc[i1]+1)//2 - ao_loc[i0]*(ao_loc[i0]+1)//2\n shape = (nij, naok, comp)\n\n if 'spinor' in intor_name:\n mat = numpy.ndarray(shape, numpy.complex, out, order='F')\n drv = libcgto.GTOr3c_drv\n fill = getattr(libcgto, 'GTOr3c_fill_'+aosym)\n else:\n mat = numpy.ndarray(shape, numpy.double, out, order='F')\n drv = libcgto.GTOnr3c_drv\n fill = getattr(libcgto, 'GTOnr3c_fill_'+aosym)\n\n if cintopt is None:\n cintopt = make_cintopt(atm, bas, env, intor_name)\n\n drv(getattr(libcgto, intor_name), fill,\n mat.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(comp),\n (ctypes.c_int*6)(*(shls_slice[:6])),\n ao_loc.ctypes.data_as(ctypes.c_void_p), cintopt,\n atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),\n bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),\n env.ctypes.data_as(ctypes.c_void_p))\n\n mat = numpy.rollaxis(mat, -1, 0)\n if comp == 1:\n mat = mat[0]\n return mat\n\ndef getints4c(intor_name, atm, bas, env, shls_slice=None, comp=1,\n aosym='s1', ao_loc=None, cintopt=None, out=None):\n aosym = _stand_sym_code(aosym)\n\n atm = numpy.asarray(atm, dtype=numpy.int32, order='C')\n bas = numpy.asarray(bas, dtype=numpy.int32, order='C')\n env = numpy.asarray(env, dtype=numpy.double, order='C')\n c_atm = atm.ctypes.data_as(ctypes.c_void_p)\n c_bas = bas.ctypes.data_as(ctypes.c_void_p)\n c_env = env.ctypes.data_as(ctypes.c_void_p)\n natm = atm.shape[0]\n nbas = bas.shape[0]\n\n ao_loc = make_loc(bas, intor_name)\n if cintopt is None:\n cintopt = make_cintopt(atm, bas, env, intor_name)\n\n if aosym == 's8':\n assert('_spinor' not in intor_name)\n assert(shls_slice is None)\n from pyscf.scf import _vhf\n nao = ao_loc[-1]\n nao_pair = nao*(nao+1)//2\n out = numpy.ndarray((nao_pair*(nao_pair+1)//2), buffer=out)\n drv = _vhf.libcvhf.GTO2e_cart_or_sph\n drv(getattr(libcgto, intor_name), cintopt,\n out.ctypes.data_as(ctypes.c_void_p),\n ao_loc.ctypes.data_as(ctypes.c_void_p),\n c_atm, ctypes.c_int(natm), c_bas, ctypes.c_int(nbas), c_env)\n return out\n\n else:\n if shls_slice is None:\n shls_slice = (0, nbas, 0, nbas, 0, nbas, 0, nbas)\n elif len(shls_slice) == 4:\n shls_slice = shls_slice + (0, nbas, 0, nbas)\n else:\n assert(shls_slice[1] <= nbas and shls_slice[3] <= nbas and\n shls_slice[5] <= nbas and shls_slice[7] <= nbas)\n i0, i1, j0, j1, k0, k1, l0, l1 = shls_slice\n naoi = ao_loc[i1] - ao_loc[i0]\n naoj = ao_loc[j1] - ao_loc[j0]\n naok = ao_loc[k1] - ao_loc[k0]\n naol = ao_loc[l1] - ao_loc[l0]\n if aosym in ('s4', 's2ij'):\n nij = naoi * (naoi + 1) // 2\n assert(numpy.all(ao_loc[i0:i1]-ao_loc[i0] == ao_loc[j0:j1]-ao_loc[j0]))\n else:\n nij = naoi * naoj\n if aosym in ('s4', 's2kl'):\n nkl = naok * (naok + 1) // 2\n assert(numpy.all(ao_loc[k0:k1]-ao_loc[k0] == ao_loc[l0:l1]-ao_loc[l0]))\n else:\n nkl = naok * naol\n if comp == 1:\n out = numpy.ndarray((nij,nkl), buffer=out)\n else:\n out = numpy.ndarray((comp,nij,nkl), buffer=out)\n\n prescreen = lib.c_null_ptr()\n drv = libcgto.GTOnr2e_fill_drv\n drv(getattr(libcgto, intor_name),\n getattr(libcgto, 'GTOnr2e_fill_'+aosym), prescreen,\n out.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(comp),\n (ctypes.c_int*8)(*shls_slice),\n ao_loc.ctypes.data_as(ctypes.c_void_p), cintopt,\n c_atm, ctypes.c_int(natm), c_bas, ctypes.c_int(nbas), c_env)\n return out\n\ndef getints_by_shell(intor_name, shls, atm, bas, env, comp=1):\n r'''For given 2, 3 or 4 shells, interface for libcint to get 1e, 2e,\n 2-center-2e or 3-center-2e integrals\n\n Args:\n intor_name : str\n See also :func:`getints` for the supported intor_name\n shls : list of int\n The AO shell-ids of the integrals\n atm : int32 ndarray\n libcint integral function argument\n bas : int32 ndarray\n libcint integral function argument\n env : float64 ndarray\n libcint integral function argument\n\n Kwargs:\n comp : int\n Components of the integrals, e.g. int1e_ipovlp has 3 components.\n\n Returns:\n ndarray of 2-dim to 5-dim, depending on the integral type (1e,\n 2e, 3c-2e, 2c2e) and the value of comp\n\n Examples:\n The gradients of the spherical 2e integrals\n\n >>> mol.build(atom='H 0 0 0; H 0 0 1.1', basis='sto-3g')\n >>> gto.getints_by_shell('int2e_ip1_sph', (0,1,0,1), mol._atm, mol._bas, mol._env, comp=3)\n [[[[[-0. ]]]]\n [[[[-0. ]]]]\n [[[[-0.08760462]]]]]\n '''\n intor_name = ascint3(intor_name)\n atm = numpy.asarray(atm, dtype=numpy.int32, order='C')\n bas = numpy.asarray(bas, dtype=numpy.int32, order='C')\n env = numpy.asarray(env, dtype=numpy.double, order='C')\n natm = ctypes.c_int(atm.shape[0])\n nbas = ctypes.c_int(bas.shape[0])\n if intor_name.endswith('_cart'):\n dtype = numpy.double\n def num_cgto_of(basid):\n l = bas[basid,ANG_OF]\n return (l+1)*(l+2)//2 * bas[basid,NCTR_OF]\n elif intor_name.endswith('_sph'):\n dtype = numpy.double\n def num_cgto_of(basid):\n l = bas[basid,ANG_OF]\n return (l*2+1) * bas[basid,NCTR_OF]\n else:\n from pyscf.gto.mole import len_spinor\n dtype = numpy.complex\n def num_cgto_of(basid):\n l = bas[basid,ANG_OF]\n k = bas[basid,KAPPA_OF]\n return len_spinor(l,k) * bas[basid,NCTR_OF]\n\n null = lib.c_null_ptr()\n if intor_name.startswith('int3c'):\n assert(len(shls) == 3)\n di = num_cgto_of(shls[0])\n dj = num_cgto_of(shls[1])\n l = bas[shls[2],ANG_OF]\n if intor_name.endswith('_ssc'): # mixed spherical-cartesian\n dk = (l+1)*(l+2)//2 * bas[shls[2],NCTR_OF]\n else:\n dk = (l*2+1) * bas[shls[2],NCTR_OF]\n buf = numpy.empty((di,dj,dk,comp), dtype, order='F')\n fintor = getattr(libcgto, intor_name)\n fintor(buf.ctypes.data_as(ctypes.c_void_p),\n null, (ctypes.c_int*3)(*shls),\n atm.ctypes.data_as(ctypes.c_void_p), natm,\n bas.ctypes.data_as(ctypes.c_void_p), nbas,\n env.ctypes.data_as(ctypes.c_void_p), null, null)\n if comp == 1:\n return buf.reshape(di,dj,dk)\n else:\n return buf.transpose(3,0,1,2)\n\n elif intor_name.startswith('int2e') or intor_name.startswith('int4c'):\n assert(len(shls) == 4)\n di, dj, dk, dl = [num_cgto_of(x) for x in shls]\n buf = numpy.empty((di,dj,dk,dl,comp), dtype, order='F')\n fintor = getattr(libcgto, intor_name)\n fintor(buf.ctypes.data_as(ctypes.c_void_p),\n null, (ctypes.c_int*4)(*shls),\n atm.ctypes.data_as(ctypes.c_void_p), natm,\n bas.ctypes.data_as(ctypes.c_void_p), nbas,\n env.ctypes.data_as(ctypes.c_void_p), null, null)\n if comp == 1:\n return buf.reshape(di,dj,dk,dl)\n else:\n return buf.transpose(4,0,1,2,3)\n\n elif (intor_name.startswith('int2c') or '1e' in intor_name or\n 'ECP' in intor_name):\n assert(len(shls) == 2)\n di = num_cgto_of(shls[0])\n dj = num_cgto_of(shls[1])\n buf = numpy.empty((di,dj,comp), dtype, order='F')\n fintor = getattr(libcgto, intor_name)\n fintor(buf.ctypes.data_as(ctypes.c_void_p),\n null, (ctypes.c_int*2)(*shls),\n atm.ctypes.data_as(ctypes.c_void_p), natm,\n bas.ctypes.data_as(ctypes.c_void_p), nbas,\n env.ctypes.data_as(ctypes.c_void_p), null, null)\n if comp == 1:\n return buf.reshape(di,dj)\n else:\n return buf.transpose(2,0,1)\n\n else:\n raise RuntimeError('Unknown intor %s' % intor_name)\n\n\ndef make_loc(bas, key):\n if 'cart' in key:\n l = bas[:,ANG_OF]\n dims = (l+1)*(l+2)//2 * bas[:,NCTR_OF]\n elif 'sph' in key:\n dims = (bas[:,ANG_OF]*2+1) * bas[:,NCTR_OF]\n else: # spinor\n l = bas[:,ANG_OF]\n k = bas[:,KAPPA_OF]\n dims = (l*4+2) * bas[:,NCTR_OF]\n dims[k<0] = (l[k<0] * 2 + 2) * bas[k<0,NCTR_OF]\n dims[k>0] = (l[k>0] * 2 ) * bas[k>0,NCTR_OF]\n\n ao_loc = numpy.empty(len(dims)+1, dtype=numpy.int32)\n ao_loc[0] = 0\n dims.cumsum(dtype=numpy.int32, out=ao_loc[1:])\n return ao_loc\n\ndef make_cintopt(atm, bas, env, intor):\n intor = intor.replace('_sph','').replace('_cart','').replace('_spinor','')\n c_atm = numpy.asarray(atm, dtype=numpy.int32, order='C')\n c_bas = numpy.asarray(bas, dtype=numpy.int32, order='C')\n c_env = numpy.asarray(env, dtype=numpy.double, order='C')\n natm = c_atm.shape[0]\n nbas = c_bas.shape[0]\n cintopt = lib.c_null_ptr()\n foptinit = getattr(libcgto, intor+'_optimizer')\n foptinit(ctypes.byref(cintopt),\n c_atm.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(natm),\n c_bas.ctypes.data_as(ctypes.c_void_p), ctypes.c_int(nbas),\n c_env.ctypes.data_as(ctypes.c_void_p))\n return ctypes.cast(cintopt, _cintoptHandler)\nclass _cintoptHandler(ctypes.c_void_p):\n def __del__(self):\n libcgto.CINTdel_optimizer(ctypes.byref(self))\n\ndef _stand_sym_code(sym):\n if isinstance(sym, int):\n return 's%d' % sym\n elif sym[0] in 'sS':\n return sym.lower()\n else:\n return 's' + sym.lower()\n\ndef ascint3(intor_name):\n '''convert cint2 function name to cint3 function name'''\n if intor_name.startswith('cint'):\n intor_name = intor_name[1:]\n if not (intor_name.endswith('_cart') or\n intor_name.endswith('_sph') or\n intor_name.endswith('_spinor')):\n intor_name = intor_name + '_spinor'\n return intor_name\n\n\nif __name__ == '__main__':\n from pyscf import gto\n mol = gto.Mole()\n mol.verbose = 0\n mol.output = None\n\n mol.atom.extend([\n [\"H\", (0, 0, 0 )],\n [\"H\", (0, 0, 1 )],\n ])\n mol.basis = {\"H\": 'cc-pvdz'}\n mol.build()\n mol.set_rinv_origin(mol.atom_coord(0))\n for i in range(mol.nbas):\n for j in range(mol.nbas):\n print(i, j, getints_by_shell('int1e_prinvxp_sph', (i,j),\n mol._atm, mol._bas, mol._env, 3))\n" ]
[ [ "numpy.empty" ], [ "numpy.empty", "numpy.rollaxis", "numpy.asarray", "numpy.ndarray", "numpy.all" ] ]
mcflugen/plume
[ "7fc65ba9461fece372eef4b2bee9ba6e72f42d19" ]
[ "setup.py" ]
[ "from setuptools import setup, find_packages\nfrom distutils.extension import Extension\n\nimport numpy as np\nimport cython_gsl\nimport versioneer\n\n\ndef read_requirements():\n import os\n\n path = os.path.dirname(os.path.abspath(__file__))\n requirements_file = os.path.join(path, 'requirements.txt')\n try:\n with open(requirements_file, 'r') as req_fp:\n requires = req_fp.read().split()\n except IOError:\n return []\n else:\n return [require.split() for require in requires]\n\n\nsetup(name='plume',\n version=versioneer.get_version(),\n description='A hypopycnal sediment-carrying plume entering the ocean',\n author='Eric Hutton',\n author_email='[email protected]',\n url='http://csdms.colorado.edu',\n install_requires=read_requirements(),\n setup_requires=['setuptools', ],\n packages=find_packages(),\n include_dirs = [np.get_include(), cython_gsl.get_include()],\n entry_points={\n 'console_scripts': [\n 'plume=plume.cli:main',\n ],\n },\n ext_modules = [\n Extension('plume.ext.centerline',\n ['plume/ext/centerline.pyx'],\n extra_compile_args=['-O3'],\n libraries=cython_gsl.get_libraries(),\n library_dirs=[cython_gsl.get_library_dir()],\n include_dirs=[cython_gsl.get_cython_include_dir()])],\n cmdclass=versioneer.get_cmdclass(),\n)\n" ]
[ [ "numpy.get_include" ] ]
Ru-Xiang/x-deeplearning
[ "781545783a4e2bbbda48fc64318fb2c6d8bbb3cc" ]
[ "xdl-algorithm-solution/Rocket/script/rnn.py" ]
[ "# Copyright (C) 2016-2018 Alibaba Group Holding Limited\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"RNN helpers for TensorFlow models.\n\n\n@@bidirectional_dynamic_rnn\n@@dynamic_rnn\n@@raw_rnn\n@@static_rnn\n@@static_state_saving_rnn\n@@static_bidirectional_rnn\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import rnn_cell_impl\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.util import nest\n\n\n# pylint: disable=protected-access\n_concat = rnn_cell_impl._concat\nassert_like_rnncell = rnn_cell_impl.assert_like_rnncell\n# pylint: enable=protected-access\n\n\ndef _transpose_batch_time(x):\n \"\"\"Transpose the batch and time dimensions of a Tensor.\n\n Retains as much of the static shape information as possible.\n\n Args:\n x: A tensor of rank 2 or higher.\n\n Returns:\n x transposed along the first two dimensions.\n\n Raises:\n ValueError: if `x` is rank 1 or lower.\n \"\"\"\n x_static_shape = x.get_shape()\n if x_static_shape.ndims is not None and x_static_shape.ndims < 2:\n raise ValueError(\n \"Expected input tensor %s to have rank at least 2, but saw shape: %s\" %\n (x, x_static_shape))\n x_rank = array_ops.rank(x)\n x_t = array_ops.transpose(\n x, array_ops.concat(\n ([1, 0], math_ops.range(2, x_rank)), axis=0))\n x_t.set_shape(\n tensor_shape.TensorShape([\n x_static_shape[1].value, x_static_shape[0].value\n ]).concatenate(x_static_shape[2:]))\n return x_t\n\n\ndef _best_effort_input_batch_size(flat_input):\n \"\"\"Get static input batch size if available, with fallback to the dynamic one.\n\n Args:\n flat_input: An iterable of time major input Tensors of shape [max_time,\n batch_size, ...]. All inputs should have compatible batch sizes.\n\n Returns:\n The batch size in Python integer if available, or a scalar Tensor otherwise.\n\n Raises:\n ValueError: if there is any input with an invalid shape.\n \"\"\"\n for input_ in flat_input:\n shape = input_.shape\n if shape.ndims is None:\n continue\n if shape.ndims < 2:\n raise ValueError(\n \"Expected input tensor %s to have rank at least 2\" % input_)\n batch_size = shape[1].value\n if batch_size is not None:\n return batch_size\n # Fallback to the dynamic batch size of the first input.\n return array_ops.shape(flat_input[0])[1]\n\n\ndef _infer_state_dtype(explicit_dtype, state):\n \"\"\"Infer the dtype of an RNN state.\n\n Args:\n explicit_dtype: explicitly declared dtype or None.\n state: RNN's hidden state. Must be a Tensor or a nested iterable containing\n Tensors.\n\n Returns:\n dtype: inferred dtype of hidden state.\n\n Raises:\n ValueError: if `state` has heterogeneous dtypes or is empty.\n \"\"\"\n if explicit_dtype is not None:\n return explicit_dtype\n elif nest.is_sequence(state):\n inferred_dtypes = [element.dtype for element in nest.flatten(state)]\n if not inferred_dtypes:\n raise ValueError(\"Unable to infer dtype from empty state.\")\n all_same = all([x == inferred_dtypes[0] for x in inferred_dtypes])\n if not all_same:\n raise ValueError(\n \"State has tensors of different inferred_dtypes. Unable to infer a \"\n \"single representative dtype.\")\n return inferred_dtypes[0]\n else:\n return state.dtype\n\n\n# pylint: disable=unused-argument\ndef _rnn_step(\n time, sequence_length, min_sequence_length, max_sequence_length,\n zero_output, state, call_cell, state_size, skip_conditionals=False):\n \"\"\"Calculate one step of a dynamic RNN minibatch.\n\n Returns an (output, state) pair conditioned on the sequence_lengths.\n When skip_conditionals=False, the pseudocode is something like:\n\n if t >= max_sequence_length:\n return (zero_output, state)\n if t < min_sequence_length:\n return call_cell()\n\n # Selectively output zeros or output, old state or new state depending\n # on if we've finished calculating each row.\n new_output, new_state = call_cell()\n final_output = np.vstack([\n zero_output if time >= sequence_lengths[r] else new_output_r\n for r, new_output_r in enumerate(new_output)\n ])\n final_state = np.vstack([\n state[r] if time >= sequence_lengths[r] else new_state_r\n for r, new_state_r in enumerate(new_state)\n ])\n return (final_output, final_state)\n\n Args:\n time: Python int, the current time step\n sequence_length: int32 `Tensor` vector of size [batch_size]\n min_sequence_length: int32 `Tensor` scalar, min of sequence_length\n max_sequence_length: int32 `Tensor` scalar, max of sequence_length\n zero_output: `Tensor` vector of shape [output_size]\n state: Either a single `Tensor` matrix of shape `[batch_size, state_size]`,\n or a list/tuple of such tensors.\n call_cell: lambda returning tuple of (new_output, new_state) where\n new_output is a `Tensor` matrix of shape `[batch_size, output_size]`.\n new_state is a `Tensor` matrix of shape `[batch_size, state_size]`.\n state_size: The `cell.state_size` associated with the state.\n skip_conditionals: Python bool, whether to skip using the conditional\n calculations. This is useful for `dynamic_rnn`, where the input tensor\n matches `max_sequence_length`, and using conditionals just slows\n everything down.\n\n Returns:\n A tuple of (`final_output`, `final_state`) as given by the pseudocode above:\n final_output is a `Tensor` matrix of shape [batch_size, output_size]\n final_state is either a single `Tensor` matrix, or a tuple of such\n matrices (matching length and shapes of input `state`).\n\n Raises:\n ValueError: If the cell returns a state tuple whose length does not match\n that returned by `state_size`.\n \"\"\"\n\n # Convert state to a list for ease of use\n flat_state = nest.flatten(state)\n flat_zero_output = nest.flatten(zero_output)\n\n def _copy_one_through(output, new_output):\n # If the state contains a scalar value we simply pass it through.\n if output.shape.ndims == 0:\n return new_output\n copy_cond = (time >= sequence_length)\n with ops.colocate_with(new_output):\n return array_ops.where(copy_cond, output, new_output)\n\n def _copy_some_through(flat_new_output, flat_new_state):\n # Use broadcasting select to determine which values should get\n # the previous state & zero output, and which values should get\n # a calculated state & output.\n flat_new_output = [\n _copy_one_through(zero_output, new_output)\n for zero_output, new_output in zip(flat_zero_output, flat_new_output)]\n flat_new_state = [\n _copy_one_through(state, new_state)\n for state, new_state in zip(flat_state, flat_new_state)]\n return flat_new_output + flat_new_state\n\n def _maybe_copy_some_through():\n \"\"\"Run RNN step. Pass through either no or some past state.\"\"\"\n new_output, new_state = call_cell()\n\n nest.assert_same_structure(state, new_state)\n\n flat_new_state = nest.flatten(new_state)\n flat_new_output = nest.flatten(new_output)\n return control_flow_ops.cond(\n # if t < min_seq_len: calculate and return everything\n time < min_sequence_length, lambda: flat_new_output + flat_new_state,\n # else copy some of it through\n lambda: _copy_some_through(flat_new_output, flat_new_state))\n\n # TODO(ebrevdo): skipping these conditionals may cause a slowdown,\n # but benefits from removing cond() and its gradient. We should\n # profile with and without this switch here.\n if skip_conditionals:\n # Instead of using conditionals, perform the selective copy at all time\n # steps. This is faster when max_seq_len is equal to the number of unrolls\n # (which is typical for dynamic_rnn).\n new_output, new_state = call_cell()\n nest.assert_same_structure(state, new_state)\n new_state = nest.flatten(new_state)\n new_output = nest.flatten(new_output)\n final_output_and_state = _copy_some_through(new_output, new_state)\n else:\n empty_update = lambda: flat_zero_output + flat_state\n final_output_and_state = control_flow_ops.cond(\n # if t >= max_seq_len: copy all state through, output zeros\n time >= max_sequence_length, empty_update,\n # otherwise calculation is required: copy some or all of it through\n _maybe_copy_some_through)\n\n if len(final_output_and_state) != len(flat_zero_output) + len(flat_state):\n raise ValueError(\"Internal error: state and output were not concatenated \"\n \"correctly.\")\n final_output = final_output_and_state[:len(flat_zero_output)]\n final_state = final_output_and_state[len(flat_zero_output):]\n\n for output, flat_output in zip(final_output, flat_zero_output):\n output.set_shape(flat_output.get_shape())\n for substate, flat_substate in zip(final_state, flat_state):\n substate.set_shape(flat_substate.get_shape())\n\n final_output = nest.pack_sequence_as(\n structure=zero_output, flat_sequence=final_output)\n final_state = nest.pack_sequence_as(\n structure=state, flat_sequence=final_state)\n\n return final_output, final_state\n\n\ndef _reverse_seq(input_seq, lengths):\n \"\"\"Reverse a list of Tensors up to specified lengths.\n\n Args:\n input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features)\n or nested tuples of tensors.\n lengths: A `Tensor` of dimension batch_size, containing lengths for each\n sequence in the batch. If \"None\" is specified, simply reverses\n the list.\n\n Returns:\n time-reversed sequence\n \"\"\"\n if lengths is None:\n return list(reversed(input_seq))\n\n flat_input_seq = tuple(nest.flatten(input_) for input_ in input_seq)\n\n flat_results = [[] for _ in range(len(input_seq))]\n for sequence in zip(*flat_input_seq):\n input_shape = tensor_shape.unknown_shape(\n ndims=sequence[0].get_shape().ndims)\n for input_ in sequence:\n input_shape.merge_with(input_.get_shape())\n input_.set_shape(input_shape)\n\n # Join into (time, batch_size, depth)\n s_joined = array_ops.stack(sequence)\n\n # Reverse along dimension 0\n s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1)\n # Split again into list\n result = array_ops.unstack(s_reversed)\n for r, flat_result in zip(result, flat_results):\n r.set_shape(input_shape)\n flat_result.append(r)\n\n results = [nest.pack_sequence_as(structure=input_, flat_sequence=flat_result)\n for input_, flat_result in zip(input_seq, flat_results)]\n return results\n\n\ndef bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=None,\n initial_state_fw=None, initial_state_bw=None,\n dtype=None, parallel_iterations=None,\n swap_memory=False, time_major=False, scope=None):\n \"\"\"Creates a dynamic version of bidirectional recurrent neural network.\n\n Takes input and builds independent forward and backward RNNs. The input_size\n of forward and backward cell must match. The initial state for both directions\n is zero by default (but can be set optionally) and no intermediate states are\n ever returned -- the network is fully unrolled for the given (passed in)\n length(s) of the sequence(s) or completely unrolled if length(s) is not\n given.\n\n Args:\n cell_fw: An instance of RNNCell, to be used for forward direction.\n cell_bw: An instance of RNNCell, to be used for backward direction.\n inputs: The RNN inputs.\n If time_major == False (default), this must be a tensor of shape:\n `[batch_size, max_time, ...]`, or a nested tuple of such elements.\n If time_major == True, this must be a tensor of shape:\n `[max_time, batch_size, ...]`, or a nested tuple of such elements.\n sequence_length: (optional) An int32/int64 vector, size `[batch_size]`,\n containing the actual lengths for each of the sequences in the batch.\n If not provided, all batch entries are assumed to be full sequences; and\n time reversal is applied from time `0` to `max_time` for each sequence.\n initial_state_fw: (optional) An initial state for the forward RNN.\n This must be a tensor of appropriate type and shape\n `[batch_size, cell_fw.state_size]`.\n If `cell_fw.state_size` is a tuple, this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell_fw.state_size`.\n initial_state_bw: (optional) Same as for `initial_state_fw`, but using\n the corresponding properties of `cell_bw`.\n dtype: (optional) The data type for the initial states and expected output.\n Required if initial_states are not provided or RNN states have a\n heterogeneous dtype.\n parallel_iterations: (Default: 32). The number of iterations to run in\n parallel. Those operations which do not have any temporal dependency\n and can be run in parallel, will be. This parameter trades off\n time for space. Values >> 1 use more memory but take less time,\n while smaller values use less memory but computations take longer.\n swap_memory: Transparently swap the tensors produced in forward inference\n but needed for back prop from GPU to CPU. This allows training RNNs\n which would typically not fit on a single GPU, with very minimal (or no)\n performance penalty.\n time_major: The shape format of the `inputs` and `outputs` Tensors.\n If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.\n If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.\n Using `time_major = True` is a bit more efficient because it avoids\n transposes at the beginning and end of the RNN calculation. However,\n most TensorFlow data is batch-major, so by default this function\n accepts input and emits output in batch-major form.\n scope: VariableScope for the created subgraph; defaults to\n \"bidirectional_rnn\"\n\n Returns:\n A tuple (outputs, output_states) where:\n outputs: A tuple (output_fw, output_bw) containing the forward and\n the backward rnn output `Tensor`.\n If time_major == False (default),\n output_fw will be a `Tensor` shaped:\n `[batch_size, max_time, cell_fw.output_size]`\n and output_bw will be a `Tensor` shaped:\n `[batch_size, max_time, cell_bw.output_size]`.\n If time_major == True,\n output_fw will be a `Tensor` shaped:\n `[max_time, batch_size, cell_fw.output_size]`\n and output_bw will be a `Tensor` shaped:\n `[max_time, batch_size, cell_bw.output_size]`.\n It returns a tuple instead of a single concatenated `Tensor`, unlike\n in the `bidirectional_rnn`. If the concatenated one is preferred,\n the forward and backward outputs can be concatenated as\n `tf.concat(outputs, 2)`.\n output_states: A tuple (output_state_fw, output_state_bw) containing\n the forward and the backward final states of bidirectional rnn.\n\n Raises:\n TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.\n \"\"\"\n\n \n assert_like_rnncell(\"cell_fw\", cell_fw)\n assert_like_rnncell(\"cell_bw\", cell_bw)\n with vs.variable_scope(scope or \"bidirectional_rnn\"):\n # Forward direction\n with vs.variable_scope(\"fw\") as fw_scope:\n output_fw, output_state_fw = dynamic_rnn(\n cell=cell_fw, inputs=inputs, sequence_length=sequence_length,\n initial_state=initial_state_fw, dtype=dtype,\n parallel_iterations=parallel_iterations, swap_memory=swap_memory,\n time_major=time_major, scope=fw_scope)\n\n # Backward direction\n if not time_major:\n time_dim = 1\n batch_dim = 0\n else:\n time_dim = 0\n batch_dim = 1\n\n def _reverse(input_, seq_lengths, seq_dim, batch_dim):\n if seq_lengths is not None:\n return array_ops.reverse_sequence(\n input=input_, seq_lengths=seq_lengths,\n seq_dim=seq_dim, batch_dim=batch_dim)\n else:\n return array_ops.reverse(input_, axis=[seq_dim])\n\n with vs.variable_scope(\"bw\") as bw_scope:\n inputs_reverse = _reverse(\n inputs, seq_lengths=sequence_length,\n seq_dim=time_dim, batch_dim=batch_dim)\n tmp, output_state_bw = dynamic_rnn(\n cell=cell_bw, inputs=inputs_reverse, sequence_length=sequence_length,\n initial_state=initial_state_bw, dtype=dtype,\n parallel_iterations=parallel_iterations, swap_memory=swap_memory,\n time_major=time_major, scope=bw_scope)\n\n output_bw = _reverse(\n tmp, seq_lengths=sequence_length,\n seq_dim=time_dim, batch_dim=batch_dim)\n\n outputs = (output_fw, output_bw)\n output_states = (output_state_fw, output_state_bw)\n\n return (outputs, output_states)\n\n\ndef dynamic_rnn(cell, inputs, att_scores=None, sequence_length=None, initial_state=None,\n dtype=None, parallel_iterations=None, swap_memory=False,\n time_major=False, scope=None):\n \"\"\"Creates a recurrent neural network specified by RNNCell `cell`.\n\n Performs fully dynamic unrolling of `inputs`.\n\n Example:\n\n ```python\n # create a BasicRNNCell\n rnn_cell = tf.nn.rnn_cell.BasicRNNCell(hidden_size)\n\n # 'outputs' is a tensor of shape [batch_size, max_time, cell_state_size]\n\n # defining initial state\n initial_state = rnn_cell.zero_state(batch_size, dtype=tf.float32)\n\n # 'state' is a tensor of shape [batch_size, cell_state_size]\n outputs, state = tf.nn.dynamic_rnn(rnn_cell, input_data,\n initial_state=initial_state,\n dtype=tf.float32)\n ```\n\n ```python\n # create 2 LSTMCells\n rnn_layers = [tf.nn.rnn_cell.LSTMCell(size) for size in [128, 256]]\n\n # create a RNN cell composed sequentially of a number of RNNCells\n multi_rnn_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers)\n\n # 'outputs' is a tensor of shape [batch_size, max_time, 256]\n # 'state' is a N-tuple where N is the number of LSTMCells containing a\n # tf.contrib.rnn.LSTMStateTuple for each cell\n outputs, state = tf.nn.dynamic_rnn(cell=multi_rnn_cell,\n inputs=data,\n dtype=tf.float32)\n ```\n\n\n Args:\n cell: An instance of RNNCell.\n inputs: The RNN inputs.\n If `time_major == False` (default), this must be a `Tensor` of shape:\n `[batch_size, max_time, ...]`, or a nested tuple of such\n elements.\n If `time_major == True`, this must be a `Tensor` of shape:\n `[max_time, batch_size, ...]`, or a nested tuple of such\n elements.\n This may also be a (possibly nested) tuple of Tensors satisfying\n this property. The first two dimensions must match across all the inputs,\n but otherwise the ranks and other shape components may differ.\n In this case, input to `cell` at each time-step will replicate the\n structure of these tuples, except for the time dimension (from which the\n time is taken).\n The input to `cell` at each time step will be a `Tensor` or (possibly\n nested) tuple of Tensors each with dimensions `[batch_size, ...]`.\n sequence_length: (optional) An int32/int64 vector sized `[batch_size]`.\n Used to copy-through state and zero-out outputs when past a batch\n element's sequence length. So it's more for correctness than performance.\n initial_state: (optional) An initial state for the RNN.\n If `cell.state_size` is an integer, this must be\n a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.\n If `cell.state_size` is a tuple, this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell.state_size`.\n dtype: (optional) The data type for the initial state and expected output.\n Required if initial_state is not provided or RNN state has a heterogeneous\n dtype.\n parallel_iterations: (Default: 32). The number of iterations to run in\n parallel. Those operations which do not have any temporal dependency\n and can be run in parallel, will be. This parameter trades off\n time for space. Values >> 1 use more memory but take less time,\n while smaller values use less memory but computations take longer.\n swap_memory: Transparently swap the tensors produced in forward inference\n but needed for back prop from GPU to CPU. This allows training RNNs\n which would typically not fit on a single GPU, with very minimal (or no)\n performance penalty.\n time_major: The shape format of the `inputs` and `outputs` Tensors.\n If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.\n If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.\n Using `time_major = True` is a bit more efficient because it avoids\n transposes at the beginning and end of the RNN calculation. However,\n most TensorFlow data is batch-major, so by default this function\n accepts input and emits output in batch-major form.\n scope: VariableScope for the created subgraph; defaults to \"rnn\".\n\n Returns:\n A pair (outputs, state) where:\n\n outputs: The RNN output `Tensor`.\n\n If time_major == False (default), this will be a `Tensor` shaped:\n `[batch_size, max_time, cell.output_size]`.\n\n If time_major == True, this will be a `Tensor` shaped:\n `[max_time, batch_size, cell.output_size]`.\n\n Note, if `cell.output_size` is a (possibly nested) tuple of integers\n or `TensorShape` objects, then `outputs` will be a tuple having the\n same structure as `cell.output_size`, containing Tensors having shapes\n corresponding to the shape data in `cell.output_size`.\n\n state: The final state. If `cell.state_size` is an int, this\n will be shaped `[batch_size, cell.state_size]`. If it is a\n `TensorShape`, this will be shaped `[batch_size] + cell.state_size`.\n If it is a (possibly nested) tuple of ints or `TensorShape`, this will\n be a tuple having the corresponding shapes. If cells are `LSTMCells`\n `state` will be a tuple containing a `LSTMStateTuple` for each cell.\n\n Raises:\n TypeError: If `cell` is not an instance of RNNCell.\n ValueError: If inputs is None or an empty list.\n \"\"\"\n\n assert_like_rnncell(\"cell\", cell)\n\n # By default, time_major==False and inputs are batch-major: shaped\n # [batch, time, depth]\n # For internal calculations, we transpose to [time, batch, depth]\n flat_input = nest.flatten(inputs)\n\n if not time_major:\n # (B,T,D) => (T,B,D)\n flat_input = [ops.convert_to_tensor(input_) for input_ in flat_input]\n flat_input = tuple(_transpose_batch_time(input_) for input_ in flat_input)\n\n parallel_iterations = parallel_iterations or 32\n if sequence_length is not None:\n sequence_length = math_ops.to_int32(sequence_length)\n if sequence_length.get_shape().ndims not in (None, 1):\n raise ValueError(\n \"sequence_length must be a vector of length batch_size, \"\n \"but saw shape: %s\" % sequence_length.get_shape())\n sequence_length = array_ops.identity( # Just to find it in the graph.\n sequence_length, name=\"sequence_length\")\n\n # Create a new scope in which the caching device is either\n # determined by the parent scope, or is set to place the cached\n # Variable using the same placement as for the rest of the RNN.\n with vs.variable_scope(scope or \"rnn\") as varscope:\n if varscope.caching_device is None:\n varscope.set_caching_device(lambda op: op.device)\n batch_size = _best_effort_input_batch_size(flat_input)\n\n if initial_state is not None:\n state = initial_state\n else:\n if not dtype:\n raise ValueError(\"If there is no initial_state, you must give a dtype.\")\n state = cell.zero_state(batch_size, dtype)\n\n def _assert_has_shape(x, shape):\n x_shape = array_ops.shape(x)\n packed_shape = array_ops.stack(shape)\n return control_flow_ops.Assert(\n math_ops.reduce_all(math_ops.equal(x_shape, packed_shape)),\n [\"Expected shape for Tensor %s is \" % x.name,\n packed_shape, \" but saw shape: \", x_shape])\n\n if sequence_length is not None:\n # Perform some shape validation\n with ops.control_dependencies(\n [_assert_has_shape(sequence_length, [batch_size])]):\n sequence_length = array_ops.identity(\n sequence_length, name=\"CheckSeqLen\")\n\n inputs = nest.pack_sequence_as(structure=inputs, flat_sequence=flat_input)\n\n (outputs, final_state) = _dynamic_rnn_loop(\n cell,\n inputs,\n state,\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory,\n att_scores = att_scores,\n sequence_length=sequence_length,\n dtype=dtype)\n\n # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].\n # If we are performing batch-major calculations, transpose output back\n # to shape [batch, time, depth]\n if not time_major:\n # (T,B,D) => (B,T,D)\n outputs = nest.map_structure(_transpose_batch_time, outputs)\n\n return (outputs, final_state)\n\n\ndef _dynamic_rnn_loop(cell,\n inputs,\n initial_state,\n parallel_iterations,\n swap_memory,\n att_scores = None,\n sequence_length=None,\n dtype=None):\n \"\"\"Internal implementation of Dynamic RNN.\n\n Args:\n cell: An instance of RNNCell.\n inputs: A `Tensor` of shape [time, batch_size, input_size], or a nested\n tuple of such elements.\n initial_state: A `Tensor` of shape `[batch_size, state_size]`, or if\n `cell.state_size` is a tuple, then this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell.state_size`.\n parallel_iterations: Positive Python int.\n swap_memory: A Python boolean\n sequence_length: (optional) An `int32` `Tensor` of shape [batch_size].\n dtype: (optional) Expected dtype of output. If not specified, inferred from\n initial_state.\n\n Returns:\n Tuple `(final_outputs, final_state)`.\n final_outputs:\n A `Tensor` of shape `[time, batch_size, cell.output_size]`. If\n `cell.output_size` is a (possibly nested) tuple of ints or `TensorShape`\n objects, then this returns a (possibly nsted) tuple of Tensors matching\n the corresponding shapes.\n final_state:\n A `Tensor`, or possibly nested tuple of Tensors, matching in length\n and shapes to `initial_state`.\n\n Raises:\n ValueError: If the input depth cannot be inferred via shape inference\n from the inputs.\n \"\"\"\n state = initial_state\n assert isinstance(parallel_iterations, int), \"parallel_iterations must be int\"\n\n state_size = cell.state_size\n\n flat_input = nest.flatten(inputs)\n flat_output_size = nest.flatten(cell.output_size)\n\n # Construct an initial output\n input_shape = array_ops.shape(flat_input[0])\n time_steps = input_shape[0]\n batch_size = _best_effort_input_batch_size(flat_input)\n\n inputs_got_shape = tuple(input_.get_shape().with_rank_at_least(3)\n for input_ in flat_input)\n\n const_time_steps, const_batch_size = inputs_got_shape[0].as_list()[:2]\n\n for shape in inputs_got_shape:\n if not shape[2:].is_fully_defined():\n raise ValueError(\n \"Input size (depth of inputs) must be accessible via shape inference,\"\n \" but saw value None.\")\n got_time_steps = shape[0].value\n got_batch_size = shape[1].value\n if const_time_steps != got_time_steps:\n raise ValueError(\n \"Time steps is not the same for all the elements in the input in a \"\n \"batch.\")\n if const_batch_size != got_batch_size:\n raise ValueError(\n \"Batch_size is not the same for all the elements in the input.\")\n\n # Prepare dynamic conditional copying of state & output\n def _create_zero_arrays(size):\n size = _concat(batch_size, size)\n return array_ops.zeros(\n array_ops.stack(size), _infer_state_dtype(dtype, state))\n\n flat_zero_output = tuple(_create_zero_arrays(output)\n for output in flat_output_size)\n zero_output = nest.pack_sequence_as(structure=cell.output_size,\n flat_sequence=flat_zero_output)\n\n if sequence_length is not None:\n min_sequence_length = math_ops.reduce_min(sequence_length)\n max_sequence_length = math_ops.reduce_max(sequence_length)\n\n time = array_ops.constant(0, dtype=dtypes.int32, name=\"time\")\n\n with ops.name_scope(\"dynamic_rnn\") as scope:\n base_name = scope\n\n def _create_ta(name, dtype):\n return tensor_array_ops.TensorArray(dtype=dtype,\n size=time_steps,\n tensor_array_name=base_name + name)\n\n output_ta = tuple(_create_ta(\"output_%d\" % i,\n _infer_state_dtype(dtype, state))\n for i in range(len(flat_output_size)))\n input_ta = tuple(_create_ta(\"input_%d\" % i, flat_input[i].dtype)\n for i in range(len(flat_input)))\n\n input_ta = tuple(ta.unstack(input_)\n for ta, input_ in zip(input_ta, flat_input))\n\n def _time_step(time, output_ta_t, state, att_scores=None):\n \"\"\"Take a time step of the dynamic RNN.\n\n Args:\n time: int32 scalar Tensor.\n output_ta_t: List of `TensorArray`s that represent the output.\n state: nested tuple of vector tensors that represent the state.\n\n Returns:\n The tuple (time + 1, output_ta_t with updated flow, new_state).\n \"\"\"\n\n input_t = tuple(ta.read(time) for ta in input_ta)\n # Restore some shape information\n for input_, shape in zip(input_t, inputs_got_shape):\n input_.set_shape(shape[1:])\n\n input_t = nest.pack_sequence_as(structure=inputs, flat_sequence=input_t)\n if att_scores is not None:\n att_score = att_scores[:, time, :]\n call_cell = lambda: cell(input_t, state, att_score)\n else:\n call_cell = lambda: cell(input_t, state)\n\n if sequence_length is not None:\n (output, new_state) = _rnn_step(\n time=time,\n sequence_length=sequence_length,\n min_sequence_length=min_sequence_length,\n max_sequence_length=max_sequence_length,\n zero_output=zero_output,\n state=state,\n call_cell=call_cell,\n state_size=state_size,\n skip_conditionals=True)\n else:\n (output, new_state) = call_cell()\n\n # Pack state if using state tuples\n output = nest.flatten(output)\n\n output_ta_t = tuple(\n ta.write(time, out) for ta, out in zip(output_ta_t, output))\n if att_scores is not None:\n return (time + 1, output_ta_t, new_state, att_scores)\n else:\n return (time + 1, output_ta_t, new_state)\n\n if att_scores is not None: \n _, output_final_ta, final_state, _ = control_flow_ops.while_loop(\n cond=lambda time, *_: time < time_steps,\n body=_time_step,\n loop_vars=(time, output_ta, state, att_scores),\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory)\n else:\n _, output_final_ta, final_state = control_flow_ops.while_loop(\n cond=lambda time, *_: time < time_steps,\n body=_time_step,\n loop_vars=(time, output_ta, state),\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory)\n\n # Unpack final output if not using output tuples.\n final_outputs = tuple(ta.stack() for ta in output_final_ta)\n\n # Restore some shape information\n for output, output_size in zip(final_outputs, flat_output_size):\n shape = _concat(\n [const_time_steps, const_batch_size], output_size, static=True)\n output.set_shape(shape)\n\n final_outputs = nest.pack_sequence_as(\n structure=cell.output_size, flat_sequence=final_outputs)\n\n return (final_outputs, final_state)\n\n\ndef raw_rnn(cell, loop_fn,\n parallel_iterations=None, swap_memory=False, scope=None):\n \"\"\"Creates an `RNN` specified by RNNCell `cell` and loop function `loop_fn`.\n\n **NOTE: This method is still in testing, and the API may change.**\n\n This function is a more primitive version of `dynamic_rnn` that provides\n more direct access to the inputs each iteration. It also provides more\n control over when to start and finish reading the sequence, and\n what to emit for the output.\n\n For example, it can be used to implement the dynamic decoder of a seq2seq\n model.\n\n Instead of working with `Tensor` objects, most operations work with\n `TensorArray` objects directly.\n\n The operation of `raw_rnn`, in pseudo-code, is basically the following:\n\n ```python\n time = tf.constant(0, dtype=tf.int32)\n (finished, next_input, initial_state, _, loop_state) = loop_fn(\n time=time, cell_output=None, cell_state=None, loop_state=None)\n emit_ta = TensorArray(dynamic_size=True, dtype=initial_state.dtype)\n state = initial_state\n while not all(finished):\n (output, cell_state) = cell(next_input, state)\n (next_finished, next_input, next_state, emit, loop_state) = loop_fn(\n time=time + 1, cell_output=output, cell_state=cell_state,\n loop_state=loop_state)\n # Emit zeros and copy forward state for minibatch entries that are finished.\n state = tf.where(finished, state, next_state)\n emit = tf.where(finished, tf.zeros_like(emit), emit)\n emit_ta = emit_ta.write(time, emit)\n # If any new minibatch entries are marked as finished, mark these.\n finished = tf.logical_or(finished, next_finished)\n time += 1\n return (emit_ta, state, loop_state)\n ```\n\n with the additional properties that output and state may be (possibly nested)\n tuples, as determined by `cell.output_size` and `cell.state_size`, and\n as a result the final `state` and `emit_ta` may themselves be tuples.\n\n A simple implementation of `dynamic_rnn` via `raw_rnn` looks like this:\n\n ```python\n inputs = tf.placeholder(shape=(max_time, batch_size, input_depth),\n dtype=tf.float32)\n sequence_length = tf.placeholder(shape=(batch_size,), dtype=tf.int32)\n inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time)\n inputs_ta = inputs_ta.unstack(inputs)\n\n cell = tf.contrib.rnn.LSTMCell(num_units)\n\n def loop_fn(time, cell_output, cell_state, loop_state):\n emit_output = cell_output # == None for time == 0\n if cell_output is None: # time == 0\n next_cell_state = cell.zero_state(batch_size, tf.float32)\n else:\n next_cell_state = cell_state\n elements_finished = (time >= sequence_length)\n finished = tf.reduce_all(elements_finished)\n next_input = tf.cond(\n finished,\n lambda: tf.zeros([batch_size, input_depth], dtype=tf.float32),\n lambda: inputs_ta.read(time))\n next_loop_state = None\n return (elements_finished, next_input, next_cell_state,\n emit_output, next_loop_state)\n\n outputs_ta, final_state, _ = raw_rnn(cell, loop_fn)\n outputs = outputs_ta.stack()\n ```\n\n Args:\n cell: An instance of RNNCell.\n loop_fn: A callable that takes inputs\n `(time, cell_output, cell_state, loop_state)`\n and returns the tuple\n `(finished, next_input, next_cell_state, emit_output, next_loop_state)`.\n Here `time` is an int32 scalar `Tensor`, `cell_output` is a\n `Tensor` or (possibly nested) tuple of tensors as determined by\n `cell.output_size`, and `cell_state` is a `Tensor`\n or (possibly nested) tuple of tensors, as determined by the `loop_fn`\n on its first call (and should match `cell.state_size`).\n The outputs are: `finished`, a boolean `Tensor` of\n shape `[batch_size]`, `next_input`: the next input to feed to `cell`,\n `next_cell_state`: the next state to feed to `cell`,\n and `emit_output`: the output to store for this iteration.\n\n Note that `emit_output` should be a `Tensor` or (possibly nested)\n tuple of tensors with shapes and structure matching `cell.output_size`\n and `cell_output` above. The parameter `cell_state` and output\n `next_cell_state` may be either a single or (possibly nested) tuple\n of tensors. The parameter `loop_state` and\n output `next_loop_state` may be either a single or (possibly nested) tuple\n of `Tensor` and `TensorArray` objects. This last parameter\n may be ignored by `loop_fn` and the return value may be `None`. If it\n is not `None`, then the `loop_state` will be propagated through the RNN\n loop, for use purely by `loop_fn` to keep track of its own state.\n The `next_loop_state` parameter returned may be `None`.\n\n The first call to `loop_fn` will be `time = 0`, `cell_output = None`,\n `cell_state = None`, and `loop_state = None`. For this call:\n The `next_cell_state` value should be the value with which to initialize\n the cell's state. It may be a final state from a previous RNN or it\n may be the output of `cell.zero_state()`. It should be a\n (possibly nested) tuple structure of tensors.\n If `cell.state_size` is an integer, this must be\n a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.\n If `cell.state_size` is a `TensorShape`, this must be a `Tensor` of\n appropriate type and shape `[batch_size] + cell.state_size`.\n If `cell.state_size` is a (possibly nested) tuple of ints or\n `TensorShape`, this will be a tuple having the corresponding shapes.\n The `emit_output` value may be either `None` or a (possibly nested)\n tuple structure of tensors, e.g.,\n `(tf.zeros(shape_0, dtype=dtype_0), tf.zeros(shape_1, dtype=dtype_1))`.\n If this first `emit_output` return value is `None`,\n then the `emit_ta` result of `raw_rnn` will have the same structure and\n dtypes as `cell.output_size`. Otherwise `emit_ta` will have the same\n structure, shapes (prepended with a `batch_size` dimension), and dtypes\n as `emit_output`. The actual values returned for `emit_output` at this\n initializing call are ignored. Note, this emit structure must be\n consistent across all time steps.\n\n parallel_iterations: (Default: 32). The number of iterations to run in\n parallel. Those operations which do not have any temporal dependency\n and can be run in parallel, will be. This parameter trades off\n time for space. Values >> 1 use more memory but take less time,\n while smaller values use less memory but computations take longer.\n swap_memory: Transparently swap the tensors produced in forward inference\n but needed for back prop from GPU to CPU. This allows training RNNs\n which would typically not fit on a single GPU, with very minimal (or no)\n performance penalty.\n scope: VariableScope for the created subgraph; defaults to \"rnn\".\n\n Returns:\n A tuple `(emit_ta, final_state, final_loop_state)` where:\n\n `emit_ta`: The RNN output `TensorArray`.\n If `loop_fn` returns a (possibly nested) set of Tensors for\n `emit_output` during initialization, (inputs `time = 0`,\n `cell_output = None`, and `loop_state = None`), then `emit_ta` will\n have the same structure, dtypes, and shapes as `emit_output` instead.\n If `loop_fn` returns `emit_output = None` during this call,\n the structure of `cell.output_size` is used:\n If `cell.output_size` is a (possibly nested) tuple of integers\n or `TensorShape` objects, then `emit_ta` will be a tuple having the\n same structure as `cell.output_size`, containing TensorArrays whose\n elements' shapes correspond to the shape data in `cell.output_size`.\n\n `final_state`: The final cell state. If `cell.state_size` is an int, this\n will be shaped `[batch_size, cell.state_size]`. If it is a\n `TensorShape`, this will be shaped `[batch_size] + cell.state_size`.\n If it is a (possibly nested) tuple of ints or `TensorShape`, this will\n be a tuple having the corresponding shapes.\n\n `final_loop_state`: The final loop state as returned by `loop_fn`.\n\n Raises:\n TypeError: If `cell` is not an instance of RNNCell, or `loop_fn` is not\n a `callable`.\n \"\"\"\n\n assert_like_rnncell(\"cell\", cell)\n if not callable(loop_fn):\n raise TypeError(\"loop_fn must be a callable\")\n\n parallel_iterations = parallel_iterations or 32\n\n # Create a new scope in which the caching device is either\n # determined by the parent scope, or is set to place the cached\n # Variable using the same placement as for the rest of the RNN.\n with vs.variable_scope(scope or \"rnn\") as varscope:\n if varscope.caching_device is None:\n varscope.set_caching_device(lambda op: op.device)\n\n time = constant_op.constant(0, dtype=dtypes.int32)\n (elements_finished, next_input, initial_state, emit_structure,\n init_loop_state) = loop_fn(\n time, None, None, None) # time, cell_output, cell_state, loop_state\n flat_input = nest.flatten(next_input)\n\n # Need a surrogate loop state for the while_loop if none is available.\n loop_state = (init_loop_state if init_loop_state is not None\n else constant_op.constant(0, dtype=dtypes.int32))\n\n input_shape = [input_.get_shape() for input_ in flat_input]\n static_batch_size = input_shape[0][0]\n\n for input_shape_i in input_shape:\n # Static verification that batch sizes all match\n static_batch_size.merge_with(input_shape_i[0])\n\n batch_size = static_batch_size.value\n if batch_size is None:\n batch_size = array_ops.shape(flat_input[0])[0]\n\n nest.assert_same_structure(initial_state, cell.state_size)\n state = initial_state\n flat_state = nest.flatten(state)\n flat_state = [ops.convert_to_tensor(s) for s in flat_state]\n state = nest.pack_sequence_as(structure=state,\n flat_sequence=flat_state)\n\n if emit_structure is not None:\n flat_emit_structure = nest.flatten(emit_structure)\n flat_emit_size = [emit.shape if emit.shape.is_fully_defined() else\n array_ops.shape(emit) for emit in flat_emit_structure]\n flat_emit_dtypes = [emit.dtype for emit in flat_emit_structure]\n else:\n emit_structure = cell.output_size\n flat_emit_size = nest.flatten(emit_structure)\n flat_emit_dtypes = [flat_state[0].dtype] * len(flat_emit_size)\n\n flat_emit_ta = [\n tensor_array_ops.TensorArray(\n dtype=dtype_i, dynamic_size=True, size=0, name=\"rnn_output_%d\" % i)\n for i, dtype_i in enumerate(flat_emit_dtypes)]\n emit_ta = nest.pack_sequence_as(structure=emit_structure,\n flat_sequence=flat_emit_ta)\n flat_zero_emit = [\n array_ops.zeros(_concat(batch_size, size_i), dtype_i)\n for size_i, dtype_i in zip(flat_emit_size, flat_emit_dtypes)]\n zero_emit = nest.pack_sequence_as(structure=emit_structure,\n flat_sequence=flat_zero_emit)\n\n def condition(unused_time, elements_finished, *_):\n return math_ops.logical_not(math_ops.reduce_all(elements_finished))\n\n def body(time, elements_finished, current_input,\n emit_ta, state, loop_state):\n \"\"\"Internal while loop body for raw_rnn.\n\n Args:\n time: time scalar.\n elements_finished: batch-size vector.\n current_input: possibly nested tuple of input tensors.\n emit_ta: possibly nested tuple of output TensorArrays.\n state: possibly nested tuple of state tensors.\n loop_state: possibly nested tuple of loop state tensors.\n\n Returns:\n Tuple having the same size as Args but with updated values.\n \"\"\"\n (next_output, cell_state) = cell(current_input, state)\n\n nest.assert_same_structure(state, cell_state)\n nest.assert_same_structure(cell.output_size, next_output)\n\n next_time = time + 1\n (next_finished, next_input, next_state, emit_output,\n next_loop_state) = loop_fn(\n next_time, next_output, cell_state, loop_state)\n\n nest.assert_same_structure(state, next_state)\n nest.assert_same_structure(current_input, next_input)\n nest.assert_same_structure(emit_ta, emit_output)\n\n # If loop_fn returns None for next_loop_state, just reuse the\n # previous one.\n loop_state = loop_state if next_loop_state is None else next_loop_state\n\n def _copy_some_through(current, candidate):\n \"\"\"Copy some tensors through via array_ops.where.\"\"\"\n def copy_fn(cur_i, cand_i):\n with ops.colocate_with(cand_i):\n return array_ops.where(elements_finished, cur_i, cand_i)\n return nest.map_structure(copy_fn, current, candidate)\n\n emit_output = _copy_some_through(zero_emit, emit_output)\n next_state = _copy_some_through(state, next_state)\n\n emit_ta = nest.map_structure(\n lambda ta, emit: ta.write(time, emit), emit_ta, emit_output)\n\n elements_finished = math_ops.logical_or(elements_finished, next_finished)\n\n return (next_time, elements_finished, next_input,\n emit_ta, next_state, loop_state)\n\n returned = control_flow_ops.while_loop(\n condition, body, loop_vars=[\n time, elements_finished, next_input,\n emit_ta, state, loop_state],\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory)\n\n (emit_ta, final_state, final_loop_state) = returned[-3:]\n\n if init_loop_state is None:\n final_loop_state = None\n\n return (emit_ta, final_state, final_loop_state)\n\n\ndef static_rnn(cell,\n inputs,\n initial_state=None,\n dtype=None,\n sequence_length=None,\n scope=None):\n \"\"\"Creates a recurrent neural network specified by RNNCell `cell`.\n\n The simplest form of RNN network generated is:\n\n ```python\n state = cell.zero_state(...)\n outputs = []\n for input_ in inputs:\n output, state = cell(input_, state)\n outputs.append(output)\n return (outputs, state)\n ```\n However, a few other options are available:\n\n An initial state can be provided.\n If the sequence_length vector is provided, dynamic calculation is performed.\n This method of calculation does not compute the RNN steps past the maximum\n sequence length of the minibatch (thus saving computational time),\n and properly propagates the state at an example's sequence length\n to the final state output.\n\n The dynamic calculation performed is, at time `t` for batch row `b`,\n\n ```python\n (output, state)(b, t) =\n (t >= sequence_length(b))\n ? (zeros(cell.output_size), states(b, sequence_length(b) - 1))\n : cell(input(b, t), state(b, t - 1))\n ```\n\n Args:\n cell: An instance of RNNCell.\n inputs: A length T list of inputs, each a `Tensor` of shape\n `[batch_size, input_size]`, or a nested tuple of such elements.\n initial_state: (optional) An initial state for the RNN.\n If `cell.state_size` is an integer, this must be\n a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.\n If `cell.state_size` is a tuple, this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell.state_size`.\n dtype: (optional) The data type for the initial state and expected output.\n Required if initial_state is not provided or RNN state has a heterogeneous\n dtype.\n sequence_length: Specifies the length of each sequence in inputs.\n An int32 or int64 vector (tensor) size `[batch_size]`, values in `[0, T)`.\n scope: VariableScope for the created subgraph; defaults to \"rnn\".\n\n Returns:\n A pair (outputs, state) where:\n\n - outputs is a length T list of outputs (one for each input), or a nested\n tuple of such elements.\n - state is the final state\n\n Raises:\n TypeError: If `cell` is not an instance of RNNCell.\n ValueError: If `inputs` is `None` or an empty list, or if the input depth\n (column size) cannot be inferred from inputs via shape inference.\n \"\"\"\n\n assert_like_rnncell(\"cell\", cell)\n if not nest.is_sequence(inputs):\n raise TypeError(\"inputs must be a sequence\")\n if not inputs:\n raise ValueError(\"inputs must not be empty\")\n\n outputs = []\n # Create a new scope in which the caching device is either\n # determined by the parent scope, or is set to place the cached\n # Variable using the same placement as for the rest of the RNN.\n with vs.variable_scope(scope or \"rnn\") as varscope:\n if varscope.caching_device is None:\n varscope.set_caching_device(lambda op: op.device)\n\n # Obtain the first sequence of the input\n first_input = inputs\n while nest.is_sequence(first_input):\n first_input = first_input[0]\n\n # Temporarily avoid EmbeddingWrapper and seq2seq badness\n # TODO(lukaszkaiser): remove EmbeddingWrapper\n if first_input.get_shape().ndims != 1:\n\n input_shape = first_input.get_shape().with_rank_at_least(2)\n fixed_batch_size = input_shape[0]\n\n flat_inputs = nest.flatten(inputs)\n for flat_input in flat_inputs:\n input_shape = flat_input.get_shape().with_rank_at_least(2)\n batch_size, input_size = input_shape[0], input_shape[1:]\n fixed_batch_size.merge_with(batch_size)\n for i, size in enumerate(input_size):\n if size.value is None:\n raise ValueError(\n \"Input size (dimension %d of inputs) must be accessible via \"\n \"shape inference, but saw value None.\" % i)\n else:\n fixed_batch_size = first_input.get_shape().with_rank_at_least(1)[0]\n\n if fixed_batch_size.value:\n batch_size = fixed_batch_size.value\n else:\n batch_size = array_ops.shape(first_input)[0]\n if initial_state is not None:\n state = initial_state\n else:\n if not dtype:\n raise ValueError(\"If no initial_state is provided, \"\n \"dtype must be specified\")\n state = cell.zero_state(batch_size, dtype)\n\n if sequence_length is not None: # Prepare variables\n sequence_length = ops.convert_to_tensor(\n sequence_length, name=\"sequence_length\")\n if sequence_length.get_shape().ndims not in (None, 1):\n raise ValueError(\n \"sequence_length must be a vector of length batch_size\")\n\n def _create_zero_output(output_size):\n # convert int to TensorShape if necessary\n size = _concat(batch_size, output_size)\n output = array_ops.zeros(\n array_ops.stack(size), _infer_state_dtype(dtype, state))\n shape = _concat(fixed_batch_size.value, output_size, static=True)\n output.set_shape(tensor_shape.TensorShape(shape))\n return output\n\n output_size = cell.output_size\n flat_output_size = nest.flatten(output_size)\n flat_zero_output = tuple(\n _create_zero_output(size) for size in flat_output_size)\n zero_output = nest.pack_sequence_as(\n structure=output_size, flat_sequence=flat_zero_output)\n\n sequence_length = math_ops.to_int32(sequence_length)\n min_sequence_length = math_ops.reduce_min(sequence_length)\n max_sequence_length = math_ops.reduce_max(sequence_length)\n\n for time, input_ in enumerate(inputs):\n if time > 0:\n varscope.reuse_variables()\n # pylint: disable=cell-var-from-loop\n call_cell = lambda: cell(input_, state)\n # pylint: enable=cell-var-from-loop\n if sequence_length is not None:\n (output, state) = _rnn_step(\n time=time,\n sequence_length=sequence_length,\n min_sequence_length=min_sequence_length,\n max_sequence_length=max_sequence_length,\n zero_output=zero_output,\n state=state,\n call_cell=call_cell,\n state_size=cell.state_size)\n else:\n (output, state) = call_cell()\n\n outputs.append(output)\n\n return (outputs, state)\n\n\ndef static_state_saving_rnn(cell,\n inputs,\n state_saver,\n state_name,\n sequence_length=None,\n scope=None):\n \"\"\"RNN that accepts a state saver for time-truncated RNN calculation.\n\n Args:\n cell: An instance of `RNNCell`.\n inputs: A length T list of inputs, each a `Tensor` of shape\n `[batch_size, input_size]`.\n state_saver: A state saver object with methods `state` and `save_state`.\n state_name: Python string or tuple of strings. The name to use with the\n state_saver. If the cell returns tuples of states (i.e.,\n `cell.state_size` is a tuple) then `state_name` should be a tuple of\n strings having the same length as `cell.state_size`. Otherwise it should\n be a single string.\n sequence_length: (optional) An int32/int64 vector size [batch_size].\n See the documentation for rnn() for more details about sequence_length.\n scope: VariableScope for the created subgraph; defaults to \"rnn\".\n\n Returns:\n A pair (outputs, state) where:\n outputs is a length T list of outputs (one for each input)\n states is the final state\n\n Raises:\n TypeError: If `cell` is not an instance of RNNCell.\n ValueError: If `inputs` is `None` or an empty list, or if the arity and\n type of `state_name` does not match that of `cell.state_size`.\n \"\"\"\n state_size = cell.state_size\n state_is_tuple = nest.is_sequence(state_size)\n state_name_tuple = nest.is_sequence(state_name)\n\n if state_is_tuple != state_name_tuple:\n raise ValueError(\"state_name should be the same type as cell.state_size. \"\n \"state_name: %s, cell.state_size: %s\" % (str(state_name),\n str(state_size)))\n\n if state_is_tuple:\n state_name_flat = nest.flatten(state_name)\n state_size_flat = nest.flatten(state_size)\n\n if len(state_name_flat) != len(state_size_flat):\n raise ValueError(\"#elems(state_name) != #elems(state_size): %d vs. %d\" %\n (len(state_name_flat), len(state_size_flat)))\n\n initial_state = nest.pack_sequence_as(\n structure=state_size,\n flat_sequence=[state_saver.state(s) for s in state_name_flat])\n else:\n initial_state = state_saver.state(state_name)\n\n (outputs, state) = static_rnn(\n cell,\n inputs,\n initial_state=initial_state,\n sequence_length=sequence_length,\n scope=scope)\n\n if state_is_tuple:\n flat_state = nest.flatten(state)\n state_name = nest.flatten(state_name)\n save_state = [\n state_saver.save_state(name, substate)\n for name, substate in zip(state_name, flat_state)\n ]\n else:\n save_state = [state_saver.save_state(state_name, state)]\n\n with ops.control_dependencies(save_state):\n last_output = outputs[-1]\n flat_last_output = nest.flatten(last_output)\n flat_last_output = [\n array_ops.identity(output) for output in flat_last_output\n ]\n outputs[-1] = nest.pack_sequence_as(\n structure=last_output, flat_sequence=flat_last_output)\n\n return (outputs, state)\n\n\ndef static_bidirectional_rnn(cell_fw,\n cell_bw,\n inputs,\n initial_state_fw=None,\n initial_state_bw=None,\n dtype=None,\n sequence_length=None,\n scope=None):\n \"\"\"Creates a bidirectional recurrent neural network.\n\n Similar to the unidirectional case above (rnn) but takes input and builds\n independent forward and backward RNNs with the final forward and backward\n outputs depth-concatenated, such that the output will have the format\n [time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of\n forward and backward cell must match. The initial state for both directions\n is zero by default (but can be set optionally) and no intermediate states are\n ever returned -- the network is fully unrolled for the given (passed in)\n length(s) of the sequence(s) or completely unrolled if length(s) is not given.\n\n Args:\n cell_fw: An instance of RNNCell, to be used for forward direction.\n cell_bw: An instance of RNNCell, to be used for backward direction.\n inputs: A length T list of inputs, each a tensor of shape\n [batch_size, input_size], or a nested tuple of such elements.\n initial_state_fw: (optional) An initial state for the forward RNN.\n This must be a tensor of appropriate type and shape\n `[batch_size, cell_fw.state_size]`.\n If `cell_fw.state_size` is a tuple, this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell_fw.state_size`.\n initial_state_bw: (optional) Same as for `initial_state_fw`, but using\n the corresponding properties of `cell_bw`.\n dtype: (optional) The data type for the initial state. Required if\n either of the initial states are not provided.\n sequence_length: (optional) An int32/int64 vector, size `[batch_size]`,\n containing the actual lengths for each of the sequences.\n scope: VariableScope for the created subgraph; defaults to\n \"bidirectional_rnn\"\n\n Returns:\n A tuple (outputs, output_state_fw, output_state_bw) where:\n outputs is a length `T` list of outputs (one for each input), which\n are depth-concatenated forward and backward outputs.\n output_state_fw is the final state of the forward rnn.\n output_state_bw is the final state of the backward rnn.\n\n Raises:\n TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.\n ValueError: If inputs is None or an empty list.\n \"\"\"\n\n if not _like_rnncell(cell_fw):\n raise TypeError(\"cell_fw must be an instance of RNNCell\")\n if not _like_rnncell(cell_bw):\n raise TypeError(\"cell_bw must be an instance of RNNCell\")\n if not nest.is_sequence(inputs):\n raise TypeError(\"inputs must be a sequence\")\n if not inputs:\n raise ValueError(\"inputs must not be empty\")\n\n with vs.variable_scope(scope or \"bidirectional_rnn\"):\n # Forward direction\n with vs.variable_scope(\"fw\") as fw_scope:\n output_fw, output_state_fw = static_rnn(\n cell_fw,\n inputs,\n initial_state_fw,\n dtype,\n sequence_length,\n scope=fw_scope)\n\n # Backward direction\n with vs.variable_scope(\"bw\") as bw_scope:\n reversed_inputs = _reverse_seq(inputs, sequence_length)\n tmp, output_state_bw = static_rnn(\n cell_bw,\n reversed_inputs,\n initial_state_bw,\n dtype,\n sequence_length,\n scope=bw_scope)\n\n output_bw = _reverse_seq(tmp, sequence_length)\n # Concat each of the forward/backward outputs\n flat_output_fw = nest.flatten(output_fw)\n flat_output_bw = nest.flatten(output_bw)\n\n flat_outputs = tuple(\n array_ops.concat([fw, bw], 1)\n for fw, bw in zip(flat_output_fw, flat_output_bw))\n\n outputs = nest.pack_sequence_as(\n structure=output_fw, flat_sequence=flat_outputs)\n\n return (outputs, output_state_fw, output_state_bw)\n" ]
[ [ "tensorflow.python.ops.math_ops.equal", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.ops.array_ops.reverse", "tensorflow.python.util.nest.flatten", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.util.nest.is_sequence", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.util.nest.assert_same_structure", "tensorflow.python.ops.array_ops.reverse_sequence", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.math_ops.reduce_min", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.math_ops.reduce_all", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.control_flow_ops.while_loop", "tensorflow.python.ops.math_ops.to_int32", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.math_ops.logical_or", "tensorflow.python.ops.array_ops.constant", "tensorflow.python.ops.control_flow_ops.cond", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.math_ops.reduce_max", "tensorflow.python.ops.tensor_array_ops.TensorArray", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.where", "tensorflow.python.util.nest.map_structure", "tensorflow.python.util.nest.pack_sequence_as" ] ]
ankurankan/game_of_life
[ "81cf2f7f70a05019e78206d1ee7a8205aa590186" ]
[ "main.py" ]
[ "from time import sleep\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef get_initial_state(size):\n return np.random.choice([0, 1], size)\n\ndef compute_next_state(state):\n new_state = np.zeros(state.shape, dtype=int)\n for i in range(state.shape[0]):\n for j in range(state.shape[1]):\n low_x, high_x = max(0, i-1), min(i+2, state.shape[0])\n low_y, high_y = max(0, j-1), min(j+2, state.shape[1])\n n_live = np.sum(state[low_x: high_x, low_y: high_y]) - state[i, j]\n\n if (state[i, j] == 1) and (n_live < 2):\n new_state[i, j] = 0\n elif (state[i, j] == 1) and (2 <= n_live <= 3):\n new_state[i, j] = 1\n elif (state[i, j] == 1) and (n_live > 3):\n new_state[i, j] = 0\n elif (state[i, j] == 0) and (n_live == 3):\n new_state[i, j] = 1\n else:\n new_state[i, j] = state[i, j]\n\n return new_state\n\n\ndef start(initial_state=None, loop_delay=1, size=(200, 200)):\n if initial_state is None:\n state = get_initial_state(size)\n else:\n state = initial_state\n size = state.shape\n\n age = np.zeros(size, dtype=int)\n counter = 0\n\n while True:\n new_state = compute_next_state(state)\n age += new_state\n age = age * new_state\n counter += 1\n plt.imshow(age, cmap='Greys')\n plt.xlim(right=size[1], left=0)\n plt.ylim(top=0, bottom=size[0])\n plt.pause(loop_delay)\n\n if (np.sum(new_state) == 0) or (new_state == state).all():\n print(counter)\n state = get_initial_state(size)\n age = np.zeros(size, dtype=int)\n counter = 0\n\n else:\n state = new_state\n\nif __name__ == \"__main__\":\n start()\n" ]
[ [ "numpy.sum", "matplotlib.pyplot.pause", "numpy.zeros", "numpy.random.choice", "matplotlib.pyplot.xlim", "matplotlib.pyplot.imshow", "matplotlib.pyplot.ylim" ] ]
ioangatop/srVAE
[ "dfee765c53f11f4653e7c6e7118a339832656867" ]
[ "src/utils/args.py" ]
[ "import torch\nimport argparse\n\n# ----- Parser -----\n\ndef parser():\n PARSER = argparse.ArgumentParser(description='Training parameters.')\n\n # Dataset\n PARSER.add_argument('--dataset', default='CIFAR10', type=str,\n choices=['CIFAR10', 'CelebA', 'Imagenette', 'ImageNet32', 'ImageNet64'],\n help=\"Data to be used.\")\n PARSER.add_argument('--img_resize', default=32, type=int,\n help='Change image resolution.')\n\n # Model\n PARSER.add_argument('--model', default='VAE', type=str,\n choices=['VAE', 'srVAE'],\n help=\"Model to be used.\")\n PARSER.add_argument('--network', default='densenet32', type=str,\n choices=['densenet32', 'densenet16x32'],\n help=\"Neural Network architecture to be used.\")\n\n # Prior\n PARSER.add_argument('--prior', default='MixtureOfGaussians', type=str,\n choices=['StandardNormal', 'MixtureOfGaussians', 'RealNVP'],\n help='Prior type.')\n PARSER.add_argument('--z_dim', default=1024, type=int,\n help='Dimensionality of z latent space.')\n PARSER.add_argument('--u_dim', default=1024, type=int,\n help='Dimensionality of z latent space.')\n\n # data likelihood\n PARSER.add_argument('--likelihood', default='dmol', type=str,\n choices=['dmol'],\n help=\"Type of likelihood.\")\n PARSER.add_argument('--iw_test', default=512, type=int,\n help=\"Number of Importance Weighting samples used for approximating the test log-likelihood.\")\n\n # Training Parameters\n PARSER.add_argument('--batch_size', default=32, type=int,\n help='Batch size.')\n PARSER.add_argument('--epochs', default=2000, type=int,\n help='Number of training epochs.')\n\n # General Configs\n PARSER.add_argument('--seed', default=None, type=int,\n help='Fix random seed.')\n PARSER.add_argument('--n_samples', default=8, type=int,\n help='Number of generated samples.')\n PARSER.add_argument('--log_interval', default=True, type=bool,\n help='Print progress on every batch.')\n PARSER.add_argument('--device', default=None, type=str,\n choices=['cpu', 'cuda'],\n help='Device to run the experiment.')\n\n PARSER.add_argument('--use_tb', default=True, type=bool,\n help='Use TensorBoard.')\n PARSER.add_argument('--tags', default='logs', type=str,\n help='Run tags.')\n\n\n ARGS = PARSER.parse_args()\n\n # Check device\n if ARGS.device is None:\n ARGS.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n return ARGS\n\n\nargs = parser()\n\n\nif __name__ == \"__main__\":\n pass\n" ]
[ [ "torch.cuda.is_available" ] ]
KanHatakeyama/annealing_project
[ "eac2dfe65c480450a5d12b09db2c1c9f83d03389" ]
[ "lib/composite/LiPolymerDataScaler.py" ]
[ "import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom DataUtility import get_column_names\n\n\nclass LiPolymerDataScaler:\n \"\"\"\n a special class to scale the lithium polymer database\n \"\"\"\n\n def __init__(self):\n self.scaling_dict = {}\n self.main_val_params = [\"SMILES_wt\", \"wt_ratio\", \"inorg_contain_ratio\"]\n self.main_txt_params = [\"structureList\", \"inorg_name\"]\n self.main_params = self.main_val_params+self.main_txt_params\n self.target_param = \"Conductivity\"\n\n def mutual_process(self, df):\n \"\"\"\n convert values (to log, etc)\n \"\"\"\n df[\"Conductivity\"] = np.log10(df[\"Conductivity\"].astype('float'))\n df[\"Temperature\"] = np.log10(df[\"Temperature\"].astype('float')+273)\n\n # fill Nan by zero\n for c in self.main_params:\n target_columns = get_column_names(df, c)\n df[target_columns] = df[target_columns].fillna(0)\n\n # convert molecular weight\n self.mw_column_list = get_column_names(df, \"MWList\")\n for c in self.mw_column_list:\n df[c] = np.log10(df[c].astype('float'))\n\n return df\n\n def fit_transform(self, original_df):\n \"\"\"\n scaling data, etc\n\n Parameters\n ----------------\n original_df: dataframe\n dataframe to be scaled\n\n Returns\n ----------------\n df: dataframe\n scaled dataframe\n \"\"\"\n df = original_df.copy()\n df = self.mutual_process(df)\n\n # fill lacking Molecular weight with average value\n self.average_mw = sum(df[self.mw_column_list].sum()) / \\\n sum(df[self.mw_column_list].count())\n\n for c in self.mw_column_list:\n df[c] = df[c].fillna(self.average_mw)\n\n # scaling\n for v in self.main_val_params + [\"Conductivity\", \"Temperature\"]+self.mw_column_list:\n for c in get_column_names(df, v):\n sc = StandardScaler()\n df[c] = sc.fit_transform(\n df[c].astype('float').values.reshape(-1, 1))\n self.scaling_dict[c] = sc\n\n # onehot encoding\n for v in self.main_txt_params:\n df = pd.get_dummies(df, columns=get_column_names(df, v))\n\n self.use_columns = []\n\n for c in [\"Conductivity\", \"Temperature\"]+self.main_params + self.mw_column_list+[\"fp_list\"]:\n self.use_columns.extend(get_column_names(df, c))\n\n \"\"\" \n **********************************************************\n delete some columns for easiness of machine learning\n following parameters can be useful for machine learning (10.1021/jacs.9b11442), but ignored in this project.\n \"\"\"\n for remove_targets in [\"MWList\", \"wt_ratio\", \"inorg\", \"structure\", \"Temperature\"]:\n del_columns = get_column_names(df, remove_targets)\n for i in del_columns:\n self.use_columns.remove(i)\n\n self.tr_df = df\n return df\n\n def transform(self, original_df):\n \"\"\"\n scaling data, etc\n\n Parameters\n ----------------\n original_df: dataframe\n dataframe to be scaled\n\n Returns\n ----------------\n df: dataframe\n scaled dataframe\n \"\"\"\n df = original_df.copy()\n df = self.mutual_process(df)\n\n for c in self.mw_column_list:\n df[c] = df[c].fillna(self.average_mw)\n\n # scaling\n for v in self.main_val_params + [\"Conductivity\", \"Temperature\"]+self.mw_column_list:\n for c in get_column_names(df, v):\n df[c] = self.scaling_dict[c].transform(\n df[c].astype('float').values.reshape(-1, 1))\n\n # onehot encoding\n for v in self.main_txt_params:\n df = pd.get_dummies(df, columns=get_column_names(df, v))\n\n # for lacking columns, add the most frequent vals\n lacking_columns = set(self.use_columns)-set(df.columns)\n\n for i in lacking_columns:\n df[i] = self.tr_df[i].mode()\n\n return df\n" ]
[ [ "sklearn.preprocessing.StandardScaler" ] ]
danielschulz/MONAI
[ "54ef6e9e700f0de3d50184c0148f953be871a58e" ]
[ "monai/metrics/surface_distance.py" ]
[ "# Copyright 2020 - 2021 MONAI Consortium\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport warnings\nfrom typing import Union\n\nimport numpy as np\nimport torch\n\nfrom monai.metrics.utils import *\nfrom monai.utils import MetricReduction\n\n\nclass SurfaceDistanceMetric:\n \"\"\"\n Compute Surface Distance between two tensors. It can support both multi-classes and multi-labels tasks.\n It supports both symmetric and asymmetric surface distance calculation.\n Input `y_pred` (BNHW[D] where N is number of classes) is compared with ground truth `y` (BNHW[D]).\n `y_preds` is expected to have binarized predictions and `y` should be in one-hot format.\n You can use suitable transforms in ``monai.transforms.post`` first to achieve binarized values.\n\n Args:\n include_background: whether to skip distance computation on the first channel of\n the predicted output. Defaults to ``False``.\n symmetric: whether to calculate the symmetric average surface distance between\n `seg_pred` and `seg_gt`. Defaults to ``False``.\n distance_metric: : [``\"euclidean\"``, ``\"chessboard\"``, ``\"taxicab\"``]\n the metric used to compute surface distance. Defaults to ``\"euclidean\"``.\n reduction: {``\"none\"``, ``\"mean\"``, ``\"sum\"``, ``\"mean_batch\"``, ``\"sum_batch\"``,\n ``\"mean_channel\"``, ``\"sum_channel\"``}\n Define the mode to reduce computation result of 1 batch data. Defaults to ``\"mean\"``.\n\n \"\"\"\n\n def __init__(\n self,\n include_background: bool = False,\n symmetric: bool = False,\n distance_metric: str = \"euclidean\",\n reduction: Union[MetricReduction, str] = MetricReduction.MEAN,\n ) -> None:\n super().__init__()\n self.include_background = include_background\n self.distance_metric = distance_metric\n self.symmetric = symmetric\n self.reduction = reduction\n\n def __call__(self, y_pred: torch.Tensor, y: torch.Tensor):\n \"\"\"\n Args:\n y_pred: input data to compute, typical segmentation model output.\n It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values\n should be binarized.\n y: ground truth to compute the distance. It must be one-hot format and first dim is batch.\n The values should be binarized.\n\n Raises:\n ValueError: when `y` is not a binarized tensor.\n ValueError: when `y_pred` has less than three dimensions.\n \"\"\"\n if not torch.all(y_pred.byte() == y_pred):\n warnings.warn(\"y_pred is not a binarized tensor here!\")\n if not torch.all(y.byte() == y):\n raise ValueError(\"y should be a binarized tensor.\")\n dims = y_pred.ndimension()\n if dims < 3:\n raise ValueError(\"y_pred should have at least three dimensions.\")\n # compute (BxC) for each channel for each batch\n f = compute_average_surface_distance(\n y_pred=y_pred,\n y=y,\n include_background=self.include_background,\n symmetric=self.symmetric,\n distance_metric=self.distance_metric,\n )\n\n # do metric reduction\n f, not_nans = do_metric_reduction(f, self.reduction)\n return f, not_nans\n\n\ndef compute_average_surface_distance(\n y_pred: Union[np.ndarray, torch.Tensor],\n y: Union[np.ndarray, torch.Tensor],\n include_background: bool = False,\n symmetric: bool = False,\n distance_metric: str = \"euclidean\",\n):\n \"\"\"\n This function is used to compute the Average Surface Distance from `y_pred` to `y`\n under the default setting.\n In addition, if sets ``symmetric = True``, the average symmetric surface distance between\n these two inputs will be returned.\n\n Args:\n y_pred: input data to compute, typical segmentation model output.\n It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values\n should be binarized.\n y: ground truth to compute mean the distance. It must be one-hot format and first dim is batch.\n The values should be binarized.\n include_background: whether to skip distance computation on the first channel of\n the predicted output. Defaults to ``False``.\n symmetric: whether to calculate the symmetric average surface distance between\n `seg_pred` and `seg_gt`. Defaults to ``False``.\n distance_metric: : [``\"euclidean\"``, ``\"chessboard\"``, ``\"taxicab\"``]\n the metric used to compute surface distance. Defaults to ``\"euclidean\"``.\n \"\"\"\n\n if not include_background:\n y_pred, y = ignore_background(\n y_pred=y_pred,\n y=y,\n )\n\n y = y.float()\n y_pred = y_pred.float()\n\n if y.shape != y_pred.shape:\n raise ValueError(\"y_pred and y should have same shapes.\")\n\n batch_size, n_class = y_pred.shape[:2]\n asd = np.empty((batch_size, n_class))\n\n for b, c in np.ndindex(batch_size, n_class):\n (edges_pred, edges_gt) = get_mask_edges(y_pred[b, c], y[b, c])\n surface_distance = get_surface_distance(edges_pred, edges_gt, distance_metric=distance_metric)\n if surface_distance.shape == (0,):\n avg_surface_distance = np.nan\n else:\n avg_surface_distance = surface_distance.mean()\n if not symmetric:\n asd[b, c] = avg_surface_distance\n else:\n surface_distance_2 = get_surface_distance(edges_gt, edges_pred, distance_metric=distance_metric)\n if surface_distance_2.shape == (0,):\n avg_surface_distance_2 = np.nan\n else:\n avg_surface_distance_2 = surface_distance_2.mean()\n asd[b, c] = np.mean((avg_surface_distance, avg_surface_distance_2))\n\n return torch.from_numpy(asd)\n" ]
[ [ "numpy.mean", "torch.from_numpy", "numpy.empty", "numpy.ndindex" ] ]
maxi-marufo/my-scipy
[ "be6c2597fcee86419592ac512319301c7ddfc118" ]
[ "scipy/integrate/quadrature.py" ]
[ "import functools\nimport numpy as np\nimport math\nimport types\nimport warnings\n\n# trapz is a public function for scipy.integrate,\n# even though it's actually a NumPy function.\nfrom numpy import trapz\nfrom scipy.special import roots_legendre\nfrom scipy.special import gammaln\n\n__all__ = ['fixed_quad', 'quadrature', 'romberg', 'trapz', 'simps', 'romb',\n 'cumtrapz', 'newton_cotes']\n\n\n# Make See Also linking for our local copy work properly\ndef _copy_func(f):\n \"\"\"Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)\"\"\"\n g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,\n argdefs=f.__defaults__, closure=f.__closure__)\n g = functools.update_wrapper(g, f)\n g.__kwdefaults__ = f.__kwdefaults__\n return g\n\n\ntrapz = _copy_func(trapz)\nif trapz.__doc__:\n trapz.__doc__ = trapz.__doc__.replace('sum, cumsum', 'numpy.cumsum')\n\n\nclass AccuracyWarning(Warning):\n pass\n\n\ndef _cached_roots_legendre(n):\n \"\"\"\n Cache roots_legendre results to speed up calls of the fixed_quad\n function.\n \"\"\"\n if n in _cached_roots_legendre.cache:\n return _cached_roots_legendre.cache[n]\n\n _cached_roots_legendre.cache[n] = roots_legendre(n)\n return _cached_roots_legendre.cache[n]\n\n\n_cached_roots_legendre.cache = dict()\n\n\ndef fixed_quad(func, a, b, args=(), n=5):\n \"\"\"\n Compute a definite integral using fixed-order Gaussian quadrature.\n\n Integrate `func` from `a` to `b` using Gaussian quadrature of\n order `n`.\n\n Parameters\n ----------\n func : callable\n A Python function or method to integrate (must accept vector inputs).\n If integrating a vector-valued function, the returned array must have\n shape ``(..., len(x))``.\n a : float\n Lower limit of integration.\n b : float\n Upper limit of integration.\n args : tuple, optional\n Extra arguments to pass to function, if any.\n n : int, optional\n Order of quadrature integration. Default is 5.\n\n Returns\n -------\n val : float\n Gaussian quadrature approximation to the integral\n none : None\n Statically returned value of None\n\n\n See Also\n --------\n quad : adaptive quadrature using QUADPACK\n dblquad : double integrals\n tplquad : triple integrals\n romberg : adaptive Romberg quadrature\n quadrature : adaptive Gaussian quadrature\n romb : integrators for sampled data\n simps : integrators for sampled data\n cumtrapz : cumulative integration for sampled data\n ode : ODE integrator\n odeint : ODE integrator\n\n Examples\n --------\n >>> from scipy import integrate\n >>> f = lambda x: x**8\n >>> integrate.fixed_quad(f, 0.0, 1.0, n=4)\n (0.1110884353741496, None)\n >>> integrate.fixed_quad(f, 0.0, 1.0, n=5)\n (0.11111111111111102, None)\n >>> print(1/9.0) # analytical result\n 0.1111111111111111\n\n >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4)\n (0.9999999771971152, None)\n >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5)\n (1.000000000039565, None)\n >>> np.sin(np.pi/2)-np.sin(0) # analytical result\n 1.0\n\n \"\"\"\n x, w = _cached_roots_legendre(n)\n x = np.real(x)\n if np.isinf(a) or np.isinf(b):\n raise ValueError(\"Gaussian quadrature is only available for \"\n \"finite limits.\")\n y = (b-a)*(x+1)/2.0 + a\n return (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1), None\n\n\ndef vectorize1(func, args=(), vec_func=False):\n \"\"\"Vectorize the call to a function.\n\n This is an internal utility function used by `romberg` and\n `quadrature` to create a vectorized version of a function.\n\n If `vec_func` is True, the function `func` is assumed to take vector\n arguments.\n\n Parameters\n ----------\n func : callable\n User defined function.\n args : tuple, optional\n Extra arguments for the function.\n vec_func : bool, optional\n True if the function func takes vector arguments.\n\n Returns\n -------\n vfunc : callable\n A function that will take a vector argument and return the\n result.\n\n \"\"\"\n if vec_func:\n def vfunc(x):\n return func(x, *args)\n else:\n def vfunc(x):\n if np.isscalar(x):\n return func(x, *args)\n x = np.asarray(x)\n # call with first point to get output type\n y0 = func(x[0], *args)\n n = len(x)\n dtype = getattr(y0, 'dtype', type(y0))\n output = np.empty((n,), dtype=dtype)\n output[0] = y0\n for i in range(1, n):\n output[i] = func(x[i], *args)\n return output\n return vfunc\n\n\ndef quadrature(func, a, b, args=(), tol=1.49e-8, rtol=1.49e-8, maxiter=50,\n vec_func=True, miniter=1):\n \"\"\"\n Compute a definite integral using fixed-tolerance Gaussian quadrature.\n\n Integrate `func` from `a` to `b` using Gaussian quadrature\n with absolute tolerance `tol`.\n\n Parameters\n ----------\n func : function\n A Python function or method to integrate.\n a : float\n Lower limit of integration.\n b : float\n Upper limit of integration.\n args : tuple, optional\n Extra arguments to pass to function.\n tol, rtol : float, optional\n Iteration stops when error between last two iterates is less than\n `tol` OR the relative change is less than `rtol`.\n maxiter : int, optional\n Maximum order of Gaussian quadrature.\n vec_func : bool, optional\n True or False if func handles arrays as arguments (is\n a \"vector\" function). Default is True.\n miniter : int, optional\n Minimum order of Gaussian quadrature.\n\n Returns\n -------\n val : float\n Gaussian quadrature approximation (within tolerance) to integral.\n err : float\n Difference between last two estimates of the integral.\n\n See also\n --------\n romberg: adaptive Romberg quadrature\n fixed_quad: fixed-order Gaussian quadrature\n quad: adaptive quadrature using QUADPACK\n dblquad: double integrals\n tplquad: triple integrals\n romb: integrator for sampled data\n simps: integrator for sampled data\n cumtrapz: cumulative integration for sampled data\n ode: ODE integrator\n odeint: ODE integrator\n\n Examples\n --------\n >>> from scipy import integrate\n >>> f = lambda x: x**8\n >>> integrate.quadrature(f, 0.0, 1.0)\n (0.11111111111111106, 4.163336342344337e-17)\n >>> print(1/9.0) # analytical result\n 0.1111111111111111\n\n >>> integrate.quadrature(np.cos, 0.0, np.pi/2)\n (0.9999999999999536, 3.9611425250996035e-11)\n >>> np.sin(np.pi/2)-np.sin(0) # analytical result\n 1.0\n\n \"\"\"\n if not isinstance(args, tuple):\n args = (args,)\n vfunc = vectorize1(func, args, vec_func=vec_func)\n val = np.inf\n err = np.inf\n maxiter = max(miniter+1, maxiter)\n for n in range(miniter, maxiter+1):\n newval = fixed_quad(vfunc, a, b, (), n)[0]\n err = abs(newval-val)\n val = newval\n\n if err < tol or err < rtol*abs(val):\n break\n else:\n warnings.warn(\n \"maxiter (%d) exceeded. Latest difference = %e\" % (maxiter, err),\n AccuracyWarning)\n return val, err\n\n\ndef tupleset(t, i, value):\n l = list(t)\n l[i] = value\n return tuple(l)\n\n\ndef cumtrapz(y, x=None, dx=1.0, axis=-1, initial=None):\n \"\"\"\n Cumulatively integrate y(x) using the composite trapezoidal rule.\n\n Parameters\n ----------\n y : array_like\n Values to integrate.\n x : array_like, optional\n The coordinate to integrate along. If None (default), use spacing `dx`\n between consecutive elements in `y`.\n dx : float, optional\n Spacing between elements of `y`. Only used if `x` is None.\n axis : int, optional\n Specifies the axis to cumulate. Default is -1 (last axis).\n initial : scalar, optional\n If given, insert this value at the beginning of the returned result.\n Typically this value should be 0. Default is None, which means no\n value at ``x[0]`` is returned and `res` has one element less than `y`\n along the axis of integration.\n\n Returns\n -------\n res : ndarray\n The result of cumulative integration of `y` along `axis`.\n If `initial` is None, the shape is such that the axis of integration\n has one less value than `y`. If `initial` is given, the shape is equal\n to that of `y`.\n\n See Also\n --------\n numpy.cumsum, numpy.cumprod\n quad: adaptive quadrature using QUADPACK\n romberg: adaptive Romberg quadrature\n quadrature: adaptive Gaussian quadrature\n fixed_quad: fixed-order Gaussian quadrature\n dblquad: double integrals\n tplquad: triple integrals\n romb: integrators for sampled data\n ode: ODE integrators\n odeint: ODE integrators\n\n Examples\n --------\n >>> from scipy import integrate\n >>> import matplotlib.pyplot as plt\n\n >>> x = np.linspace(-2, 2, num=20)\n >>> y = x\n >>> y_int = integrate.cumtrapz(y, x, initial=0)\n >>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')\n >>> plt.show()\n\n \"\"\"\n y = np.asarray(y)\n if x is None:\n d = dx\n else:\n x = np.asarray(x)\n if x.ndim == 1:\n d = np.diff(x)\n # reshape to correct shape\n shape = [1] * y.ndim\n shape[axis] = -1\n d = d.reshape(shape)\n elif len(x.shape) != len(y.shape):\n raise ValueError(\"If given, shape of x must be 1-D or the \"\n \"same as y.\")\n else:\n d = np.diff(x, axis=axis)\n\n if d.shape[axis] != y.shape[axis] - 1:\n raise ValueError(\"If given, length of x along axis must be the \"\n \"same as y.\")\n\n nd = len(y.shape)\n slice1 = tupleset((slice(None),)*nd, axis, slice(1, None))\n slice2 = tupleset((slice(None),)*nd, axis, slice(None, -1))\n res = np.cumsum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis)\n\n if initial is not None:\n if not np.isscalar(initial):\n raise ValueError(\"`initial` parameter should be a scalar.\")\n\n shape = list(res.shape)\n shape[axis] = 1\n res = np.concatenate([np.full(shape, initial, dtype=res.dtype), res],\n axis=axis)\n\n return res\n\n\ndef _basic_simps(y, start, stop, x, dx, axis):\n nd = len(y.shape)\n if start is None:\n start = 0\n step = 2\n slice_all = (slice(None),)*nd\n slice0 = tupleset(slice_all, axis, slice(start, stop, step))\n slice1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))\n slice2 = tupleset(slice_all, axis, slice(start+2, stop+2, step))\n\n if x is None: # Even-spaced Simpson's rule.\n result = np.sum(dx/3.0 * (y[slice0]+4*y[slice1]+y[slice2]),\n axis=axis)\n else:\n # Account for possibly different spacings.\n # Simpson's rule changes a bit.\n h = np.diff(x, axis=axis)\n sl0 = tupleset(slice_all, axis, slice(start, stop, step))\n sl1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))\n h0 = h[sl0]\n h1 = h[sl1]\n hsum = h0 + h1\n hprod = h0 * h1\n h0divh1 = h0 / h1\n tmp = hsum/6.0 * (y[slice0]*(2-1.0/h0divh1) +\n y[slice1]*hsum*hsum/hprod +\n y[slice2]*(2-h0divh1))\n result = np.sum(tmp, axis=axis)\n return result\n\n\ndef simps(y, x=None, dx=1, axis=-1, even='avg'):\n \"\"\"\n Integrate y(x) using samples along the given axis and the composite\n Simpson's rule. If x is None, spacing of dx is assumed.\n\n If there are an even number of samples, N, then there are an odd\n number of intervals (N-1), but Simpson's rule requires an even number\n of intervals. The parameter 'even' controls how this is handled.\n\n Parameters\n ----------\n y : array_like\n Array to be integrated.\n x : array_like, optional\n If given, the points at which `y` is sampled.\n dx : int, optional\n Spacing of integration points along axis of `x`. Only used when\n `x` is None. Default is 1.\n axis : int, optional\n Axis along which to integrate. Default is the last axis.\n even : str {'avg', 'first', 'last'}, optional\n 'avg' : Average two results:1) use the first N-2 intervals with\n a trapezoidal rule on the last interval and 2) use the last\n N-2 intervals with a trapezoidal rule on the first interval.\n\n 'first' : Use Simpson's rule for the first N-2 intervals with\n a trapezoidal rule on the last interval.\n\n 'last' : Use Simpson's rule for the last N-2 intervals with a\n trapezoidal rule on the first interval.\n\n See Also\n --------\n quad: adaptive quadrature using QUADPACK\n romberg: adaptive Romberg quadrature\n quadrature: adaptive Gaussian quadrature\n fixed_quad: fixed-order Gaussian quadrature\n dblquad: double integrals\n tplquad: triple integrals\n romb: integrators for sampled data\n cumtrapz: cumulative integration for sampled data\n ode: ODE integrators\n odeint: ODE integrators\n\n Notes\n -----\n For an odd number of samples that are equally spaced the result is\n exact if the function is a polynomial of order 3 or less. If\n the samples are not equally spaced, then the result is exact only\n if the function is a polynomial of order 2 or less.\n\n Examples\n --------\n >>> from scipy import integrate\n >>> x = np.arange(0, 10)\n >>> y = np.arange(0, 10)\n\n >>> integrate.simps(y, x)\n 40.5\n\n >>> y = np.power(x, 3)\n >>> integrate.simps(y, x)\n 1642.5\n >>> integrate.quad(lambda x: x**3, 0, 9)[0]\n 1640.25\n\n >>> integrate.simps(y, x, even='first')\n 1644.5\n\n \"\"\"\n y = np.asarray(y)\n nd = len(y.shape)\n N = y.shape[axis]\n last_dx = dx\n first_dx = dx\n returnshape = 0\n if x is not None:\n x = np.asarray(x)\n if len(x.shape) == 1:\n shapex = [1] * nd\n shapex[axis] = x.shape[0]\n saveshape = x.shape\n returnshape = 1\n x = x.reshape(tuple(shapex))\n elif len(x.shape) != len(y.shape):\n raise ValueError(\"If given, shape of x must be 1-D or the \"\n \"same as y.\")\n if x.shape[axis] != N:\n raise ValueError(\"If given, length of x along axis must be the \"\n \"same as y.\")\n if N % 2 == 0:\n val = 0.0\n result = 0.0\n slice1 = (slice(None),)*nd\n slice2 = (slice(None),)*nd\n if even not in ['avg', 'last', 'first']:\n raise ValueError(\"Parameter 'even' must be \"\n \"'avg', 'last', or 'first'.\")\n # Compute using Simpson's rule on first intervals\n if even in ['avg', 'first']:\n slice1 = tupleset(slice1, axis, -1)\n slice2 = tupleset(slice2, axis, -2)\n if x is not None:\n last_dx = x[slice1] - x[slice2]\n val += 0.5*last_dx*(y[slice1]+y[slice2])\n result = _basic_simps(y, 0, N-3, x, dx, axis)\n # Compute using Simpson's rule on last set of intervals\n if even in ['avg', 'last']:\n slice1 = tupleset(slice1, axis, 0)\n slice2 = tupleset(slice2, axis, 1)\n if x is not None:\n first_dx = x[tuple(slice2)] - x[tuple(slice1)]\n val += 0.5*first_dx*(y[slice2]+y[slice1])\n result += _basic_simps(y, 1, N-2, x, dx, axis)\n if even == 'avg':\n val /= 2.0\n result /= 2.0\n result = result + val\n else:\n result = _basic_simps(y, 0, N-2, x, dx, axis)\n if returnshape:\n x = x.reshape(saveshape)\n return result\n\n\ndef romb(y, dx=1.0, axis=-1, show=False):\n \"\"\"\n Romberg integration using samples of a function.\n\n Parameters\n ----------\n y : array_like\n A vector of ``2**k + 1`` equally-spaced samples of a function.\n dx : float, optional\n The sample spacing. Default is 1.\n axis : int, optional\n The axis along which to integrate. Default is -1 (last axis).\n show : bool, optional\n When `y` is a single 1-D array, then if this argument is True\n print the table showing Richardson extrapolation from the\n samples. Default is False.\n\n Returns\n -------\n romb : ndarray\n The integrated result for `axis`.\n\n See also\n --------\n quad : adaptive quadrature using QUADPACK\n romberg : adaptive Romberg quadrature\n quadrature : adaptive Gaussian quadrature\n fixed_quad : fixed-order Gaussian quadrature\n dblquad : double integrals\n tplquad : triple integrals\n simps : integrators for sampled data\n cumtrapz : cumulative integration for sampled data\n ode : ODE integrators\n odeint : ODE integrators\n\n Examples\n --------\n >>> from scipy import integrate\n >>> x = np.arange(10, 14.25, 0.25)\n >>> y = np.arange(3, 12)\n\n >>> integrate.romb(y)\n 56.0\n\n >>> y = np.sin(np.power(x, 2.5))\n >>> integrate.romb(y)\n -0.742561336672229\n\n >>> integrate.romb(y, show=True)\n Richardson Extrapolation Table for Romberg Integration\n ====================================================================\n -0.81576\n 4.63862 6.45674\n -1.10581 -3.02062 -3.65245\n -2.57379 -3.06311 -3.06595 -3.05664\n -1.34093 -0.92997 -0.78776 -0.75160 -0.74256\n ====================================================================\n -0.742561336672229\n \"\"\"\n y = np.asarray(y)\n nd = len(y.shape)\n Nsamps = y.shape[axis]\n Ninterv = Nsamps-1\n n = 1\n k = 0\n while n < Ninterv:\n n <<= 1\n k += 1\n if n != Ninterv:\n raise ValueError(\"Number of samples must be one plus a \"\n \"non-negative power of 2.\")\n\n R = {}\n slice_all = (slice(None),) * nd\n slice0 = tupleset(slice_all, axis, 0)\n slicem1 = tupleset(slice_all, axis, -1)\n h = Ninterv * np.asarray(dx, dtype=float)\n R[(0, 0)] = (y[slice0] + y[slicem1])/2.0*h\n slice_R = slice_all\n start = stop = step = Ninterv\n for i in range(1, k+1):\n start >>= 1\n slice_R = tupleset(slice_R, axis, slice(start, stop, step))\n step >>= 1\n R[(i, 0)] = 0.5*(R[(i-1, 0)] + h*y[slice_R].sum(axis=axis))\n for j in range(1, i+1):\n prev = R[(i, j-1)]\n R[(i, j)] = prev + (prev-R[(i-1, j-1)]) / ((1 << (2*j))-1)\n h /= 2.0\n\n if show:\n if not np.isscalar(R[(0, 0)]):\n print(\"*** Printing table only supported for integrals\" +\n \" of a single data set.\")\n else:\n try:\n precis = show[0]\n except (TypeError, IndexError):\n precis = 5\n try:\n width = show[1]\n except (TypeError, IndexError):\n width = 8\n formstr = \"%%%d.%df\" % (width, precis)\n\n title = \"Richardson Extrapolation Table for Romberg Integration\"\n print(\"\", title.center(68), \"=\" * 68, sep=\"\\n\", end=\"\\n\")\n for i in range(k+1):\n for j in range(i+1):\n print(formstr % R[(i, j)], end=\" \")\n print()\n print(\"=\" * 68)\n print()\n\n return R[(k, k)]\n\n# Romberg quadratures for numeric integration.\n#\n# Written by Scott M. Ransom <[email protected]>\n# last revision: 14 Nov 98\n#\n# Cosmetic changes by Konrad Hinsen <[email protected]>\n# last revision: 1999-7-21\n#\n# Adapted to SciPy by Travis Oliphant <[email protected]>\n# last revision: Dec 2001\n\n\ndef _difftrap(function, interval, numtraps):\n \"\"\"\n Perform part of the trapezoidal rule to integrate a function.\n Assume that we had called difftrap with all lower powers-of-2\n starting with 1. Calling difftrap only returns the summation\n of the new ordinates. It does _not_ multiply by the width\n of the trapezoids. This must be performed by the caller.\n 'function' is the function to evaluate (must accept vector arguments).\n 'interval' is a sequence with lower and upper limits\n of integration.\n 'numtraps' is the number of trapezoids to use (must be a\n power-of-2).\n \"\"\"\n if numtraps <= 0:\n raise ValueError(\"numtraps must be > 0 in difftrap().\")\n elif numtraps == 1:\n return 0.5*(function(interval[0])+function(interval[1]))\n else:\n numtosum = numtraps/2\n h = float(interval[1]-interval[0])/numtosum\n lox = interval[0] + 0.5 * h\n points = lox + h * np.arange(numtosum)\n s = np.sum(function(points), axis=0)\n return s\n\n\ndef _romberg_diff(b, c, k):\n \"\"\"\n Compute the differences for the Romberg quadrature corrections.\n See Forman Acton's \"Real Computing Made Real,\" p 143.\n \"\"\"\n tmp = 4.0**k\n return (tmp * c - b)/(tmp - 1.0)\n\n\ndef _printresmat(function, interval, resmat):\n # Print the Romberg result matrix.\n i = j = 0\n print('Romberg integration of', repr(function), end=' ')\n print('from', interval)\n print('')\n print('%6s %9s %9s' % ('Steps', 'StepSize', 'Results'))\n for i in range(len(resmat)):\n print('%6d %9f' % (2**i, (interval[1]-interval[0])/(2.**i)), end=' ')\n for j in range(i+1):\n print('%9f' % (resmat[i][j]), end=' ')\n print('')\n print('')\n print('The final result is', resmat[i][j], end=' ')\n print('after', 2**(len(resmat)-1)+1, 'function evaluations.')\n\n\ndef romberg(function, a, b, args=(), tol=1.48e-8, rtol=1.48e-8, show=False,\n divmax=10, vec_func=False):\n \"\"\"\n Romberg integration of a callable function or method.\n\n Returns the integral of `function` (a function of one variable)\n over the interval (`a`, `b`).\n\n If `show` is 1, the triangular array of the intermediate results\n will be printed. If `vec_func` is True (default is False), then\n `function` is assumed to support vector arguments.\n\n Parameters\n ----------\n function : callable\n Function to be integrated.\n a : float\n Lower limit of integration.\n b : float\n Upper limit of integration.\n\n Returns\n -------\n results : float\n Result of the integration.\n\n Other Parameters\n ----------------\n args : tuple, optional\n Extra arguments to pass to function. Each element of `args` will\n be passed as a single argument to `func`. Default is to pass no\n extra arguments.\n tol, rtol : float, optional\n The desired absolute and relative tolerances. Defaults are 1.48e-8.\n show : bool, optional\n Whether to print the results. Default is False.\n divmax : int, optional\n Maximum order of extrapolation. Default is 10.\n vec_func : bool, optional\n Whether `func` handles arrays as arguments (i.e., whether it is a\n \"vector\" function). Default is False.\n\n See Also\n --------\n fixed_quad : Fixed-order Gaussian quadrature.\n quad : Adaptive quadrature using QUADPACK.\n dblquad : Double integrals.\n tplquad : Triple integrals.\n romb : Integrators for sampled data.\n simps : Integrators for sampled data.\n cumtrapz : Cumulative integration for sampled data.\n ode : ODE integrator.\n odeint : ODE integrator.\n\n References\n ----------\n .. [1] 'Romberg's method' https://en.wikipedia.org/wiki/Romberg%27s_method\n\n Examples\n --------\n Integrate a gaussian from 0 to 1 and compare to the error function.\n\n >>> from scipy import integrate\n >>> from scipy.special import erf\n >>> gaussian = lambda x: 1/np.sqrt(np.pi) * np.exp(-x**2)\n >>> result = integrate.romberg(gaussian, 0, 1, show=True)\n Romberg integration of <function vfunc at ...> from [0, 1]\n\n ::\n\n Steps StepSize Results\n 1 1.000000 0.385872\n 2 0.500000 0.412631 0.421551\n 4 0.250000 0.419184 0.421368 0.421356\n 8 0.125000 0.420810 0.421352 0.421350 0.421350\n 16 0.062500 0.421215 0.421350 0.421350 0.421350 0.421350\n 32 0.031250 0.421317 0.421350 0.421350 0.421350 0.421350 0.421350\n\n The final result is 0.421350396475 after 33 function evaluations.\n\n >>> print(\"%g %g\" % (2*result, erf(1)))\n 0.842701 0.842701\n\n \"\"\"\n if np.isinf(a) or np.isinf(b):\n raise ValueError(\"Romberg integration only available \"\n \"for finite limits.\")\n vfunc = vectorize1(function, args, vec_func=vec_func)\n n = 1\n interval = [a, b]\n intrange = b - a\n ordsum = _difftrap(vfunc, interval, n)\n result = intrange * ordsum\n resmat = [[result]]\n err = np.inf\n last_row = resmat[0]\n for i in range(1, divmax+1):\n n *= 2\n ordsum += _difftrap(vfunc, interval, n)\n row = [intrange * ordsum / n]\n for k in range(i):\n row.append(_romberg_diff(last_row[k], row[k], k+1))\n result = row[i]\n lastresult = last_row[i-1]\n if show:\n resmat.append(row)\n err = abs(result - lastresult)\n if err < tol or err < rtol * abs(result):\n break\n last_row = row\n else:\n warnings.warn(\n \"divmax (%d) exceeded. Latest difference = %e\" % (divmax, err),\n AccuracyWarning)\n\n if show:\n _printresmat(vfunc, interval, resmat)\n return result\n\n\n# Coefficients for Newton-Cotes quadrature\n#\n# These are the points being used\n# to construct the local interpolating polynomial\n# a are the weights for Newton-Cotes integration\n# B is the error coefficient.\n# error in these coefficients grows as N gets larger.\n# or as samples are closer and closer together\n\n# You can use maxima to find these rational coefficients\n# for equally spaced data using the commands\n# a(i,N) := integrate(product(r-j,j,0,i-1) * product(r-j,j,i+1,N),r,0,N) / ((N-i)! * i!) * (-1)^(N-i);\n# Be(N) := N^(N+2)/(N+2)! * (N/(N+3) - sum((i/N)^(N+2)*a(i,N),i,0,N));\n# Bo(N) := N^(N+1)/(N+1)! * (N/(N+2) - sum((i/N)^(N+1)*a(i,N),i,0,N));\n# B(N) := (if (mod(N,2)=0) then Be(N) else Bo(N));\n#\n# pre-computed for equally-spaced weights\n#\n# num_a, den_a, int_a, num_B, den_B = _builtincoeffs[N]\n#\n# a = num_a*array(int_a)/den_a\n# B = num_B*1.0 / den_B\n#\n# integrate(f(x),x,x_0,x_N) = dx*sum(a*f(x_i)) + B*(dx)^(2k+3) f^(2k+2)(x*)\n# where k = N // 2\n#\n_builtincoeffs = {\n 1: (1,2,[1,1],-1,12),\n 2: (1,3,[1,4,1],-1,90),\n 3: (3,8,[1,3,3,1],-3,80),\n 4: (2,45,[7,32,12,32,7],-8,945),\n 5: (5,288,[19,75,50,50,75,19],-275,12096),\n 6: (1,140,[41,216,27,272,27,216,41],-9,1400),\n 7: (7,17280,[751,3577,1323,2989,2989,1323,3577,751],-8183,518400),\n 8: (4,14175,[989,5888,-928,10496,-4540,10496,-928,5888,989],\n -2368,467775),\n 9: (9,89600,[2857,15741,1080,19344,5778,5778,19344,1080,\n 15741,2857], -4671, 394240),\n 10: (5,299376,[16067,106300,-48525,272400,-260550,427368,\n -260550,272400,-48525,106300,16067],\n -673175, 163459296),\n 11: (11,87091200,[2171465,13486539,-3237113, 25226685,-9595542,\n 15493566,15493566,-9595542,25226685,-3237113,\n 13486539,2171465], -2224234463, 237758976000),\n 12: (1, 5255250, [1364651,9903168,-7587864,35725120,-51491295,\n 87516288,-87797136,87516288,-51491295,35725120,\n -7587864,9903168,1364651], -3012, 875875),\n 13: (13, 402361344000,[8181904909, 56280729661, -31268252574,\n 156074417954,-151659573325,206683437987,\n -43111992612,-43111992612,206683437987,\n -151659573325,156074417954,-31268252574,\n 56280729661,8181904909], -2639651053,\n 344881152000),\n 14: (7, 2501928000, [90241897,710986864,-770720657,3501442784,\n -6625093363,12630121616,-16802270373,19534438464,\n -16802270373,12630121616,-6625093363,3501442784,\n -770720657,710986864,90241897], -3740727473,\n 1275983280000)\n }\n\n\ndef newton_cotes(rn, equal=0):\n r\"\"\"\n Return weights and error coefficient for Newton-Cotes integration.\n\n Suppose we have (N+1) samples of f at the positions\n x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the\n integral between x_0 and x_N is:\n\n :math:`\\int_{x_0}^{x_N} f(x)dx = \\Delta x \\sum_{i=0}^{N} a_i f(x_i)\n + B_N (\\Delta x)^{N+2} f^{N+1} (\\xi)`\n\n where :math:`\\xi \\in [x_0,x_N]`\n and :math:`\\Delta x = \\frac{x_N-x_0}{N}` is the average samples spacing.\n\n If the samples are equally-spaced and N is even, then the error\n term is :math:`B_N (\\Delta x)^{N+3} f^{N+2}(\\xi)`.\n\n Parameters\n ----------\n rn : int\n The integer order for equally-spaced data or the relative positions of\n the samples with the first sample at 0 and the last at N, where N+1 is\n the length of `rn`. N is the order of the Newton-Cotes integration.\n equal : int, optional\n Set to 1 to enforce equally spaced data.\n\n Returns\n -------\n an : ndarray\n 1-D array of weights to apply to the function at the provided sample\n positions.\n B : float\n Error coefficient.\n\n Examples\n --------\n Compute the integral of sin(x) in [0, :math:`\\pi`]:\n\n >>> from scipy.integrate import newton_cotes\n >>> def f(x):\n ... return np.sin(x)\n >>> a = 0\n >>> b = np.pi\n >>> exact = 2\n >>> for N in [2, 4, 6, 8, 10]:\n ... x = np.linspace(a, b, N + 1)\n ... an, B = newton_cotes(N, 1)\n ... dx = (b - a) / N\n ... quad = dx * np.sum(an * f(x))\n ... error = abs(quad - exact)\n ... print('{:2d} {:10.9f} {:.5e}'.format(N, quad, error))\n ...\n 2 2.094395102 9.43951e-02\n 4 1.998570732 1.42927e-03\n 6 2.000017814 1.78136e-05\n 8 1.999999835 1.64725e-07\n 10 2.000000001 1.14677e-09\n\n Notes\n -----\n Normally, the Newton-Cotes rules are used on smaller integration\n regions and a composite rule is used to return the total integral.\n\n \"\"\"\n try:\n N = len(rn)-1\n if equal:\n rn = np.arange(N+1)\n elif np.all(np.diff(rn) == 1):\n equal = 1\n except Exception:\n N = rn\n rn = np.arange(N+1)\n equal = 1\n\n if equal and N in _builtincoeffs:\n na, da, vi, nb, db = _builtincoeffs[N]\n an = na * np.array(vi, dtype=float) / da\n return an, float(nb)/db\n\n if (rn[0] != 0) or (rn[-1] != N):\n raise ValueError(\"The sample positions must start at 0\"\n \" and end at N\")\n yi = rn / float(N)\n ti = 2 * yi - 1\n nvec = np.arange(N+1)\n C = ti ** nvec[:, np.newaxis]\n Cinv = np.linalg.inv(C)\n # improve precision of result\n for i in range(2):\n Cinv = 2*Cinv - Cinv.dot(C).dot(Cinv)\n vec = 2.0 / (nvec[::2]+1)\n ai = Cinv[:, ::2].dot(vec) * (N / 2.)\n\n if (N % 2 == 0) and equal:\n BN = N/(N+3.)\n power = N+2\n else:\n BN = N/(N+2.)\n power = N+1\n\n BN = BN - np.dot(yi**power, ai)\n p1 = power+1\n fac = power*math.log(N) - gammaln(p1)\n fac = math.exp(fac)\n return ai, BN*fac\n" ]
[ [ "numpy.sum", "numpy.cumsum", "scipy.special.gammaln", "numpy.empty", "numpy.diff", "numpy.linalg.inv", "numpy.isinf", "scipy.special.roots_legendre", "numpy.asarray", "numpy.arange", "numpy.full", "numpy.array", "numpy.dot", "numpy.isscalar", "numpy.real" ] ]
fubiye/edgar-abs-kg
[ "3973059c7b1cdaab8a4e857a43c702ac0be7e725" ]
[ "dataset/corpus_to_txts.py" ]
[ "# coding=utf-8\n\nimport pandas as pd\nfrom pathlib import Path\n# extract corpus to seprate files\nOUT_PUT_DIR = r'D:\\data\\edgar\\example\\documents'\ndf = pd.read_csv(r'D:\\data\\edgar\\example\\corpus.csv')\n# def write_to_file(cik,filingId,fileName,content):\ndef write_to_file(cik,filingId,fileName,content):\n base_dir = Path(OUT_PUT_DIR)\n file_name = str(cik) + '+' + str(filingId) + '+' + str(fileName)\n file_name = file_name.replace('.htm', '.txt')\n (base_dir/file_name).write_text(content,encoding='utf-8')\n\ndf.apply(lambda row: write_to_file(row['CIK'],row['FilingId'],row['FileName'],row['Content']), axis=1)\n" ]
[ [ "pandas.read_csv" ] ]
Yili-Yang/Litterman_Carbon_Pricing
[ "71eeefc5e2d9b4c1473a9a6ae85c33b019e32d84" ]
[ "ezclimate/optimization.py" ]
[ "from __future__ import division, print_function\nimport numpy as np\nimport multiprocessing\nfrom tools import _pickle_method, _unpickle_method\ntry:\n import copy_reg\nexcept:\n import copyreg as copy_reg\nimport types\n\ncopy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)\n\nclass GeneticAlgorithm(object):\n\t\"\"\"Optimization algorithm for the EZ-Climate model. \n\n\tParameters\n\t----------\n\tpop_amount : int\n\t\tnumber of individuals in the population\n\tnum_feature : int \n\t\tnumber of elements in each individual, i.e. number of nodes in tree-model\n\tnum_generations : int \n\t\tnumber of generations of the populations to be evaluated\n\tbound : float\n\t\tupper bound of mitigation in each node\n\tcx_prob : float\n\t\t probability of mating\n\tmut_prob : float\n\t\tprobability of mutation.\n\tutility : `Utility` object\n\t\tobject of utility class\n\tfixed_values : ndarray, optional\n\t\tnodes to keep fixed\n\tfixed_indicies : ndarray, optional\n\t\tindicies of nodes to keep fixed\n\tprint_progress : bool, optional\n\t\tif the progress of the evolution should be printed\n\n\tAttributes\n\t----------\n\tpop_amount : int\n\t\tnumber of individuals in the population\n\tnum_feature : int \n\t\tnumber of elements in each individual, i.e. number of nodes in tree-model\n\tnum_generations : int \n\t\tnumber of generations of the populations to be evaluated\n\tbound : float\n\t\tupper bound of mitigation in each node\n\tcx_prob : float\n\t\t probability of mating\n\tmut_prob : float\n\t\tprobability of mutation.\n\tu : `Utility` object\n\t\tobject of utility class\n\tfixed_values : ndarray, optional\n\t\tnodes to keep fixed\n\tfixed_indicies : ndarray, optional\n\t\tindicies of nodes to keep fixed\n\tprint_progress : bool, optional\n\t\tif the progress of the evolution should be printed\n\n\t\"\"\"\n\tdef __init__(self, pop_amount, num_generations, cx_prob, mut_prob, bound, num_feature, utility,\n\t\t\t\t fixed_values=None, fixed_indicies=None, print_progress=False):\n\t\tself.num_feature = num_feature\n\t\tself.pop_amount = pop_amount\n\t\tself.num_gen = num_generations\n\t\tself.cx_prob = cx_prob\n\t\tself.mut_prob = mut_prob\n\t\tself.u = utility\n\t\tself.bound = bound\n\t\tself.fixed_values = fixed_values\n\t\tself.fixed_indicies = fixed_indicies\n\t\tself.print_progress = print_progress\n\n\tdef _generate_population(self, size):\n\t\t\"\"\"Return 1D-array of random values in the given bound as the initial population.\"\"\"\n\t\tpop = np.random.random([size, self.num_feature])*self.bound\n\t\tif self.fixed_values is not None:\n\t\t\tfor ind in pop:\n\t\t\t\tind[self.fixed_indicies] = self.fixed_values # override fix values\n\t\treturn pop\n\n\tdef _evaluate(self, indvidual):\n\t\t\"\"\"Returns the utility of given individual.\"\"\"\n\t\treturn self.u.utility(indvidual)\n\n\tdef _select(self, pop, rate):\n\t\t\"\"\"Returns a 1D-array of selected individuals.\n\t \n\t Parameters\n\t ----------\n\t pop : ndarray \n\t \tpopulation given by 2D-array with shape ('pop_amount', 'num_feature')\n\t rate : float \n\t \tthe probability of an individual being selected\n\t\t \n\t Returns\n\t -------\n\t ndarray \n\t \tselected individuals\n\n\t\t\"\"\"\n\t\tindex = np.random.choice(self.pop_amount, int(rate*self.pop_amount), replace=False) \n\t\treturn pop[index,:] #return a list of random instance of pop\n\n\tdef _random_index(self, individuals, size):\n\t\t\"\"\"Generate a random index of individuals of size 'size'.\n\n\t\tParameters\n\t\t----------\n\t\tindividuals : ndarray or list\n\t\t\t2D-array of individuals\n\t\tsize : int \n\t\t\tnumber of indices to generate\n\t\t\n\t\tReturns\n\t\t-------\n\t\tndarray \n\t\t\t1D-array of indices\n\n\t\t\"\"\"\n\t\tinds_size = len(individuals)\n\t\treturn np.random.choice(inds_size, size)\n\n\tdef _selection_tournament(self, pop, k, tournsize, fitness):\n\t \"\"\"Select `k` individuals from the input `individuals` using `k`\n\t tournaments of `tournsize` individuals.\n\t \n\t Parameters\n\t ----------\n\t individuals : ndarray or list\n\t \t2D-array of individuals to select from\n\t k : int\n\t \t number of individuals to select\n\t tournsize : int\n\t \tnumber of individuals participating in each tournament\n\t \tfitness : \n\t \t\tutility in our model\n\t \tReturns\n\t \t-------\n\t \tndarray s\n\t \t\tselected individuals\n\t \n\t \"\"\"\n\t chosen = []\n\t # for k times, randomly choose a tournsize number of index and pick up the one with the highest fitness\n\t for i in xrange(k):\n\t index = self._random_index(pop, tournsize)\n\t aspirants = pop[index] \n\t aspirants_fitness = fitness[index]\n\t chosen_index = np.where(aspirants_fitness == np.max(aspirants_fitness))[0]\n\t if len(chosen_index) != 0:\n\t \tchosen_index = chosen_index[0]\n\t chosen.append(aspirants[chosen_index])\n\t return np.array(chosen)\n\n\tdef _two_point_cross_over(self, pop):\n\t\t\"\"\"Performs a two-point cross-over of the population.\n\t \n\t Parameters\n\t ----------\n\t\tpop : ndarray \n\t\t\tpopulation given by 2D-array with shape ('pop_amount', 'num_feature')\n\n\t\t\"\"\"\n\t\tchild_group1 = pop[::2] # instance with even index\n\t\tchild_group2 = pop[1::2]# instance with odd index\n\t\tfor child1, child2 in zip(child_group1, child_group2):\n\t\t\tif np.random.random() <= self.cx_prob:\n\t\t\t\t#generates 2 random index for the swap, can be done much better.\n\t\t\t\tcxpoint1 = np.random.randint(1, self.num_feature)\n\t\t\t\tcxpoint2 = np.random.randint(1, self.num_feature - 1)\n\t\t\t\tif cxpoint2 >= cxpoint1:\n\t\t\t\t\tcxpoint2 += 1\n\t\t\t\telse: # Swap the two cx points\n\t\t\t\t\tcxpoint1, cxpoint2 = cxpoint2, cxpoint1\n\t\t\t\tchild1[cxpoint1:cxpoint2], child2[cxpoint1:cxpoint2] \\\n\t\t\t\t= child2[cxpoint1:cxpoint2].copy(), child1[cxpoint1:cxpoint2].copy()\n\t\t\t\tif self.fixed_values is not None:\n\t\t\t\t\tchild1[self.fixed_indicies] = self.fixed_values\n\t\t\t\t\tchild2[self.fixed_indicies] = self.fixed_values\n\t\n\tdef _uniform_cross_over(self, pop, ind_prob):\n\t\t\"\"\"Performs a uniform cross-over of the population.\n\t \n\t Parameters\n\t ----------\n\t pop : ndarray\n\t \tpopulation given by 2D-array with shape ('pop_amount', 'num_feature')\n\t ind_prob : float\n\t \tprobability of feature cross-over\n\t \n\t\t\"\"\"\n\t\tchild_group1 = pop[::2]\n\t\tchild_group2 = pop[1::2]\n\t\tfor child1, child2 in zip(child_group1, child_group2):\n\t\t\tsize = min(len(child1), len(child2))\n\t\t\tfor i in range(size):\n\t\t\t\tif np.random.random() < ind_prob:\n\t\t\t\t\tchild1[i], child2[i] = child2[i], child1[i]\n\n\tdef _mutate(self, pop, ind_prob, scale=2.0):\n\t\t\"\"\"Mutates individual's elements. The individual has a probability of `mut_prob` of \n\t\tbeeing selected and every element in this individual has a probability `ind_prob` of beeing \n\t\tmutated. The mutated value is a random number.\n\n\t\tParameters\n\t\t----------\n\t\tpop : ndarray\n\t\t\tpopulation given by 2D-array with shape ('pop_amount', 'num_feature')\n\t ind_prob : float \n\t \tprobability of feature mutation \n\t scale : float \n\t \tscaling constant of the random generated number for mutation\n\n\t\t\"\"\"\n\t\t# it is using a expectation of prob. Can be done much better.\n\t\tpop_tmp = np.copy(pop)\n\t\tmutate_index = np.random.choice(self.pop_amount, int(self.mut_prob * self.pop_amount), replace=False)\n\t\tfor i in mutate_index:\n\t\t\tfeature_index = np.random.choice(self.num_feature, int(ind_prob * self.num_feature), replace=False)\n\t\t\tfor j in feature_index:\n\t\t\t\tif self.fixed_indicies is not None and j in self.fixed_indicies:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tpop[i][j] = max(0.0, pop[i][j]+(np.random.random()-0.5)*scale)\n\t\n\tdef _uniform_mutation(self, pop, ind_prob, scale=2.0):\n\t\t\"\"\"Mutates individual's elements. The individual has a probability of `mut_prob` of\n\t\tbeeing selected and every element in this individual has a probability `ind_prob` of beeing \n\t\tmutated. The mutated value is the current value plus a scaled uniform [-0.5,0.5] random value.\n\n\t\tParameters\n\t\t----------\n\t\tpop : ndarray\n\t\t\tpopulation given by 2D-array with shape ('pop_amount', 'num_feature')\n\t ind_prob : float \n\t \tprobability of feature mutation \n\t scale : float \n\t \tscaling constant of the random generated number for mutation\n\n\t \"\"\" \n\t\tpop_len = len(pop)\n\t\tmutate_index = np.random.choice(pop_len, int(self.mut_prob * pop_len), replace=False)\n\t\tfor i in mutate_index:\n\t\t\tprob = np.random.random(self.num_feature) \n\t\t\tinc = (np.random.random(self.num_feature) - 0.5)*scale\n\t\t\tpop[i] += (prob > (1.0-ind_prob)).astype(int)*inc\n\t\t\tpop[i] = np.maximum(1e-5, pop[i])\n\t\t\tif self.fixed_values is not None:\n\t\t\t\tpop[i][self.fixed_indicies] = self.fixed_values\n\n\tdef _show_evolution(self, fits, pop):\n\t\t\"\"\"Print statistics of the evolution of the population.\"\"\"\n\t\tlength = len(pop)\n\t\tmean = fits.mean()\n\t\tstd = fits.std()\n\t\tmin_val = fits.min()\n\t\tmax_val = fits.max()\n\t\tprint (\" Min {} \\n Max {} \\n Avg {}\".format(min_val, max_val, mean))\n\t\tprint (\" Std {} \\n Population Size {}\".format(std, length))\n\t\tprint (\" Best Individual: \", pop[np.argmax(fits)])\n\n\tdef _survive(self, pop_tmp, fitness_tmp):\n\t\t\"\"\"The 80 percent of the individuals with best fitness survives to\n\t\tthe next generation.\n\n\t\tParameters\n\t\t----------\n\t\tpop_tmp : ndarray\n\t\t\tpopulation\n\t\tfitness_tmp : ndarray\n\t\t\tfitness values of `pop_temp`\n\n\t\tReturns\n\t\t-------\n\t\tndarray \n\t\t\tindividuals that survived\n\n\t\t\"\"\"\n\t\tindex_fits = np.argsort(fitness_tmp)[::-1]\n\t\tfitness = fitness_tmp[index_fits]\n\t\tpop = pop_tmp[index_fits]\n\t\tnum_survive = int(0.8*self.pop_amount) \n\t\tsurvive_pop = np.copy(pop[:num_survive])\n\t\tsurvive_fitness = np.copy(fitness[:num_survive])\n\t\treturn np.copy(survive_pop), np.copy(survive_fitness)\n\n\tdef run(self):\n\t\t\"\"\"Start the evolution process.\n\t\t\n\t\tThe evolution steps are:\n\t\t\t1. Select the individuals to perform cross-over and mutation.\n\t\t\t2. Cross over among the selected candidate.\n\t\t\t3. Mutate result as offspring.\n\t\t\t4. Combine the result of offspring and parent together. And selected the top \n\t\t\t 80 percent of original population amount.\n\t\t\t5. Random Generate 20 percent of original population amount new individuals \n\t\t\t and combine the above new population.\n\n\t\tReturns\n\t\t-------\n\t\ttuple\n\t\t\tfinal population and the fitness for the final population\n\n\t\tNote\n\t\t----\n\t\tUses the :mod:`~multiprocessing` package.\n\n\t\t\"\"\"\n\t\tprint(\"----------------Genetic Evolution Starting----------------\")\n\t\tpop = self._generate_population(self.pop_amount)\n\t\tpool = multiprocessing.Pool(processes=multiprocessing.cpu_count())\n\t\tfitness = pool.map(self._evaluate, pop) # how do we know pop[i] belongs to fitness[i]?\n\t\tfitness = np.array([val[0] for val in fitness])\n\t\tu_hist = np.zeros(self.num_gen) # not been used ...\n\t\tfor g in range(0, self.num_gen):\n\t\t\tprint (\"-- Generation {} --\".format(g+1))\n\t\t\tpop_select = self._select(np.copy(pop), rate=1)\n\t\t\t\n\t\t\tself._uniform_cross_over(pop_select, 0.50)\n\t\t\tself._uniform_mutation(pop_select, 0.25, np.exp(-float(g)/self.num_gen)**2)\n\t\t\t#self._mutate(pop_select, 0.05)\n\t\t\t\n\t\t\tfitness_select = pool.map(self._evaluate, pop_select)\n\t\t\tfitness_select = np.array([val[0] for val in fitness_select])\n\t\t\t\n\t\t\tpop_tmp = np.append(pop, pop_select, axis=0)\n\t\t\tfitness_tmp = np.append(fitness, fitness_select, axis=0)\n\n\t\t\tpop_survive, fitness_survive = self._survive(pop_tmp, fitness_tmp)\n\n\t\t\tpop_new = self._generate_population(self.pop_amount - len(pop_survive))\n\t\t\tfitness_new = pool.map(self._evaluate, pop_new)\n\t\t\tfitness_new = np.array([val[0] for val in fitness_new])\n\n\t\t\tpop = np.append(pop_survive, pop_new, axis=0)\n\t\t\tfitness = np.append(fitness_survive, fitness_new, axis=0)\n\t\t\tif self.print_progress:\n\t\t\t\tself._show_evolution(fitness, pop)\n\t\t\tu_hist[g] = fitness[0]\n\n\t\tfitness = pool.map(self._evaluate, pop)\n\t\tfitness = np.array([val[0] for val in fitness])\n\t\treturn pop, fitness\n\n\nclass GradientSearch(object) :\n\t\"\"\"Gradient search optimization algorithm for the EZ-Climate model.\n\n\tParameters\n\t----------\n\tutility : `Utility` object\n\t\tobject of utility class\n\tlearning_rate : float\n\t\tstarting learning rate of gradient descent\n\tvar_nums : int\n\t\tnumber of elements in array to optimize\n\taccuracy : float\n\t\tstop value for the gradient descent\n\tfixed_values : ndarray, optional\n\t\tnodes to keep fixed\n\tfixed_indicies : ndarray, optional\n\t\tindicies of nodes to keep fixed\n\tprint_progress : bool, optional\n\t\tif the progress of the evolution should be printed\n\tscale_alpha : ndarray, optional\n\t\tarray to scale the learning rate\n\n\tAttributes\n\t----------\n\tutility : `Utility` object\n\t\tobject of utility class\n\tlearning_rate : float\n\t\tstarting learning rate of gradient descent\n\tvar_nums : int\n\t\tnumber of elements in array to optimize\n\taccuracy : float\n\t\tstop value for the gradient descent\n\tfixed_values : ndarray, optional\n\t\tnodes to keep fixed\n\tfixed_indicies : ndarray, optional\n\t\tindicies of nodes to keep fixed\n\tprint_progress : bool, optional\n\t\tif the progress of the evolution should be printed\n\tscale_alpha : ndarray, optional\n\t\tarray to scale the learning rate\n\n\t\"\"\"\n\n\tdef __init__(self, utility, var_nums, accuracy=1e-06, iterations=100, fixed_values=None, \n\t\t fixed_indicies=None, print_progress=False, scale_alpha=None):\n\t\tself.u = utility\n\t\tself.var_nums = var_nums\n\t\tself.accuracy = accuracy\n\t\tself.iterations = iterations\n\t\tself.fixed_values = fixed_values\n\t\tself.fixed_indicies = fixed_indicies\n\t\tself.print_progress = print_progress\n\t\tself.scale_alpha = scale_alpha\n\t\tif scale_alpha is None:\n\t\t\tself.scale_alpha = np.exp(np.linspace(0.0, 3.0, var_nums))\n\n\tdef _partial_grad(self, i):\n\t\t\"\"\"Calculate the ith element of the gradient vector.\"\"\"\n\t\tm_copy = self.m.copy()\n\t\tm_copy[i] = m_copy[i] - self.delta if (m_copy[i] - self.delta)>=0 else 0.0\n\t\tminus_utility = self.u.utility(m_copy)\n\t\tm_copy[i] += 2*self.delta\n\t\tplus_utility = self.u.utility(m_copy)\n\t\tgrad = (plus_utility-minus_utility) / (2*self.delta) # the math is trival\n\t\treturn grad, i\n\n\tdef numerical_gradient(self, m, delta=1e-08, fixed_indicies=None):\n\t\t\"\"\"Calculate utility gradient numerically.\n\n\t\tParameters\n\t\t----------\n\t\tm : ndarray or list\n\t\t\tarray of mitigation\n\t\tdelta : float, optional\n\t\t\tchange in mitigation \n\t\tfixed_indicies : ndarray or list, optional\n\t\t\tindicies of gradient that should not be calculated\n\n\t\tReturns\n\t\t-------\n\t\tndarray\n\t\t\tgradient\n\n\t\t\"\"\"\n\t\tself.delta = delta\n\t\tself.m = m\n\t\tif fixed_indicies is None:\n\t\t\tfixed_indicies = []\n\t\tgrad = np.zeros(len(m))\n\t\tif not isinstance(m, np.ndarray):\n\t\t\tself.m = np.array(m)\n\t\tpool = multiprocessing.Pool()\n\t\tindicies = np.delete(range(len(m)), fixed_indicies)\n\t\tres = pool.map(self._partial_grad, indicies)\n\t\tfor g, i in res:\n\t\t\tgrad[i] = g\n\t\tpool.close()\n\t\tpool.join()\n\t\tdel self.m\n\t\tdel self.delta\n\t\treturn grad \n\n\tdef _partial_grad_cons(self, i):\n\t\t\"\"\"Calculate the ith element of the gradient vector.\"\"\"\n\t\tm_copy = self.m.copy()\n\t\tm_copy[i] = m_copy[i] - self.delta if (m_copy[i] - self.delta)>=0 else 0.0\n\t\tminus_utility = self.u.adjusted_utility(m_copy,first_period_consadj=self.cons)\n\t\tm_copy[i] += 2*self.delta\n\t\tplus_utility = self.u.adjusted_utility(m_copy,first_period_consadj=self.cons)\n\t\tgrad = (plus_utility-minus_utility) / (2*self.delta) # the math is trival\n\t\treturn grad, i\n\n\tdef numerical_gradient_cons(self, m, cons,delta=1e-08):\n\t\t\"\"\"Calculate utility gradient numerically.\n\n\t\tParameters\n\t\t----------\n\t\tm : ndarray or list\n\t\t\tarray of mitigation\n\t\tdelta : float, optional\n\t\t\tchange in mitigation \n\t\tfixed_indicies : ndarray or list, optional\n\t\t\tindicies of gradient that should not be calculated\n\n\t\tReturns\n\t\t-------\n\t\tndarray\n\t\t\tgradient\n\n\t\t\"\"\"\n\t\tself.delta = delta\n\t\tself.m = m\n\t\tself.cons = cons\n\t\tgrad = np.zeros(len(m))\n\t\tif not isinstance(m, np.ndarray):\n\t\t\tself.m = np.array(m)\n\t\tpool = multiprocessing.Pool()\n\t\tindicies = np.array(range(len(m)))\n\t\tres = pool.map(self._partial_grad_cons, indicies)\n\t\tfor g, i in res:\n\t\t\tgrad[i] = g\n\t\tpool.close()\n\t\tpool.join()\n\t\tdel self.m\n\t\tdel self.delta\n\t\tdel self.cons\n\t\treturn grad \n\n\tdef _accelerate_scale(self, accelerator, prev_grad, grad):\n\t\tsign_vector = np.sign(prev_grad * grad)\n\t\tscale_vector = np.ones(self.var_nums) * ( 1 + 0.10)\n\t\taccelerator[sign_vector <= 0] = 1\n\t\taccelerator *= scale_vector\n\t\treturn accelerator\n\n\n\tdef gradient_descent(self, initial_point, return_last=False):\n\t\t\"\"\"Gradient descent algorithm. The `initial_point` is updated using the \n\t\tAdam algorithm. Adam uses the history of the gradient to compute individual \n\t\tstep sizes for each element in the mitigation vector. The vector of step \n\t\tsizes are calculated using estimates of the first and second moments of \n\t\tthe gradient.\n\n\t\tParameters\n\t\t----------\n\t\tinitial_point : ndarray\n\t\t\tinitial guess of the mitigation\n\t\treturn_last : bool, optional\n\t\t\tif True the function returns the last point, else the point \n\t\t\t\twith highest utility\n\n\t\tReturns\n\t\t-------\n\t\ttuple\n\t\t\t(best point, best utility)\n\t\t\n\t\t\"\"\"\n\t\tnum_decision_nodes = initial_point.shape[0]\n\t\tx_hist = np.zeros((self.iterations+1, num_decision_nodes))\n\t\tu_hist = np.zeros(self.iterations+1)\n\t\tu_hist[0] = self.u.utility(initial_point)\n\t\tx_hist[0] = initial_point\n\t\t\n\t\tbeta1, beta2 = 0.90, 0.90\n\t\teta = 0.0015 # learning rate\n\t\teps = 1e-3\n\t\tm_t, v_t = 0, 0\n\n\t\tprev_grad = 0.0\n\t\taccelerator = np.ones(self.var_nums)\n\t\t# formula at http://sebastianruder.com/optimizing-gradient-descent/index.html#fnref:15\t\n\t\tfor i in range(self.iterations):\n\t\t\tgrad = self.numerical_gradient(x_hist[i], fixed_indicies=self.fixed_indicies)\n\t\t\tm_t = beta1*m_t + (1-beta1)*grad\n\t\t\tv_t = beta2*v_t + (1-beta2)*np.power(grad, 2) \n\t\t\tm_hat = m_t / (1-beta1**(i+1))\n\t\t\tv_hat = v_t / (1-beta2**(i+1))\n\t\t\tif i != 0:\n\t\t\t\taccelerator = self._accelerate_scale(accelerator, prev_grad, grad)\n\t\t\t\n\t\t\tnew_x = x_hist[i] + ((eta*m_hat)/(np.square(v_hat)+eps)) * accelerator # empirical acceleration, parameter =1.1 is need to be proved later on\n\t\t\tnew_x[new_x < 0] = 0.0\n\n\t\t\tif self.fixed_values is not None:\n\t\t\t\tnew_x[self.fixed_indicies] = self.fixed_values\n\n\t\t\tx_hist[i+1] = new_x\n\t\t\tu_hist[i+1] = self.u.utility(new_x)[0]\n\t\t\tprev_grad = grad.copy()\n\n\t\t\tif self.print_progress:\n\t\t\t\tprint(\"-- Iteration {} -- \\n Current Utility: {}\".format(i+1, u_hist[i+1]))\n\t\t\t\tprint(new_x)\n\n\t\tif return_last:\n\t\t\treturn x_hist[i+1], u_hist[i+1]\n\t\tbest_index = np.argmax(u_hist)\n\t\treturn x_hist[best_index], u_hist[best_index]\n\n\tdef run(self, initial_point_list, topk=4):\n\t\t\"\"\"Initiate the gradient search algorithm. \n\n\t\tParameters\n\t\t----------\n\t\tinitial_point_list : list\n\t\t\tlist of initial points to select from\n\t\ttopk : int, optional\n\t\t\tselect and run gradient descent on the `topk` first points of \n\t\t\t`initial_point_list`\n\n\t\tReturns\n\t\t-------\n\t\ttuple\n\t\t\tbest mitigation point and the utility of the best mitigation point\n\n\t\tRaises\n\t\t------\n\t\tValueError\n\t\t\tIf `topk` is larger than the length of `initial_point_list`.\n\n\t\tNote\n\t\t----\n\t\tUses the :mod:`~multiprocessing` package.\n\n\t\t\"\"\"\n\t\tprint(\"----------------Gradient Search Starting----------------\")\n\t\t\n\t\tif topk > len(initial_point_list):\n\t\t\traise ValueError(\"topk {} > number of initial points {}\".format(topk, len(initial_point_list)))\n\n\t\tcandidate_points = initial_point_list[:topk]\n\t\tmitigations = []\n\t\tutilities = np.zeros(topk)\n\t\tfor cp, count in zip(candidate_points, range(topk)):\n\t\t\tif not isinstance(cp, np.ndarray):\n\t\t\t\tcp = np.array(cp)\n\t\t\tprint(\"Starting process {} of Gradient Descent\".format(count+1))\n\t\t\tm, u = self.gradient_descent(cp)\n\t\t\tmitigations.append(m)\n\t\t\tutilities[count] = u\n\t\tbest_index = np.argmax(utilities)\n\t\treturn mitigations[best_index], utilities[best_index]\n\n\nclass CoordinateDescent(object):\n\t\"\"\"Coordinate descent optimization algorithm for the EZ-Climate model.\n\n\tParameters\n\t----------\n\tutility : `Utility` object\n\t\tobject of utility class\n\tvar_nums : int\n\t\tnumber of elements in array to optimize\n\taccuracy : float\n\t\tstop value for the utility increase \n\titerations : int \n\t\tmaximum number of iterations\n\n\tAttributes\n\t----------\n\tutility : `Utility` object\n\t\tobject of utility class\n\tvar_nums : int\n\t\tnumber of elements in array to optimize\n\taccuracy : float\n\t\tstop value for the utility increase\n\titerations : int \n\t\tmaximum number of iterations\n\n\t\"\"\"\n\tdef __init__(self, utility, var_nums, accuracy=1e-4, iterations=100):\n\t\tself.u = utility\n\t\tself.var_nums = var_nums\n\t\tself.accuracy = accuracy\n\t\tself.iterations = iterations\n\t\n\tdef _min_func(self, x, m, i):\n\t\tm_copy = m.copy()\n\t\tm_copy[i] = x\n\t\treturn -self.u.utility(m_copy)[0]\n\n\tdef _minimize_node(self, node, m):\n\t\tfrom scipy.optimize import fmin\n\t\treturn fmin(self._min_func, x0=m[node], args=(m, node), disp=False)\n\n\tdef run(self, m):\n\t\t\"\"\"Run the coordinate descent iterations.\n\n\t\tParameters\n\t\t----------\n\t\tm : initial point\n\n\t\tReturns\n\t\t-------\n\t\ttuple\n\t\t\tbest mitigation point and the utility of the best mitigation point\n\n\t\tNote\n\t\t----\n\t\tUses the :mod:`~scipy` package.\n\n\t\t\"\"\"\n\t\tnum_decision_nodes = m.shape[0]\n\t\tx_hist = []\n\t\tu_hist = []\n\t\tnodes = range(self.var_nums)\n\t\tx_hist.append(m.copy())\n\t\tu_hist.append(self.u.utility(m)[0])\n\t\tprint(\"----------------Coordinate Descent Starting----------------\")\n\t\tprint(\"Starting Utility: {}\".format(u_hist[0]))\n\t\tfor i in range(self.iterations):\n\t\t\tprint(\"-- Iteration {} --\".format(i+1))\n\t\t\tnode_iteration = np.random.choice(nodes, replace=False, size=len(nodes))\n\t\t\tfor node in node_iteration:\n\t\t\t\tm[node] = max(0.0, self._minimize_node(node, m))\n\t\t\tx_hist.append(m.copy())\n\t\t\tu_hist.append(self.u.utility(m)[0])\n\t\t\tprint(\"Current Utility: {}\".format(u_hist[i+1]))\n\t\t\tif np.abs(u_hist[i+1] - u_hist[i]) < self.accuracy:\n\t\t\t\tbreak\n\t\treturn x_hist[-1], u_hist[-1]" ]
[ [ "numpy.ones", "numpy.sign", "numpy.append", "numpy.zeros", "numpy.maximum", "numpy.argsort", "numpy.random.choice", "numpy.copy", "numpy.argmax", "numpy.random.random", "numpy.abs", "numpy.power", "numpy.max", "numpy.array", "numpy.square", "numpy.random.randint", "numpy.linspace", "scipy.optimize.fmin" ] ]
steuxyo/Pandora
[ "57db04f31d6cecba93fa3bc0091f624c8b8ec5f1" ]
[ "tests/test_disparity.py" ]
[ "#!/usr/bin/env python\n# coding: utf8\n#\n# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).\n#\n# This file is part of PANDORA\n#\n# https://github.com/CNES/Pandora\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\"\"\"\nThis module contains functions to test the disparity module.\n\"\"\"\n\nimport unittest\n\nimport numpy as np\nimport xarray as xr\n\nimport common\nimport pandora\nimport pandora.constants as cst\nimport pandora.disparity as disparity\nimport pandora.matching_cost as matching_cost\nfrom pandora.img_tools import read_img\nfrom pandora.state_machine import PandoraMachine\n\n\nclass TestDisparity(unittest.TestCase):\n \"\"\"\n TestDisparity class allows to test the disparity module\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Method called to prepare the test fixture\n\n \"\"\"\n # Create stereo images\n data = np.array(([[1, 2, 4, 6],\n [2, 4, 1, 6],\n [6, 7, 8, 10]]), dtype=np.float64)\n self.left = xr.Dataset({'im': (['row', 'col'], data)},\n coords={'row': np.arange(data.shape[0]), 'col': np.arange(data.shape[1])})\n self.left.attrs = {'valid_pixels': 0, 'no_data_mask': 1}\n\n data = np.array(([[6, 1, 2, 4],\n [6, 2, 4, 1],\n [10, 6, 7, 8]]), dtype=np.float64)\n self.right = xr.Dataset({'im': (['row', 'col'], data)},\n coords={'row': np.arange(data.shape[0]), 'col': np.arange(data.shape[1])})\n self.right.attrs = {'valid_pixels': 0, 'no_data_mask': 1}\n\n def test_to_disp(self):\n \"\"\"\n Test the to disp method\n\n \"\"\"\n\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -3 disp_max 1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 1,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, 1)\n\n # Disparity map ground truth, for the images described in the setUp method\n gt_disp = np.array([[1, 1, 1, -3],\n [1, 1, 1, -3],\n [1, 1, 1, -3]])\n\n # Compute the disparity\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n disp = disparity_.to_disp(cv)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp['disparity_map'].data, gt_disp)\n\n #\n # Test the to_disp method with negative disparity range\n #\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, -1)\n\n # Disparity map ground truth\n gt_disp = np.array([[0, -1, -2, -3],\n [0, -1, -1, -3],\n [0, -1, -2, -3]])\n\n # Compute the disparity\n disp = disparity_.to_disp(cv)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp['disparity_map'].data, gt_disp)\n\n #\n # Test the to_disp method with positive disparity range\n #\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, 1, 3)\n\n # Disparity map ground truth\n gt_disp = np.array([[1, 1, 1, 0],\n [1, 1, 1, 0],\n [1, 1, 1, 0]])\n\n # Compute the disparity\n disp = disparity_.to_disp(cv)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp['disparity_map'].data, gt_disp)\n\n # Test disp_indices copy\n # Modify the disparity map\n disp['disparity_map'].data[0, 0] = -95\n # Check if the xarray disp_indices is equal to the ground truth disparity map\n np.testing.assert_array_equal(cv['disp_indices'].data, gt_disp)\n\n def test_to_disp_with_offset(self):\n \"\"\"\n Test the to disp method with window_size > 1\n\n \"\"\"\n\n # Create the left cost volume, with SAD measure window size 3, subpixel 1, disp_min -3 disp_max 1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 3,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, 1)\n\n # Disparity map ground truth, for the images described in the setUp method\n # Check if gt is full size and border (i.e [offset:-offset] equal to invalid_disparity\n gt_disp = np.array([[-99, -99, -99, -99],\n [-99, 1, 0, -99],\n [-99, -99, -99, -99]])\n\n # Compute the disparity\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': -99})\n disp = disparity_.to_disp(cv)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp['disparity_map'].data, gt_disp)\n\n #\n # Test the to_disp method with negative disparity range\n #\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, -1)\n\n # Disparity map ground truth\n gt_disp = np.array([[-99, -99, -99, -99],\n [-99, -99, -1, -99],\n [-99, -99, -99, -99]])\n\n # Compute the disparity\n disp = disparity_.to_disp(cv)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp['disparity_map'].data, gt_disp)\n\n #\n # Test the to_disp method with positive disparity range\n #\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, 1, 3)\n\n # Disparity map ground truth\n gt_disp = np.array([[-99, -99, -99, -99],\n [-99, 1, -99, -99],\n [-99, -99, -99, -99]])\n # Compute the disparity\n disp = disparity_.to_disp(cv)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp['disparity_map'].data, gt_disp)\n\n # Test disp_indices copy\n # Modify the disparity map\n disp['disparity_map'].data[0, 0] = -95\n # Check if the xarray disp_indices is equal to the ground truth disparity map\n np.testing.assert_array_equal(cv['disp_indices'].data, gt_disp)\n\n def test_argmin_split(self):\n \"\"\"\n Test the argmin_split method\n\n \"\"\"\n # Create the left cost volume, with SAD measure, window size 1, subpixel 2, disp_min -3 disp_max 1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 1,\n 'subpix': 2})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, 1)\n indices_nan = np.isnan(cv['cost_volume'].data)\n cv['cost_volume'].data[indices_nan] = np.inf\n\n # ground truth\n gt_disp = np.array([[1., 1., 1., -3.],\n [1., -0.5, 1., -3.],\n [1., 1., -1.5, -3]], dtype=np.float32)\n\n # Compute the disparity\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n disp = disparity_.argmin_split(cv)\n\n # Check if the calculated coefficient map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(gt_disp, disp)\n\n def test_argmax_split(self):\n \"\"\"\n Test the argmax_split method\n\n \"\"\"\n # Create the left cost volume, with ZNCC measure, window size 1, subpixel 2, disp_min -3 disp_max 1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'zncc', 'window_size': 1,\n 'subpix': 2})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, 1)\n indices_nan = np.isnan(cv['cost_volume'].data)\n cv['cost_volume'].data[indices_nan] = -np.inf\n\n # ground truth\n gt_disp = np.array([[0., -1., -2., -3.],\n [0., -1., -2., -3.],\n [0., -1., -2., -3.]], dtype=np.float32)\n\n # Compute the disparity\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n disp = disparity_.argmax_split(cv)\n\n # Check if the calculated coefficient map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(gt_disp, disp)\n\n def test_coefficient_map(self):\n \"\"\"\n Test the method coefficient map\n\n \"\"\"\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -3 disp_max 1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 1,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, 1)\n\n # Compute the disparity\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n disparity_.to_disp(cv)\n\n # Coefficient map ground truth, for the images described in the setUp method\n gt_coeff = np.array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]])\n # Compute the disparity, and the coefficient map\n coeff = disparity_.coefficient_map(cv)\n\n # Check if the calculated coefficient map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(coeff.data, gt_coeff)\n\n def test_approximate_right_disparity(self):\n \"\"\"\n Test the approximate_right_disparity method\n\n \"\"\"\n # Create the left cost volume, with SAD measure window size 3 and subpixel 1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 3,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -2, 1)\n\n # Right disparity map ground truth, for the images described in the setUp method\n gt_disp = np.array([[0, 0, 0, 0],\n [0, 0, -1, 0],\n [0, 0, 0, 0]])\n\n # Compute the right disparity map\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n disp_r = disparity_.approximate_right_disparity(cv, self.right)\n\n # Check if the calculated right disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp_r['disparity_map'].data, gt_disp)\n\n def test_right_disparity_subpixel(self):\n \"\"\"\n Test the right disparity method, with subpixel disparity\n\n \"\"\"\n # Create the left cost volume, with SAD measure window size 3 and subpixel 4\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 3,\n 'subpix': 4})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -2, 1)\n\n # Right disparity map ground truth\n gt_disp = np.array([[0, 0, 0, 0],\n [0, 0, -1, 0],\n [0, 0, 0, 0]])\n\n # Compute the right disparity map\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n disp_r = disparity_.approximate_right_disparity(cv, self.right)\n\n # Check if the calculated right disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(disp_r['disparity_map'].data, gt_disp)\n\n @staticmethod\n def test_right_disparity_comparaison():\n \"\"\"\n Test the right disparity method by comparing the right disparity map calculated from scratch with the one\n calculated with the fast method\n\n \"\"\"\n # Build the default configuration\n default_cfg = pandora.check_json.default_short_configuration\n\n pandora_left = read_img('tests/pandora/left.png', no_data=np.nan, mask=None)\n pandora_right = read_img('tests/pandora/right.png', no_data=np.nan, mask=None)\n\n fast_cfg = {\n 'pipeline': {\n 'right_disp_map': {\n 'method': 'accurate'\n },\n 'matching_cost': {\n 'matching_cost_method': 'census'\n },\n 'disparity': {\n 'disparity_method': 'wta'\n },\n 'refinement': {\n 'refinement_method': 'vfit'\n },\n 'validation': {\n 'validation_method': 'cross_checking',\n 'right_left_mode': 'approximate'\n }\n }\n }\n\n pandora_machine_fast = PandoraMachine()\n cfg = pandora.check_json.update_conf(default_cfg, fast_cfg)\n left, right_fast = \\\n pandora.run(pandora_machine_fast, pandora_left, pandora_right, -60, 0, cfg['pipeline']) # pylint: disable=unused-variable\n\n acc_cfg = {\n 'pipeline':\n {\n 'right_disp_map': {\n 'method': 'accurate'\n },\n 'matching_cost': {\n 'matching_cost_method': 'census'\n },\n 'disparity': {\n 'disparity_method': 'wta'\n },\n 'refinement': {\n 'refinement_method': 'vfit'\n },\n 'validation': {\n 'validation_method': 'cross_checking',\n 'right_left_mode': 'accurate',\n }\n }\n }\n\n pandora_machine_acc = PandoraMachine()\n cfg = pandora.check_json.update_conf(default_cfg, acc_cfg)\n left, right_acc = pandora.run(pandora_machine_acc, pandora_left, pandora_right, -60, 0, cfg['pipeline'])\n # Check if the calculated disparity map in fast mode is equal to the disparity map in accurate mode\n np.testing.assert_array_equal(right_fast['disparity_map'].data, right_acc['disparity_map'].data)\n\n # Check if the calculated coefficient map in fast mode is equal to the coefficient map in accurate mode\n np.testing.assert_array_equal(right_fast['interpolated_coeff'].data, right_acc['interpolated_coeff'].data)\n\n def test_to_disp_validity_mask(self):\n \"\"\"\n Test the generated validity mask in the to_disp method\n\n # If bit 1 == 1 : Invalid pixel : the disparity interval is missing in the right image\n # If bit 2 == 1 : Information: the disparity interval is incomplete (edge reached in the right image)\n \"\"\"\n # ------ Negative disparities ------\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -3 disp_max -1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 1,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, -1)\n\n # Compute the disparity map and validity mask\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0]], dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Positive disparities ------\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min 1 disp_max 2\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, 1, 2)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[0, 0, 1 << 2, cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING],\n [0, 0, 1 << 2, cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING],\n [0, 0, 1 << 2, cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING]],\n dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Negative and positive disparities ------\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -1 disp_max 1\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -1, 1)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE]],\n dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Variable grids of disparities ------\n # Disp_min and disp_max\n disp_min_grid = np.array([[-3, -2, -3, -1],\n [-2, -2, -1, -3],\n [-1, -2, -2, -3]])\n\n disp_max_grid = np.array([[-1, -1, -2, 0],\n [0, -1, 0, 0],\n [0, 0, -1, -1]])\n\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -3 disp_max -1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 1,\n 'subpix': 1})\n dmin, dmax = matching_cost_plugin.dmin_dmax(disp_min_grid, disp_max_grid)\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, dmin, dmax)\n matching_cost_plugin.cv_masked(self.left, self.right, cv, disp_min_grid, disp_max_grid)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0]], dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n def test_to_disp_validity_mask_with_offset(self):\n \"\"\"\n Test the generated validity mask in the to_disp method\n\n # If bit 1 == 1 : Invalid pixel : the disparity interval is missing in the right image\n # If bit 2 == 1 : Information: the disparity interval is incomplete (edge reached in the right image)\n \"\"\"\n # ------ Negative disparities ------\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -3 disp_max -1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 3,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -3, -1)\n\n # Compute the disparity map and validity mask\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER]], dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Positive disparities ------\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min 1 disp_max 2\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, 1, 2)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER]], dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Negative and positive disparities ------\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -1 disp_max 1\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -1, 1)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER]], dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Variable grids of disparities ------\n # Disp_min and disp_max\n disp_min_grid = np.array([[-3, -2, -3, -1],\n [-2, -2, -1, -3],\n [-1, -2, -2, -3]])\n\n disp_max_grid = np.array([[-1, -1, -2, 0],\n [0, -1, 0, 0],\n [0, 0, -1, -1]])\n\n # Create the left cost volume, with SAD measure window size 1, subpixel 1, disp_min -3 disp_max -1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 3,\n 'subpix': 1})\n dmin, dmax = matching_cost_plugin.dmin_dmax(disp_min_grid, disp_max_grid)\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, dmin, dmax)\n matching_cost_plugin.cv_masked(self.left, self.right, cv, disp_min_grid, disp_max_grid)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, self.left, self.right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER]], dtype=np.uint16)\n\n # Check if the calculated disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n def test_approximate_right_disparity_validity_mask(self):\n \"\"\"\n Test the generated validity mask in the right_disparity method\n\n # If bit 1 == 1 : Invalid pixel : the disparity interval is missing in the right image\n # If bit 2 == 1 : Information: the disparity interval is incomplete (edge reached in the right image)\n \"\"\"\n # Create the left cost volume, with SAD measure window size 1 and subpixel 1\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 1,\n 'subpix': 1})\n\n # ------ Negative and positive disparities ------\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -2, 1)\n\n # Validity mask ground truth ( for disparities -1 0 1 2 )\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE]], dtype=np.uint16)\n\n # Compute the right disparity map and the validity mask\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n dataset = disparity_.approximate_right_disparity(cv, self.right)\n\n # Check if the calculated right disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Negative disparities ------\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, 1, 2)\n\n # Validity mask ground truth ( for disparities -2 -1 )\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n 0, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n 0, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n 0, 0]], dtype=np.uint16)\n\n # Compute the right disparity map and the validity mask\n dataset = disparity_.approximate_right_disparity(cv, self.right)\n\n # Check if the calculated right disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ------ Positive disparities ------\n cv = matching_cost_plugin.compute_cost_volume(self.left, self.right, -2, -1)\n\n # Validity mask ground truth ( for disparities 1 2 )\n gt_mask = np.array([[0, 0, cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING],\n [0, 0, cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING],\n [0, 0, cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING]], dtype=np.uint16)\n\n # Compute the right disparity map and the validity mask\n dataset = disparity_.approximate_right_disparity(cv, self.right)\n\n # Check if the calculated right disparity map is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n @staticmethod\n def test_validity_mask():\n \"\"\"\n # If bit 0 == 1 : Invalid pixel : the disparity interval is missing in the right image\n # If bit 1 == 1 : Invalid pixel : the disparity interval is missing in the right image\n # If bit 2 == 1 : Information: the disparity interval is incomplete (edge reached in the right image)\n # If bit 6 == 1 : Invalid pixel : invalidated by the validity mask of the left image given as input\n # If bit 7 == 1 : Invalid pixel : right positions invalidated by the mask of the right image given as\n # input\n\n \"\"\"\n # Masks convention\n # 1 = valid\n # 2 = no_data\n # ---------------------- Test with positive and negative disparity range ----------------------\n data = np.array(([[1, 2, 4, 6],\n [2, 4, 1, 6],\n [6, 7, 8, 10]]), dtype=np.float64)\n left_mask = np.array([[2, 1, 1, 1],\n [1, 2, 4, 1],\n [5, 1, 1, 2]], dtype=np.uint8)\n left = xr.Dataset({'im': (['row', 'col'], data),\n 'msk': (['row', 'col'], left_mask)},\n coords={'row': np.arange(data.shape[0]), 'col': np.arange(data.shape[1])})\n left.attrs = {'valid_pixels': 1, 'no_data_mask': 2}\n\n data = np.array(([[6, 1, 2, 4],\n [6, 2, 4, 1],\n [10, 6, 7, 8]]), dtype=np.float64)\n right_mask = np.array([[1, 1, 3, 5],\n [4, 1, 1, 1],\n [2, 2, 4, 6]], dtype=np.uint8)\n\n right = xr.Dataset({'im': (['row', 'col'], data),\n 'msk': (['row', 'col'], right_mask)},\n coords={'row': np.arange(data.shape[0]), 'col': np.arange(data.shape[1])})\n right.attrs = {'valid_pixels': 1, 'no_data_mask': 2}\n\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 1,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(left, right, -1, 1)\n\n # Compute the disparity map and validity mask\n disparity_ = disparity.AbstractDisparity(**{'disparity_method': 'wta', 'invalid_disparity': 0})\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, left, right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array(\n [[cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE + cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE + cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_RIGHT],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_LEFT, cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE],\n [cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE + cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_LEFT +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE + cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER +\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_RIGHT]], dtype=np.uint16)\n\n # Check if the calculated validity mask is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ---------------------- Test with negative disparity range ----------------------\n cv = matching_cost_plugin.compute_cost_volume(left, right, -2, -1)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, left, right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING +\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER +\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_RIGHT,\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_LEFT, 0],\n [cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING +\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_LEFT,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER]],\n dtype=np.uint16)\n\n # Check if the calculated validity mask is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ---------------------- Test with positive disparity range ----------------------\n cv = matching_cost_plugin.compute_cost_volume(left, right, 1, 2)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, left, right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER, cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_RIGHT,\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_RIGHT +\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING],\n [0, cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_LEFT,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING],\n [cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_LEFT, cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_RIGHT,\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_RIGHT +\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING]],\n dtype=np.uint16)\n\n # Check if the calculated validity mask is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ---------------------- Test with positive and negative disparity range and window size = 3----------------\n data = np.array(([[1, 2, 4, 6, 1],\n [2, 4, 1, 6, 1],\n [6, 7, 8, 10, 1],\n [0, 5, 6, 7, 8]]), dtype=np.float64)\n left_mask = np.array([[2, 1, 1, 1, 1],\n [1, 2, 4, 1, 1],\n [5, 2, 1, 1, 1],\n [1, 1, 1, 1, 1]], dtype=np.uint8)\n left = xr.Dataset({'im': (['row', 'col'], data),\n 'msk': (['row', 'col'], left_mask)},\n coords={'row': np.arange(data.shape[0]), 'col': np.arange(data.shape[1])})\n left.attrs = {'valid_pixels': 1, 'no_data_mask': 2}\n\n data = np.array(([[6, 1, 2, 4, 1],\n [6, 2, 4, 1, 6],\n [10, 6, 7, 8, 1],\n [5, 6, 7, 8, 0]]), dtype=np.float64)\n right_mask = np.array([[1, 1, 1, 2, 1],\n [5, 1, 1, 1, 1],\n [2, 1, 1, 6, 1],\n [0, 1, 1, 1, 1]], dtype=np.uint8)\n\n right = xr.Dataset({'im': (['row', 'col'], data),\n 'msk': (['row', 'col'], right_mask)},\n coords={'row': np.arange(data.shape[0]), 'col': np.arange(data.shape[1])})\n right.attrs = {'valid_pixels': 1, 'no_data_mask': 2}\n\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 3,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(left, right, -1, 1)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, left, right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array(\n [[cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE + cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING +\n cst.PANDORA_MSK_PIXEL_IN_VALIDITY_MASK_LEFT,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE + cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER, cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n ],\n dtype=np.uint16)\n\n # Check if the calculated validity mask is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n # ---------------------- Test with positive and negative disparity range on flag 1 ----------------------\n # Masks convention\n # 1 = valid\n # 0 = no_data\n\n data = np.ones((10, 10), dtype=np.float64)\n left_mask = np.ones((10, 10), dtype=np.uint8)\n\n left = xr.Dataset({'im': (['row', 'col'], data),\n 'msk': (['row', 'col'], left_mask)},\n coords={'row': np.arange(5, data.shape[0] + 5), 'col': np.arange(4, data.shape[1] + 4)})\n left.attrs = {'valid_pixels': 1, 'no_data_mask': 0}\n\n data = np.ones((10, 10), dtype=np.float64)\n right_mask = np.ones((10, 10), dtype=np.uint8)\n right_mask = np.tril(right_mask, -1.5)\n\n right = xr.Dataset({'im': (['row', 'col'], data),\n 'msk': (['row', 'col'], right_mask)},\n coords={'row': np.arange(5, data.shape[0] + 5), 'col': np.arange(4, data.shape[1] + 4)})\n right.attrs = {'valid_pixels': 1, 'no_data_mask': 0}\n\n matching_cost_plugin = matching_cost.AbstractMatchingCost(**{'matching_cost_method': 'sad', 'window_size': 3,\n 'subpix': 1})\n cv = matching_cost_plugin.compute_cost_volume(left, right, -3, 2)\n\n # Compute the disparity map and validity mask\n dataset = disparity_.to_disp(cv)\n disparity_.validity_mask(dataset, left, right, cv)\n\n # Validity mask ground truth\n gt_mask = np.array([[cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE +\n cst.PANDORA_MSK_PIXEL_RIGHT_NODATA_OR_DISPARITY_RANGE_MISSING,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE, 0, 0, 0,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_RIGHT_INCOMPLETE_DISPARITY_RANGE,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER],\n [cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER,\n cst.PANDORA_MSK_PIXEL_LEFT_NODATA_OR_BORDER]\n ],\n dtype=np.uint8)\n\n # Check if the calculated validity mask is equal to the ground truth (same shape and all elements equals)\n np.testing.assert_array_equal(dataset['validity_mask'].data, gt_mask)\n\n\nif __name__ == '__main__':\n common.setup_logging()\n unittest.main()\n" ]
[ [ "numpy.ones", "numpy.testing.assert_array_equal", "numpy.arange", "numpy.isnan", "numpy.array", "numpy.tril" ] ]
mylar-pr/DaaS
[ "e41fa9e9fbda66d7150f00e6db13dd3a76cd3501" ]
[ "first_lambda/service.py" ]
[ "import datetime\nimport json\nimport os\nimport boto3\nimport pandas as pd\nimport io\nimport requests\nimport numpy as np\nfrom io import StringIO\nimport uuid\n\n\n\ns3 = boto3.resource(\n service_name='s3',\n region_name='us-east-2')\nbucket_name = 'secom-daas-bucket' # already created on S3\n\nlink1 = 'https://archive.ics.uci.edu/ml/machine-learning-databases/secom/secom.data'\nlink2 = \"https://archive.ics.uci.edu/ml/machine-learning-databases/secom/secom_labels.data\"\nlinks = [link1,link2]\n\npath = \"/tmp/\"\ntimestamp = str(int(datetime.datetime.timestamp(datetime.datetime.now())))\n\ndef timestampify(link,timestamp):\n return link.split(\"/\")[-1].split(\".\")[0]+\"_\"+timestamp+\".data\"\n\ndata_filename = timestampify(link1,timestamp)\nlabel_filename = timestampify(link2,timestamp)\n\n\ndef download_data():\n \n url = link1\n \n r = requests.get(url)\n with open(path + data_filename, 'wb') as f:\n f.write(r.content)\n files = r.content\n f.close()\n print(\"Downloaded Secom data.\")\n \n url = link2\n r = requests.get(url)\n with open(path + label_filename, 'wb') as f:\n f.write(r.content)\n files = r.content\n f.close()\n print(\"Downloaded Secom labels.\")\n #time_stamp = str(int(datetime.datetime.timestamp(datetime.datetime.now())))\n\ndef process_time(secom_labels):\n return [\" \".join(i.decode(\"utf-8\").split()[1:]).split('\"')[1] for i in secom_labels]\n\ndef process_data(secom):\n return np.array([pd.to_numeric(bytearray(i).decode(\"UTF-8\").split(),errors='coerce') for i in secom]).astype(str)\n\ndef process_dataset(secom_path,secom_labels_path):\n\n print(\"processing dataset from {} and {}\".format(secom_path,secom_labels_path))\n #read the downloaded .data files \n with open(secom_path,'rb') as myfile:\n secom= myfile.readlines() \n myfile.close()\n\n with open(secom_labels_path,'rb') as myfile:\n secom_labels= myfile.readlines() \n myfile.close()\n\n columns1= [\"Time\"]\n df1 = pd.DataFrame(data=process_time(secom_labels),\n columns=columns1)\n df1\n\n features_size = len(secom[0].split())\n columns2 = [\"feature \"+ str(i) for i in range(features_size)]\n df2 = pd.DataFrame(data=process_data(secom),\n columns=columns2)\n\n df2.fillna(df2.mean(),inplace=True)\n df3 = pd.concat([df1,df2],axis=1).reset_index()\n\n df3 = df3.rename(columns = {'index':'secomId'})\n #set the secomId as unique ids\n df3['secomId'] = pd.Series([int(uuid.uuid4().int/(10**30)) for i in range(df3.shape[0])])\n\n\n return df3\n\n\n\n\n \n#bucket = 'my_bucket_name' # already created on S3\ndef upload_to_s3(df,bucket_name,dest_path='df.csv'):\n csv_buffer = StringIO()\n df.to_csv(csv_buffer)\n #s3_resource = boto3.resource('s3')\n s3.Object(bucket_name, dest_path).put(Body=csv_buffer.getvalue())\n print(\"Succesfully stored csv file into S3...\")\n\n\n\n\ndef handler(event, context):\n # Your code goes here!\n startTime = datetime.datetime.now()\n \n download_data()\n \n df = process_dataset(path + data_filename,path + label_filename)\n\n upload_to_s3(df, bucket_name, 'processed/processed_'+timestamp+\".csv\" )\n \n\n print(datetime.datetime.now() - startTime)\n\n\n\n\nhandler(1,1)" ]
[ [ "pandas.concat" ] ]
antonyvigouret/Text-Recognition-PyTorch
[ "7576480684612e856602169b3229fe6c8f4b4b9d" ]
[ "train.py" ]
[ "import string\n\nimport torch\nfrom torch.nn import CrossEntropyLoss\nfrom torch.nn import CTCLoss\nimport torch.optim as optim\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchsummary import summary\nfrom tqdm import tqdm\n\nfrom cnn_seq2seq import ConvSeq2Seq\nfrom cnn_seq2seq import Decoder\nfrom cnn_seq2seq import Encoder\nfrom cnn_seq2seq_att import ConvSeq2SeqAtt\nfrom crnn import CRNN\nfrom data_utils import FakeTextImageGenerator\nfrom utils import labels_to_text\nfrom utils import text_to_labels\n\n\ndef train(path=None):\n dataset = FakeTextImageGenerator(batch_size=16).iter()\n\n criterion = CTCLoss(reduction=\"mean\", zero_infinity=True)\n\n net = CRNN(nclass=100).float()\n optimizer = optim.Adam(net.parameters(), lr=0.001)\n\n if path:\n checkpoint = torch.load(path)\n net.load_state_dict(checkpoint[\"model_state_dict\"])\n optimizer.load_state_dict(checkpoint[\"optimizer_state_dict\"])\n epoch = checkpoint[\"epoch\"]\n loss = checkpoint[\"loss\"]\n print(f\"model current epoch: {epoch} with loss: {loss}\")\n\n # loop over the dataset multiple times\n for epoch in range(1, 1000):\n running_loss = 0.0\n loop = tqdm(range(100))\n for i in loop:\n data = next(dataset)\n images = data[\"the_inputs\"]\n labels = data[\"the_labels\"]\n input_length = data[\"input_length\"]\n label_length = data[\"label_length\"]\n targets = data[\"targets\"]\n\n # print(\"target\", targets)\n # print(\"target l\", targets.size())\n # print(\"label_l\", label_length)\n # print(\"label_l l\", label_length.size())\n # print(\"pred_l\", input_length)\n # print(\"pred_l l\", input_length.size())\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(images.float())\n # print(outputs[8, 0, :])\n # print(outputs[:, 0, :])\n # print(outputs.size())\n loss = criterion(outputs, labels, input_length, label_length)\n\n # print(loss.item())\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n loop.set_postfix(epoch=epoch, loss=(running_loss / (i + 1)))\n\n # print(f\"Epoch: {epoch} | Loss: {running_loss/100}\")\n torch.save(\n {\n \"epoch\": epoch,\n \"model_state_dict\": net.state_dict(),\n \"optimizer_state_dict\": optimizer.state_dict(),\n \"loss\": running_loss,\n },\n \"checkpoint5.pt\",\n )\n\n print(\"Finished Training\")\n\n\ndef train_cs2s(path=None):\n alphabet = string.printable\n nclass = len(alphabet)\n\n writer = SummaryWriter()\n dataset = FakeTextImageGenerator(batch_size=4).iter()\n\n criterion = CrossEntropyLoss(ignore_index=97)\n\n encoder = Encoder(512, 512, 1, 0)\n decoder = Decoder(512, 100, 100, 1, 0)\n net = ConvSeq2Seq(encoder, decoder, nclass=nclass).float()\n\n optimizer = optim.Adam(net.parameters(), lr=0.003)\n\n if path:\n net2 = CRNN(nclass=100).float()\n checkpoint = torch.load(path)\n net2.load_state_dict(checkpoint[\"model_state_dict\"])\n # optimizer.load_state_dict(checkpoint[\"optimizer_state_dict\"])\n # epoch = checkpoint[\"epoch\"]\n # loss = checkpoint[\"loss\"]\n # print(f\"model current epoch: {epoch} with loss: {loss}\")\n print(net2)\n\n net.conv1.load_state_dict(net2.conv1.state_dict())\n net.conv2.load_state_dict(net2.conv2.state_dict())\n net.conv3.load_state_dict(net2.conv3.state_dict())\n net.conv4.load_state_dict(net2.conv4.state_dict())\n net.conv5.load_state_dict(net2.conv5.state_dict())\n net.conv6.load_state_dict(net2.conv6.state_dict())\n net.conv7.load_state_dict(net2.conv7.state_dict())\n net.train()\n\n # loop over the dataset multiple times\n step = 0\n for epoch in range(1, 1000):\n running_loss = 0.0\n loop = tqdm(range(100))\n for i in loop:\n data = next(dataset)\n images = data[\"the_inputs\"]\n labels = data[\"the_labels\"]\n input_length = data[\"input_length\"]\n label_length = data[\"label_length\"]\n targets = data[\"targets\"]\n\n # print(\"target\", targets)\n # print(\"target l\", targets.size())\n # print(\"label_l\", label_length)\n # print(\"label_l l\", label_length.size())\n # print(\"pred_l\", input_length)\n # print(\"pred_l l\", input_length.size())\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(images.float(), labels, 0.5)\n # permute batchsize and seq_len dim to match labels when using .view(-1, output.size()[2])\n outputs = outputs.permute(1, 0, 2)\n # print(outputs[8, 0, :])\n # print(outputs[:, 0, :])\n # print(outputs.size())\n # print(labels.size())\n output_argmax = outputs.argmax(2)\n # print(output_argmax.view(-1))\n # print(labels.reshape(-1))\n loss = criterion(outputs.reshape(-1, 100), labels.reshape(-1))\n\n writer.add_scalar(\"loss\", loss.item(), step)\n step += 1\n loss.backward()\n # torch.nn.utils.clip_grad_norm_(net.parameters(), 1)\n optimizer.step()\n\n running_loss += loss.item()\n\n loop.set_postfix(epoch=epoch, Loss=(running_loss / (i + 1)))\n\n # print(f\"Epoch: {epoch} | Loss: {running_loss/100}\")\n torch.save(\n {\n \"epoch\": epoch,\n \"model_state_dict\": net.state_dict(),\n \"optimizer_state_dict\": optimizer.state_dict(),\n \"loss\": running_loss,\n },\n \"cs2s_good.pt\",\n )\n torch.save(net, \"model_test_pretrained.pt\")\n\n print(\"Finished Training\")\n\n\ndef train_cs2satt(path=None):\n writer = SummaryWriter()\n dataset = FakeTextImageGenerator(batch_size=8).iter()\n\n criterion = CrossEntropyLoss(ignore_index=97)\n\n net = ConvSeq2SeqAtt(nclass=100).float()\n\n optimizer = optim.Adam(net.parameters(), lr=3e-4)\n if path:\n checkpoint = torch.load(path)\n net.load_state_dict(checkpoint[\"model_state_dict\"])\n optimizer.load_state_dict(checkpoint[\"optimizer_state_dict\"])\n epoch = checkpoint[\"epoch\"]\n loss = checkpoint[\"loss\"]\n print(f\"model current epoch: {epoch} with loss: {loss}\")\n net.train()\n\n # loop over the dataset multiple times\n step = 0\n for epoch in range(1, 1000):\n running_loss = 0.0\n loop = tqdm(range(100))\n for i in loop:\n data = next(dataset)\n images = data[\"the_inputs\"]\n labels = data[\"the_labels\"]\n input_length = data[\"input_length\"]\n label_length = data[\"label_length\"]\n targets = data[\"targets\"]\n\n # print(\"target\", targets)\n # print(\"target l\", targets.size())\n # print(\"label_l\", label_length)\n # print(\"label_l l\", label_length.size())\n # print(\"pred_l\", input_length)\n # print(\"pred_l l\", input_length.size())\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(images.float(), labels, 0.5)\n # permute batchsize and seq_len dim to match labels when using .view(-1, output.size()[2])\n outputs = outputs.permute(1, 0, 2)\n # print(outputs[8, 0, :])\n # print(outputs[:, 0, :])\n # print(outputs.size())\n # print(labels.size())\n output_argmax = outputs.argmax(2)\n # print(output_argmax.view(-1))\n # print(labels.reshape(-1))\n loss = criterion(outputs.reshape(-1, 100), labels.reshape(-1))\n\n # print(loss.item())\n writer.add_scalar(\"loss\", loss.item(), step)\n step += 1\n loss.backward()\n torch.nn.utils.clip_grad_norm_(net.parameters(), 1)\n optimizer.step()\n\n running_loss += loss.item()\n\n loop.set_postfix(epoch=epoch, Loss=(running_loss / (i + 1)))\n\n print(f\"Epoch: {epoch} | Loss: {running_loss/100}\")\n torch.save(\n {\n \"epoch\": epoch,\n \"model_state_dict\": net.state_dict(),\n \"optimizer_state_dict\": optimizer.state_dict(),\n \"loss\": running_loss,\n },\n \"cs2satt_good.pt\",\n )\n # torch.save(net, \"model_test_pretrained.pt\")\n\n print(\"Finished Training\")\n\n\nif __name__ == \"__main__\":\n train_cs2satt(\"cs2satt_good.pt\")\n" ]
[ [ "torch.load", "torch.save", "torch.nn.CrossEntropyLoss", "torch.utils.tensorboard.SummaryWriter", "torch.nn.CTCLoss" ] ]
aspuru-guzik-group/routescore
[ "3adedbc1d6193751bd1cd0af33395572b35a8e43" ]
[ "_Figure_S18.py" ]
[ "#!/usr/bin/env python\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Custom style\nplt.style.use('scientific')\n\n# absolute tolerances for chimera\nabsolutes = np.array([0.67, 1080000, 0.2, 0.15848931924611134])\n\n# load in gryffin runs with Naive score as objective\ndf_naive = pd.read_pickle('Optimization/runs/gryffin_runs_naive.pkl')\n\n# make the plot\n\nfig, axes = plt.subplots(nrows=4, ncols=1, sharex=True, figsize=(8, 10))\n\nsns.lineplot(x='eval', y='peak_score', data=df_naive, ax=axes[0], label='Naive Score Included')\naxes[0].axhline(absolutes[0], ls='--', linewidth=2, c='k', alpha=0.6)\naxes[0].fill_between(df_naive['eval'], absolutes[0], np.amin(df_naive['peak_score']), color='#8C9196', alpha=0.25)\naxes[0].set_ylim(0.25, 0.9)\naxes[0].set_ylabel('Peak score ', fontsize=15)\naxes[0].tick_params(labelsize=13)\naxes[0].legend(loc='lower right', ncol=1, fontsize=15)\n\nsns.lineplot(x='eval', y='naive_score', data=df_naive, ax=axes[1])\naxes[1].set_yscale('log')\naxes[1].axhline(absolutes[1], ls='--', linewidth=2, c='k', alpha=0.6)\naxes[1].fill_between(df_naive['eval'], absolutes[1], np.amax(df_naive['naive_score']), color='#8C9196', alpha=0.25)\naxes[1].set_ylim(np.amin(df_naive['naive_score']), np.amax(df_naive['naive_score']))\naxes[1].set_ylabel('Naive score \\n$( \\$ \\cdot (mol \\ target)^{-1}$)', fontsize=15)\naxes[1].tick_params(labelsize=13)\n\nsns.lineplot(x='eval', y='spectral_overlap', data=df_naive, ax=axes[2])\naxes[2].axhline(absolutes[2], ls='--', linewidth=2, c='k', alpha=0.6)\naxes[2].fill_between(df_naive['eval'], absolutes[2], np.amax(df_naive['spectral_overlap']), color='#8C9196', alpha=0.25)\naxes[2].set_ylim(0., 0.3)\naxes[2].set_ylabel('Spectral \\noverlap', fontsize=15)\naxes[2].tick_params(labelsize=13)\n\nsns.lineplot(x='eval', y='fluo_rate', data=df_naive, ax=axes[3])\naxes[3].axhline(absolutes[3], ls='--', linewidth=2, c='k', alpha=0.6)\naxes[3].fill_between(df_naive['eval'], absolutes[3], np.amin(df_naive['fluo_rate']), color='#8C9196', alpha=0.25)\naxes[3].set_ylim(0., 0.6)\naxes[3].set_ylabel('Fluorescence \\nrate (ns$^{-1}$)', fontsize=15)\naxes[3].tick_params(labelsize=13)\naxes[3].set_xlabel('Number of evaluations', fontsize=15)\n\nfor ax in axes:\n ax.set_xlim(0, 500)\n\nplt.tight_layout()\nplt.savefig('Figure_S18.png', dpi=300)\nplt.show()\n" ]
[ [ "pandas.read_pickle", "matplotlib.pyplot.style.use", "matplotlib.pyplot.savefig", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplots", "numpy.amax", "numpy.amin", "matplotlib.pyplot.show", "numpy.array" ] ]
jingshuw/sctransfer
[ "380c3f26934c26cd177e63aacf4f3bdcf9a29c47" ]
[ "sctransfer/network.py" ]
[ "## code simplified from the dca package\n\nimport os\nimport numpy as np\nimport scanpy.api as sc\n\nimport keras\nfrom keras.layers import Input, Dense, Dropout, Activation, BatchNormalization\nfrom keras.models import Model\nfrom keras.objectives import mean_squared_error\nfrom keras import backend as K\n\nimport tensorflow as tf\n\nfrom .loss import NB\nfrom .layers import ConstantDispersionLayer, ColWiseMultLayer\n\n\nMeanAct = lambda x: tf.clip_by_value(K.exp(x), 1e-5, 1e6)\nDispAct = lambda x: tf.clip_by_value(tf.nn.softplus(x), 1e-4, 1e4)\n\n\nclass Autoencoder():\n def __init__(self,\n input_size,\n output_size=None,\n hidden_size=(64, 32, 64),\n hidden_dropout=0.,\n input_dropout=0.,\n batchnorm=True,\n activation='relu',\n init='glorot_uniform',\n nonmissing_indicator = None,\n debug = False):\n\n self.input_size = input_size\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.hidden_dropout = hidden_dropout\n self.input_dropout = input_dropout\n self.batchnorm = batchnorm\n self.activation = activation\n self.init = init\n self.loss = None\n self.extra_models = {}\n self.model = None\n self.input_layer = None\n self.sf_layer = None\n self.debug = debug\n self.nonmissing_indicator = nonmissing_indicator\n\n if self.output_size is None:\n self.output_size = input_size\n\n\n if isinstance(self.hidden_dropout, list):\n assert len(self.hidden_dropout) == len(self.hidden_size)\n else:\n self.hidden_dropout = [self.hidden_dropout]*len(self.hidden_size)\n\n def build(self):\n\n self.input_layer = Input(shape=(self.input_size,), name='count')\n self.sf_layer = Input(shape=(1,), name='size_factors')\n last_hidden = self.input_layer\n\n if self.input_dropout > 0.0:\n last_hidden = Dropout(self.input_dropout, name='input_dropout')(last_hidden)\n\n for i, (hid_size, hid_drop) in enumerate(zip(self.hidden_size, self.hidden_dropout)):\n center_idx = int(np.floor(len(self.hidden_size) / 2.0))\n if i == center_idx:\n layer_name = 'center'\n stage = 'center' # let downstream know where we are\n elif i < center_idx:\n layer_name = 'enc%s' % i\n stage = 'encoder'\n else:\n layer_name = 'dec%s' % (i-center_idx)\n stage = 'decoder'\n\n\n last_hidden = Dense(hid_size, activation=None, kernel_initializer=self.init,\n name=layer_name)(last_hidden)\n \n if self.batchnorm:\n last_hidden = BatchNormalization(center=True, scale=False)(last_hidden)\n ### TODO: check why scale = False\n\n last_hidden = Activation(self.activation, name='%s_act'%layer_name)(last_hidden)\n if hid_drop > 0.0:\n last_hidden = Dropout(hid_drop, name='%s_drop'%layer_name)(last_hidden)\n\n self.decoder_output = last_hidden\n self.build_output()\n\n def build_output(self):\n\n ## For Gaussian loss\n self.loss = mean_squared_error\n mean = Dense(self.output_size, activation=MeanAct, kernel_initializer=self.init,\n name='mean')(self.decoder_output)\n output = ColWiseMultLayer(name='output')([mean, self.sf_layer])\n\n # keep unscaled output as an extra model\n self.extra_models['mean_norm'] = Model(inputs=self.input_layer, outputs=mean)\n self.model = Model(inputs=[self.input_layer, self.sf_layer], outputs=output)\n\n\n ######## ADD WEIGHTS ###########\n\n\n def load_weights(self, filename):\n self.model.load_weights(filename)\n\n\n def predict(self, adata, colnames=None, dimreduce=True, reconstruct=True, error=True):\n\n res = {}\n colnames = adata.var_names.values if colnames is None else colnames\n rownames = adata.obs_names.values\n\n # print('Calculating reconstructions...')\n\n res['mean_norm'] = self.extra_models['mean_norm'].predict(adata.X)\n \n return res\n\n\nclass NBConstantDispAutoencoder(Autoencoder):\n\n def build_output(self):\n mean = Dense(self.output_size, activation=MeanAct, kernel_initializer=self.init,\n name='mean')(self.decoder_output)\n\n # Plug in dispersion parameters via fake dispersion layer\n disp = ConstantDispersionLayer(name='dispersion')\n mean = disp(mean)\n\n output = ColWiseMultLayer(name='output')([mean, self.sf_layer])\n\n nb = NB(disp.theta_exp, nonmissing_indicator = self.nonmissing_indicator)\n self.extra_models['dispersion'] = lambda :K.function([], [nb.theta])([])[0].squeeze()\n self.extra_models['mean_norm'] = Model(inputs=self.input_layer, outputs=mean)\n self.model = Model(inputs=[self.input_layer, self.sf_layer], outputs=output)\n\n\n def predict(self, adata, colnames=None, **kwargs):\n colnames = adata.var_names.values if colnames is None else colnames\n rownames = adata.obs_names.values\n res = super().predict(adata, colnames=colnames, **kwargs)\n\n res['dispersion'] = self.extra_models['dispersion']()\n \n return res\n\n" ]
[ [ "tensorflow.nn.softplus" ] ]
glos/ioos_qc
[ "17e69ad582275be7ad0f5a2af40c11d810b344e8" ]
[ "ioos_qc/results.py" ]
[ "#!/usr/bin/env python\n# coding=utf-8\nimport logging\nfrom typing import NamedTuple, List\nfrom dataclasses import dataclass\nfrom collections import OrderedDict as odict, defaultdict\n\nimport numpy as np\nfrom ioos_qc.qartod import QartodFlags\n\nL = logging.getLogger(__name__) # noqa\n\n\nclass CallResult(NamedTuple):\n package: str\n test: str\n function: callable\n results: np.ndarray\n\n def __repr__(self):\n return f'<CallResult package={self.package} test={self.test}>'\n\n\nclass ContextResult(NamedTuple):\n stream_id: str\n results: List[CallResult]\n subset_indexes: np.ndarray\n data: np.ndarray = None\n tinp: np.ndarray = None\n zinp: np.ndarray = None\n lat: np.ndarray = None\n lon: np.ndarray = None\n\n def __repr__(self):\n return f'<ContextResult stream_id={self.stream_id}>'\n\n\n@dataclass\nclass CollectedResult:\n stream_id: str\n package: str\n test: str\n function: callable\n results: np.ma.core.MaskedArray = None\n data: np.ndarray = None\n tinp: np.ndarray = None\n zinp: np.ndarray = None\n lat: np.ndarray = None\n lon: np.ndarray = None\n\n def __repr__(self):\n return f'<CollectedResult stream_id={self.stream_id} package={self.package} test={self.test}>'\n\n def function_name(self) -> str:\n return self.function.__name__\n\n @property\n def hash_key(self) -> str:\n return f'{self.stream_id}:{self.package}.{self.test}'\n\n\ndef collect_results(results, how='list'):\n if how in ['list', list]:\n return collect_results_list(results)\n elif how in ['dict', dict]:\n return collect_results_dict(results)\n\n\ndef collect_results_list(results):\n \"\"\" Turns a list of ContextResult objects into an iterator of CollectedResult objects\n by combining the subset_index information in each ContextResult together into\n a single array of results.\n \"\"\"\n collected = odict()\n\n # ContextResults\n for r in results:\n\n cr = None\n # Shortcut for CallResult objects when someone uses QcConfig.run() directly\n # and doesn't go through a Stream object\n if isinstance(r, CallResult):\n cr = CollectedResult(\n stream_id=None,\n package=r.package,\n test=r.test,\n function=r.function,\n results=r.results,\n )\n collected[cr.hash_key] = cr\n continue\n\n # CallResults\n for tr in r.results:\n\n cr = CollectedResult(\n stream_id=r.stream_id,\n package=tr.package,\n test=tr.test,\n function=tr.function\n )\n\n if cr.hash_key not in collected:\n # Set the initial values\n cr.results = np.ma.masked_all(shape=r.subset_indexes.shape, dtype=tr.results.dtype)\n cr.data = np.ma.masked_all(shape=r.subset_indexes.shape, dtype=r.data.dtype)\n cr.tinp = np.ma.masked_all(shape=r.subset_indexes.shape, dtype=r.tinp.dtype)\n cr.zinp = np.ma.masked_all(shape=r.subset_indexes.shape, dtype=r.zinp.dtype)\n cr.lat = np.ma.masked_all(shape=r.subset_indexes.shape, dtype=r.lat.dtype)\n cr.lon = np.ma.masked_all(shape=r.subset_indexes.shape, dtype=r.lon.dtype)\n collected[cr.hash_key] = cr\n\n collected[cr.hash_key].results[r.subset_indexes] = tr.results\n\n if cr is not None:\n if r.subset_indexes.all():\n collected[cr.hash_key].data = r.data\n collected[cr.hash_key].tinp = r.tinp\n collected[cr.hash_key].zinp = r.zinp\n collected[cr.hash_key].lat = r.lat\n collected[cr.hash_key].lon = r.lon\n else:\n collected[cr.hash_key].data[r.subset_indexes] = r.data\n collected[cr.hash_key].tinp[r.subset_indexes] = r.tinp\n collected[cr.hash_key].zinp[r.subset_indexes] = r.zinp\n collected[cr.hash_key].lat[r.subset_indexes] = r.lat\n collected[cr.hash_key].lon[r.subset_indexes] = r.lon\n\n return list(collected.values())\n\n\ndef collect_results_dict(results):\n \"\"\" Turns a list of ContextResult objects into a dictionary of test results\n by combining the subset_index information in each ContextResult together into\n a single array of results. This is mostly here for historical purposes. Users\n should migrate to using the Result objects directly.\n \"\"\"\n # Magic for nested key generation\n # https://stackoverflow.com/a/27809959\n collected = defaultdict(lambda: defaultdict(odict))\n\n # ContextResults\n for r in results:\n\n # Shortcut for CallResult objects when someone uses QcConfig.run() directly\n # and doesn't go through a Stream object\n if isinstance(r, CallResult):\n collected[r.package][r.test] = r.results\n continue\n\n flag_arr = np.ma.empty_like(r.subset_indexes, dtype='uint8')\n flag_arr.fill(QartodFlags.UNKNOWN)\n\n # iterate over the CallResults\n for tr in r.results:\n testpackage = tr.package\n testname = tr.test\n testresults = tr.results\n\n if testname not in collected[r.stream_id][testpackage]:\n collected[r.stream_id][testpackage][testname] = np.copy(flag_arr)\n collected[r.stream_id][testpackage][testname][r.subset_indexes] = testresults\n\n return collected\n" ]
[ [ "numpy.ma.empty_like", "numpy.ma.masked_all", "numpy.copy" ] ]
semio/zipline
[ "f13e9fd1253a500771bf10217b1d37031272c03c" ]
[ "tests/test_assets.py" ]
[ "#\n# Copyright 2015 Quantopian, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTests for the zipline.assets package\n\"\"\"\n\nimport sys\nfrom unittest import TestCase\n\nfrom datetime import datetime, timedelta\nimport pickle\nimport uuid\nimport warnings\n\nimport pandas as pd\nfrom pandas.tseries.tools import normalize_date\nfrom pandas.util.testing import assert_frame_equal\n\nfrom nose_parameterized import parameterized\nfrom numpy import full\n\nfrom zipline.assets import Asset, Equity, Future, AssetFinder\nfrom zipline.assets.futures import FutureChain\nfrom zipline.errors import (\n SymbolNotFound,\n MultipleSymbolsFound,\n SidAssignmentError,\n RootSymbolNotFound,\n)\nfrom zipline.finance.trading import with_environment\nfrom zipline.utils.test_utils import (\n all_subindices,\n make_rotating_asset_info,\n)\n\n\ndef build_lookup_generic_cases():\n \"\"\"\n Generate test cases for AssetFinder test_lookup_generic.\n \"\"\"\n\n unique_start = pd.Timestamp('2013-01-01', tz='UTC')\n unique_end = pd.Timestamp('2014-01-01', tz='UTC')\n\n dupe_0_start = pd.Timestamp('2013-01-01', tz='UTC')\n dupe_0_end = dupe_0_start + timedelta(days=1)\n\n dupe_1_start = pd.Timestamp('2013-01-03', tz='UTC')\n dupe_1_end = dupe_1_start + timedelta(days=1)\n\n frame = pd.DataFrame.from_records(\n [\n {\n 'sid': 0,\n 'file_name': 'duplicated',\n 'company_name': 'duplicated_0',\n 'start_date_nano': dupe_0_start.value,\n 'end_date_nano': dupe_0_end.value,\n 'exchange': '',\n },\n {\n 'sid': 1,\n 'file_name': 'duplicated',\n 'company_name': 'duplicated_1',\n 'start_date_nano': dupe_1_start.value,\n 'end_date_nano': dupe_1_end.value,\n 'exchange': '',\n },\n {\n 'sid': 2,\n 'file_name': 'unique',\n 'company_name': 'unique',\n 'start_date_nano': unique_start.value,\n 'end_date_nano': unique_end.value,\n 'exchange': '',\n },\n ],\n )\n finder = AssetFinder(metadata=frame)\n dupe_0, dupe_1, unique = assets = [\n finder.retrieve_asset(i)\n for i in range(3)\n ]\n\n dupe_0_start = dupe_0.start_date\n dupe_1_start = dupe_1.start_date\n cases = [\n ##\n # Scalars\n\n # Asset object\n (finder, assets[0], None, assets[0]),\n (finder, assets[1], None, assets[1]),\n (finder, assets[2], None, assets[2]),\n # int\n (finder, 0, None, assets[0]),\n (finder, 1, None, assets[1]),\n (finder, 2, None, assets[2]),\n # Duplicated symbol with resolution date\n (finder, 'duplicated', dupe_0_start, dupe_0),\n (finder, 'duplicated', dupe_1_start, dupe_1),\n # Unique symbol, with or without resolution date.\n (finder, 'unique', unique_start, unique),\n (finder, 'unique', None, unique),\n\n ##\n # Iterables\n\n # Iterables of Asset objects.\n (finder, assets, None, assets),\n (finder, iter(assets), None, assets),\n # Iterables of ints\n (finder, (0, 1), None, assets[:-1]),\n (finder, iter((0, 1)), None, assets[:-1]),\n # Iterables of symbols.\n (finder, ('duplicated', 'unique'), dupe_0_start, [dupe_0, unique]),\n (finder, ('duplicated', 'unique'), dupe_1_start, [dupe_1, unique]),\n # Mixed types\n (finder,\n ('duplicated', 2, 'unique', 1, dupe_1),\n dupe_0_start,\n [dupe_0, assets[2], unique, assets[1], dupe_1]),\n ]\n return cases\n\n\nclass AssetTestCase(TestCase):\n\n def test_asset_object(self):\n self.assertEquals({5061: 'foo'}[Asset(5061)], 'foo')\n self.assertEquals(Asset(5061), 5061)\n self.assertEquals(5061, Asset(5061))\n\n self.assertEquals(Asset(5061), Asset(5061))\n self.assertEquals(int(Asset(5061)), 5061)\n\n self.assertEquals(str(Asset(5061)), 'Asset(5061)')\n\n def test_asset_is_pickleable(self):\n\n # Very wow\n s = Asset(\n 1337,\n symbol=\"DOGE\",\n asset_name=\"DOGECOIN\",\n start_date=pd.Timestamp('2013-12-08 9:31AM', tz='UTC'),\n end_date=pd.Timestamp('2014-06-25 11:21AM', tz='UTC'),\n first_traded=pd.Timestamp('2013-12-08 9:31AM', tz='UTC'),\n exchange='THE MOON',\n )\n s_unpickled = pickle.loads(pickle.dumps(s))\n\n attrs_to_check = ['end_date',\n 'exchange',\n 'first_traded',\n 'end_date',\n 'asset_name',\n 'start_date',\n 'sid',\n 'start_date',\n 'symbol']\n\n for attr in attrs_to_check:\n self.assertEqual(getattr(s, attr), getattr(s_unpickled, attr))\n\n def test_asset_comparisons(self):\n\n s_23 = Asset(23)\n s_24 = Asset(24)\n\n self.assertEqual(s_23, s_23)\n self.assertEqual(s_23, 23)\n self.assertEqual(23, s_23)\n\n self.assertNotEqual(s_23, s_24)\n self.assertNotEqual(s_23, 24)\n self.assertNotEqual(s_23, \"23\")\n self.assertNotEqual(s_23, 23.5)\n self.assertNotEqual(s_23, [])\n self.assertNotEqual(s_23, None)\n\n self.assertLess(s_23, s_24)\n self.assertLess(s_23, 24)\n self.assertGreater(24, s_23)\n self.assertGreater(s_24, s_23)\n\n def test_lt(self):\n self.assertTrue(Asset(3) < Asset(4))\n self.assertFalse(Asset(4) < Asset(4))\n self.assertFalse(Asset(5) < Asset(4))\n\n def test_le(self):\n self.assertTrue(Asset(3) <= Asset(4))\n self.assertTrue(Asset(4) <= Asset(4))\n self.assertFalse(Asset(5) <= Asset(4))\n\n def test_eq(self):\n self.assertFalse(Asset(3) == Asset(4))\n self.assertTrue(Asset(4) == Asset(4))\n self.assertFalse(Asset(5) == Asset(4))\n\n def test_ge(self):\n self.assertFalse(Asset(3) >= Asset(4))\n self.assertTrue(Asset(4) >= Asset(4))\n self.assertTrue(Asset(5) >= Asset(4))\n\n def test_gt(self):\n self.assertFalse(Asset(3) > Asset(4))\n self.assertFalse(Asset(4) > Asset(4))\n self.assertTrue(Asset(5) > Asset(4))\n\n def test_type_mismatch(self):\n if sys.version_info.major < 3:\n self.assertIsNotNone(Asset(3) < 'a')\n self.assertIsNotNone('a' < Asset(3))\n else:\n with self.assertRaises(TypeError):\n Asset(3) < 'a'\n with self.assertRaises(TypeError):\n 'a' < Asset(3)\n\n\nclass TestFuture(TestCase):\n future = Future(\n 2468,\n symbol='OMH15',\n root_symbol='OM',\n notice_date=pd.Timestamp('2014-01-20', tz='UTC'),\n expiration_date=pd.Timestamp('2014-02-20', tz='UTC'),\n contract_multiplier=500\n )\n\n def test_str(self):\n strd = self.future.__str__()\n self.assertEqual(\"Future(2468 [OMH15])\", strd)\n\n def test_repr(self):\n reprd = self.future.__repr__()\n self.assertTrue(\"Future\" in reprd)\n self.assertTrue(\"2468\" in reprd)\n self.assertTrue(\"OMH15\" in reprd)\n self.assertTrue(\"root_symbol='OM'\" in reprd)\n self.assertTrue((\"notice_date=Timestamp('2014-01-20 00:00:00+0000', \"\n \"tz='UTC')\") in reprd)\n self.assertTrue(\"expiration_date=Timestamp('2014-02-20 00:00:00+0000'\"\n in reprd)\n self.assertTrue(\"contract_multiplier=500\" in reprd)\n\n def test_reduce(self):\n reduced = self.future.__reduce__()\n self.assertEqual(Future, reduced[0])\n\n def test_to_and_from_dict(self):\n dictd = self.future.to_dict()\n self.assertTrue('root_symbol' in dictd)\n self.assertTrue('notice_date' in dictd)\n self.assertTrue('expiration_date' in dictd)\n self.assertTrue('contract_multiplier' in dictd)\n\n from_dict = Future.from_dict(dictd)\n self.assertTrue(isinstance(from_dict, Future))\n self.assertEqual(self.future, from_dict)\n\n def test_root_symbol(self):\n self.assertEqual('OM', self.future.root_symbol)\n\n\nclass AssetFinderTestCase(TestCase):\n\n def test_lookup_symbol_fuzzy(self):\n as_of = pd.Timestamp('2013-01-01', tz='UTC')\n frame = pd.DataFrame.from_records(\n [\n {\n 'sid': i,\n 'file_name': 'TEST@%d' % i,\n 'company_name': \"company%d\" % i,\n 'start_date_nano': as_of.value,\n 'end_date_nano': as_of.value,\n 'exchange': uuid.uuid4().hex,\n }\n for i in range(3)\n ]\n )\n finder = AssetFinder(frame, fuzzy_char='@')\n asset_0, asset_1, asset_2 = (\n finder.retrieve_asset(i) for i in range(3)\n )\n\n for i in range(2): # we do it twice to test for caching bugs\n self.assertIsNone(finder.lookup_symbol('test', as_of))\n self.assertEqual(\n asset_1,\n finder.lookup_symbol('test@1', as_of)\n )\n\n # Adding an unnecessary fuzzy shouldn't matter.\n self.assertEqual(\n asset_1,\n finder.lookup_symbol('test@1', as_of, fuzzy=True)\n )\n\n # Shouldn't find this with no fuzzy_str passed.\n self.assertIsNone(finder.lookup_symbol('test1', as_of))\n # Should find exact match.\n self.assertEqual(\n asset_1,\n finder.lookup_symbol('test1', as_of, fuzzy=True),\n )\n\n def test_lookup_symbol_resolve_multiple(self):\n\n # Incrementing by two so that start and end dates for each\n # generated Asset don't overlap (each Asset's end_date is the\n # day after its start date.)\n dates = pd.date_range('2013-01-01', freq='2D', periods=5, tz='UTC')\n df = pd.DataFrame.from_records(\n [\n {\n 'sid': i,\n 'file_name': 'existing',\n 'company_name': 'existing',\n 'start_date_nano': date.value,\n 'end_date_nano': (date + timedelta(days=1)).value,\n 'exchange': 'NYSE',\n }\n for i, date in enumerate(dates)\n ]\n )\n\n finder = AssetFinder(df)\n for _ in range(2): # Run checks twice to test for caching bugs.\n with self.assertRaises(SymbolNotFound):\n finder.lookup_symbol_resolve_multiple('non_existing', dates[0])\n\n with self.assertRaises(MultipleSymbolsFound):\n finder.lookup_symbol_resolve_multiple('existing', None)\n\n for i, date in enumerate(dates):\n # Verify that we correctly resolve multiple symbols using\n # the supplied date\n result = finder.lookup_symbol_resolve_multiple(\n 'existing',\n date,\n )\n self.assertEqual(result.symbol, 'existing')\n self.assertEqual(result.sid, i)\n\n @parameterized.expand(\n build_lookup_generic_cases()\n )\n def test_lookup_generic(self, finder, symbols, reference_date, expected):\n \"\"\"\n Ensure that lookup_generic works with various permutations of inputs.\n \"\"\"\n results, missing = finder.lookup_generic(symbols, reference_date)\n self.assertEqual(results, expected)\n self.assertEqual(missing, [])\n\n def test_lookup_generic_handle_missing(self):\n data = pd.DataFrame.from_records(\n [\n # Sids that will be found when we do lookups.\n {\n 'sid': 0,\n 'file_name': 'real',\n 'company_name': 'real',\n 'start_date_nano': pd.Timestamp('2013-1-1', tz='UTC'),\n 'end_date_nano': pd.Timestamp('2014-1-1', tz='UTC'),\n 'exchange': '',\n },\n {\n 'sid': 1,\n 'file_name': 'also_real',\n 'company_name': 'also_real',\n 'start_date_nano': pd.Timestamp('2013-1-1', tz='UTC'),\n 'end_date_nano': pd.Timestamp('2014-1-1', tz='UTC'),\n 'exchange': '',\n },\n # Sid whose end date is before our query date. We should\n # still correctly find it.\n {\n 'sid': 2,\n 'file_name': 'real_but_old',\n 'company_name': 'real_but_old',\n 'start_date_nano': pd.Timestamp('2002-1-1', tz='UTC'),\n 'end_date_nano': pd.Timestamp('2003-1-1', tz='UTC'),\n 'exchange': '',\n },\n # Sid whose end date is before our query date. We should\n # still correctly find it.\n {\n 'sid': 3,\n 'file_name': 'real_but_in_the_future',\n 'company_name': 'real_but_in_the_future',\n 'start_date_nano': pd.Timestamp('2014-1-1', tz='UTC'),\n 'end_date_nano': pd.Timestamp('2020-1-1', tz='UTC'),\n 'exchange': 'THE FUTURE',\n },\n ]\n )\n finder = AssetFinder(data)\n results, missing = finder.lookup_generic(\n ['real', 1, 'fake', 'real_but_old', 'real_but_in_the_future'],\n pd.Timestamp('2013-02-01', tz='UTC'),\n )\n\n self.assertEqual(len(results), 3)\n self.assertEqual(results[0].symbol, 'real')\n self.assertEqual(results[0].sid, 0)\n self.assertEqual(results[1].symbol, 'also_real')\n self.assertEqual(results[1].sid, 1)\n\n self.assertEqual(len(missing), 2)\n self.assertEqual(missing[0], 'fake')\n self.assertEqual(missing[1], 'real_but_in_the_future')\n\n def test_insert_metadata(self):\n finder = AssetFinder()\n finder.insert_metadata(0,\n asset_type='equity',\n start_date='2014-01-01',\n end_date='2015-01-01',\n symbol=\"PLAY\",\n foo_data=\"FOO\",)\n\n # Test proper insertion\n equity = finder.retrieve_asset(0)\n self.assertIsInstance(equity, Equity)\n self.assertEqual('PLAY', equity.symbol)\n self.assertEqual(pd.Timestamp('2015-01-01', tz='UTC'),\n equity.end_date)\n\n # Test invalid field\n self.assertFalse('foo_data' in finder.metadata_cache[0])\n\n def test_consume_metadata(self):\n\n # Test dict consumption\n finder = AssetFinder()\n dict_to_consume = {0: {'symbol': 'PLAY'},\n 1: {'symbol': 'MSFT'}}\n finder.consume_metadata(dict_to_consume)\n\n equity = finder.retrieve_asset(0)\n self.assertIsInstance(equity, Equity)\n self.assertEqual('PLAY', equity.symbol)\n\n finder = AssetFinder()\n\n # Test dataframe consumption\n df = pd.DataFrame(columns=['asset_name', 'exchange'], index=[0, 1])\n df['asset_name'][0] = \"Dave'N'Busters\"\n df['exchange'][0] = \"NASDAQ\"\n df['asset_name'][1] = \"Microsoft\"\n df['exchange'][1] = \"NYSE\"\n finder.consume_metadata(df)\n self.assertEqual('NASDAQ', finder.metadata_cache[0]['exchange'])\n self.assertEqual('Microsoft', finder.metadata_cache[1]['asset_name'])\n\n def test_consume_asset_as_identifier(self):\n # Build some end dates\n eq_end = pd.Timestamp('2012-01-01', tz='UTC')\n fut_end = pd.Timestamp('2008-01-01', tz='UTC')\n\n # Build some simple Assets\n equity_asset = Equity(1, symbol=\"TESTEQ\", end_date=eq_end)\n future_asset = Future(200, symbol=\"TESTFUT\", end_date=fut_end)\n\n # Consume the Assets\n finder = AssetFinder()\n finder.consume_identifiers([equity_asset, future_asset])\n\n # Test equality with newly built Assets\n self.assertEqual(equity_asset, finder.retrieve_asset(1))\n self.assertEqual(future_asset, finder.retrieve_asset(200))\n self.assertEqual(eq_end, finder.retrieve_asset(1).end_date)\n self.assertEqual(fut_end, finder.retrieve_asset(200).end_date)\n\n def test_sid_assignment(self):\n\n # This metadata does not contain SIDs\n metadata = {'PLAY': {'symbol': 'PLAY'},\n 'MSFT': {'symbol': 'MSFT'}}\n\n today = normalize_date(pd.Timestamp('2015-07-09', tz='UTC'))\n\n # Build a finder that is allowed to assign sids\n finder = AssetFinder(metadata=metadata,\n allow_sid_assignment=True)\n\n # Verify that Assets were built and different sids were assigned\n play = finder.lookup_symbol('PLAY', today)\n msft = finder.lookup_symbol('MSFT', today)\n self.assertEqual('PLAY', play.symbol)\n self.assertIsNotNone(play.sid)\n self.assertNotEqual(play.sid, msft.sid)\n\n def test_sid_assignment_failure(self):\n\n # This metadata does not contain SIDs\n metadata = {'PLAY': {'symbol': 'PLAY'},\n 'MSFT': {'symbol': 'MSFT'}}\n\n # Build a finder that is not allowed to assign sids, asserting failure\n with self.assertRaises(SidAssignmentError):\n AssetFinder(metadata=metadata, allow_sid_assignment=False)\n\n def test_security_dates_warning(self):\n\n # Build an asset with an end_date\n eq_end = pd.Timestamp('2012-01-01', tz='UTC')\n equity_asset = Equity(1, symbol=\"TESTEQ\", end_date=eq_end)\n\n # Catch all warnings\n with warnings.catch_warnings(record=True) as w:\n # Cause all warnings to always be triggered\n warnings.simplefilter(\"always\")\n equity_asset.security_start_date\n equity_asset.security_end_date\n equity_asset.security_name\n # Verify the warning\n self.assertEqual(3, len(w))\n for warning in w:\n self.assertTrue(issubclass(warning.category,\n DeprecationWarning))\n\n def test_lookup_future_chain(self):\n metadata = {\n # Notice day is today, so not valid\n 2: {\n 'symbol': 'ADN15',\n 'root_symbol': 'AD',\n 'asset_type': 'future',\n 'notice_date': pd.Timestamp('2015-05-14', tz='UTC'),\n 'start_date': pd.Timestamp('2015-01-01', tz='UTC')\n },\n 1: {\n 'symbol': 'ADV15',\n 'root_symbol': 'AD',\n 'asset_type': 'future',\n 'notice_date': pd.Timestamp('2015-08-14', tz='UTC'),\n 'start_date': pd.Timestamp('2015-01-01', tz='UTC')\n },\n # Starts trading today, so should be valid.\n 0: {\n 'symbol': 'ADF16',\n 'root_symbol': 'AD',\n 'asset_type': 'future',\n 'notice_date': pd.Timestamp('2015-11-16', tz='UTC'),\n 'start_date': pd.Timestamp('2015-05-14', tz='UTC')\n },\n # Copy of the above future, but starts trading in August,\n # so it isn't valid.\n 3: {\n 'symbol': 'ADF16',\n 'root_symbol': 'AD',\n 'asset_type': 'future',\n 'notice_date': pd.Timestamp('2015-11-16', tz='UTC'),\n 'start_date': pd.Timestamp('2015-08-01', tz='UTC')\n },\n\n }\n\n finder = AssetFinder(metadata=metadata)\n dt = pd.Timestamp('2015-05-14', tz='UTC')\n last_year = pd.Timestamp('2014-01-01', tz='UTC')\n first_day = pd.Timestamp('2015-01-01', tz='UTC')\n\n # Check that we get the expected number of contracts, in the\n # right order\n ad_contracts = finder.lookup_future_chain('AD', dt, dt)\n self.assertEqual(len(ad_contracts), 2)\n self.assertEqual(ad_contracts[0].sid, 1)\n self.assertEqual(ad_contracts[1].sid, 0)\n\n # Check that we get nothing if our knowledge date is last year\n ad_contracts = finder.lookup_future_chain('AD', dt, last_year)\n self.assertEqual(len(ad_contracts), 0)\n\n # Check that we get things that start on the knowledge date\n ad_contracts = finder.lookup_future_chain('AD', dt, first_day)\n self.assertEqual(len(ad_contracts), 1)\n\n def test_map_identifier_index_to_sids(self):\n # Build an empty finder and some Assets\n dt = pd.Timestamp('2014-01-01', tz='UTC')\n finder = AssetFinder()\n asset1 = Equity(1, symbol=\"AAPL\")\n asset2 = Equity(2, symbol=\"GOOG\")\n asset200 = Future(200, symbol=\"CLK15\")\n asset201 = Future(201, symbol=\"CLM15\")\n\n # Check for correct mapping and types\n pre_map = [asset1, asset2, asset200, asset201]\n post_map = finder.map_identifier_index_to_sids(pre_map, dt)\n self.assertListEqual([1, 2, 200, 201], post_map)\n for sid in post_map:\n self.assertIsInstance(sid, int)\n\n # Change order and check mapping again\n pre_map = [asset201, asset2, asset200, asset1]\n post_map = finder.map_identifier_index_to_sids(pre_map, dt)\n self.assertListEqual([201, 2, 200, 1], post_map)\n\n @with_environment()\n def test_compute_lifetimes(self, env=None):\n num_assets = 4\n trading_day = env.trading_day\n first_start = pd.Timestamp('2015-04-01', tz='UTC')\n\n frame = make_rotating_asset_info(\n num_assets=num_assets,\n first_start=first_start,\n frequency=env.trading_day,\n periods_between_starts=3,\n asset_lifetime=5\n )\n finder = AssetFinder(frame)\n\n all_dates = pd.date_range(\n start=first_start,\n end=frame.end_date.max(),\n freq=trading_day,\n )\n\n for dates in all_subindices(all_dates):\n expected_mask = full(\n shape=(len(dates), num_assets),\n fill_value=False,\n dtype=bool,\n )\n\n for i, date in enumerate(dates):\n it = frame[['start_date', 'end_date']].itertuples()\n for j, start, end in it:\n if start <= date <= end:\n expected_mask[i, j] = True\n\n # Filter out columns with all-empty columns.\n expected_result = pd.DataFrame(\n data=expected_mask,\n index=dates,\n columns=frame.sid.values,\n )\n actual_result = finder.lifetimes(dates)\n assert_frame_equal(actual_result, expected_result)\n\n\nclass TestFutureChain(TestCase):\n metadata = {\n 0: {\n 'symbol': 'CLG06',\n 'root_symbol': 'CL',\n 'asset_type': 'future',\n 'start_date': pd.Timestamp('2005-12-01', tz='UTC'),\n 'notice_date': pd.Timestamp('2005-12-20', tz='UTC'),\n 'expiration_date': pd.Timestamp('2006-01-20', tz='UTC')},\n 1: {\n 'root_symbol': 'CL',\n 'symbol': 'CLK06',\n 'asset_type': 'future',\n 'start_date': pd.Timestamp('2005-12-01', tz='UTC'),\n 'notice_date': pd.Timestamp('2006-03-20', tz='UTC'),\n 'expiration_date': pd.Timestamp('2006-04-20', tz='UTC')},\n 2: {\n 'symbol': 'CLQ06',\n 'root_symbol': 'CL',\n 'asset_type': 'future',\n 'start_date': pd.Timestamp('2005-12-01', tz='UTC'),\n 'notice_date': pd.Timestamp('2006-06-20', tz='UTC'),\n 'expiration_date': pd.Timestamp('2006-07-20', tz='UTC')},\n 3: {\n 'symbol': 'CLX06',\n 'root_symbol': 'CL',\n 'asset_type': 'future',\n 'start_date': pd.Timestamp('2006-02-01', tz='UTC'),\n 'notice_date': pd.Timestamp('2006-09-20', tz='UTC'),\n 'expiration_date': pd.Timestamp('2006-10-20', tz='UTC')}\n }\n\n asset_finder = AssetFinder(metadata=metadata)\n\n def test_len(self):\n \"\"\" Test the __len__ method of FutureChain.\n \"\"\"\n # None of the contracts have started yet.\n cl = FutureChain(self.asset_finder, lambda: '2005-11-30', 'CL')\n self.assertEqual(len(cl), 0)\n\n # Sids 0, 1, & 2 have started, 3 has not yet started.\n cl = FutureChain(self.asset_finder, lambda: '2005-12-01', 'CL')\n self.assertEqual(len(cl), 3)\n\n # Sid 0 is still valid the day before its notice date.\n cl = FutureChain(self.asset_finder, lambda: '2005-12-19', 'CL')\n self.assertEqual(len(cl), 3)\n\n # Sid 0 is now invalid, leaving only Sids 1 & 2 valid.\n cl = FutureChain(self.asset_finder, lambda: '2005-12-20', 'CL')\n self.assertEqual(len(cl), 2)\n\n # Sid 3 has started, so 1, 2, & 3 are now valid.\n cl = FutureChain(self.asset_finder, lambda: '2006-02-01', 'CL')\n self.assertEqual(len(cl), 3)\n\n # All contracts are no longer valid.\n cl = FutureChain(self.asset_finder, lambda: '2006-09-20', 'CL')\n self.assertEqual(len(cl), 0)\n\n def test_getitem(self):\n \"\"\" Test the __getitem__ method of FutureChain.\n \"\"\"\n cl = FutureChain(self.asset_finder, lambda: '2005-12-01', 'CL')\n self.assertEqual(cl[0], 0)\n self.assertEqual(cl[1], 1)\n self.assertEqual(cl[2], 2)\n with self.assertRaises(IndexError):\n cl[3]\n\n cl = FutureChain(self.asset_finder, lambda: '2005-12-19', 'CL')\n self.assertEqual(cl[0], 0)\n\n cl = FutureChain(self.asset_finder, lambda: '2005-12-20', 'CL')\n self.assertEqual(cl[0], 1)\n\n cl = FutureChain(self.asset_finder, lambda: '2006-02-01', 'CL')\n self.assertEqual(cl[-1], 3)\n\n def test_root_symbols(self):\n \"\"\" Test that different variations on root symbols are handled\n as expected.\n \"\"\"\n # Make sure this successfully gets the chain for CL.\n cl = FutureChain(self.asset_finder, lambda: '2005-12-01', 'CL')\n self.assertEqual(cl.root_symbol, 'CL')\n\n # These root symbols don't exist, so RootSymbolNotFound should\n # be raised immediately.\n with self.assertRaises(RootSymbolNotFound):\n FutureChain(self.asset_finder, lambda: '2005-12-01', 'CLZ')\n\n with self.assertRaises(RootSymbolNotFound):\n FutureChain(self.asset_finder, lambda: '2005-12-01', '')\n\n def test_repr(self):\n \"\"\" Test the __repr__ method of FutureChain.\n \"\"\"\n cl = FutureChain(self.asset_finder, lambda: '2005-12-01', 'CL')\n cl_feb = FutureChain(self.asset_finder, lambda: '2005-12-01', 'CL',\n as_of_date='2006-02-01')\n\n # The default chain should not include the as of date.\n self.assertEqual(repr(cl), \"FutureChain(root_symbol='CL')\")\n\n # An explicit as of date should show up in the repr.\n self.assertEqual(\n repr(cl_feb),\n (\"FutureChain(root_symbol='CL', \"\n \"as_of_date='2006-02-01 00:00:00+00:00')\")\n )\n\n def test_as_of(self):\n \"\"\" Test the as_of method of FutureChain.\n \"\"\"\n cl = FutureChain(self.asset_finder, lambda: '2005-12-01', 'CL')\n\n # Test that the as_of_date is set correctly to the future\n feb = '2006-02-01'\n cl_feb = cl.as_of(feb)\n self.assertEqual(\n cl_feb.as_of_date,\n pd.Timestamp(feb, tz='UTC')\n )\n\n # Test that the as_of_date is set correctly to the past, with\n # args of str, datetime.datetime, and pd.Timestamp.\n feb_prev = '2005-02-01'\n cl_feb_prev = cl.as_of(feb_prev)\n self.assertEqual(\n cl_feb_prev.as_of_date,\n pd.Timestamp(feb_prev, tz='UTC')\n )\n\n feb_prev = datetime(year=2005, month=2, day=1)\n cl_feb_prev = cl.as_of(feb_prev)\n self.assertEqual(\n cl_feb_prev.as_of_date,\n pd.Timestamp(feb_prev, tz='UTC')\n )\n\n feb_prev = pd.Timestamp('2005-02-01')\n cl_feb_prev = cl.as_of(feb_prev)\n self.assertEqual(\n cl_feb_prev.as_of_date,\n pd.Timestamp(feb_prev, tz='UTC')\n )\n\n # The chain as of the current dt should always be the same as\n # the defualt chain. Tests date as str, pd.Timestamp, and\n # datetime.datetime.\n self.assertEqual(cl[0], cl.as_of('2005-12-01')[0])\n self.assertEqual(cl[0], cl.as_of(pd.Timestamp('2005-12-01'))[0])\n self.assertEqual(\n cl[0],\n cl.as_of(datetime(year=2005, month=12, day=1))[0]\n )\n\n def test_offset(self):\n \"\"\" Test the offset method of FutureChain.\n \"\"\"\n cl = FutureChain(self.asset_finder, lambda: '2005-12-01', 'CL')\n\n # Test that an offset forward sets as_of_date as expected\n self.assertEqual(\n cl.offset('3 days').as_of_date,\n cl.as_of_date + pd.Timedelta(days=3)\n )\n\n # Test that an offset backward sets as_of_date as expected, with\n # time delta given as str, datetime.timedelta, and pd.Timedelta.\n self.assertEqual(\n cl.offset('-1000 days').as_of_date,\n cl.as_of_date + pd.Timedelta(days=-1000)\n )\n self.assertEqual(\n cl.offset(timedelta(days=-1000)).as_of_date,\n cl.as_of_date + pd.Timedelta(days=-1000)\n )\n self.assertEqual(\n cl.offset(pd.Timedelta('-1000 days')).as_of_date,\n cl.as_of_date + pd.Timedelta(days=-1000)\n )\n\n # An offset of zero should give the original chain.\n self.assertEqual(cl[0], cl.offset(0)[0])\n self.assertEqual(cl[0], cl.offset(\"0 days\")[0])\n\n # A string that doesn't represent a time delta should raise a\n # ValueError.\n with self.assertRaises(ValueError):\n cl.offset(\"blah\")\n" ]
[ [ "pandas.date_range", "pandas.DataFrame", "pandas.Timedelta", "pandas.DataFrame.from_records", "pandas.util.testing.assert_frame_equal", "pandas.Timestamp" ] ]
keunhong/toolbox
[ "e8d1dadab4d9ccf8d78fe86ea933819ac6a07fca" ]
[ "toolbox/sampling/__init__.py" ]
[ "import logging\nimport random\nfrom typing import List, Tuple\n\nimport numpy as np\nfrom skimage.transform import resize\nfrom scipy.ndimage import zoom\n\nfrom toolbox import images\nfrom toolbox.images import crop, mask_bbox\nfrom .poisson_disk import sample_poisson_uniform\n\nlogger = logging.getLogger(__name__)\n\n\nclass PatchType:\n S2F_MASKED_BLACK = 'cropped_scaled_to_fit'\n S2F_MASKED_WHITE = 'cropped_scaled_to_fit_white'\n S2F = 'scaled_to_fit'\n RANDOM = 'random2'\n\n\ndef sample_poisson_mask(mask, r, k):\n ymin, ymax, xmin, xmax = mask_bbox(mask)\n height = ymax - ymin\n width = xmax - xmin\n points = np.array(sample_poisson_uniform(height, width, r, k,\n mask[ymin:ymax, xmin:xmax]))\n points[:, 0] += ymin\n points[:, 1] += xmin\n points = np.floor(points).astype(int)\n return points\n\n\ndef generate_dense_bboxes(\n mask: np.ndarray,\n scale=0.23,\n min_dist=0.091):\n mask_height, mask_width = mask.shape\n min_length = min(mask_height, mask_width)\n patch_sample_size = scale * min_length\n centers = sample_poisson_mask(mask, min_length * min_dist, 1000)\n half = int(patch_sample_size / 2)\n bboxes = []\n for center in centers:\n ycent, xcent = center\n bbox = (ycent - half,\n ycent + half + 1,\n xcent - half,\n xcent + half + 1)\n if (bbox[0] >= 0 and bbox[1] < mask_height\n and bbox[2] >= 0 and bbox[3] < mask_width):\n bboxes.append(bbox)\n print('bboxes={} centers={}, mask_size={}, min_dist={}'.format(\n len(bboxes), len(centers), mask.shape, min_length * min_dist))\n return bboxes\n\n\ndef random_crops(image, patch_size, num_crops):\n border_mask = np.ones(image.shape[:2], dtype=bool)\n left = patch_size/2\n right = image.shape[1] - patch_size/2\n top = patch_size/2\n bottom = image.shape[0] - patch_size/2\n border_mask[:, :left] = False\n border_mask[:, right:] = False\n border_mask[:top, :] = False\n border_mask[bottom:, :] = False\n\n yinds, xinds = np.where(border_mask)\n\n bboxes = []\n for i in range(num_crops):\n point_idx = np.random.randint(0, len(yinds))\n ycent, xcent = yinds[point_idx], xinds[point_idx]\n half = int(patch_size / 2)\n\n # Just squash the patch if it's out of bounds.\n bbox = (ycent - half,\n ycent + half + 1,\n xcent - half,\n xcent + half + 1)\n bboxes.append(bbox)\n\n return bboxes_to_patches(image, bboxes, patch_size)\n\n\ndef generate_random_bboxes(mask: np.ndarray, scale_range=(1.0, 1.0),\n num_patches=5, fixed_size=None):\n \"\"\"\n Generates random bounding boxes at random scales with centroid within the\n mask.\n :param mask: The contrained area for the centroid of the patch.\n :param min_scale: The min scale (multiple of the minimum length of the\n input mask) of the sampling.\n :param max_scale: The max scale (multiple of the minimum length of the\n input mask) of the sampling.\n :param num_patches: Number of patches to generate.\n :return: Bounding boxes.\n \"\"\"\n mask_height, mask_width = mask.shape[:2]\n min_length = min(mask_height, mask_width)\n\n yinds, xinds = np.where(mask)\n\n patch_bboxes = []\n patch_scales = []\n tries = 0\n while len(patch_bboxes) < num_patches:\n scale = random.uniform(*scale_range)\n patch_scales.append(scale)\n patch_size = scale * fixed_size if fixed_size else int(scale * min_length)\n point_idx = np.random.randint(0, len(yinds))\n ycent, xcent = yinds[point_idx], xinds[point_idx]\n half = int(patch_size / 2)\n\n # Just squash the patch if it's out of bounds.\n if (ycent - half < 0 or ycent + half > mask.shape[0] or\n xcent - half < 0 or xcent + half > mask.shape[1]):\n if tries < 100:\n tries += 1\n continue\n\n bbox = (max(ycent - half, 0),\n min(ycent + half + 1, mask.shape[0]),\n max(xcent - half, 0),\n min(xcent + half + 1, mask.shape[1]))\n patch_bboxes.append(bbox)\n\n return patch_bboxes, patch_scales\n\n\ndef bboxes_to_patches(im: np.ndarray,\n bboxes: List[Tuple[int, int, int, int]],\n patch_size: int, use_pil=False):\n \"\"\"\n Converts bounding boxes to actual patches. Patches are all resized to the\n patch size regardless of the original bounding box size.\n :param im: To crop patch from.\n :param bboxes: Boxes defining the patch.\n :param patch_size: Patch size to return.\n :return: Image patches.\n \"\"\"\n patches = []\n for bbox in bboxes:\n cropped = crop(im, bbox)\n if cropped.shape[0] != patch_size or cropped.shape[1] != patch_size:\n scale = [patch_size/cropped.shape[0], patch_size/cropped.shape[1]]\n if len(im.shape) == 3:\n scale.append(1.0)\n if use_pil:\n cropped = resize(cropped, (patch_size, patch_size)) \\\n .astype(dtype=np.float32)\n else:\n cropped = zoom(cropped, scale, im.dtype, order=1)\n patches.append(cropped)\n return patches\n\n\ndef compute_mask_tight_patch(im: np.ndarray,\n mask: np.ndarray,\n patch_size: int):\n \"\"\"\n Computes a patch which contains all the pixels active in the mask scaled to\n the patch size.\n :param im:\n :param mask:\n :param patch_size:\n :return:\n \"\"\"\n bbox = images.compute_mask_bbox(mask)\n cropped = images.crop(im, bbox)\n resized = imresize(cropped, (patch_size, patch_size, cropped.shape[2]))\n return resized\n\n\ndef compute_minmax_thickness(mask):\n max_width = 0\n max_height = 0\n for row_id in range(mask.shape[0]):\n row = mask[row_id, :]\n split_locs = np.where(np.diff(row) != 0)[0] + 1\n for segment in (np.split(row, split_locs)):\n if segment[0] != 0:\n max_width = max(max_width, len(segment))\n for col_id in range(mask.shape[1]):\n col = mask[:, col_id]\n split_locs = np.where(np.diff(col) != 0)[0] + 1\n for segment in (np.split(col, split_locs)):\n if segment[0] != 0:\n max_height = max(max_height, len(segment))\n\n return min(max_width, max_height), max(max_width, max_height)\n" ]
[ [ "numpy.ones", "scipy.ndimage.zoom", "numpy.diff", "numpy.floor", "numpy.where", "numpy.split" ] ]
medialandstudio/bias
[ "9548a2b66c0134c797fa3d00de3711cfef9dbb70" ]
[ "SCANNER_FTX_PERP.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 7 12:02:50 2021\n\n@author: ministudio\n\"\"\"\n\nfrom datetime import datetime, timezone\nimport pandas as pd\nimport numpy as np\nfrom alive_progress import alive_bar\n\n\ndef get_all_futures(ftx_client):\n tickers = ftx_client.fetchMarkets()\n list_perp =[]\n \n #with alive_bar(len(tickers),length=20) as bar:\n for ticker in tickers:\n if 'PERP' in ticker['id']: \n list_perp.append(ticker['id'])\n #bar()\n\n return list_perp\n\n\ndef scanner(day,month,year,ticker,ftx): \n results = pd.DataFrame(columns=['P/L %'])\n start_trade = datetime(year, month, day, 0, 0, 0)\n timestamp = start_trade.replace(tzinfo=timezone.utc).timestamp()\n candles = ftx.fetchOHLCV(ticker, timeframe='1h', since=timestamp*1000, limit=5000)\n candles_df = pd.DataFrame(candles, columns=['MTS','OPEN','HIGH','LOW','CLOSE','VOLUME'])\n volume = candles_df.VOLUME.sum()\n \n for j in range(0,24):\n # algoritmo per andare di candela in candela\n ledger = pd.DataFrame(columns=['POSITION','ENTRY PRICE','P_L SINGLE','P_L TOTAL'])\n long = True\n time_scanner = ''\n \n # calcolo l'offset tra una candela e l'altra di mio interesse \n offset = 12\n \n if j != 0:\n candles = candles[1:] \n \n try:\n for i in range(0,len(candles),offset):\n entry_price = candles[i][1]\n \n if i == 0:\n start = datetime.utcfromtimestamp(candles[i][0]/1000)\n end = datetime.utcfromtimestamp(candles[i+offset][0]/1000) #datetime.utcfromtimestamp(candles[i+offset+10][0]/1000)\n #print('FROM',start.strftime(\"%H:%M\"),'TO',end.strftime(\"%H:%M\"))\n var_pct = p_l_total = 0\n position = 'LONG'\n time_scanner = f'{start.strftime(\"%H:%M\")} to {end.strftime(\"%H:%M\")}'\n \n else:\n #r_exit_entry = candles[i][4]/candles[i-offset][4] #if not long else candles[i][4]/candles[i-offset][4]\n \n # calcolo il profitto\n if long:\n var_pct = round((candles[i-offset][1] - candles[i][1])/candles[i-offset][1]*100, 3)\n p_l_total = ledger['P_L TOTAL'].iloc[-1] + var_pct\n \n if not long:\n var_pct = round((candles[i][1]-candles[i-offset][1])/candles[i][1]*100, 3)\n p_l_total = ledger['P_L TOTAL'].iloc[-1] + var_pct\n \n if long:\n date = datetime.utcfromtimestamp(candles[i][0]/1000)\n position = 'LONG'\n long = False\n else:\n # quindi vado in short\n date = datetime.utcfromtimestamp(candles[i][0]/1000) #candles[i+10][0]/1000\n position = 'SHORT'\n long = True\n \n ledger.loc[date] = [position, entry_price, var_pct, p_l_total]\n \n results.loc[time_scanner] = round(ledger['P_L TOTAL'][-1],2)\n #print('P/L TOTAL :\\t',round(ledger['P_L TOTAL'][-1],2), '%\\n') \n \n except Exception as e: \n results.loc[time_scanner] = np.NAN\n \n return results, volume\n\n" ]
[ [ "pandas.DataFrame" ] ]
srijithmass/RANK-OF-A-MATRIX
[ "f0b2dacac02159a1385cfa23b180859444013911" ]
[ "Rank of a matrix.py" ]
[ "#Program to find the rank of a matrix.\r\n#Developed by: SRIJITH R\r\n#RegisterNumber: 21004191\r\nimport numpy as np\r\nA=np.array([[5,-3,-10],[2,2,-3],[-3,-1,5]])\r\nval=np.linalg.matrix_rank(A)\r\nprint(val)" ]
[ [ "numpy.array", "numpy.linalg.matrix_rank" ] ]
negiaditya/PROJECTS-Data_Science
[ "d26e1fdfc6ce51f02e65c4dbca3edfb5cd97f0a1" ]
[ "Data Science salary prediction/FlaskAPI/app.py" ]
[ "import flask\nfrom flask import Flask,jsonify,request\nimport json\nfrom data_input import data_in\nimport numpy as np\nimport pickle\n\n\n\ndef load_models():\n\tfile_name = './models/model_file.p'\n\twith open(file_name,'rb') as pickled:\n\t\tdata = pickle.load(pickled)\n\t\tmodel = data['model']\n\treturn model\n\napp = Flask(__name__)\n\[email protected]('/predict',methods=['GET'])\ndef predict():\n\trequest_json = request.get_json()\n\tx = request_json['input']\n\tx_in = np.array(x).reshape(1,-1)\n\tmodel = load_models()\n\tprediction = model.predict(x_in)[0]\n\tresponse = json.dumps({'response': prediction})\n\treturn response,200\n\n\nif __name__ == '__main__':\n\tapplication.run(debug=True)" ]
[ [ "numpy.array" ] ]
lfdversluis/wta-tools
[ "e9d505df03fff9bb57208dfb82212977ef5e7ca2" ]
[ "parse_scripts/parquet_parsers/galaxy_to_parquet.py" ]
[ "import json\nimport os\nimport sys\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\n\nfrom objects.task import Task\nfrom objects.workflow import Workflow\nfrom objects.workload import Workload\npd.set_option('display.max_columns', None)\n\n\nUSAGE = 'Usage: python(3) ./galaxy_to_parquet.py galaxy_folder'\nNAME = 'Galaxy'\nTARGET_DIR = os.path.join(os.path.dirname(os.getcwd()), 'output_parquet', NAME)\nDATETIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'\nEPOCH = datetime(1970, 1, 1)\nJOBS = None\nMETRICS = None\nWORKFLOWS = None\nWORKFLOW_INVOCATIONS = None\nWORKFLOW_STEPS = None\nWORKFLOW_INVOKE_STEPS = None\nWORKFLOW_CONNECTIONS = None\nWORKFLOW_STEP_INPUT = None\n\n\ndef read_files(folder_path):\n global METRICS\n METRICS = pd.read_csv(os.path.join(folder_path, 'job_metrics_numeric.csv'),\n names=[\"id\", \"job_id\", \"plugin\", \"metric_name\", \"metric_value\"], dtype={\n \"id\": np.float,\n \"job_id\": np.float,\n \"plugin\": np.str,\n \"metric_name\": np.str,\n \"metric_value\": np.float,\n })\n print(\"Done with reading metrics\")\n global WORKFLOWS\n WORKFLOWS = pd.read_csv(os.path.join(folder_path, 'workflows.csv'),\n names=[\"id\", \"create_time\", \"update_time\", \"stored_workflow_id\", \"has_cycles\", \"has_errors\",\n \"parent_workflow_id\", \"uuid\"], dtype={\n \"id\": np.float,\n \"create_time\": np.str,\n \"update_time\": np.str,\n \"stored_workflow_id\": np.float,\n \"has_cycles\": np.str,\n \"has_errors\": np.str,\n \"parent_workflow_id\": np.float,\n \"uuid\": np.str,\n })\n print(\"Done with reading workflows\")\n\n global WORKFLOW_INVOCATIONS\n WORKFLOW_INVOCATIONS = pd.read_csv(os.path.join(folder_path, 'workflow-invocations.csv'),\n names=[\"id\", \"create_time\", \"update_time\", \"workflow_id\", \"state\", \"scheduler\",\n \"handler\"], dtype={\n \"id\": np.float,\n \"create_time\": np.str,\n \"update_time\": np.str,\n \"workflow_id\": np.float,\n \"state\": np.str,\n \"scheduler\": np.str,\n \"handler\": np.str,\n })\n print(\"Done with reading workflow invocations\")\n\n global WORKFLOW_STEPS\n WORKFLOW_STEPS = pd.read_csv(os.path.join(folder_path, 'workflow-steps.csv'),\n names=[\"id\", \"create_time\", \"update_time\", \"workflow_id\", \"type\", \"tool_id\",\n \"tool_version\", \"order_index\", \"subworkflow_id\", \"dynamic_tool_id\"], dtype={\n \"id\": np.float,\n \"create_time\": np.str,\n \"update_time\": np.str,\n \"workflow_id\": np.float,\n \"type\": np.str,\n \"tool_id\": np.str,\n \"tool_version\": np.str,\n \"order_index\": np.float,\n \"subworkflow_id\": np.str,\n \"dynamic_tool_id\": np.str,\n })\n print(\"Done with reading workflow steps\")\n\n global WORKFLOW_INVOKE_STEPS\n WORKFLOW_INVOKE_STEPS = pd.read_csv(os.path.join(folder_path, 'workflow-invoke-steps.csv'), keep_default_na=True,\n names=[\"id\", \"create_time\", \"update_time\", \"workflow_invocation_id\",\n \"workflow_step_id\", \"job_id\", \"state\"], dtype={\n \"id\": np.float,\n \"create_time\": np.str,\n \"update_time\": np.str,\n \"workflow_invocation_id\": np.float,\n \"workflow_step_id\": np.float,\n \"job_id\": np.float,\n \"state\": np.str,\n })\n print(\"Done with reading workflow invocation steps\")\n\n global WORKFLOW_CONNECTIONS\n WORKFLOW_CONNECTIONS = pd.read_csv(os.path.join(folder_path, 'workflow-connections.csv'),\n names=[\"id\", \"output_step_id\", \"input_step_input_id\", \"output_name\",\n \"input_subworkflow_step_id\"], dtype={\n \"id\": np.float,\n \"output_step_id\": np.float,\n \"input_step_input_id\": np.float,\n \"output_name\": np.str,\n \"input_subworkflow_step_id\": np.float,\n })\n print(\"Done with reading workflow connections\")\n\n global WORKFLOW_STEP_INPUT\n WORKFLOW_STEP_INPUT = pd.read_csv(os.path.join(folder_path, 'workflow-step-input.csv'),\n names=[\"id\", \"workflow_step_id\", \"name\"], dtype={\n \"id\": np.float,\n \"workflow_step_id\": np.float,\n \"name\": np.str,\n })\n print(\"Done with reading workflow step input\")\n\n\ndef check_if_empty(*args):\n for field in args:\n if np.isnan(field):\n return True\n\n\ndef compute_children(step_job_ids, tasks_in_workflow):\n for task in tasks_in_workflow:\n step_id = None\n for pair in step_job_ids:\n # find task id's corresponding step id\n if pair[1] == task.id:\n step_id = pair[0]\n\n children = set()\n df = WORKFLOW_CONNECTIONS.loc[(WORKFLOW_CONNECTIONS[\"output_step_id\"] == step_id)]\n\n if df.empty:\n task.children = children\n continue\n\n for wc_row in df.itertuples():\n\n # find id for subsequent connected step\n row = WORKFLOW_STEP_INPUT.loc[(WORKFLOW_STEP_INPUT[\"id\"] == wc_row[3])]\n\n child_step_id = row.iloc[0][\"workflow_step_id\"]\n\n # find child_step_id in step-job pairs and add corresponding job_id to children set\n for pair2 in step_job_ids:\n if pair2[0] == child_step_id:\n children.add(np.int64(pair2[1]))\n for child in tasks_in_workflow:\n if child.id == pair2[1]:\n child.parents.append(np.int64(task.id))\n break\n break\n task.children = children\n for task2 in tasks_in_workflow:\n unique_parents = set(task2.parents)\n unique_parents_list = list(unique_parents)\n task2.parents = unique_parents_list\n\n return tasks_in_workflow\n\n\ndef parse():\n os.makedirs(TARGET_DIR, exist_ok=True)\n task_counter = 0\n workflow_counter = 0\n processed_workflows = []\n final_workflows = []\n final_tasks = []\n task_offset = 0\n workflow_offset = None\n\n for wi_row in WORKFLOW_INVOCATIONS.itertuples():\n flag = False\n # only use one execution of a workflow\n if wi_row[4] in processed_workflows:\n continue\n\n # check if workflow contains cycles\n workflow_row = WORKFLOWS.loc[(WORKFLOWS[\"id\"] == getattr(wi_row, \"workflow_id\"))]\n if workflow_row.iloc[0][\"has_cycles\"] == \"t\":\n continue\n\n # workflows contain a number of workflow steps but this is not the ID of their actual execution\n # this list is used to tie the workflow steps to their actual execution ID\n step_job_ids = []\n\n tasks_in_workflow = []\n workflow_index = wi_row[4]\n # check if workflow id is null\n if pd.isnull(workflow_index):\n continue\n\n df = WORKFLOW_INVOKE_STEPS.loc[(WORKFLOW_INVOKE_STEPS[\"workflow_invocation_id\"] == getattr(wi_row, \"id\"))]\n\n # check if workflow is not empty\n if df.empty:\n processed_workflows.append(workflow_index)\n continue\n\n for wis_row in df.itertuples():\n\n # check if entry in WF_INVOKE_STEPS has the same wf_invocation_id\n if getattr(wis_row, \"workflow_invocation_id\") == getattr(wi_row, \"id\"):\n\n # check if required fields are not empty\n if check_if_empty(getattr(wis_row, \"workflow_step_id\"), getattr(wis_row, \"job_id\")):\n processed_workflows.append(workflow_index)\n flag = True\n break\n\n # get step id and corresponding execution id\n step_job_pair = [getattr(wis_row, \"workflow_step_id\"), getattr(wis_row, \"job_id\")]\n step_job_ids.append(step_job_pair)\n\n job_id = getattr(wis_row, \"job_id\")\n submit_time = int(((datetime.strptime(getattr(wis_row, \"create_time\"),DATETIME_FORMAT) - EPOCH).total_seconds()) * 1000)\n job_metrics = METRICS.loc[(METRICS[\"job_id\"] == job_id)]\n runtime = job_metrics.loc[(job_metrics[\"metric_name\"] == \"runtime_seconds\"), 'metric_value'] * 1000\n memory = job_metrics.loc[(job_metrics[\"metric_name\"] == \"memory.memsw.max_usage_in_bytes\"), 'metric_value']\n cpu_time = job_metrics.loc[(job_metrics[\"metric_name\"] == \"cpuacct.usage\"), 'metric_value']\n\n # check if any required fields are empty\n if runtime.empty or memory.empty or cpu_time.empty:\n processed_workflows.append(workflow_index)\n flag = True\n break\n\n # used to find the task with lowest submit time, this time will be used ass offset\n if task_offset == 0:\n task_offset = submit_time\n elif submit_time < task_offset:\n task_offset = submit_time\n\n runtime = runtime.iloc[0]\n memory = memory.iloc[0]\n cpu_time = cpu_time.iloc[0] / 1000000\n\n if cpu_time > runtime:\n cpu_time = runtime\n\n task = Task(np.int64(job_id), \"Composite\", submit_time, 0, runtime, 1, None, workflow_index, -1, \"cpu-time\",resource=cpu_time, memory_requested=memory)\n task_counter += 1\n tasks_in_workflow.append(task)\n flag = False\n\n # if flag is true, a task in the workflow is not usable to we skip it\n if flag:\n processed_workflows.append((workflow_index))\n continue\n\n # compute children of tasks\n final_tasks.extend(compute_children(step_job_ids, tasks_in_workflow))\n\n workflow_submit_time = int(((datetime.strptime(getattr(wi_row, \"create_time\"),DATETIME_FORMAT) - EPOCH).total_seconds()) * 1000)\n\n # find smallest workflow submit time as offset\n if workflow_offset is None:\n workflow_offset = workflow_submit_time\n elif workflow_submit_time < workflow_offset:\n workflow_offset = workflow_submit_time\n\n workflow = Workflow(workflow_index, workflow_submit_time, tasks_in_workflow, \"core\", \"Engineering\",\n \"Galaxy\", \"Biological Engineering\")\n workflow.compute_critical_path()\n processed_workflows.append(workflow_index)\n final_workflows.append(workflow)\n workflow_counter += 1\n\n # apply offset\n for x in final_tasks:\n x.ts_submit = x.ts_submit - task_offset\n\n # apply offset\n for y in final_workflows:\n y.ts_submit = y.ts_submit - workflow_offset\n\n # make tasks dataframe\n task_df = pd.DataFrame([t.get_parquet_dict() for t in final_tasks])\n\n # create parquet file in specified folder\n os.makedirs(os.path.join(TARGET_DIR, Task.output_path()), exist_ok=True)\n task_df.to_parquet(os.path.join(TARGET_DIR, Task.output_path(), \"part.0.parquet\"), engine=\"pyarrow\")\n\n # make workflows dataframe\n workflow_df = pd.DataFrame([w.get_parquet_dict() for w in final_workflows])\n\n # create parquet file in specified folder\n os.makedirs(os.path.join(TARGET_DIR, Workflow.output_path()), exist_ok=True)\n workflow_df.to_parquet(os.path.join(TARGET_DIR, Workflow.output_path(), \"part.0.parquet\"), engine=\"pyarrow\")\n\n json_dict = Workload.get_json_dict_from_pandas_task_dataframe(task_df,\n domain=\"Biological Engineering\",\n authors=[\"Jaro Bosch\", \"Laurens Versluis\"],\n workload_description=\"Traces from different biomedical research workflows, executed on the public Galaxy server in Europe.\"\n )\n os.makedirs(os.path.join(TARGET_DIR, Workload.output_path()), exist_ok=True)\n\n with open(os.path.join(TARGET_DIR, Workload.output_path(), \"generic_information.json\"), \"w\") as file:\n # Need this on 32-bit python.\n def default(o):\n if isinstance(o, np.int64): return int(o)\n raise TypeError\n\n file.write(json.dumps(json_dict, default=default))\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print(USAGE)\n sys.exit(1)\n\n folder_path = sys.argv[1]\n read_files(folder_path)\n parse()\n" ]
[ [ "numpy.int64", "pandas.isnull", "numpy.isnan", "pandas.set_option" ] ]
KillerStrike17/PyDeNN
[ "2f0dfaf3e092a4f995ed30e2f8db946e30724551", "2f0dfaf3e092a4f995ed30e2f8db946e30724551" ]
[ "DeNN/visualization/gradcam.py", "DeNN/dataset_loader/data_loader.py" ]
[ "import seaborn as sns\nimport matplotlib.pyplot as plt\nimport torch\nimport numpy as np\nimport cv2\nfrom .cam import GradCAM\n\n\n# def load_gradcam(images, labels, model, device, target_layers):\ndef load_gradcam(test, model, device, target_layers,size = 25,classified = True):\n\n _images = []\n _target = []\n _pred = []\n\n # model, device = self.trainer.model, self.trainer.device\n\n # set the model to evaluation mode\n model.eval()\n\n # turn off gradients\n with torch.no_grad():\n for data, target in test:\n # move them to respective device\n data, target = data.to(device), target.to(device)\n\n # do inferencing\n output = model(data)\n # print(\"output:\",output[0])\n # get the predicted output\n pred = output.argmax(dim=1, keepdim=True)\n # print(pred,pred.view_as(target))\n\n # get the current misclassified in this batch\n list_images = (target.eq(pred.view_as(target)) == classified)\n batch_misclassified = data[list_images]\n batch_mis_pred = pred[list_images]\n batch_mis_target = target[list_images]\n\n # batch_misclassified =\n\n _images.append(batch_misclassified)\n _pred.append(batch_mis_pred)\n _target.append(batch_mis_target)\n\n # group all the batched together\n img = torch.cat(_images)\n pred = torch.cat(_pred)\n tar = torch.cat(_target)\n # move the model to device\n\n images = img[:size]\n labels = tar[:size]\n\n model.to(device)\n\n # set the model in evaluation mode\n model.eval()\n\n # get the grad cam\n gcam = GradCAM(model=model, candidate_layers=target_layers)\n\n # images = torch.stack(images).to(device)\n\n # predicted probabilities and class ids\n pred_probs, pred_ids = gcam.forward(images)\n\n # actual class ids\n # target_ids = torch.LongTensor(labels).view(len(images), -1).to(device)\n target_ids = labels.view(len(images), -1).to(device)\n\n # backward pass wrt to the actual ids\n gcam.backward(ids=target_ids)\n\n # we will store the layers and correspondings images activations here\n layers_region = {}\n\n # fetch the grad cam layers of all the images\n for target_layer in target_layers:\n\n # Grad-CAM\n regions = gcam.generate(target_layer=target_layer)\n\n layers_region[target_layer] = regions\n\n # we are done here, remove the hooks\n gcam.remove_hook()\n\n return layers_region, pred_probs, pred_ids,images, labels\n\n\nsns.set()\n# plt.style.use(\"dark_background\")\n\n\ndef plot_gradcam(gcam_layers, images, target_labels, predicted_labels, class_labels, denormalize):\n\n images = images.cpu()\n # convert BCHW to BHWC for plotting stufffff\n images = images.permute(0, 2, 3, 1)\n target_labels = target_labels.cpu()\n\n fig, axs = plt.subplots(nrows=len(images), ncols=len(\n gcam_layers.keys())+1, figsize=((len(gcam_layers.keys()) + 2)*3, len(images)*3))\n fig.suptitle(\"Grad-CAM\", fontsize=16)\n\n for image_idx, image in enumerate(images):\n\n # denormalize the imaeg\n denorm_img = denormalize(image.permute(2, 0, 1)).permute(1, 2, 0)\n\n # axs[image_idx, 0].text(\n # 0.5, 0.5, f'predicted: {class_labels[predicted_labels[image_idx][0] ]}\\nactual: {class_labels[target_labels[image_idx]] }', horizontalalignment='center', verticalalignment='center', fontsize=14, )\n # axs[image_idx, 0].axis('off')\n\n axs[image_idx, 0].imshow(\n (denorm_img.numpy() * 255).astype(np.uint8), interpolation='bilinear')\n axs[image_idx, 0].axis('off')\n\n for layer_idx, layer_name in enumerate(gcam_layers.keys()):\n # gets H X W of the cam layer\n _layer = gcam_layers[layer_name][image_idx].cpu().numpy()[0]\n heatmap = 1 - _layer\n heatmap = np.uint8(255 * heatmap)\n heatmap_img = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)\n\n superimposed_img = cv2.addWeighted(\n (denorm_img.numpy() * 255).astype(np.uint8), 0.6, heatmap_img, 0.4, 0)\n\n axs[image_idx, layer_idx +\n 1].imshow(superimposed_img, interpolation='bilinear')\n axs[image_idx, layer_idx+1].set_title(f'layer: {layer_name}')\n axs[image_idx, layer_idx+1].axis('off')\n axs[image_idx, 0].set_title(f'Predicted: {class_labels[predicted_labels[image_idx][0] ]}\\nTarget: {class_labels[target_labels[image_idx]] }')\n\n plt.tight_layout()\n plt.subplots_adjust(top=0.95, wspace=0.2, hspace=0.2)\n plt.show()", "from torch.utils.data import DataLoader, Dataset\nfrom torchvision import datasets\nfrom .util import download_and_extract_archive\nimport os, glob\nfrom PIL import Image\nclass DatasetMnist:\n \"\"\"\n This class loads MNIST dataset with applied transformations\n\n # Functions:\n\n __repr__:\n\n This is a representation function, It returns the printable representation of the object.\n\n __str__:\n\n It returns useful string representation of the object.\n\n __init__:\n\n This is the constructor of DataMnist class< It initializes dataset and applied transformations over it.\n \n load_data:\n\n This function returns the generated datasaet.\n \"\"\"\n def __repr__(self):\n return \"Loading MNIST Dataset\"\n\n def __str__(self):\n return \"Loading MNIST Dataset\"\n\n def __init__(self, data_path:str, *, batch_size = 32, shuffle = True,transformations, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None, generator=None):\n \"\"\"\n This function initializes the dataset based on the values provided as parameters\n\n # Param:\n\n data_path: Root directory of dataset where MNIST/processed/training.pt and MNIST/processed/testing.pt exist.\n\n batch_size (int, optional): how many samples per batch to load (default: ``1``).\n\n shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``).\n\n transformations: A function/transform that takes in an PIL image and returns a transformed version. E.g, transforms.RandomCrop \n \n sampler (Sampler, optional): defines the strategy to draw samples from the dataset. If specified, ``shuffle`` must be False.\n \n batch_sampler (Sampler, optional): like sampler, but returns a batch ofindices at a time. Mutually exclusive with :attr:`batch_size`,:attr:`shuffle`, :attr:`sampler`, and :attr:`drop_last`.\n \n num_workers (int, optional): how many subprocesses to use for dataloading. 0 means that the data will be loaded in the main process.(default: ``0``)\n \n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\n \n pin_memory (bool, optional): If ``True``, the data loader will copy tensors into CUDA pinned memory before returning them. If your data elements are a custom type, or your ``collate_fn`` returns a batch that is a custom type\n see the example below.\n \n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then the last batch\n will be smaller. (default: ``False``)\n\n timeout (numeric, optional): if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default: ``0``)\n \n worker_init_fn (callable, optional): If not ``None``, this will be called on each worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as input, after seeding and before data loading. (default: ``None``)\n \"\"\"\n self.data_path = data_path\n self.train_set = datasets.MNIST(root = self.data_path,train = True,download = True, transform = transformations.apply_transforms(train = True))\n self.test_set = datasets.MNIST(root = self.data_path,train = False,download = True, transform = transformations.apply_transforms(train = False))\n self.params = {\n 'shuffle': shuffle,\n 'batch_size': batch_size,\n 'sampler': sampler,\n 'batch_sampler':batch_sampler,\n 'collate_fn':collate_fn,\n 'drop_last':drop_last,\n 'timeout':timeout,\n 'worker_init_fn':worker_init_fn,\n 'multiprocessing_context':multiprocessing_context,\n 'generator':generator,\n 'num_workers': num_workers,\n 'pin_memory': pin_memory\n }\n\n def load_data(self):\n \"\"\"\n This function returns the generated dataset\n\n # Returns:\n\n Dataset,Dataset : Generated test and train dataset\n \"\"\"\n return DataLoader(self.train_set,**self.params),DataLoader(self.test_set,**self.params)\n \nclass DatasetCifar10:\n\n def __repr__(self):\n return \"Loading CIFAR 10 Dataset\"\n\n def __str__(self):\n return \"Loading CIFAR 10 Dataset\"\n\n def __init__(self, data_path,transformations,*, batch_size = 32 , shuffle = True, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None, generator=None):\n \"\"\"\n This function initializes the dataset based on the values provided as parameters\n\n # Param:\n\n data_path: Root directory of dataset where CIFAR10/processed/train.pt and CIFAR10/processed/test.pt exist.\n\n batch_size (int, optional): how many samples per batch to load (default: ``1``).\n\n shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``).\n\n transformations: A function/transform that takes in an PIL image and returns a transformed version. E.g, transforms.RandomCrop \n \n sampler (Sampler, optional): defines the strategy to draw samples from the dataset. If specified, ``shuffle`` must be False.\n \n batch_sampler (Sampler, optional): like sampler, but returns a batch ofindices at a time. Mutually exclusive with :attr:`batch_size`,:attr:`shuffle`, :attr:`sampler`, and :attr:`drop_last`.\n \n num_workers (int, optional): how many subprocesses to use for dataloading. 0 means that the data will be loaded in the main process.(default: ``0``)\n \n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\n \n pin_memory (bool, optional): If ``True``, the data loader will copy tensors into CUDA pinned memory before returning them. If your data elements are a custom type, or your ``collate_fn`` returns a batch that is a custom type\n see the example below.\n \n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then the last batch\n will be smaller. (default: ``False``)\n\n timeout (numeric, optional): if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default: ``0``)\n \n worker_init_fn (callable, optional): If not ``None``, this will be called on each worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as input, after seeding and before data loading. (default: ``None``)\n \"\"\"\n self.data_path = data_path\n self.train_set = datasets.CIFAR10(root = self.data_path,train = True,download = True, transform = transformations.apply_transforms(train = True))\n self.test_set = datasets.CIFAR10(root = self.data_path,train = False,download = True, transform = transformations.apply_transforms(train = False))\n self.params = {\n 'shuffle': shuffle,\n 'batch_size': batch_size,\n 'sampler': sampler,\n 'batch_sampler':batch_sampler,\n 'collate_fn':collate_fn,\n 'drop_last':drop_last,\n 'timeout':timeout,\n 'worker_init_fn':worker_init_fn,\n 'multiprocessing_context':multiprocessing_context,\n 'generator':generator,\n 'num_workers': num_workers,\n 'pin_memory': pin_memory\n }\n\n def load_data(self):\n \"\"\"\n This function returns the generated dataset\n\n # Returns:\n\n Dataset,Dataset : Generated test and train dataset\n \"\"\"\n return DataLoader(self.train_set,**self.params),DataLoader(self.test_set,**self.params)\n\nclass TINYIMAGENET:\n url = 'http://cs231n.stanford.edu/tiny-imagenet-200.zip'\n filename = 'tiny-imagenet-200.zip'\n dataset_folder_name = 'tiny-imagenet-200'\n\n EXTENSION = 'JPEG'\n NUM_IMAGES_PER_CLASS = 500\n CLASS_LIST_FILE = 'wnids.txt'\n VAL_ANNOTATION_FILE = 'val_annotations.txt'\n\n def __init__(self, root, train=True, transform=None, target_transform=None, download=False):\n self.root = root\n self.transform = transform\n self.target_transform = target_transform\n\n if download and (not os.path.isdir(os.path.join(self.root, self.dataset_folder_name))):\n self.download()\n\n self.split_dir = 'train' if train else 'val'\n self.split_dir = os.path.join(\n self.root, self.dataset_folder_name, self.split_dir)\n self.image_paths = sorted(glob.iglob(os.path.join(\n self.split_dir, '**', '*.%s' % self.EXTENSION), recursive=True))\n\n self.target = []\n self.labels = {}\n\n # build class label - number mapping\n with open(os.path.join(self.root, self.dataset_folder_name, self.CLASS_LIST_FILE), 'r') as fp:\n self.label_texts = sorted([text.strip()\n for text in fp.readlines()])\n self.label_text_to_number = {\n text: i for i, text in enumerate(self.label_texts)}\n\n # build labels for NUM_IMAGES_PER_CLASS images\n if train:\n for label_text, i in self.label_text_to_number.items():\n for cnt in range(self.NUM_IMAGES_PER_CLASS):\n self.labels[f'{label_text}_{cnt}.{self.EXTENSION}'] = i\n\n # build the validation dataset\n else:\n with open(os.path.join(self.split_dir, self.VAL_ANNOTATION_FILE), 'r') as fp:\n for line in fp.readlines():\n terms = line.split('\\t')\n file_name, label_text = terms[0], terms[1]\n self.labels[file_name] = self.label_text_to_number[label_text]\n\n self.target = [self.labels[os.path.basename(\n filename)] for filename in self.image_paths]\n\n def download(self):\n download_and_extract_archive(\n self.url, self.root, filename=self.filename)\n\n def __getitem__(self, index):\n filepath = self.image_paths[index]\n img = Image.open(filepath)\n img = img.convert(\"RGB\")\n target = self.target[index]\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n \n def __len__(self):\n return len(self.image_paths)\n\nclass DatasetTinyImageNet:\n\n def __repr__(self):\n return \"Loading TinyImageNet Dataset\"\n\n def __str__(self):\n return \"Loading TinyImageNet Dataset\"\n\n def __init__(self, data_path,transformations,*, batch_size = 32 , shuffle = True, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None, generator=None):\n \"\"\"\n This function initializes the dataset based on the values provided as parameters\n\n # Param:\n\n data_path: Root directory of dataset where TinyImageNet/processed/train.pt and TinyImageNet/processed/test.pt exist.\n\n batch_size (int, optional): how many samples per batch to load (default: ``1``).\n\n shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``).\n\n transformations: A function/transform that takes in an PIL image and returns a transformed version. E.g, transforms.RandomCrop \n \n sampler (Sampler, optional): defines the strategy to draw samples from the dataset. If specified, ``shuffle`` must be False.\n \n batch_sampler (Sampler, optional): like sampler, but returns a batch ofindices at a time. Mutually exclusive with :attr:`batch_size`,:attr:`shuffle`, :attr:`sampler`, and :attr:`drop_last`.\n \n num_workers (int, optional): how many subprocesses to use for dataloading. 0 means that the data will be loaded in the main process.(default: ``0``)\n \n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\n \n pin_memory (bool, optional): If ``True``, the data loader will copy tensors into CUDA pinned memory before returning them. If your data elements are a custom type, or your ``collate_fn`` returns a batch that is a custom type\n see the example below.\n \n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch, if the dataset size is not divisible by the batch size. If ``False`` and the size of dataset is not divisible by the batch size, then the last batch\n will be smaller. (default: ``False``)\n\n timeout (numeric, optional): if positive, the timeout value for collecting a batch from workers. Should always be non-negative. (default: ``0``)\n \n worker_init_fn (callable, optional): If not ``None``, this will be called on each worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as input, after seeding and before data loading. (default: ``None``)\n \"\"\"\n self.data_path = data_path\n self.train_set = TINYIMAGENET(root = self.data_path,train = True,download = True, transform = transformations.apply_transforms(train = True))\n self.test_set = TINYIMAGENET(root = self.data_path,train = False,download = True, transform = transformations.apply_transforms(train = False))\n self.params = {\n 'shuffle': shuffle,\n 'batch_size': batch_size,\n 'sampler': sampler,\n 'batch_sampler':batch_sampler,\n 'collate_fn':collate_fn,\n 'drop_last':drop_last,\n 'timeout':timeout,\n 'worker_init_fn':worker_init_fn,\n 'multiprocessing_context':multiprocessing_context,\n 'generator':generator,\n 'num_workers': num_workers,\n 'pin_memory': pin_memory\n }\n\n def load_data(self):\n \"\"\"\n This function returns the generated dataset\n\n # Returns:\n\n Dataset,Dataset : Generated test and train dataset \n \"\"\"\n return DataLoader(self.train_set,**self.params),DataLoader(self.test_set,**self.params)" ]
[ [ "matplotlib.pyplot.tight_layout", "torch.no_grad", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.show", "torch.cat", "numpy.uint8" ], [ "torch.utils.data.DataLoader" ] ]
jaeckie/covid19-containment-embeddings
[ "e27e63266113231ee399f3a55f76b823d514c6f7" ]
[ "store_data.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 4 15:37:43 2020\n\n@author: moder\n\"\"\"\nimport os\nfrom datetime import datetime\nimport pandas as pd\nimport urllib.request\nfrom bs4 import BeautifulSoup \n\nuser_agent = \"user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)\"\n\ndef scrap_wikipedia_text(url):\n request = urllib.request.Request(url, data=None, headers={'User-Agent' : user_agent})\n html = urllib.request.urlopen(request).read().decode('utf-8') \n soup = BeautifulSoup(html, 'html.parser')\n content_div = soup.find('div', attrs={'id': 'mw-content-text'})\n # remove tables and graphs\n if content_div is not None: \n for s in content_div.select('table'): \n s.extract()\n for s in content_div.select('img'): \n s.extract()\n # remove references\n for s in content_div.select('div.reflist'):\n s.extract()\n print('div.reflist extracted from %s...' % url)\n # iterate all p tags and append to text\n tags = ['h1', 'h2', 'h3', 'li', 'p']\n bodytext = ''\n for con in content_div.find_all(tags):\n bodytext += con.text \n return bodytext \n return None\n\nif __name__ == '__main__':\n print('store data started...') \n # load containment history file from kaggle\n df_contain = pd.read_csv(r'data/COVID 19 Containment measures data.csv')\n \n # cfilter = df_contain['Country'].isin(['Austria', 'Germany', 'Italy', 'Spain', 'Denmark'])\n # df_c = df_contain[cfilter]\n df_c = df_contain\n \n df = df_c[df_c['Source'].notna()]\n df_drop = df.drop_duplicates(subset='Source', keep='last')\n \n wfilter = df_drop['Source'].str.contains('en.wikipedia.org')\n df_red = df_drop[wfilter]\n \n df_res = df_red[['Date Start', 'Country', 'Keywords', 'Source']]\n df_res.to_csv(r'data/covid19-all-countries.csv')\n\n for index, row in df_res.iterrows():\n text = scrap_wikipedia_text(row['Source'])\n time = datetime.now().strftime('%Y%m%d_%H%M%S')\n filename = '%s_%s_covid19-wikipedia.txt' % (time, row['Country'])\n with open(os.path.join('data',filename), 'w', encoding='utf-8') as file:\n file.write(text)\n print('saved file %s ...' % filename)\n file.close()\n # \\[\\d+\\]\n \n" ]
[ [ "pandas.read_csv" ] ]
VIROBO-15/yolov1
[ "b7824a6cc7e89a6c29ab63f636a236d923fa0a64" ]
[ "loss.py" ]
[ "import torch\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nLAMBDA_COORD = 5\nLAMBDA_NOOBJ = 0.5\n\n\ndef calc_loss(inp , target, opt):\n if inp.size(0) != target.size(0):\n raise Exception(\"Batch size does not match\")\n\n total_loss = torch.tensor(0.0)\n #total_loss = total_loss.dtype(tensor)\n\n for i in range(inp.size(0)):\n inp = inp[i]\n target = target[i]\n Q = predict_one_bbox(inp, target, opt)\n total_loss = total_loss + calc_loss_single(Q, target, opt)\n return total_loss\n\ndef predict_one_bbox(inp, target, opt):\n Q = torch.zeros(opt.S, opt.S, 5 + opt.C)\n\n select = torch.tensor(0).to(device)\n\n for i in range(opt.S):\n for j in range(opt.S):\n for b in range(opt.B):\n if b==0:\n boxes = inp[i, j, b*5 : b*5+5].to(device)\n else:\n boxes = torch.stack((boxes, inp[i, j, b*5 : b*5+5])).to(device)\n\n if len(target[i, j, :].nonzero()) > 1:\n max_iou = torch.tensor([0.]).to(device)\n\n\n groundtruth_box = target[i, j, :4].clone()\n\n for b in range(opt.B):\n iou = calc_IOU(groundtruth_box, boxes[b][:-1], device)\n\n if iou > max_iou:\n max_iou = iou\n select = torch.tensor(b).to(device)\n\n else:\n max_confidence = torch.tensor(0.).to(device)\n\n for b in range(opt.B):\n confidence = boxes[b][-1]\n\n if confidence > max_confidence:\n max_confidence = confidence\n select = torch.tensor(b).to(device)\n\n Q[i, j, :5] = boxes[select]\n Q[i, j, 5:] = inp[i, j, -opt.C:]\n return Q\n\ndef calc_loss_single(inp, target, opt):\n\n loss = torch.zeros(1)\n for i in range(opt.S):\n for j in range(opt.S):\n # case 1: grid cell HAS object\n if len(target[i, j, :].nonzero()) > 1:\n # localization\n loss = loss + LAMBDA_COORD * (torch.pow(inp[i, j, 0] - target[i, j, 0], 2) + torch.pow(inp[i, j, 1] - target[i, j, 1], 2))\n\n loss = loss + LAMBDA_COORD * (torch.pow(torch.sqrt(torch.abs(inp[i, j, 2])) - torch.sqrt(torch.abs(target[i, j,2])), 2) \\\n + torch.pow(torch.sqrt(torch.abs(inp[i, j, 3])) - torch.sqrt(torch.abs(target[i, j, 3])), 2)) # org\n # loss = loss + LAMBDA_COORD * (torch.sqrt(torch.abs(P[i, j, 2] - G[i, j, 2])) +\n # torch.sqrt(torch.abs(P[i, j, 3] - G[i, j, 3]))) # ZZ\n\n loss = loss + torch.pow(inp[i, j, 4]-1, 2) # Ground truth confidence is constant 1\n # classification\n true_cls = target[i, j, -1].type(torch.int64)\n true_cls_vec = torch.zeros(opt.C)\n true_cls_vec[true_cls] = torch.tensor(1)\n pred_cls_vec = inp[i, j, -opt.C:]\n loss = loss + torch.sum(torch.pow(pred_cls_vec - true_cls_vec, 2))\n\n # case 2: grid cell NO object\n # classification\n else:\n loss = loss + LAMBDA_NOOBJ * torch.pow(inp[i, j, 4] - 0, 2) # Ground truth confidence is constant 0\n\n return loss\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef calc_IOU(box_1, box_2, device=torch.device('cpu'), use_float64=False):\n \"\"\"\n Tensor version of calc_IOU()\n compute IOU between two bounding boxes\n :param box_1: Detection x, y, w, h image coordinates in [0, 1]\n :param box_2: GroundTruth x, y, w, h image coordinates in [0, 1]\n :return:\n \"\"\"\n '''\n x_min_1 = torch.clamp((box_1[0] - box_1[2] / 2), 0, 1).to(device)\n x_max_1 = torch.clamp((box_1[0] + box_1[2] / 2), 0, 1).to(device)\n y_min_1 = torch.clamp((box_1[1] - box_1[3] / 2), 0, 1).to(device)\n y_max_1 = torch.clamp((box_1[1] + box_1[3] / 2), 0, 1).to(device)\n '''\n\n x_min_1 = torch.clamp((abs(box_1[0]) - abs(box_1[2]) / 2), 0, 1).to(device)\n x_max_1 = torch.clamp((abs(box_1[0]) + abs(box_1[2]) / 2), 0, 1).to(device)\n y_min_1 = torch.clamp((abs(box_1[1]) - abs(box_1[3]) / 2), 0, 1).to(device)\n y_max_1 = torch.clamp((abs(box_1[1]) + abs(box_1[3]) / 2), 0, 1).to(device)\n\n x_min_2 = torch.clamp((box_2[0] - box_2[2] / 2), 0, 1).to(device)\n x_max_2 = torch.clamp((box_2[0] + box_2[2] / 2), 0, 1).to(device)\n y_min_2 = torch.clamp((box_2[1] - box_2[3] / 2), 0, 1).to(device)\n y_max_2 = torch.clamp((box_2[1] + box_2[3] / 2), 0, 1).to(device)\n\n\n # z = torch.tensor(0, dtype=torch.float).to(device)\n z = torch.tensor(0.).to(device)\n\n a = torch.min(x_max_1, x_max_2)\n b = torch.max(x_min_1, x_min_2)\n c = torch.min(y_max_1, y_max_2)\n d = torch.max(y_min_1, y_min_2)\n\n overlap_width = torch.max(a-b, z)\n overlap_height = torch.max(c-d, z)\n overlap_area = overlap_width * overlap_height\n\n union_area = (x_max_1 - x_min_1) * (y_max_1 - y_min_1) \\\n + (x_max_2 - x_min_2) * (y_max_2 - y_min_2) \\\n - overlap_area\n intersection_over_union = overlap_area / union_area\n return intersection_over_union\n\n\n" ]
[ [ "torch.min", "torch.stack", "torch.pow", "torch.tensor", "torch.cuda.is_available", "torch.abs", "torch.max", "torch.zeros", "torch.device", "torch.clamp" ] ]
EQt/graphidx
[ "9716488cf29f6235072fc920fa1a473bf88e954f" ]
[ "python/test/test_biadjacent.py" ]
[ "import numpy as np\nfrom graphidx.idx import BiAdjacent\n\n\ndef square():\n head = np.array([0, 0, 1, 2])\n tail = np.array([1, 2, 3, 3])\n return BiAdjacent(head, tail)\n\n\ndef test_sqare():\n neigh = square()\n assert repr(neigh) == \"BiAdjacent[m = 4, n = 4]\"\n assert set(neigh[0]) == {1, 2}\n assert set(neigh[1]) == {0, 3}\n assert set(neigh[2]) == {0, 3}\n assert set(neigh[3]) == {1, 2}\n\n\ndef test_1():\n head = np.array([0, 1, 2, 3], dtype=np.int32)\n tail = np.array([1, 3, 1, 2], dtype=np.int32)\n index = BiAdjacent(head, tail)\n assert repr(index) == \"BiAdjacent[m = 4, n = 4]\"\n\n i2 = index[2]\n assert len(i2) == 2\n\n assert list(i2) == [1, 3]\n assert list(index[0]) == [1]\n assert list(index[1]) == [0, 3, 2]\n" ]
[ [ "numpy.array" ] ]
tza0035/RMG-Py
[ "38c49f7107d1b19e4a534408a1040ddd313b8596" ]
[ "arkane/encorr/ae.py" ]
[ "#!/usr/bin/env python3\n\n###############################################################################\n# #\n# RMG - Reaction Mechanism Generator #\n# #\n# Copyright (c) 2002-2021 Prof. William H. Green ([email protected]), #\n# Prof. Richard H. West ([email protected]) and the RMG Team ([email protected]) #\n# #\n# Permission is hereby granted, free of charge, to any person obtaining a #\n# copy of this software and associated documentation files (the 'Software'), #\n# to deal in the Software without restriction, including without limitation #\n# the rights to use, copy, modify, merge, publish, distribute, sublicense, #\n# and/or sell copies of the Software, and to permit persons to whom the #\n# Software is furnished to do so, subject to the following conditions: #\n# #\n# The above copyright notice and this permission notice shall be included in #\n# all copies or substantial portions of the Software. #\n# #\n# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER #\n# DEALINGS IN THE SOFTWARE. #\n# #\n###############################################################################\n\n\"\"\"\nThis module provides classes for fitting atom energies based on a very\nsmall, predetermined set of molecules.\n\"\"\"\n\nimport importlib\nimport json\nimport logging\nfrom collections import Counter\nfrom typing import Dict, Hashable, List, Union\n\nimport numpy as np\nfrom scipy.stats import distributions\n\nfrom rmgpy import constants\nfrom rmgpy.molecule import get_element, Molecule\n\nimport arkane.encorr.data as data\nfrom arkane.encorr.reference import ReferenceDatabase\nfrom arkane.modelchem import LevelOfTheory, CompositeLevelOfTheory\n\n# List of species labels that will be used for fitting (labels should match reference database)\nSPECIES_LABELS = [\n 'Dihydrogen',\n 'Dinitrogen',\n 'Dioxygen',\n 'Disulfur',\n 'Difluorine',\n 'Dichlorine',\n 'Dibromine',\n 'Hydrogen fluoride',\n 'Hydrogen chloride',\n 'Hydrogen bromide',\n 'Hydrogen sulfide',\n 'Water',\n 'Methane',\n 'Methyl',\n 'Ammonia',\n 'Chloromethane'\n]\n\n\nclass AEJob:\n \"\"\"\n A job for fitting atom energies.\n \"\"\"\n\n def __init__(self,\n species_energies: Dict[str, float],\n level_of_theory: Union[LevelOfTheory, CompositeLevelOfTheory] = None,\n write_to_database: bool = False,\n overwrite: bool = False):\n \"\"\"\n Initialize an AEJob instance.\n\n Notes:\n The species energies should be provided as a dictionary\n containing the species labels as keys and their single-\n point electronic energies in Hartree as values. The\n energies should be calculated using the experimental\n geometry provided for the species in the reference\n database, and the zero-point energy should not be included\n in the electronic energy.\n\n Args:\n species_energies: Dictionary of species labels with single-point electronic energies (Hartree).\n level_of_theory: Dictionary key for saving atom energies to the database.\n write_to_database: Save the fitted atom energies directly to the RMG database.\n overwrite: Overwrite atom energies in the RMG database if they already exist.\n \"\"\"\n self.spcs_energies = species_energies\n self.level_of_theory = level_of_theory\n self.write_to_database = write_to_database\n self.overwrite = overwrite\n self.ae = AE(species_energies)\n\n def execute(self, output_file: str = None):\n \"\"\"\n Execute the atom energy job.\n\n Args:\n output_file: Write the fitted energies to this file.\n \"\"\"\n if self.level_of_theory is None:\n logging.info('Fitting atom energies')\n else:\n logging.info(f'Fitting atom energies for {self.level_of_theory}')\n self.ae.fit()\n\n if output_file is not None:\n with open(output_file, 'a') as f:\n if self.level_of_theory is not None:\n f.write(f'# {self.level_of_theory}\\n')\n for element, energy in self.ae.atom_energies.items():\n f.write(f'# {element:2}: {energy:15.8f} +/- {self.ae.confidence_intervals[element]:.8f} Hartree\\n')\n f.writelines(self.ae.format_atom_energies(\n 'atom_energies' if self.level_of_theory is None else self.level_of_theory))\n\n if self.write_to_database:\n if self.level_of_theory is None:\n raise Exception('Level of theory is required for writing to database')\n try:\n self.ae.write_to_database(self.level_of_theory, overwrite=self.overwrite)\n except ValueError as e:\n logging.warning('Could not write atom energies to database. Captured error:')\n logging.warning(str(e))\n\n\nclass AE:\n \"\"\"\n A class for fitting atom energies.\n \"\"\"\n\n ref_data_src = 'CCCBDB' # Use CCCBDB data\n ref_data = None # Dictionary of reference data entries\n\n def __init__(self, species_energies: Dict[str, float]):\n self.species_energies = species_energies # Hartree\n self.atom_energies = None\n self.confidence_intervals = None\n\n for lbl in SPECIES_LABELS:\n if lbl not in self.species_energies:\n logging.warning(f'{lbl} missing from provided species energies!')\n\n @classmethod\n def _load_refdata(cls):\n if cls.ref_data is None:\n logging.info('Loading reference database')\n db = ReferenceDatabase()\n db.load()\n cls.ref_data = {lbl: spc for lbl, spc in zip(SPECIES_LABELS, db.get_species_from_label(SPECIES_LABELS))}\n\n def fit(self):\n \"\"\"\n Fit atom energies using the provided species energies and\n corresponding atomization energies from the reference data.\n \"\"\"\n self._load_refdata()\n\n mols = [\n Molecule().from_adjacency_list(\n self.ref_data[lbl].adjacency_list,\n raise_atomtype_exception=False,\n raise_charge_exception=False\n ) for lbl in self.species_energies\n ]\n atom_counts = [Counter(atom.element.symbol for atom in mol.atoms) for mol in mols]\n elements = sorted({element for ac in atom_counts for element in ac}, key=lambda s: get_element(s).number)\n x = np.array([[ac[element] for element in elements] for ac in atom_counts]) # Nmols x Nelements\n\n atomization_energies = np.array([\n self.ref_data[lbl].reference_data[self.ref_data_src].atomization_energy.value_si\n / constants.E_h / constants.Na for lbl in self.species_energies\n ])\n zpes = np.array([\n self.ref_data[lbl].reference_data[self.ref_data_src].zpe.value_si\n / constants.E_h / constants.Na for lbl in self.species_energies\n ])\n elec_energies = np.array(list(self.species_energies.values())) # Should already be in Hartree\n y = atomization_energies + elec_energies + zpes\n\n w = np.linalg.solve(x.T @ x, x.T @ y)\n self.atom_energies = dict(zip(elements, w))\n\n # Get confidence intervals\n n = len(y) # Ndata\n k = len(w) # Nparam\n ypred = x @ w\n sigma2 = np.sum((y - ypred)**2) / (n - k - 1) # MSE\n cov = sigma2 * np.linalg.inv(x.T @ x) # covariance matrix\n se = np.sqrt(np.diag(cov)) # standard error\n alpha = 0.05 # 95% confidence level\n tdist = distributions.t.ppf(1 - alpha/2, n - k - 1) # student-t\n ci = tdist * se # confidence interval half-width\n self.confidence_intervals = dict(zip(elements, ci)) # Parameter estimates are w +/- ci\n\n def write_to_database(self, key: Hashable, overwrite: bool = False, alternate_path: str = None):\n \"\"\"\n Write atom energies to database.\n\n Args:\n key: Dictionary key to use for atom energies in database.\n overwrite: Overwrite existing atom energies.\n alternate_path: Write atom energies and existing database to this path instead.\n \"\"\"\n if self.atom_energies is None:\n raise ValueError('No atom energies available for writing')\n\n data_path = data.quantum_corrections_path\n with open(data_path) as f:\n lines = f.readlines()\n\n ae_formatted = self.format_atom_energies(key, indent=True)\n\n # Add new atom energies to file without changing existing formatting\n for i, line in enumerate(lines):\n if 'atom_energies' in line:\n if key in data.atom_energies:\n if overwrite:\n # Does not overwrite comments\n del_idx_start = del_idx_end = None\n for j, line2 in enumerate(lines[i:]):\n if repr(key) in line2:\n del_idx_start = i + j\n del_idx_end = None\n elif line2.rstrip() == ' },': # Can't have a comment after final brace\n del_idx_end = i + j + 1\n if del_idx_start is not None and del_idx_end is not None:\n if (lines[del_idx_start - 1].lstrip().startswith('#')\n or lines[del_idx_end + 1].lstrip().startswith('#')):\n logging.warning('There may be left over comments from previous atom energies')\n lines[del_idx_start:del_idx_end] = ae_formatted\n break\n else:\n raise ValueError(f'{key} already exists. Set `overwrite` to True.')\n else:\n lines[(i+1):(i+1)] = ['\\n'] + ae_formatted\n break\n\n with open(data_path if alternate_path is None else alternate_path, 'w') as f:\n f.writelines(lines)\n\n # Reload data to update atom energy dictionary\n if alternate_path is None:\n importlib.reload(data)\n\n def format_atom_energies(self, key: Hashable, indent: bool = False) -> List[str]:\n \"\"\"\n Obtain a list of nicely formatted atom energies suitable for\n writelines.\n\n Args:\n key: Dictionary key to use for formatting dictionary.\n indent: Indent each line.\n\n Returns:\n Formatted list of atom energies.\n \"\"\"\n ae_formatted = json.dumps(self.atom_energies, indent=4).replace('\"', \"'\").split('\\n')\n ae_formatted[0] = f'\"{key}\": ' + ae_formatted[0]\n ae_formatted[-1] += ','\n ae_formatted = [e + '\\n' for e in ae_formatted]\n if indent:\n ae_formatted = [' ' + e for e in ae_formatted]\n return ae_formatted\n" ]
[ [ "numpy.sum", "numpy.linalg.solve", "numpy.diag", "numpy.linalg.inv", "scipy.stats.distributions.t.ppf", "numpy.array" ] ]
intel/lp-opt-tool
[ "130eefa3586b38df6c0ff78cc8807ae273f6a63f" ]
[ "test/test_adaptor_pytorch.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.quantized as nnq\nfrom torch.quantization import QuantStub, DeQuantStub\nimport torchvision\nimport unittest\nimport os\nfrom neural_compressor.adaptor import FRAMEWORKS\nfrom neural_compressor.model import MODELS\nfrom neural_compressor.adaptor.pytorch import PyTorchVersionMode\nimport neural_compressor.adaptor.pytorch as nc_torch\nfrom neural_compressor.experimental import Quantization, common\nfrom neural_compressor.conf.config import Quantization_Conf\nfrom neural_compressor.utils.pytorch import load\nfrom neural_compressor.utils.utility import recover\nimport shutil\nimport copy\nimport numpy as np\nimport yaml\n\ntry:\n try:\n import intel_pytorch_extension as ipex\n except:\n import intel_extension_for_pytorch as ipex\n TEST_IPEX = True\nexcept:\n TEST_IPEX = False\n\nPT_VERSION = nc_torch.get_torch_version()\nif PT_VERSION >= PyTorchVersionMode.PT18.value:\n FX_MODE = True\nelse:\n FX_MODE = False\n\n\nfake_dyn_yaml = '''\n model:\n name: imagenet\n framework: pytorch\n\n quantization:\n approach: post_training_dynamic_quant\n op_wise: {\n 'decoder': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n }\n }\n evaluation:\n accuracy:\n metric:\n topk: 1\n performance:\n warmup: 5\n iteration: 10\n\n tuning:\n accuracy_criterion:\n relative: 0.01\n exit_policy:\n timeout: 0\n random_seed: 9527\n workspace:\n path: saved\n '''\n\n\nfake_ptq_yaml = '''\n model:\n name: imagenet\n framework: pytorch\n\n quantization:\n op_wise: {\n 'quant': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer1.0.conv1': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer1.0.conv2': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer2.0.conv1': {\n 'activation': {'dtype': ['uint8'], 'algorithm': ['minmax'], 'granularity': ['per_tensor'], 'scheme':['sym']},\n 'weight': {'dtype': ['int8'], 'algorithm': ['minmax'], 'granularity': ['per_channel'], 'scheme':['sym']}\n },\n 'layer3.0.conv1': {\n 'activation': {'dtype': ['uint8'], 'algorithm': ['kl'], 'granularity': ['per_tensor'], 'scheme':['sym']},\n 'weight': {'dtype': ['int8'], 'algorithm': ['minmax'], 'granularity': ['per_channel'], 'scheme':['sym']}\n },\n 'layer1.0.add_relu': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n }\n evaluation:\n accuracy:\n metric:\n topk: 1\n performance:\n warmup: 1\n iteration: 10\n\n tuning:\n accuracy_criterion:\n relative: 0.01\n exit_policy:\n timeout: 0\n random_seed: 9527\n workspace:\n path: saved\n '''\n\nfake_ptq_yaml_for_fx = '''\n model:\n name: imagenet\n framework: pytorch_fx\n\n quantization:\n op_wise: {\n 'quant': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer1.0.conv1': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer1.0.conv2': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer2.0.conv1': {\n 'activation': {'dtype': ['uint8'], 'algorithm': ['minmax'], 'granularity': ['per_tensor'], 'scheme':['sym']},\n 'weight': {'dtype': ['int8'], 'algorithm': ['minmax'], 'granularity': ['per_channel'], 'scheme':['sym']}\n },\n 'layer3.0.conv1': {\n 'activation': {'dtype': ['uint8'], 'algorithm': ['kl'], 'granularity': ['per_tensor'], 'scheme':['sym']},\n 'weight': {'dtype': ['int8'], 'algorithm': ['minmax'], 'granularity': ['per_channel'], 'scheme':['sym']}\n },\n 'layer1.0.add_relu': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'default_qconfig': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n }\n }\n evaluation:\n accuracy:\n metric:\n topk: 1\n performance:\n warmup: 5\n iteration: 10\n\n tuning:\n accuracy_criterion:\n relative: 0.01\n exit_policy:\n timeout: 0\n random_seed: 9527\n workspace:\n path: saved\n '''\n\n\nfake_qat_yaml = '''\n model:\n name: imagenet\n framework: pytorch\n\n quantization:\n approach: quant_aware_training\n train:\n end_epoch: 1\n iteration: 1\n optimizer:\n SGD:\n learning_rate: 0.0001\n criterion:\n CrossEntropyLoss:\n reduction: mean\n op_wise: {\n 'quant': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer1.0.conv1': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer1.0.conv2': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n },\n 'layer2.0.conv1': {\n 'activation': {'dtype': ['uint8'], 'algorithm': ['minmax'], 'granularity': ['per_tensor'], 'scheme':['sym']},\n 'weight': {'dtype': ['int8'], 'algorithm': ['minmax'], 'granularity': ['per_channel'], 'scheme':['sym']}\n },\n 'layer3.0.conv1': {\n 'activation': {'dtype': ['uint8'], 'algorithm': ['kl'], 'granularity': ['per_tensor'], 'scheme':['sym']},\n 'weight': {'dtype': ['int8'], 'algorithm': ['minmax'], 'granularity': ['per_channel'], 'scheme':['sym']}\n },\n 'layer1.0.add_relu': {\n 'activation': {'dtype': ['fp32']},\n 'weight': {'dtype': ['fp32']}\n }\n }\n evaluation:\n accuracy:\n metric:\n topk: 1\n\n tuning:\n accuracy_criterion:\n relative: 0.01\n exit_policy:\n timeout: 0\n random_seed: 9527\n workspace:\n path: saved\n '''\n\n\ndef build_pytorch_yaml():\n with open('ptq_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_ptq_yaml)\n\n with open('dynamic_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_dyn_yaml)\n\n with open('qat_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_qat_yaml)\n\n\ndef build_pytorch_fx_yaml():\n if PT_VERSION >= PyTorchVersionMode.PT19.value:\n fake_fx_ptq_yaml = fake_ptq_yaml_for_fx\n else:\n fake_fx_ptq_yaml = fake_ptq_yaml.replace('pytorch', 'pytorch_fx')\n with open('fx_ptq_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_fx_ptq_yaml)\n\n fake_fx_dyn_yaml = fake_dyn_yaml.replace('pytorch', 'pytorch_fx')\n with open('fx_dynamic_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_fx_dyn_yaml)\n\n fake_fx_qat_yaml = fake_qat_yaml.replace('pytorch', 'pytorch_fx')\n with open('fx_qat_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_fx_qat_yaml)\n\n\ndef build_ipex_yaml():\n fake_yaml = '''\n model:\n name: imagenet\n framework: pytorch_ipex\n\n evaluation:\n accuracy:\n metric:\n topk: 1\n performance:\n warmup: 5\n iteration: 10\n\n tuning:\n accuracy_criterion:\n relative: 0.01\n exit_policy:\n timeout: 0\n random_seed: 9527\n workspace:\n path: saved\n '''\n with open('ipex_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_yaml)\n\n\ndef build_dump_tensors_yaml():\n fake_yaml = '''\n model:\n name: imagenet\n framework: pytorch\n\n evaluation:\n accuracy:\n metric:\n topk: 1\n\n tuning:\n accuracy_criterion:\n relative: 0.01\n exit_policy:\n timeout: 0\n random_seed: 9527\n workspace:\n path: saved\n tensorboard: true\n '''\n with open('dump_yaml.yaml', 'w', encoding=\"utf-8\") as f:\n f.write(fake_yaml)\n\n\nclass M(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.quant = QuantStub()\n self.conv = nn.Conv2d(3, 1, 1)\n self.linear = nn.Linear(224 * 224, 5)\n self.dequant = DeQuantStub()\n\n def forward(self, x):\n x = self.quant(x)\n x = self.conv(x)\n x = x.view(1, -1)\n x = self.linear(x)\n x = self.dequant(x)\n return x\n\n\nclass FP32Model(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n times = x.size(1)\n if times == 1:\n return x + x\n return x\n\n\nclass DynamicModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.conv = nn.Conv2d(1, 1, 1)\n def forward(self, x):\n if x is not None:\n x = self.conv(x)\n return x\n\n\nclass SubModel(torch.nn.Module):\n def __init__(self, bypass=True):\n super().__init__()\n self.quant = QuantStub()\n self.conv = nn.Conv2d(1, 1, 1)\n self.conv1 = nn.Conv2d(1, 1, 1)\n self.bn = nn.BatchNorm2d(1)\n self.relu = nn.ReLU()\n self.fp32 = FP32Model()\n self.norm = nn.LayerNorm([1, 224, 224])\n self.dequant = DeQuantStub()\n self.bypass = bypass\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.quant(x)\n x = self.relu(x)\n x = self.conv1(x)\n x = self.dequant(x)\n if not self.bypass:\n x = self.fp32(x)\n x = self.norm(x)\n return x\n\n\nclass PartialQuantModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.quant = QuantStub()\n self.conv = nn.Conv2d(3, 1, 1)\n self.bn = nn.BatchNorm2d(1)\n self.conv1 = nn.Conv2d(1, 1, 1)\n self.bn1 = nn.BatchNorm2d(1)\n self.conv2 = nn.Conv2d(1, 1, 1)\n self.linear = nn.Linear(224 * 224, 1)\n self.dequant = DeQuantStub()\n self.sub = SubModel(bypass=False)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.sub(x)\n x = self.quant(x)\n x = self.conv2(x)\n x = x.view(1, -1)\n x = self.linear(x)\n x = self.dequant(x)\n return x\n\nclass DynamicControlModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.conv = nn.Conv2d(3, 1, 1)\n self.bn = nn.BatchNorm2d(1)\n self.linear = nn.Linear(224 * 224, 1)\n self.sub = SubModel()\n self.fp32 = FP32Model()\n self.dyn = DynamicModel()\n\n def forward(self, x):\n x = self.conv(x)\n x = self.dyn(x)\n x = self.bn(x)\n x = self.sub(x)\n x = self.fp32(x)\n x = x.view(1, -1)\n x = self.linear(x)\n return x\n\n\ndef eval_func(model):\n # switch to evaluate mode\n model.eval()\n with torch.no_grad():\n input = torch.randn(1, 3, 224, 224)\n # compute output\n output = model(input)\n return 0.0\n\n\ndef q_func(model):\n optimizer = torch.optim.SGD(model.parameters(), lr=0.0001)\n # switch to evaluate mode\n model.train()\n input = torch.randn(1, 3, 224, 224)\n # compute output\n output = model(input)\n loss = output.mean()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return model\n\n\nclass TestPytorchAdaptor(unittest.TestCase):\n framework_specific_info = {\"device\": \"cpu\",\n \"approach\": \"post_training_static_quant\",\n \"random_seed\": 1234,\n \"q_dataloader\": None,\n \"workspace_path\": \"./\"}\n framework = \"pytorch\"\n adaptor = FRAMEWORKS[framework](framework_specific_info)\n model = torchvision.models.quantization.resnet18()\n nc_model = MODELS['pytorch'](model)\n\n @classmethod\n def setUpClass(self):\n build_pytorch_yaml()\n build_dump_tensors_yaml()\n\n @classmethod\n def tearDownClass(self):\n os.remove('ptq_yaml.yaml')\n os.remove('dynamic_yaml.yaml')\n os.remove('qat_yaml.yaml')\n os.remove('dump_yaml.yaml')\n shutil.rmtree('./saved', ignore_errors=True)\n shutil.rmtree('runs', ignore_errors=True)\n\n def test_get_all_weight_name(self):\n assert len(list(self.nc_model.get_all_weight_names())) == 62\n\n def test_get_weight(self):\n for name, param in self.model.named_parameters():\n if name == \"layer4.1.conv2.weight\":\n param.data.fill_(0.0)\n if name == \"fc.bias\":\n param.data.fill_(0.1)\n assert int(torch.sum(self.nc_model.get_weight(\"layer4.1.conv2.weight\"))) == 0\n assert torch.allclose(\n torch.sum(\n self.nc_model.get_weight(\"fc.bias\")),\n torch.tensor(100.))\n\n def test_get_input(self):\n model = MODELS['pytorch'](torchvision.models.quantization.resnet18())\n model.model.eval().fuse_model()\n model.register_forward_pre_hook()\n rand_input = torch.rand(100, 3, 224, 224).float()\n model.model(rand_input)\n assert torch.equal(model.get_inputs('x'), rand_input)\n model.remove_hooks()\n\n def test_update_weights(self):\n self.nc_model.update_weights('fc.bias', torch.zeros([1000]))\n assert int(torch.sum(self.nc_model.get_weight(\"fc.bias\"))) == 0\n\n def test_get_gradient(self):\n with self.assertRaises(AssertionError):\n self.nc_model.get_gradient('fc.bias')\n\n for name, tensor in self.nc_model._model.named_parameters():\n if name == 'fc.bias':\n tensor.grad = torch.zeros_like(tensor)\n break\n assert torch.equal(torch.Tensor(self.nc_model.get_gradient('fc.bias')), torch.zeros_like(tensor))\n\n rand_input = torch.rand(100, 3, 224, 224).float()\n rand_input.grad = torch.ones_like(rand_input)\n assert torch.equal(torch.Tensor(self.nc_model.get_gradient(rand_input)),\n torch.ones_like(rand_input))\n\n def test_report_sparsity(self):\n df, total_sparsity = self.nc_model.report_sparsity()\n self.assertTrue(total_sparsity > 0)\n self.assertTrue(len(df) == 22)\n\n def test_quantization_saved(self):\n for fake_yaml in ['dynamic_yaml.yaml', 'qat_yaml.yaml', 'ptq_yaml.yaml']:\n model = M()\n quantizer = Quantization(fake_yaml)\n quantizer.conf.usr_cfg.tuning.exit_policy['performance_only'] = True\n dataset = quantizer.dataset('dummy', (100, 3, 224, 224), label=True)\n quantizer.model = model\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_dataloader = common.DataLoader(dataset)\n q_model = quantizer.fit()\n eval_func(q_model)\n q_model.save('./saved')\n # Load configure and weights by neural_compressor.utils\n saved_model = load(\"./saved\", model)\n eval_func(saved_model)\n # recover int8 model from history\n history_file = './saved/history.snapshot'\n model_recover = recover(model, history_file, 0)\n eval_func(model_recover)\n self.assertEqual(type(saved_model.conv), \\\n type(model_recover.conv))\n shutil.rmtree('./saved', ignore_errors=True)\n from neural_compressor.experimental import Benchmark\n evaluator = Benchmark('ptq_yaml.yaml')\n # Load configure and weights by neural_compressor.model\n evaluator.model = model\n evaluator.b_dataloader = common.DataLoader(dataset)\n evaluator()\n evaluator.model = model\n evaluator()\n\n for fake_yaml in ['qat_yaml.yaml', 'ptq_yaml.yaml']:\n model = copy.deepcopy(self.model)\n if fake_yaml == 'ptq_yaml.yaml':\n model.eval().fuse_model()\n conf = Quantization_Conf(fake_yaml)\n quantizer = Quantization(conf)\n dataset = quantizer.dataset('dummy', (100, 3, 224, 224))\n quantizer.model = model\n if fake_yaml == 'qat_yaml.yaml':\n quantizer.q_func = q_func\n else:\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_func = eval_func\n q_model = quantizer.fit()\n q_model.save('./saved')\n # Load configure and weights by neural_compressor.utils\n saved_model = load(\"./saved\", model)\n eval_func(saved_model)\n shutil.rmtree('./saved', ignore_errors=True)\n\n def test_quantization_new_saved(self):\n for fake_yaml in ['dynamic_yaml.yaml', 'qat_yaml.yaml', 'ptq_yaml.yaml']:\n model = M()\n quantizer = Quantization(fake_yaml)\n quantizer.conf.usr_cfg.tuning.exit_policy['performance_only'] = True\n dataset = quantizer.dataset('dummy', (100, 3, 224, 224), label=True)\n quantizer.model = model\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_dataloader = common.DataLoader(dataset)\n q_model = quantizer.fit()\n eval_func(q_model)\n torch.save(q_model.quantized_state_dict(), './saved/model.pt')\n # Load configure and weights by neural_compressor.utils\n from neural_compressor.experimental.common import Model\n common_model = Model(model)\n common_model.load_quantized_state_dict(torch.load('./saved/model.pt'))\n eval_func(common_model)\n self.assertEqual(type(q_model._model.linear), \\\n type(common_model._model.linear))\n shutil.rmtree('./saved', ignore_errors=True)\n\n def test_non_quant_module(self):\n for fake_yaml in ['qat_yaml.yaml', 'ptq_yaml.yaml']:\n model = PartialQuantModel()\n conf = Quantization_Conf(fake_yaml)\n quantizer = Quantization(conf)\n dataset = quantizer.dataset('dummy', (1, 3, 224, 224))\n non_quant_dict = {'non_quant_module_name': ['conv', 'conv1', 'sub.conv'], \\\n 'non_quant_module_class': ['BatchNorm2d', 'FP32Model']}\n quantizer.model = common.Model(model, **non_quant_dict)\n if fake_yaml == 'qat_yaml.yaml':\n quantizer.q_func = q_func\n else:\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_func = eval_func\n q_model = quantizer.fit()\n q_model.save('./saved')\n saved_model = load(\"./saved\", model, **non_quant_dict)\n eval_func(saved_model)\n shutil.rmtree('./saved', ignore_errors=True)\n\n def test_workspace_path(self):\n model = M()\n quantizer = Quantization('ptq_yaml.yaml')\n quantizer.conf.usr_cfg.tuning.exit_policy['performance_only'] = True\n dataset = quantizer.dataset('dummy', (100, 3, 224, 224), label=True)\n quantizer.model = model\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_dataloader = common.DataLoader(dataset)\n q_model = quantizer.fit()\n eval_func(q_model)\n torch.save(q_model.quantized_state_dict(), './saved/best_model.pt')\n # Load configure and weights by workspace_path\n from neural_compressor.experimental.common import Model\n common_model = Model(model)\n common_model.workspace_path = './saved'\n eval_func(common_model)\n self.assertEqual(type(q_model._model.linear), \\\n type(common_model._model.linear))\n shutil.rmtree('./saved', ignore_errors=True)\n\n def test_get_graph_info(self):\n from neural_compressor.model.torch_model import PyTorchModel\n model = PyTorchModel(self.model)\n op_map = model.graph_info\n self.assertTrue(op_map['conv1'] == 'Conv2d')\n\n def test_tensorboard(self):\n model = copy.deepcopy(self.nc_model)\n model.model.eval().fuse_model()\n quantizer = Quantization('dump_yaml.yaml')\n dataset = quantizer.dataset('dummy', (100, 3, 224, 224), label=True)\n quantizer.model = model.model\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_func = eval_func\n quantizer.fit()\n self.assertTrue(True if os.path.exists('runs/eval/baseline_acc0.0') else False)\n quantizer.eval_dataloader = common.DataLoader(dataset)\n quantizer.eval_func = None\n quantizer.fit()\n self.assertTrue(True if os.path.exists('runs/eval/baseline_acc0.0') else False)\n\n def test_tensor_dump_and_set(self):\n model = copy.deepcopy(self.nc_model)\n model.model.eval().fuse_model()\n quantizer = Quantization('ptq_yaml.yaml')\n dataset = quantizer.dataset('dummy', (100, 3, 224, 224), label=True)\n dataloader = common.DataLoader(dataset)\n dataloader = common._generate_common_dataloader(dataloader, 'pytorch')\n quantizer.eval_dataloader = dataloader\n quantizer.calib_dataloader = dataloader\n quantizer.model = model.model\n q_model = quantizer.fit()\n quantizer.strategy.adaptor.inspect_tensor(\n model, dataloader, op_list=['conv1.0', 'layer1.0.conv1.0'],\n iteration_list=[1, 2], inspect_type='all', save_to_disk=True)\n load_array = lambda *a, **k: np.load(*a, allow_pickle=True, **k)\n a = load_array('saved/dump_tensor/activation_iter1.npz')\n w = load_array('saved/dump_tensor/weight.npz')\n if PT_VERSION >= PyTorchVersionMode.PT18.value:\n self.assertTrue(w['conv1.0'].item()['conv1.0.weight'].shape[0] ==\n a['conv1.0'].item()['conv1.0.output0'].shape[1])\n else:\n self.assertTrue(w['conv1.0'].item()['conv1.0.weight'].shape[0] ==\n a['conv1.0'].item()['conv1.1.output0'].shape[1])\n data = np.random.random(w['conv1.0'].item()['conv1.0.weight'].shape).astype(np.float32)\n quantizer.strategy.adaptor.set_tensor(q_model, {'conv1.0.weight': data})\n changed_tensor = q_model.get_weight('conv1.weight')\n scales = changed_tensor.q_per_channel_scales()\n changed_tensor_fp32 = torch.dequantize(changed_tensor)\n self.assertTrue(np.allclose(data, changed_tensor_fp32.numpy(), atol=2 / np.min(scales.numpy())))\n quantizer.strategy.adaptor.inspect_tensor(\n q_model, dataloader, op_list=['conv1.0', 'layer1.0.conv1.0'],\n iteration_list=[1, 2], inspect_type='all', save_to_disk=False)\n\n def test_get_graph_info(self):\n from neural_compressor.adaptor.pytorch import get_ops_recursively\n model = copy.deepcopy(self.model)\n op_map = {}\n get_ops_recursively(model, '', op_map)\n self.assertTrue(op_map['conv1'] == 'Conv2d')\n\n def test_forward_wrapper(self):\n vision_model = torchvision.models.resnet18()\n class dummymodel(torch.nn.Module):\n def __init__(self, model):\n super(dummymodel, self).__init__()\n self._model = model\n def forward(self,input=None):\n return self._model(input)\n\n data = [[{'input': torch.rand(3,224,224)}, torch.ones(1,1)], ]\n # dataloader.batch_size=100\n dataloader = common.DataLoader(data, batch_size=1)\n\n quantizer = Quantization('dynamic_yaml.yaml')\n model = dummymodel(vision_model)\n quantizer.model = model\n quantizer.calib_dataloader = dataloader\n quantizer.eval_dataloader = dataloader\n quantizer.fit()\n\n def test_floatfunctions_fallback(self):\n class ModelWithFunctionals(torch.nn.Module):\n def __init__(self):\n super(ModelWithFunctionals, self).__init__()\n self.mycat = nnq.FloatFunctional()\n self.myadd = nnq.FloatFunctional()\n self.myadd_relu = nnq.FloatFunctional()\n # Tracing doesnt work yet for c10 ops with scalar inputs\n # https://github.com/pytorch/pytorch/issues/27097\n self.my_scalar_add = nnq.FloatFunctional()\n self.mymul = nnq.FloatFunctional()\n self.my_scalar_mul = nnq.FloatFunctional()\n self.quant = QuantStub()\n self.dequant = DeQuantStub()\n\n def forward(self, x):\n x = self.quant(x)\n y = self.mycat.cat([x, x, x])\n z = self.myadd.add(y, y)\n w = self.myadd_relu.add_relu(z, z)\n # Tracing doesnt work yet for c10 ops with scalar inputs\n # https://github.com/pytorch/pytorch/issues/27097\n w = self.my_scalar_add.add_scalar(w, -0.5)\n w = self.mymul.mul(w, w)\n w = self.my_scalar_mul.mul_scalar(w, 0.5)\n w = self.dequant(w)\n return w\n\n model = ModelWithFunctionals()\n model = MODELS['pytorch'](model)\n x = torch.rand(10, 1, dtype=torch.float)\n y = model.model(x)\n fallback_ops = []\n q_capability = self.adaptor.query_fw_capability(model)\n for k, v in q_capability[\"opwise\"].items():\n if k[0] != \"quant\" and k[0] != \"dequant\":\n fallback_ops.append(k[0])\n model.model.qconfig = torch.quantization.default_qconfig\n model.model.quant.qconfig = torch.quantization.default_qconfig\n if PT_VERSION >= PyTorchVersionMode.PT18.value:\n model.model.dequant.qconfig = torch.quantization.default_qconfig\n nc_torch._fallback_quantizable_ops_recursively(\n model.model, '', fallback_ops, op_qcfgs={})\n torch.quantization.add_observer_(model.model)\n model.model(x)\n torch.quantization.convert(model.model, self.adaptor.q_mapping, inplace=True)\n qy = model.model(x)\n tol = {'atol': 1e-01, 'rtol': 1e-03}\n self.assertTrue(np.allclose(y, qy, **tol))\n\n\[email protected](not TEST_IPEX, \"Unsupport Intel PyTorch Extension\")\nclass TestPytorchIPEXAdaptor(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n build_ipex_yaml()\n\n @classmethod\n def tearDownClass(self):\n os.remove('ipex_yaml.yaml')\n shutil.rmtree('./saved', ignore_errors=True)\n shutil.rmtree('runs', ignore_errors=True)\n\n def test_tuning_ipex(self):\n from neural_compressor.experimental import Quantization\n model = M()\n quantizer = Quantization('ipex_yaml.yaml')\n quantizer.conf.usr_cfg.tuning.exit_policy['performance_only'] = True\n dataset = quantizer.dataset('dummy', (100, 3, 224, 224), label=True)\n quantizer.model = model\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_dataloader = common.DataLoader(dataset)\n nc_model = quantizer.fit()\n nc_model.save('./saved')\n try:\n script_model = torch.jit.script(model.to(ipex.DEVICE))\n except:\n script_model = torch.jit.trace(model.to(ipex.DEVICE), torch.randn(10, 3, 224, 224).to(ipex.DEVICE))\n from neural_compressor.experimental import Benchmark\n evaluator = Benchmark('ipex_yaml.yaml')\n evaluator.model = script_model\n evaluator.b_dataloader = common.DataLoader(dataset)\n results = evaluator()\n\n\[email protected](not FX_MODE, \"Unsupport Fx Mode with PyTorch Version Below 1.8\")\nclass TestPytorchFXAdaptor(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n build_pytorch_fx_yaml()\n\n @classmethod\n def tearDownClass(self):\n os.remove('fx_ptq_yaml.yaml')\n os.remove('fx_dynamic_yaml.yaml')\n shutil.rmtree('./saved', ignore_errors=True)\n shutil.rmtree('runs', ignore_errors=True)\n\n def test_fx_quant(self):\n for fake_yaml in ['fx_qat_yaml.yaml', 'fx_ptq_yaml.yaml']:\n model_origin = torchvision.models.resnet18()\n # run fx_quant in neural_compressor and save the quantized GraphModule\n quantizer = Quantization(fake_yaml)\n dataset = quantizer.dataset('dummy', (10, 3, 224, 224), label=True)\n quantizer.eval_func = eval_func\n if fake_yaml == 'fx_qat_yaml.yaml':\n quantizer.q_func = q_func\n else:\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.model = common.Model(model_origin,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n q_model = quantizer.fit()\n q_model.save('./saved')\n # Load configure and weights with neural_compressor.utils\n model_fx = load('./saved', model_origin,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n self.assertTrue(isinstance(model_fx, torch.fx.graph_module.GraphModule))\n\n # recover int8 model with only tune_cfg\n history_file = './saved/history.snapshot'\n model_fx_recover = recover(model_origin, history_file, 0,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n self.assertEqual(model_fx.code, model_fx_recover.code)\n shutil.rmtree('./saved', ignore_errors=True)\n\n for fake_yaml in ['fx_qat_yaml.yaml', 'fx_ptq_yaml.yaml']:\n model_origin = M()\n # run fx_quant in neural_compressor and save the quantized GraphModule\n quantizer = Quantization(fake_yaml)\n quantizer.conf.usr_cfg.tuning.exit_policy['performance_only'] = True\n dataset = quantizer.dataset('dummy', (10, 3, 224, 224), label=True)\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.eval_dataloader = common.DataLoader(dataset)\n quantizer.model = common.Model(model_origin,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n q_model = quantizer.fit()\n q_model.save('./saved')\n # Load configure and weights with neural_compressor.utils\n model_fx = load('./saved', model_origin,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n self.assertTrue(isinstance(model_fx, torch.fx.graph_module.GraphModule))\n shutil.rmtree('./saved', ignore_errors=True)\n\n @unittest.skipIf(PT_VERSION < PyTorchVersionMode.PT19.value,\n \"Please use PyTroch 1.9 or higher version for dynamic quantization with pytorch_fx backend\")\n def test_fx_dynamic_quant(self):\n # Model Definition\n class LSTMModel(nn.Module):\n '''Container module with an encoder, a recurrent module, and a decoder.'''\n\n def __init__(self, ntoken, ninp, nhid, nlayers, dropout=0.5):\n super(LSTMModel, self).__init__()\n self.drop = nn.Dropout(dropout)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.rnn = nn.LSTM(ninp, nhid, nlayers, dropout=dropout)\n self.decoder = nn.Linear(nhid, ntoken)\n self.init_weights()\n self.nhid = nhid\n self.nlayers = nlayers\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, input, hidden):\n emb = self.drop(self.encoder(input))\n output, hidden = self.rnn(emb, hidden)\n output = self.drop(output)\n decoded = self.decoder(output)\n return decoded, hidden\n\n model = LSTMModel(\n ntoken = 10,\n ninp = 512,\n nhid = 256,\n nlayers = 5,\n )\n\n # run fx_quant in neural_compressor and save the quantized GraphModule\n model.eval()\n quantizer = Quantization('fx_dynamic_yaml.yaml')\n quantizer.model = common.Model(model,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n q_model = quantizer.fit()\n q_model.save('./saved')\n\n # Load configure and weights by neural_compressor.utils\n model_fx = load(\"./saved\", model,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n self.assertTrue(isinstance(model_fx, torch.fx.graph_module.GraphModule))\n # recover int8 model with only tune_cfg\n history_file = './saved/history.snapshot'\n model_fx_recover = recover(model, history_file, 0,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n self.assertEqual(model_fx.code, model_fx_recover.code)\n shutil.rmtree('./saved', ignore_errors=True)\n\n def test_fx_sub_module_quant(self):\n for fake_yaml in ['fx_qat_yaml.yaml', 'fx_ptq_yaml.yaml']:\n model_origin = DynamicControlModel()\n # run fx_quant in neural_compressor and save the quantized GraphModule\n quantizer = Quantization(fake_yaml)\n dataset = quantizer.dataset('dummy', (1, 3, 224, 224), label=True)\n quantizer.eval_func = eval_func\n if fake_yaml == 'fx_qat_yaml.yaml':\n quantizer.q_func = q_func\n else:\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.model = common.Model(model_origin,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n q_model = quantizer.fit()\n q_model.save('./saved')\n # Load configure and weights with neural_compressor.utils\n model_fx = load('./saved/best_model.pt', model_origin,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n self.assertTrue(isinstance(model_fx.sub, torch.fx.graph_module.GraphModule))\n\n # recover int8 model with only tune_cfg\n history_file = './saved/history.snapshot'\n model_fx_recover = recover(model_origin, history_file, 0,\n **{'prepare_custom_config_dict': \\\n {'non_traceable_module_name': ['a']},\n 'convert_custom_config_dict': \\\n {'preserved_attributes': []}\n })\n self.assertEqual(model_fx.sub.code, model_fx_recover.sub.code)\n shutil.rmtree('./saved', ignore_errors=True)\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "torch.rand", "torch.no_grad", "torch.dequantize", "torch.nn.Conv2d", "torch.quantization.QuantStub", "torch.nn.Dropout", "torch.nn.BatchNorm2d", "numpy.allclose", "torch.randn", "torch.nn.LayerNorm", "torch.ones_like", "numpy.load", "torch.quantization.convert", "torch.ones", "torch.nn.LSTM", "torch.quantization.add_observer_", "torch.load", "torch.tensor", "torch.quantization.DeQuantStub", "torch.nn.Linear", "torch.nn.quantized.FloatFunctional", "torch.zeros_like", "torch.nn.Embedding", "torch.zeros", "torch.nn.ReLU" ] ]
0wu/mlflow
[ "2b5a21af05defcfa80255c081b5d9f07443f3f64" ]
[ "tests/tensorflow/test_tensorflow_model_export.py" ]
[ "# pep8: disable=E501\n\nfrom __future__ import print_function\n\nimport collections\nimport os\nimport pandas\nimport shutil\nimport unittest\n\nimport pandas as pd\nimport sklearn.datasets as datasets\nimport tensorflow as tf\n\nfrom mlflow import tensorflow, pyfunc\nfrom mlflow import tracking\nfrom mlflow.utils.file_utils import TempDir\n\n\nclass TestModelExport(unittest.TestCase):\n\n def helper(self, feature_spec, tmp, estimator, df):\n \"\"\"\n This functions handles exporting, logging, loading back, and predicting on an estimator for\n testing purposes.\n \"\"\"\n receiver_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(feature_spec)\n saved_estimator_path = tmp.path(\"model\")\n os.makedirs(saved_estimator_path)\n # Saving TensorFlow model.\n saved_estimator_path = estimator.export_savedmodel(saved_estimator_path,\n receiver_fn).decode(\"utf-8\")\n # Logging the TensorFlow model just saved.\n tensorflow.log_saved_model(saved_model_dir=saved_estimator_path,\n signature_def_key=\"predict\",\n artifact_path=tmp.path(\"hello\"))\n # Loading the saved TensorFlow model as a pyfunc.\n x = pyfunc.load_pyfunc(saved_estimator_path)\n # Predicting on the dataset using the pyfunc.\n return x.predict(df)\n\n def test_log_saved_model(self):\n # This tests model logging capabilities on the sklearn.iris dataset.\n iris = datasets.load_iris()\n X = iris.data[:, :2] # we only take the first two features.\n y = iris.target\n trainingFeatures = {}\n for i in range(0, 2):\n # TensorFlow is fickle about feature names, so we remove offending characters\n iris.feature_names[i] = iris.feature_names[i].replace(\" \", \"\")\n iris.feature_names[i] = iris.feature_names[i].replace(\"(\", \"\")\n iris.feature_names[i] = iris.feature_names[i].replace(\")\", \"\")\n trainingFeatures[iris.feature_names[i]] = iris.data[:, i:i+1]\n tf_feat_cols = []\n feature_names = iris.feature_names[:2]\n # Creating TensorFlow-specific numeric columns for input.\n for col in iris.feature_names[:2]:\n tf_feat_cols.append(tf.feature_column.numeric_column(col))\n # Creating input training function.\n input_train = tf.estimator.inputs.numpy_input_fn(trainingFeatures,\n y,\n shuffle=False,\n batch_size=1)\n # Creating Deep Neural Network Regressor.\n estimator = tf.estimator.DNNRegressor(feature_columns=tf_feat_cols,\n hidden_units=[1])\n # Training and creating expected predictions on training dataset.\n estimator.train(input_train, steps=10)\n # Saving the estimator's prediction on the training data; assume the DNNRegressor\n # produces a single output column named 'predictions'\n pred_col = \"predictions\"\n estimator_preds = [s[pred_col] for s in estimator.predict(input_train)]\n estimator_preds_df = pd.DataFrame({pred_col: estimator_preds})\n\n old_tracking_uri = tracking.get_tracking_uri()\n # should_start_run tests whether or not calling log_model() automatically starts a run.\n for should_start_run in [False, True]:\n with TempDir(chdr=True, remove_on_exit=True) as tmp:\n try:\n # Creating dict of features names (str) to placeholders (tensors)\n feature_spec = {}\n for name in feature_names:\n feature_spec[name] = tf.placeholder(\"float\", name=name, shape=[150])\n tracking.set_tracking_uri(\"test\")\n if should_start_run:\n tracking.start_run()\n pyfunc_preds_df = self.helper(feature_spec, tmp, estimator,\n pandas.DataFrame(data=X, columns=feature_names))\n\n # Asserting that the loaded model predictions are as expected.\n assert estimator_preds_df.equals(pyfunc_preds_df)\n finally:\n # Restoring the old logging location.\n tracking.end_run()\n tracking.set_tracking_uri(old_tracking_uri)\n\n def test_categorical_columns(self):\n \"\"\"\n This tests logging capabilities on datasets with categorical columns.\n See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/get_started/\\\n regression/imports85.py\n for reference code.\n \"\"\"\n with TempDir(chdr=False, remove_on_exit=True) as tmp:\n path = os.path.abspath(\"tests/data/uci-autos-imports-85.data\")\n # Order is important for the csv-readers, so we use an OrderedDict here.\n defaults = collections.OrderedDict([\n (\"body-style\", [\"\"]),\n (\"curb-weight\", [0.0]),\n (\"highway-mpg\", [0.0]),\n (\"price\", [0.0])\n ])\n\n types = collections.OrderedDict((key, type(value[0]))\n for key, value in defaults.items())\n df = pandas.read_csv(path, names=types.keys(), dtype=types, na_values=\"?\")\n df = df.dropna()\n\n # Extract the label from the features dataframe.\n y_train = df.pop(\"price\")\n\n # Creating the input training function required.\n trainingFeatures = {}\n\n for i in df:\n trainingFeatures[i] = df[i].values\n\n input_train = tf.estimator.inputs.numpy_input_fn(trainingFeatures,\n y_train.values,\n shuffle=False,\n batch_size=1)\n\n # Creating the feature columns required for the DNNRegressor.\n body_style_vocab = [\"hardtop\", \"wagon\", \"sedan\", \"hatchback\", \"convertible\"]\n body_style = tf.feature_column.categorical_column_with_vocabulary_list(\n key=\"body-style\", vocabulary_list=body_style_vocab)\n feature_columns = [\n tf.feature_column.numeric_column(key=\"curb-weight\"),\n tf.feature_column.numeric_column(key=\"highway-mpg\"),\n # Since this is a DNN model, convert categorical columns from sparse\n # to dense.\n # Wrap them in an `indicator_column` to create a\n # one-hot vector from the input.\n tf.feature_column.indicator_column(body_style)\n ]\n\n # Build a DNNRegressor, with 2x20-unit hidden layers, with the feature columns\n # defined above as input.\n estimator = tf.estimator.DNNRegressor(\n hidden_units=[20, 20], feature_columns=feature_columns)\n\n # Training the estimator.\n estimator.train(input_fn=input_train, steps=10)\n # Saving the estimator's prediction on the training data; assume the DNNRegressor\n # produces a single output column named 'predictions'\n pred_col = \"predictions\"\n estimator_preds = [s[pred_col] for s in estimator.predict(input_train)]\n estimator_preds_df = pd.DataFrame({pred_col: estimator_preds})\n # Setting the logging such that it is in the temp folder and deleted after the test.\n old_tracking_dir = tracking.get_tracking_uri()\n tracking_dir = os.path.abspath(tmp.path(\"mlruns\"))\n tracking.set_tracking_uri(\"file://%s\" % tracking_dir)\n tracking.start_run()\n try:\n # Creating dict of features names (str) to placeholders (tensors)\n feature_spec = {}\n feature_spec[\"body-style\"] = tf.placeholder(\"string\",\n name=\"body-style\",\n shape=[None])\n feature_spec[\"curb-weight\"] = tf.placeholder(\"float\",\n name=\"curb-weight\",\n shape=[None])\n feature_spec[\"highway-mpg\"] = tf.placeholder(\"float\",\n name=\"highway-mpg\",\n shape=[None])\n\n pyfunc_preds_df = self.helper(feature_spec, tmp, estimator, df)\n # Asserting that the loaded model predictions are as expected. Allow for some\n # imprecision as this is expected with TensorFlow.\n pandas.testing.assert_frame_equal(\n pyfunc_preds_df, estimator_preds_df, check_less_precise=6)\n finally:\n # Restoring the old logging location.\n tracking.end_run()\n tracking.set_tracking_uri(old_tracking_dir)\n" ]
[ [ "tensorflow.feature_column.numeric_column", "tensorflow.placeholder", "pandas.DataFrame", "tensorflow.feature_column.categorical_column_with_vocabulary_list", "tensorflow.estimator.export.build_raw_serving_input_receiver_fn", "tensorflow.estimator.inputs.numpy_input_fn", "tensorflow.feature_column.indicator_column", "pandas.testing.assert_frame_equal", "tensorflow.estimator.DNNRegressor", "sklearn.datasets.load_iris" ] ]
helene-todd/XPPAUT_code
[ "e4caf112c03889a68eed0f4e5fa9d9d436918914" ]
[ "g_function_weak_coupling/G_function.py" ]
[ "from matplotlib import cm, rcParams\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math as math\nimport random as rand\n\n\"\"\" G(phi) function in Rinzel & Lewis' article (2003) under weak coupling \"\"\"\n\"\"\" This is under weak coupling theory, although one can note that gamma only serves to scale the function \"\"\"\n\nc = ['#aa3863', '#d97020', '#ef9f07', '#449775', '#3b7d86']\nrcParams.update({'figure.autolayout': True})\n\ndef T(I):\n return math.log(I/(I-1))\n\ndef G(phi, I, gamma):\n if phi != 0 and phi != 1:\n return gamma*(2/T(I))*(phi*math.sinh((1-phi)*T(I)) - (1-phi)*math.sinh(phi*T(I))) + gamma*(beta/(I*T(I)*T(I)))*(math.exp(phi*T(I)) - math.exp((1-phi)*T(I)))\n else :\n return 0\n\n\"\"\" Varying Gamma \"\"\"\n\ngamma = [0.4, 0.3, 0.2, 0.1, 0.01]\nbeta = 0.1\nI = 1.8\n\nplt.figure(figsize=(8,5))\nvector_phi = np.linspace(0,1,1000)\nzero_line = np.zeros(len(vector_phi))\nplt.plot(vector_phi, zero_line, color='black', linestyle='--')\n\nk = 0\nfor g in gamma :\n vector_G = []\n for el in vector_phi:\n vector_G.append(G(el, I, g))\n vector_G = np.array(vector_G)\n plt.plot(vector_phi, vector_G, label=f'$\\gamma = {g}$', color = c[k])\n k += 1\n\nplt.xlabel('$\\phi$', size=14)\nplt.ylabel('$G(\\phi)$', size=14)\nplt.title(f'G function for $I={I}, \\\\beta={beta}$')\n\nzero_crossings = np.where(np.diff(np.sign(vector_G-zero_line)))[0]\nprint(zero_crossings)\n\nplt.legend(loc='upper left')\nplt.savefig(f'G_function_range_gammas_I={I}.png', dpi=600)\nplt.show()\nplt.close()\n\n\"\"\" Varying I \"\"\"\n\"\"\"\ngamma = 1\nbeta = 0.2\nI = [1.15, 1.2, 1.4]\n\nplt.figure(figsize=(8,5))\nvector_phi = np.linspace(0,1,1000)\nzero_line = np.zeros(len(vector_phi))\nplt.plot(vector_phi, zero_line, linestyle='--', color='k')\n\nk = 0\nfor current in I :\n vector_G = []\n for el in vector_phi:\n vector_G.append(G(el, current, gamma))\n vector_G = np.array(vector_G)\n plt.plot(vector_phi, vector_G, label=f'$I = {current}$', color = c[k])\n k += 1\n\n\nplt.xlabel('$\\phi$', size=14)\nplt.ylabel('$G(\\phi)$', size=14)\n\nzero_crossings = np.where(np.diff(np.sign(vector_G-zero_line)))[0]\nprint(zero_crossings)\n\nplt.legend()\nplt.show()\n\"\"\"\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.sign", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.rcParams.update", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.close", "numpy.array", "matplotlib.pyplot.plot", "numpy.linspace", "matplotlib.pyplot.xlabel" ] ]
nevertheless-ui/TelegramData_Analyst
[ "6c7b33560a2b8b26bce99c9a82efa6b4796d5828" ]
[ "run_analyst.py" ]
[ "# Filename: analyst.py\n\"\"\"Analyst is a tool to look up (and export selected) data and insights\nfrom exported data from chats and channels in Telegram\nusing Python and PyQt5.\"\"\"\n\nimport sys\n\nimport pandas as pd\nfrom pathlib import Path\n\nfrom PyQt5 import QtWidgets, QtCore\nfrom PyQt5 import uic\n\nfrom backend import (\n converter,\n handler,\n)\n\n__version__ = '0.1'\n__author__ = 'Artyom Filippenko'\n\ndf = pd.DataFrame({'a': ['Mary', 'Jim', 'John'],\n 'b': [100, 200, 300],\n 'c': ['a', 'b', 'c']})\n\n\n# VARS SECTION\n# IMPORT LOCALE\nIMPORT_WINDOW_TITLE = 'TelegramData Analyst - Import'\nIMPORT_WINDOW_MSG = 'This software is designed for analysis of Telegram channels and chats.'\nIMPORT_BROWSE_MSG = 'Open file'\nIMPORT_PATHLINE_MSG = 'Please, add path to JSON file, exported from Telegram Application...'\nIMPORT_BROWSE_BTN_NAME = 'Browse'\nIMPORT_ANALYSE_BTN_NAME = 'Analyze'\nIMPORT_PATH_MSG = 'File'\n\n# ANALYST LOCALE\nANALYST_WINDOW_TITLE = 'TelegramData Analyst - Explorer'\nANALYST_STATUSBAR_PREFIX_MSG = 'Exploring data from json-file:'\nANALYST_WINDOW_MSG = 'Analyzing file'\nANALYST_RETURN_BTN_NAME = 'Return to import...'\nANALYST_EXPORT_BTN_NAME = 'Export results...'\n\n# ANALYST LOCALE\n#ALERT_WINDOW_TITLE = 'Alert!'\n\n# UI path\nIMPORT_UI_PATH = './frontend/import_data.ui'\nMAIN_UI_PATH = './frontend/workspace.ui'\n#ALERT_UI_PATH = './frontend/alert.ui'\n\nclass ImportWindow(QtWidgets.QDialog):\n def __init__(self, parent=None):\n super().__init__(parent)\n self._build()\n self.ui.show()\n\n def _build(self):\n self.ui = uic.loadUi(IMPORT_UI_PATH)\n\n # Locale\n self.ui.setWindowTitle(IMPORT_WINDOW_TITLE)\n self.ui.import_description_message.setText(IMPORT_WINDOW_MSG)\n self.ui.browse_files_btn.setText(IMPORT_BROWSE_BTN_NAME)\n self.ui.analyse_file_btn.setText(IMPORT_ANALYSE_BTN_NAME)\n self.ui.import_file_pathline.setText(IMPORT_PATHLINE_MSG)\n\n # Loading UI logic\n self.ui.browse_files_btn.clicked.connect(self._browse_files)\n self.ui.analyse_file_btn.clicked.connect(self._open_analyst)\n\n def _browse_files(self):\n import_file = QtWidgets.QFileDialog.getOpenFileName(self, IMPORT_BROWSE_MSG,\n './', \"Json file (*.json)\")\n self.ui.import_file_pathline.setText(import_file[0])\n\n def _open_analyst(self):\n if self.ui.import_file_pathline.text() == IMPORT_PATHLINE_MSG:\n json_file_path = ''\n\n else:\n json_file_path = Path(self.ui.import_file_pathline.text())\n self.analyst = AnalysisWindow(self)\n self.analyst.import_json_file(json_file_path)\n self.analyst.update_table_view\n self.analyst.ui.statusbar.showMessage(ANALYST_STATUSBAR_PREFIX_MSG + ' ' + \\\n str(json_file_path))\n self.ui.hide()\n\n\nclass AnalysisWindow(QtWidgets.QMainWindow):\n def __init__(self, parent=None):\n super().__init__(parent, QtCore.Qt.Window)\n self._build()\n self.ui.show()\n #self.import_json_file()\n #self.update_table_view()\n\n def _build(self):\n self.ui = uic.loadUi(MAIN_UI_PATH)\n # Locale\n self.ui.setWindowTitle(ANALYST_WINDOW_TITLE)\n self.ui.return_btn.setText(ANALYST_RETURN_BTN_NAME)\n self.ui.export_btn.setText(ANALYST_EXPORT_BTN_NAME)\n # Loading UI logic\n self.ui.return_btn.clicked.connect(self._return_to_import)\n\n def _return_to_import(self):\n self.ui.close()\n self.parent().ui.show()\n\n def import_json_file(self, json_file_path):\n self._data = converter.convert_tg_json(json_file_path)\n\n def update_table_view(self):\n self.ui.test_msg.setText(str(df.columns))\n self.model = handler.pandasModel(self._data)\n self.ui.table_view.setModel(self.model)\n self.ui.table_view.show()\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv)\n window = ImportWindow()\n #window.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.DataFrame" ] ]
shallowyuan/cosegmentor-crf
[ "c84a9418b70f3f3c7c6a7e998de5835182619f30" ]
[ "tlib/networks/VGGnet_train.py" ]
[ "import tensorflow as tf\nfrom networks.network import Network\n\n\n#define\n\nn_classes = 21\n_feat_stride = [16,]\nanchor_scales = [8, 16, 32]\n\nclass VGGnet_train(Network):\n def __init__(self, trainable=True):\n self.inputs = []\n self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3])\n #self.im_info = tf.placeholder(tf.float32, shape=[None, 3])\n #self.gt_boxes = tf.placeholder(tf.float32, shape=[None, 5])\n self.keep_prob = tf.placeholder(tf.float32)\n self.segmentation=tf.placeholder(tf.float32,shape=[None,900])\n self.rois=tf.placeholder(tf.float32,shape=[None,5])\n #self.mweights=tf.placeholder(tf.float32,shape=[None,2])\n self.sweights=tf.placeholder(tf.bool,shape=[None])\n self.labels=tf.placeholder(tf.int32,shape=[None])\n self.layers = dict({'data':self.data, 'segmentation':self.segmentation, 'sweight':self.sweights, 'labels': self.labels, \"rois\": self.rois})\n self.trainable = trainable\n self.setup()\n\n\n def setup(self):\n (self.feed('data')\n .conv(3, 3, 64, 1, 1, name='conv1_1', trainable=False)\n .conv(3, 3, 64, 1, 1, name='conv1_2', trainable=False)\n .max_pool(2, 2, 2, 2, padding='VALID', name='pool1')\n .conv(3, 3, 128, 1, 1, name='conv2_1', trainable=False)\n .conv(3, 3, 128, 1, 1, name='conv2_2', trainable=False)\n .max_pool(2, 2, 2, 2, padding='VALID', name='pool2')\n .conv(3, 3, 256, 1, 1, name='conv3_1')\n .conv(3, 3, 256, 1, 1, name='conv3_2')\n .conv(3, 3, 256, 1, 1, name='conv3_3')\n .max_pool(2, 2, 2, 2, padding='VALID', name='pool3')\n .conv(3, 3, 512, 1, 1, name='conv4_1')\n .conv(3, 3, 512, 1, 1, name='conv4_2')\n .conv(3, 3, 512, 1, 1, name='conv4_3'))\n #=========ROIPOOLING=======\n (self.feed('conv4_3','rois')\n .roi_pool(7, 7, 1.0/16, name='pool_4')\n .conv(3, 3, 512, 1, 1, name='conv5_1')\n .conv(3, 3, 512, 1, 1, name='conv5_2')\n .conv(3, 3, 512, 1, 1, name='conv5_3')\n .max_pool(2, 2, 2, 2, padding='VALID', name='pool5'))\n\n\n #========= RPN ============\n# (self.feed('conv5_3')\n# .conv(3,3,512,1,1,name='rpn_conv/3x3')\n# .conv(1,1,len(anchor_scales)*3*2 ,1 , 1, padding='VALID', relu = False, name='rpn_cls_score'))#\n\n# (self.feed('rpn_cls_score','gt_boxes','im_info','data')\n# .anchor_target_layer(_feat_stride, anchor_scales, name = 'rpn-data' ))#\n\n# # Loss of rpn_cls & rpn_boxes\n\n# (self.feed('rpn_conv/3x3')\n# .conv(1,1,len(anchor_scales)*3*4, 1, 1, padding='VALID', relu = False, name='rpn_bbox_pred'))\n\n #========= RoI Proposal ============\n# (self.feed('rpn_cls_score')\n# .reshape_layer(2,name = 'rpn_cls_score_reshape')\n# .softmax(name='rpn_cls_prob'))\n#\n# (self.feed('rpn_cls_prob')\n# .reshape_layer(len(anchor_scales)*3*2,name = 'rpn_cls_prob_reshape'))\n#\n# (self.feed('rpn_cls_prob_reshape','rpn_bbox_pred','im_info')\n# .proposal_layer(_feat_stride, anchor_scales, 'TRAIN',name = 'rpn_rois'))\n#\n# (self.feed('rpn_rois','gt_boxes')\n# .proposal_target_layer(n_classes,name = 'roi-data'))\n\n\n #========= RCNN ============\n (self.feed('pool5')\n .fc(1024, name='fc6')\n .dropout(0.5, name='drop6')\n .fc(1024, name='fc7')\n .dropout(0.5, name='drop7')\n .fc(n_classes, relu=False, name='cls_score')\n .softmax(name='cls_prob'))\n\n # (self.feed('drop7')\n # .fc(n_classes*4, relu=False, name='bbox_pred'))\n\n #==========segment network===\n (self.feed('conv5_3')\n .conv(1,1,512,1 , 1, padding='VALID', name='conv5_4')\n .fc(512, name='fc8')\n .fc(900, relu=False, name='seg_score'))\n\n" ]
[ [ "tensorflow.placeholder" ] ]