repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
ORG-MARS/zenml
|
[
"8ee9a9264397d4e24a34c906e34a443782b189d3",
"8ee9a9264397d4e24a34c906e34a443782b189d3"
] |
[
"zenml/steps/trainer/pytorch_trainers/torch_ff_trainer.py",
"zenml/pipelines/nlp_pipeline.py"
] |
[
"# Copyright (c) maiot GmbH 2020. 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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n\nimport os\nfrom typing import List, Text, Dict\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom zenml.steps.trainer import TorchBaseTrainerStep\nfrom zenml.steps.trainer import utils\nfrom zenml.steps.trainer.pytorch_trainers import utils as torch_utils\nfrom zenml.utils import path_utils\n\n\nclass BinaryClassifier(nn.Module):\n def __init__(self):\n super(BinaryClassifier, self).__init__()\n self.layer_1 = nn.Linear(8, 64)\n self.layer_2 = nn.Linear(64, 64)\n self.layer_out = nn.Linear(64, 1)\n\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout(p=0.1)\n self.batchnorm1 = nn.BatchNorm1d(64)\n self.batchnorm2 = nn.BatchNorm1d(64)\n\n def forward(self, inputs):\n x = self.relu(self.layer_1(inputs))\n x = self.batchnorm1(x)\n x = self.relu(self.layer_2(x))\n x = self.batchnorm2(x)\n x = self.dropout(x)\n x = self.layer_out(x)\n\n return x\n\n\ndef binary_acc(y_pred, y_test):\n y_pred_tag = torch.round(torch.sigmoid(y_pred))\n correct_results_sum = (y_pred_tag == y_test).sum().float()\n acc = correct_results_sum / y_test.shape[0]\n acc = torch.round(acc * 100)\n\n return acc\n\n\nclass FeedForwardTrainer(TorchBaseTrainerStep):\n def __init__(self,\n batch_size: int = 32,\n lr: float = 0.0001,\n epochs: int = 10,\n dropout_chance: int = 0.2,\n loss: str = 'mse',\n metrics: List[str] = None,\n hidden_layers: List[int] = None,\n hidden_activation: str = 'relu',\n last_activation: str = 'sigmoid',\n input_units: int = 8,\n output_units: int = 1,\n device: str = None,\n **kwargs):\n self.batch_size = batch_size\n self.lr = lr\n self.epochs = epochs\n self.dropout_chance = dropout_chance\n self.loss = loss\n self.metrics = metrics or []\n self.hidden_layers = hidden_layers or [64, 32, 16]\n self.hidden_activation = hidden_activation\n self.last_activation = last_activation\n self.input_units = input_units\n self.output_units = output_units\n self.device = torch_utils.assign_device(device)\n \n\n super(FeedForwardTrainer, self).__init__(\n batch_size=self.batch_size,\n lr=self.lr,\n epochs=self.epochs,\n dropout_chance=self.dropout_chance,\n loss=self.loss,\n metrics=self.metrics,\n hidden_layers=self.hidden_layers,\n hidden_activation=self.hidden_activation,\n last_activation=self.last_activation,\n input_units=self.input_units,\n output_units=self.output_units,\n device = device,\n **kwargs)\n\n def input_fn(self,\n file_patterns: List[Text]):\n\n dataset = torch_utils.TFRecordTorchDataset(file_patterns,\n self.schema)\n loader = torch.utils.data.DataLoader(dataset,\n batch_size=self.batch_size,\n drop_last=True)\n return loader\n\n def model_fn(self, train_dataset, eval_dataset):\n return BinaryClassifier()\n\n def test_fn(self, model, dataset):\n # Activate the evaluation mode\n model.eval()\n\n batch_list = []\n for x, y, raw in dataset:\n # start with an empty batch\n batch = {}\n\n # add the raw features with the transformed features and labels\n batch.update(x)\n batch.update(y)\n batch.update(raw)\n\n # finally, add the output of the model\n x_batch = torch.cat([v.to(self.device) for v in x.values()], dim=-1)\n p = model(x_batch)\n\n if isinstance(p, torch.Tensor):\n batch.update({'output': p})\n elif isinstance(p, dict):\n batch.update(p)\n elif isinstance(p, list):\n batch.update(\n {'output_{}'.format(i): v for i, v in enumerate(p)})\n else:\n raise TypeError('Unknown output format!')\n\n batch_list.append(batch)\n\n combined_batch = utils.combine_batch_results(batch_list)\n\n return combined_batch\n\n def run_fn(self):\n train_split_patterns = [self.input_patterns[split] for split in\n self.split_mapping[utils.TRAIN_SPLITS]]\n train_dataset = self.input_fn(train_split_patterns)\n\n eval_split_patterns = [self.input_patterns[split] for split in\n self.split_mapping[utils.EVAL_SPLITS]]\n eval_dataset = self.input_fn(eval_split_patterns)\n\n model = self.model_fn(train_dataset, eval_dataset)\n\n model.to(self.device)\n criterion = nn.BCEWithLogitsLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.001)\n\n writer = SummaryWriter(self.log_dir)\n\n model.train()\n\n total_count = 0\n\n for e in range(1, self.epochs + 1):\n epoch_loss = 0\n epoch_acc = 0\n step_count = 0\n for x, y, _ in train_dataset:\n step_count += 1\n total_count += 1\n\n x_batch = torch.cat([v.to(self.device) for v in x.values()], dim=-1)\n y_batch = torch.cat([v.to(self.device) for v in y.values()], dim=-1)\n optimizer.zero_grad()\n\n y_pred = model(x_batch)\n\n loss = criterion(y_pred, y_batch)\n acc = binary_acc(y_pred, y_batch)\n\n loss.backward()\n optimizer.step()\n\n epoch_loss += loss.item()\n epoch_acc += acc.item()\n\n if e == 1 and step_count == 1:\n writer.add_graph(model, x_batch)\n\n writer.add_scalar('training_loss', loss, total_count)\n writer.add_scalar('training_accuracy', acc, total_count)\n\n print(f'Epoch {e + 0:03}: | Loss: '\n f'{epoch_loss / step_count:.5f} | Acc: '\n f'{epoch_acc / step_count:.3f}')\n\n # test\n for split in self.split_mapping[utils.TEST_SPLITS]:\n assert split in self.input_patterns, \\\n f'There are currently no inputs for the split \"{split}\" ' \\\n f'which is currently used in the {utils.TEST_SPLITS} of the ' \\\n f'split mapping.'\n pattern = self.input_patterns[split]\n test_dataset = self.input_fn([pattern])\n test_results = self.test_fn(model, test_dataset)\n utils.save_test_results(test_results, self.output_patterns[split])\n\n path_utils.create_dir_if_not_exists(self.serving_model_dir)\n if path_utils.is_remote(self.serving_model_dir):\n temp_model_dir = '__temp_model_dir__'\n temp_path = os.path.join(os.getcwd(), temp_model_dir)\n if path_utils.is_dir(temp_path):\n raise PermissionError('{} is used as a temp path but it '\n 'already exists. Please remove it to '\n 'continue.')\n torch.save(model, temp_path)\n path_utils.copy_dir(temp_path, self.serving_model_dir)\n path_utils.rm_dir(temp_path)\n else:\n torch.save(model, os.path.join(self.serving_model_dir, 'model.pt'))\n",
"# Copyright (c) maiot GmbH 2021. 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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\"\"\"ZenML NLP Pipeline Prototype.\"\"\"\n\nimport os\nfrom typing import Dict, Text, Any, List\nfrom typing import Optional, Union\n\nimport tensorflow as tf\nfrom tfx.dsl.components.common.importer import Importer\nfrom tfx.components.schema_gen.component import SchemaGen\nfrom tfx.components.statistics_gen.component import StatisticsGen\nfrom tfx.components.trainer.component import Trainer\nfrom tfx.proto import trainer_pb2\nfrom tfx.types import standard_artifacts\n\nfrom zenml import constants\nfrom zenml.backends.training import TrainingBaseBackend\nfrom zenml.components import SplitGen, Trainer\nfrom zenml.components import Tokenizer\nfrom zenml.enums import GDPComponent\nfrom zenml.enums import PipelineStatusTypes\nfrom zenml.logger import get_logger\nfrom zenml.pipelines import BasePipeline\nfrom zenml.standards import standard_keys as keys\nfrom zenml.steps.split import BaseSplitStep\nfrom zenml.steps.tokenizer import BaseTokenizer\nfrom zenml.steps.trainer import BaseTrainerStep\n\nlogger = get_logger(__name__)\n\n\nclass NLPPipeline(BasePipeline):\n PIPELINE_TYPE = \"nlp\"\n\n def predict_sentence(self, sequence: Union[Text, List[Text]]):\n \"\"\"Call operator for local inference method\"\"\"\n\n if not self.get_status() == PipelineStatusTypes.Succeeded.name:\n logger.info(\n \"Please run the pipeline first before running inference!\")\n return\n\n trainer_step = self.steps_dict[keys.NLPSteps.TRAINER]\n\n # e.g. HuggingFace has special APIs for model loading,\n # so we fall back to a trainer step class method\n model_uri = os.path.join(self.get_model_uri(), \"serving_model_dir\")\n model = trainer_step.load_model(model_uri)\n\n tokenizer_step = self.steps_dict[keys.NLPSteps.TOKENIZER]\n\n tokenizer_step.load_vocab(self.get_tokenizer_uri())\n\n encoded = tokenizer_step.encode(sequence=sequence,\n output_format=\"tf_tensors\")\n\n transformed_bert_features = {k: tf.reshape(v, (1, -1)) for k, v in\n encoded.items()}\n\n prediction = model(input_ids=transformed_bert_features, training=False)\n\n formatted = [\n {\"label\": model.config.id2label[item.argmax()],\n \"score\": item.max().item()}\n for item in tf.math.sigmoid(prediction.logits).numpy()\n ]\n\n logger.info(formatted)\n\n def get_tfx_component_list(self, config: Dict[Text, Any]) -> List:\n \"\"\"\n Builds the NLP pipeline as a series of TFX components.\n\n Args:\n config: A ZenML configuration in dictionary format.\n\n Returns:\n A chronological list of TFX components making up the NLP\n pipeline.\n\n \"\"\"\n steps = config[keys.GlobalKeys.PIPELINE][keys.PipelineKeys.STEPS]\n\n component_list = []\n\n ############\n # RAW DATA #\n ############\n # if there are no commits, then lets make one\n if self.datasource.is_empty:\n logger.info(\n f'Datasource {self.datasource.name} has no commits. Creating '\n f'the first one..')\n # Have to use the same metadata store and artifact store\n logger.info(\n 'Setting metadata store and artifact store of datasource to '\n 'conform to the ones defined in this pipeline.')\n self.datasource.metadata_store = self.metadata_store\n self.datasource.artifact_store = self.artifact_store\n self.datasource_commit_id = self.datasource.commit()\n\n data = Importer(\n source_uri=\n self.datasource.get_artifact_uri_by_component_and_commit_id(\n self.datasource_commit_id, GDPComponent.DataGen.name)[0],\n artifact_type=standard_artifacts.Examples).with_id(\n GDPComponent.DataGen.name)\n\n schema_data = Importer(\n source_uri=\n self.datasource.get_artifact_uri_by_component_and_commit_id(\n self.datasource_commit_id, GDPComponent.DataSchema.name)[0],\n artifact_type=standard_artifacts.Schema).with_id(\n GDPComponent.DataSchema.name)\n\n statistics_data = Importer(\n source_uri=\n self.datasource.get_artifact_uri_by_component_and_commit_id(\n self.datasource_commit_id, GDPComponent.DataStatistics.name)[\n 0],\n artifact_type=standard_artifacts.ExampleStatistics).with_id(\n GDPComponent.DataStatistics.name)\n\n component_list.extend([data, schema_data, statistics_data])\n\n #############\n # TOKENIZER #\n #############\n tokenizer_config = steps[keys.NLPSteps.TOKENIZER]\n tokenizer = Tokenizer(\n source=tokenizer_config[keys.StepKeys.SOURCE],\n source_args=tokenizer_config[keys.StepKeys.ARGS],\n examples=data.outputs.result,\n ).with_id(GDPComponent.Tokenizer.name)\n\n component_list.extend([tokenizer])\n\n # return component_list\n\n statistics_data = StatisticsGen(\n examples=tokenizer.outputs.output_examples\n ).with_id(GDPComponent.DataStatistics.name)\n\n schema_data = SchemaGen(\n statistics=statistics_data.outputs.statistics,\n infer_feature_shape=True,\n ).with_id(GDPComponent.DataSchema.name)\n\n split_config = steps[keys.NLPSteps.SPLIT]\n splits = SplitGen(\n input_examples=tokenizer.outputs.output_examples,\n source=split_config[keys.StepKeys.SOURCE],\n source_args=split_config[keys.StepKeys.ARGS],\n schema=schema_data.outputs.schema,\n statistics=statistics_data.outputs.output,\n ).with_id(GDPComponent.SplitGen.name)\n\n component_list.extend([data,\n statistics_data,\n schema_data,\n splits])\n\n ############\n # TRAINING #\n ############\n training_backend: Optional[TrainingBaseBackend] = \\\n self.steps_dict[keys.NLPSteps.TRAINER].backend\n\n # default to local\n if training_backend is None:\n training_backend = TrainingBaseBackend()\n\n training_kwargs = {\n 'custom_executor_spec': training_backend.get_executor_spec(),\n 'custom_config': steps[keys.NLPSteps.TRAINER]\n }\n training_kwargs['custom_config'].update(\n training_backend.get_custom_config())\n\n trainer = Trainer(\n examples=splits.outputs.examples,\n run_fn=constants.TRAINER_FN,\n schema=schema_data.outputs.schema,\n **training_kwargs\n ).with_id(GDPComponent.Trainer.name)\n\n component_list.extend([trainer])\n\n return component_list\n\n def steps_completed(self) -> bool:\n mandatory_steps = [keys.NLPSteps.TOKENIZER, keys.NLPSteps.SPLIT,\n keys.NLPSteps.TRAINER]\n\n for step_name in mandatory_steps:\n if step_name not in self.steps_dict.keys():\n raise AssertionError(f'Mandatory step {step_name} not added.')\n return True\n\n def add_tokenizer(self, tokenizer_step: BaseTokenizer):\n self.steps_dict[keys.NLPSteps.TOKENIZER] = tokenizer_step\n\n def add_split(self, split_step: BaseSplitStep):\n self.steps_dict[keys.NLPSteps.SPLIT] = split_step\n\n def add_trainer(self, trainer_step: BaseTrainerStep):\n self.steps_dict[keys.NLPSteps.TRAINER] = trainer_step\n\n def get_model_uri(self):\n \"\"\"Gets model artifact.\"\"\"\n uris = self.get_artifacts_uri_by_component(\n GDPComponent.Trainer.name, False)\n return uris[0]\n\n def get_schema_uri(self):\n \"\"\"Gets transform artifact.\"\"\"\n uris = self.get_artifacts_uri_by_component(\n GDPComponent.DataSchema.name, False)\n return uris[0]\n\n def get_tokenizer_uri(self):\n \"\"\"Gets transform artifact.\"\"\"\n uris = self.get_artifacts_uri_by_component(\n GDPComponent.Tokenizer.name, False)\n return uris[0]\n"
] |
[
[
"torch.nn.BatchNorm1d",
"torch.nn.Dropout",
"torch.sigmoid",
"torch.round",
"torch.utils.data.DataLoader",
"torch.nn.Linear",
"torch.nn.BCEWithLogitsLoss",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.ReLU",
"torch.save"
],
[
"tensorflow.math.sigmoid",
"tensorflow.reshape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
egurapha/prot_domain_segmentor
|
[
"407ae9f5ff37ae20a32f07dd46b85ef8201659e1"
] |
[
"classes/DomainSegmentor.py"
] |
[
"import os, sys\nsys.path.insert(0, 'model')\nfrom segmentor_model_v2 import *\nfrom segmentor_utils import *\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.nn.functional as F\nimport scipy.stats\n\nidx_to_class = {0: 'Unassigned (Loop)',\n 1: 'Orthogonal Bundle',\n 2: 'Up-down Bundle',\n 3: 'Alpha Horseshoe',\n 4: 'Alpha/alpha barrel',\n 5: 'Ribbon',\n 6: 'Aligned Prism',\n 7: '3-layer Sandwich',\n 8: '4 Propeller',\n 9: '5 Propeller',\n 10: '6 Propeller',\n 11: '7 Propeller',\n 12: '2 Solenoid',\n 13: '3 Solenoid',\n 14: 'Beta Complex',\n 15: 'Single Sheet',\n 16: 'Roll',\n 17: 'Beta Barrel',\n 18: 'Clam',\n 19: 'Sandwich',\n 20: 'Distorted Sandwich',\n 21: 'Trefoil',\n 22: 'Orthogonal Prism',\n 23: 'Roll',\n 24: 'Ribosomal Protein L15; Chain: K; domain 2',\n 25: 'Super Roll',\n 26: 'Alpha-Beta Barrel',\n 27: '2-Layer Sandwich',\n 28: '3-Layer(aba) Sandwich',\n 29: '3-Layer(bba) Sandwich',\n 30: '3-Layer(bab) Sandwich',\n 31: '4-Layer Sandwich',\n 32: 'Alpha-beta prism',\n 33: 'Box',\n 34: '5-stranded Propeller',\n 35: 'Alpha-Beta Horseshoe',\n 36: 'Alpha-Beta Complex',\n 37: 'Irregular',\n -1: 'NULL'}\n\nclass DomainSegmentor:\n def __init__(self, model_path='model/segmentor_epoch95_model_v2', class_dict=idx_to_class, try_gpu=True):\n self.class_dict = class_dict\n self.cuda_avail = torch.cuda.is_available() and try_gpu\n self.num_classes = len(self.class_dict)-1 \n self.model = SegmentorModel(1,8,16, self.num_classes)\n self._init_model(self.model, model_path)\n \n def _init_model(self, net, model_path):\n if self.cuda_avail:\n net.load_state_dict(torch.load(model_path))\n net.cuda()\n net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count())) \n print(\"Model Initialized on GPU.\")\n else:\n net.load_state_dict(torch.load(model_path, map_location=lambda storage, loc: storage))\n print(\"Model Initialized on CPU.\")\n net.eval() # Set model to evaluation mode to remove stochastic regularization.\n \n def _get_input(self, pdb_name):\n seq_len, numbering = get_pdb_info(pdb_name)\n cm, numbering = makeContactMapTensor(pdb_name, seq_len, numbering, target_size=512, upper_tol=512)\n if self.cuda_avail:\n model_input = Variable(cm).cuda()\n else:\n model_input = Variable(cm)\n return numbering, model_input\n\n def predict(self, pdb_name, ignore_index=-9999, log=False):\n '''\n Input: pdb name as string.\n Output: \n trunc_class_probs -- 38 x 512 matrix. Entry (i,j) is the probility of residue j being in class i.\n res_num -- the list of pdb_residue numberings corresponding to the columns of trunc_class_probs. For example, out_num[i] = 50, then the i-th column of trunc_class_probs corresponds to residue 50 in the actual PDB.\n '''\n numbering, model_input = self._get_input(pdb_name)\n outputs = self.model(model_input)\n if log:\n outputs = F.log_softmax(outputs, dim=1)\n else:\n outputs = F.softmax(outputs, dim=1)\n outputs = outputs.data[0,:,:,:]\n # Format for output.\n class_probs = outputs.cpu().numpy().squeeze() # 38 x 512 matrix. The columns define a probability distribution over the 38 classes for each residue.\n res_num = []\n trunc_class_probs = np.array([None])\n for i in range(len(numbering)): # Remove entries outside of the range of the PDB.\n if numbering[i] != ignore_index:\n res_num.append(numbering[i])\n if not trunc_class_probs.any():\n trunc_class_probs = np.expand_dims(class_probs[:,i], axis=1)\n else:\n trunc_class_probs = np.column_stack([trunc_class_probs, class_probs[:,i]])\n return trunc_class_probs, res_num\n\n def predictClass(self, pdb_name, ignore_index=-9999):\n '''\n Input: pdb name as string.\n Output:\n out_pred -- the predicted classes for each residue.\n res_num -- the pdb residue numberings corresponding to the entries in out_pred. For example, if res_num[i] = 10 and out_pred[i] = 15, then the model predicts class 15 for residue 10. \n '''\n numbering, model_input = self._get_input(pdb_name)\n outputs = self.model(model_input)\n _, predicted = torch.max(outputs.data, 1)\n # Format for output.\n predicted = predicted[0,:,:].cpu().numpy().flatten()\n out_pred = []\n res_num = []\n for i in range(len(numbering)):\n if numbering[i] != ignore_index:\n out_pred.append(predicted[i])\n res_num.append(numbering[i])\n assert len(out_pred) == len(res_num)\n return out_pred, res_num\n\n def computeEntropy(self, pdb_name, ignore_index=-9999):\n trunc_class_probs, res_num = self.predict(pdb_name, log=False)\n entropy = scipy.stats.entropy(trunc_class_probs)\n assert len(entropy) == len(res_num)\n return entropy, res_num\n\n# Usage Example.\nif __name__ == '__main__':\n segmentor = DomainSegmentor() # Initialize model, no params needed.\n classes, res_nums = segmentor.predictClass('test_cases/3gqyA.pdb') # Run prediction. Pass in a path to a pdb file.\n probs, res_nums = segmentor.predict('test_cases/3gqyA.pdb') # The predict function returns probabilities, the predictClass function returns a class prediction.\n print(\"Residue Numbers: \")\n print(res_nums)\n print(\"Class Predictions: \")\n print(classes)\n print(\"Probability Matrix: \")\n print(probs)\n"
] |
[
[
"torch.nn.functional.softmax",
"numpy.expand_dims",
"torch.max",
"torch.nn.functional.log_softmax",
"torch.load",
"torch.cuda.is_available",
"numpy.column_stack",
"torch.cuda.device_count",
"numpy.array",
"torch.autograd.Variable"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
IBM/covid19-india-data
|
[
"e2be04e74e753fbd1b1580f62856bf7335b95d33"
] |
[
"serve_db/vizapi.py"
] |
[
"import sqlite3\nimport pandas as pd\nimport json\n\n\ndef get_queries():\n CONFIGPATH = './configs/visualization.sql.json'\n with open(CONFIGPATH, 'r') as f:\n queries = json.load(f)\n return queries\n\n\ndef get_generic_query_result(db_uri, queryid, return_csv=True):\n\n queries = get_queries()\n query = queries[queryid]\n sql = query['query']\n cols = query['columns']\n\n data = read_from_db(db_uri, sql)\n df = pd.DataFrame(data)\n df.columns = cols\n\n if return_csv:\n csvdata = df.to_csv(index=False)\n return csvdata\n\n return df\n\n\ndef read_from_db(db_uri, query):\n try:\n con = sqlite3.connect(db_uri, uri=True)\n cursor = con.cursor()\n cursor.execute(query)\n except Exception as err:\n print(err)\n records = None\n else:\n records = cursor.fetchall()\n finally:\n con.close()\n return records\n\n\ndef hospitalization(db_uri, last_60_days=False):\n\n with open('./configs/visualization.sql.json', 'r') as f:\n queries = json.load(f)\n\n if last_60_days:\n hospital_query = queries['hospitalizations.queries.60days']\n else:\n hospital_query = queries['hospitalizations.queries']\n\n datadict = {}\n ALL_STATES = sorted(hospital_query.keys())\n NA = \"N/A\"\n\n for statename in ALL_STATES:\n query = hospital_query[statename]\n records = read_from_db(db_uri, query)\n\n if records is not None:\n for date, val in records:\n if date not in datadict:\n datadict[date] = {key: NA for key in ALL_STATES}\n \n datadict[date][statename] = val\n \n df = pd.DataFrame.from_records(datadict).T\n df = df.reset_index()\n df.columns = ['date'] + ALL_STATES\n csvdata = df.to_csv(index=False)\n return csvdata\n\n\ndef hospitalization_last60days(db_uri):\n return hospitalization(db_uri, last_60_days=True)\n\ndef DL_hospitalization_overall(db_uri):\n key = 'DL.hospitalization.overall'\n return get_generic_query_result(db_uri, key)\n\ndef DL_hospitalization_60days(db_uri):\n key = 'DL.hospitalization.60days'\n return get_generic_query_result(db_uri, key)\n\ndef DL_containment_zones(db_uri):\n key = 'DL.containment.zones'\n return get_generic_query_result(db_uri, key)\n\ndef DL_rtpcr_percentage(db_uri):\n key = 'DL.rtpcr.percentage'\n return get_generic_query_result(db_uri, key)\n\ndef GA_hospitalization(db_uri):\n key = 'GA.hospitalization'\n return get_generic_query_result(db_uri, key)\n\ndef HR_gender_samples(db_uri):\n key = 'HR.gender.wise.samples'\n return get_generic_query_result(db_uri, key)\n\ndef HR_homeisolation(db_uri):\n key = 'HR.home.isolation'\n return get_generic_query_result(db_uri, key)\n\ndef KA_gender_fatalities(db_uri):\n key = 'KA.gender.wise.fatalities'\n data = get_generic_query_result(db_uri, key, return_csv=False)\n data = data.pivot_table(index=['month'], columns=['gender'], values=['count']).fillna('N/A').reset_index()\n data = data.values.tolist()\n data = pd.DataFrame(data, columns=['month', 'fatalities (female)', 'fatalities (male)'])\n\n total = data['fatalities (female)'] + data['fatalities (male)']\n data['fatalities (female)'] = data['fatalities (female)'] * 100.0 / total\n data['fatalities (male)'] = data['fatalities (male)'] * 100.0 / total\n\n data = data.to_csv(index=False)\n return data\n\ndef KA_agewise_fatalities(db_uri):\n\n def transform(val):\n low = int(val/10.0) * 10\n return f'{low}-{low+10}'\n\n key = 'KA.age.wise.fatalities'\n data = get_generic_query_result(db_uri, key, return_csv=False)\n data['count'] = 1.0\n data['age'] = data['age'].apply(transform)\n data = data.pivot_table(index=['month'], columns=['age'], values=['count'], aggfunc='count').fillna(0).reset_index()\n data = data.T.reset_index(drop=True, level=[0]).T\n\n colorder = sorted(list(data.columns), key=lambda x: int(x.split('-')[0]) if x != '' else -1)\n data = data[colorder]\n\n cols = list(data.columns)\n cols[0] = 'Month'\n data.columns = cols \n\n data = data.to_csv(index=False)\n return data\n\ndef KL_gender_fatalities(db_uri):\n key = 'KL.gender.wise.fatalities'\n data = get_generic_query_result(db_uri, key, return_csv=False)\n data = data.pivot_table(index=['month'], columns=['gender'], values=['count']).fillna('N/A').reset_index()\n data = data.values.tolist()\n data = pd.DataFrame(data, columns=['month', 'fatalities (female)', 'fatalities (male)'])\n\n total = data['fatalities (female)'] + data['fatalities (male)']\n data['fatalities (female)'] = data['fatalities (female)'] * 100.0 / total\n data['fatalities (male)'] = data['fatalities (male)'] * 100.0 / total\n\n data = data.to_csv(index=False)\n return data\n\ndef KL_agewise_fatalities(db_uri):\n\n def transform(val):\n low = int(val/10.0) * 10\n return f'{low}-{low+10}'\n\n key = 'KL.age.wise.fatalities'\n data = get_generic_query_result(db_uri, key, return_csv=False)\n data['count'] = 1.0\n data['age'] = data['age'].apply(transform)\n data = data.pivot_table(index=['month'], columns=['age'], values=['count'], aggfunc='count').fillna(0).reset_index()\n data = data.T.reset_index(drop=True, level=[0]).T\n\n colorder = sorted(list(data.columns), key=lambda x: int(x.split('-')[0]) if x != '' else -1)\n data = data[colorder]\n\n cols = list(data.columns)\n cols[0] = 'Month'\n data.columns = cols \n\n data = data.to_csv(index=False)\n return data"
] |
[
[
"pandas.DataFrame.from_records",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
mcm7f/thesis
|
[
"412f35de9b1ce25ed4447d077a2a5292a57063f9"
] |
[
"histogram.py"
] |
[
"# Need to parse .csv log files, process them, and plot results\n# in an organize fashion.\n# Thesis work\n# Michael C. Murphy\n# Code started: March 1, 2016\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport matplotlib.mlab as mlab # what is this?\nfrom math import log\nfrom statistics import variance\nimport time\n\ndef main():\n print( \"Detected\", len(sys.argv), \"arguments\")\n\n # I need to process data files for slopes and append them to x\n x = []\n y = []\n\n\n # Taken from matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html\n #mu, sigma = 100, 15\n #x = mu + sigma*np.random.randn(10000)\n #x = np.random.randn(10000)\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n # Here is the array of box widths\n d = [3, 5, 10, 20, 30, 50, 100, 150, 300]\n\n F = {} # Data Dictionary using filenames as keys\n filelist = sys.argv[1:] # hold a list of files used\n for filename in filelist:\n N = {} # Data Dictonary holding Noise data\n file = open(filename, 'r')\n for line in file:\n if line[0] != '#':\n line = line.strip()\n data = line.split(',')\n # Noise % is the key, the array of counted boxes is the data\n N[ data[1] ] = data[4:13]\n F[filename] = N\n\n # Steal image file name from the path:\n image_name = sys.argv[1].split(\"/\")\n image_name = image_name[-1].split(\"_\")\n image_name = image_name[0]\n\n # Debug print the size of our data structure\n print(\">> Size of F:\",len(F))\n\n # Now that we've read in the data, it is time to process it.\n R = {} # Data Dictionary holding aggregate results\n for filekey in F:\n for noisekey in F[filekey]:\n # F[filekey][noisekey] holds one array of 9 boxcounts\n # Need to calculate an arithmetic mean of the dimension (dim_mean)\n \n log_bc = []\n # store the log(boxcounts)\n for bc in F[filekey][noisekey]:\n bc = int(bc)\n if( bc == 0 ):\n log_bc.append( log(1) )\n else:\n log_bc.append( log(bc) )\n\n slopes = []\n # Calculate Dimension slopes by taking delta(log(boxcounts) / delta(log(1/d))\n for i in range(len(d)-1):\n slopes.append( (log_bc[i] - log_bc[i+1]) / (log(1/d[i]) - log(1/d[i+1])) )\n\n if( noisekey == \"0.0\" ):\n print(\"NoiseKey:\", noisekey, \"Slopes: \", slopes)\n x += slopes # append slopes to x\n if( noisekey == \"0.001\" ):\n print(\"NoiseKey:\", noisekey, \"Slopes: \", slopes)\n y += slopes # append slopes to x\n \n dim_mean = np.mean(slopes)\n \n # Need to calculate the variance of the dimensional slopes (dsl_var)\n dsl_var = np.var(slopes, ddof=1) #ddof = 1 matches old-style variance calculations\n\n # Add each dim/var calculation to an array and store in results.\n if noisekey in R:\n R[noisekey].append( (dim_mean,dsl_var) )\n else:\n R[noisekey] = [ (dim_mean,dsl_var) ]\n\n # Plot slopes\n # the histogram of the data\n print(\">> Counted\", len(x), \"slopes...\")\n print(\">> Slope vector: \", x)\n binCount = 50\n n, bins, patches = plt.hist(x, binCount, normed=1, facecolor='green', alpha=0.50)\n n, bins, patches = plt.hist(y, binCount, normed=1, facecolor='red', alpha=0.50)\n # add a 'best fit' line\n #y = mlab.normpdf( bins, mu, sigma )\n #l = plt.plot(bins, y, 'r--', linewidth=1)\n\n plt.xlabel('Dimensional Estimate')\n plt.ylabel('Count')\n #plt.title(r'$\\mathrm{Histogram\\ of\\ IQ:}\\ \\mu=100,\\ \\sigma=15$')\n #plt.axis([1,2.1,0,20])\n plt.grid(True)\n\n plt.show()\n\n\n\n\n\n\n # Now all the results should be processed; currently R is an array of tuples (Dim, Var)\n print(\"Size of R:\", len(R), \"# results:\",len(R['0.2']))\n #print(\">>\",R['0.2'])\n\n # separate the values and run statistics on them.\n aggregated_results = [] # store final data to print here\n for noisekey in R:\n dim_array = []\n dsl_array = []\n # separate the data\n for dataset in R[noisekey]: # dataset is 100 pairs of (Dim, Var)\n dim_array.append(dataset[0])\n dsl_array.append(dataset[1])\n \n # calculate statistics\n average_dimensional_estimate = np.mean(dim_array)\n average_slope_variance_estimate = np.mean(dsl_array)\n dim_standard_error = np.std(dim_array,ddof=1)/len(R[noisekey])\n dsl_standard_error = np.std(dsl_array,ddof=1)/len(R[noisekey])\n # add to aggregated results\n aggregated_results.append( (float(noisekey), average_dimensional_estimate, dim_standard_error, average_slope_variance_estimate, dsl_standard_error) )\n\n aggregated_results.sort()\n \n #for item in aggregated_results:\n # print(\">> \", item)\n \n # TODO: Need to save this data to a file\n aggregate_datalog( aggregated_results, filelist, image_name )\n \n # Attempt to plot:\n nx = []\n dimy = []\n vary = []\n dimerr = []\n varerr = []\n for item in aggregated_results:\n nx.append( item[0] )\n dimy.append( item[1] )\n dimerr.append( item[2] )\n vary.append( item[3] )\n varerr.append( item[4] )\n\n fig, axarr = plt.subplots(2, sharex=True)\n fig.suptitle(\"Box Count Algorithm on \" + image_name + \" (Uniform Noise, 100 Seeds)\", fontsize=14, fontweight='bold')\n axarr[0].set_ylabel(\"dimension\")\n axarr[0].set_xscale('log')\n axarr[0].set_title(\"Mean Fractal Dimension vs. Noise %\")\n axarr[0].set_ylim(0,2)\n axarr[0].errorbar(nx,dimy,dimerr,fmt='r')\n axarr[0].plot(nx,dimy, label=\"dimension\")\n\n axarr[1].set_ylabel(\"slope variance\")\n axarr[1].set_xlabel(\"noise %\")\n axarr[1].set_xscale('log')\n axarr[1].set_title(\"Mean Slope Variance vs. Noise %\")\n axarr[1].set_ylim(0,1)\n axarr[1].errorbar(nx,vary,varerr,fmt='r')\n axarr[1].plot(nx,vary, label=\"variance\")\n\n plt.savefig(\"figures/\" + image_name + \"_uniform_D_V_vs_N.png\")\n #plt.show()\n \n\n# results_array - an array of tuples of the form (noise, dimension, dimension std err, variance, variance std err)\n# filelist - a list of filenames that were included in the aggregated data\n# Version: V1.00 - initial log format\ndef aggregate_datalog( results_array, filelist, image_name ):\n LOG_VERSION = \"1.00\"\n pathname = \"logfiles/\"\n filename = pathname + image_name + \"_\" + str(len(filelist)) + \"_aggregateLog.csv\"\n\n log = open(filename, 'w')\n # Write the header\n log.write(\"# Aggregate Log Version: \" + LOG_VERSION + \",,,,\\n\")\n log.write(\"# Log Name: \" + filename + \",,,,\\n\")\n log.write(\"# Noise%, Dimension, Dim Std Err, Variance, Var Std Err\\n\")\n\n # Write the data\n for data in results_array:\n log.write(str(data[0]) + \",\" + str(data[1]) + \",\" + str(data[2]) + \",\" + str(data[3]) + \",\" + str(data[4]) + \"\\n\")\n\n # Write a list of the files included in this data aggregation\n log.write(\"# The data files below are included in this aggregation:,,,,\\n\")\n for file in filelist:\n log.write(\"# \" + file + \",,,,\\n\")\n\n print(\">> Created aggregate datalog:\", filename)\n log.close()\n\n \n \n \n\n\n\n\n\n\n\nmain()\n'''\n\n# example data\n#x = np.arange(0, 10, 1)\nnoise = np.array([0.0001, 0.001, 0.01, 0.1, 1, 10, 50])\ndim = np.array([1.1, 1.15, 1.3, 1.6, 1.85, 1.95, 2])\nvar = np.array([0.1, 0.3, 0.2, 0.1, 0.01, 0.001, 0])\n\n\n\n# example variable error bar values\nstderr = np.array([.01,.1,.1,.05,.02,.01,0])\n#xerr = 0.1 + yerr\n\n# First illustrate basic byplot interface, using defaults where possible\n#fig = plt.figure() # what does this do?\n#fig.suptitle(\"Main Title\", fontsize=14, fontweight='bold')\n\n\nfig, axarr = plt.subplots(2, sharex=True)\nfig.suptitle(\"Dimension and Slope Variance vs. Noise %\", fontsize=14, fontweight='bold')\naxarr[0].set_ylabel(\"dimension\")\naxarr[0].set_xscale('log')\naxarr[0].errorbar(noise,dim,stderr,fmt='ro')\naxarr[0].plot(noise,dim, label=\"dimension\")\n\naxarr[1].set_ylabel(\"slope variance\")\naxarr[1].set_xlabel(\"noise %\")\naxarr[1].set_xscale('log')\naxarr[1].errorbar(noise,var,stderr,fmt='ro')\naxarr[1].plot(noise,var, label=\"variance\")\n\n'''\n\n'''\n# create subplot (so that axis can be manipulated\nax = fig.add_subplot(111)\nax.set_title(\"subtitle\")\nax.set_xlabel(\"noise axis\")\nax.set_ylabel(\"dimension\")\nax.set_xscale('log') # set x-axis to log scale\n\n#plt.errorbar(x, dim, yerr=yerr, fmt='ro') # error bar plot, formatting\nax.errorbar(noise,dim, stderr, fmt='ro')\nax.errorbar(noise,var, stderr, fmt='ro')\nax.plot(noise,dim) # normal plot, formatting\nax.plot(noise,var)\n#plt.title(\"Simplest errorbars, 0.2 in x, 0.4 in y\")\n'''\n\n'''\nplt.savefig(\"thesisPlotsExcample.png\")\n\nplt.show()\n'''\n\n\n\n\n"
] |
[
[
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.std",
"numpy.mean",
"matplotlib.pyplot.grid",
"numpy.var",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mexuaz/AccTrussDecomposition
|
[
"15a9e8fd2f123f5acace5f3b40b94f1a74eb17d4"
] |
[
"python_experiments/data_analysis/figures_icde19/opt_gpu.py"
] |
[
"import json\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom data_analysis.figures_icde19.general_config import *\nfrom data_analysis.figures_icde19.parse_overall.parse_gpu_results import varying_gpu_tag, summary_tag, \\\n off_tc_tag, off_cpu_iep_tag, off_gpu_iep_tag, off_iep_total_tag, config_lst\nfrom data_analysis.figures_icde19.parse_overall.parse_support_initialization import si_dir\nfrom data_analysis.util.read_file_utils import *\nfrom data_analysis.vis.vis_util import *\n\nFIG_SIZE_MULTIPLE = (16, 4.5)\n\ndata_set_lst = ['webgraph_eu', 'webgraph_it', 'webgraph_twitter']\ncuda_off_load_opt = 'cuda-pkt-offload-opt'\ncuda_off_load = 'cuda-pkt-offload'\ncuda_off_load_shrink = 'cuda-pkt-shrink-all-opt'\n\n\ndef get_opt_cpu_tc_lst():\n with open('{}/{}/{}'.format('parse_overall', si_dir, 'pkt-eval-tc-wp.json')) as ifs:\n tc_wp_si = json.load(ifs)\n return [tc_wp_si[data]['40'] for data in data_set_lst]\n\n\ndef get_opt_cpu_iep_lst(cpu_exp_dir='exp-2019-10-04-eid'):\n with open('parse_overall/varying_cpu/{}/{}.json'.format(cpu_exp_dir, 'pkt-bmpf')) as ifs:\n bmpf_dict = json.load(ifs)\n with open('parse_overall/varying_cpu/{}/{}.json'.format(cpu_exp_dir, 'pkt-inter-shrink')) as ifs:\n bmpf_idx_dict = json.load(ifs)\n\n def get_single_iep_time(data_dict, data):\n return sum([data_dict[data][tag] for tag in [\"Sync Time\", \"Shrink Time\", \"Scan Time\", \"Proc Time\"]])\n\n return [min(get_single_iep_time(bmpf_dict, data), get_single_iep_time(bmpf_idx_dict, data)) for data in\n data_set_lst]\n\n\ndef get_off_iep_with_tag(tag, exec_name, lst):\n with open('parse_overall/{}/{}/{}.json'.format(varying_gpu_tag, config_lst[0], exec_name)) as ifs:\n cuda_offload_opt_dict = json.load(ifs)\n return [cuda_offload_opt_dict[data][summary_tag][tag] for data in lst]\n\n\ndef get_off_tc():\n return get_off_iep_with_tag(off_tc_tag, cuda_off_load_opt, data_set_lst)\n\n\nbar_lst_lst = [\n get_opt_cpu_tc_lst(), # OPT-CPU-TC\n get_off_tc(), # OFF-TC\n get_opt_cpu_iep_lst(), # OPT-CPU-IEP\n get_off_iep_with_tag(off_iep_total_tag, cuda_off_load_shrink, data_set_lst),\n get_off_iep_with_tag(off_iep_total_tag, cuda_off_load_opt, data_set_lst),\n get_off_iep_with_tag(off_cpu_iep_tag, cuda_off_load_opt, data_set_lst),\n get_off_iep_with_tag(off_gpu_iep_tag, cuda_off_load_opt, data_set_lst),\n]\n\nbar_legend_lst = ['\\\\textbf{' + name + '}' for name in\n ['OPT-TC', 'OFF-TC', 'OPT-IEP', 'OFF-EIEP',\n 'OFF-RIEP-Total',\n 'OFF-RIEP-CPU',\n 'OFF-RIEP-GPU']]\n\ndataset_abbr_lst = ['WE', 'WI', 'TW']\n\nfor idx, bar_lst in enumerate(bar_lst_lst):\n print(bar_legend_lst[idx], bar_lst)\n\n\ndef draw_bars(bar_lst_lst, legend_label_lst, x_tick_label_lst, x_label_name, fig_folder, file_name):\n size_of_fig = (FIG_SIZE_MULTIPLE[0], FIG_SIZE_MULTIPLE[1])\n fig, ax = plt.subplots()\n\n assert len(bar_lst_lst) > 0\n N = len(bar_lst_lst[0])\n assert N == len(x_tick_label_lst)\n\n # indent lst\n width = 1.1 / len(legend_label_lst)\n ind = 1.3 * np.arange(N) # the x locations for the groups\n indent_lst = [ind + idx * width for idx in range(len(bar_lst_lst))]\n\n for i in range(2, 5):\n indent_lst[i] += 0.3 * width\n for i in range(5, 7):\n indent_lst[i] += 0.6 * width\n\n # 1st: bars\n for idx, bar_lst in enumerate(bar_lst_lst):\n my_bar = ax.bar(indent_lst[idx], bar_lst, width, hatch=hatch_lst[idx], label=legend_label_lst[idx],\n edgecolor=color_lst[idx], fill=False)\n autolabel(ax, my_bar, roration=45, fontsize=20)\n\n # 2nd: x and y's ticks and labels\n ax.set_xticks(ind + 3.3 * width)\n ax.set_xticklabels(x_tick_label_lst, fontsize=LABEL_SIZE)\n plt.xticks(fontsize=TICK_SIZE)\n\n plt.yscale('log')\n ax.set_ylabel(\"Time (seconds)\", fontsize=LABEL_SIZE)\n plt.yticks(fontsize=TICK_SIZE)\n\n max_val = max([max(lst) for lst in bar_lst_lst])\n min_val = min([min(list(filter(lambda v: v != 0, lst)) + [max_val]) for lst in bar_lst_lst])\n\n plt.ylim(min_val / 3, max_val * (10 ** 3) * 40)\n plt.yticks(list(filter(lambda v: v > min_val / 10, [10 ** i for i in range(-1, 5, 1)])))\n\n ax.set_xlabel(x_label_name, fontsize=LABEL_SIZE)\n\n # 3rd: figure properties\n fig.set_size_inches(*size_of_fig) # set ratio\n plt.legend(legend_label_lst,\n prop={'size': LEGEND_SIZE - 3, \"weight\": \"bold\"}, loc=\"upper left\", ncol=4)\n\n plt.tight_layout()\n\n os.system('mkdir -p ' + fig_folder)\n fig.savefig(os.sep.join([fig_folder, file_name]), bbox_inches='tight', dpi=300)\n plt.close()\n\n\ndef option_time_tag_wrapper(obj):\n return obj[time_tag] if obj is not None else 0\n\n\nif __name__ == '__main__':\n # matplotlib.rc('pdf', fonttype=42)\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n\n for suffix in ['.pdf']:\n def draw_varying_algorithm():\n draw_bars(bar_lst_lst, bar_legend_lst, dataset_abbr_lst, 'Dataset',\n '../data-pdf/icde20', 'OFF-opts' + suffix)\n\n\n draw_varying_algorithm()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.ylim",
"numpy.arange",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xticks"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yrik/datasketch
|
[
"82d9639bc0011932a952bbae1d4b5bd5ac03c7c8",
"82d9639bc0011932a952bbae1d4b5bd5ac03c7c8",
"82d9639bc0011932a952bbae1d4b5bd5ac03c7c8"
] |
[
"benchmark/lsh_benchmark_plot.py",
"benchmark/inclusion_benchmark.py",
"benchmark/b_bit_minhash_benchmark.py"
] |
[
"import json, sys, argparse\nimport numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\n\ndef get_precision_recall(found, reference):\n reference = set(reference)\n intersect = sum(1 for i in found if i in reference)\n if len(found) == 0:\n precision = 0.0\n else:\n precision = float(intersect) / float(len(found))\n if len(reference) == 0:\n recall = 1.0\n else:\n recall = float(intersect) / float(len(reference))\n if len(found) == len(reference) == 0:\n precision = 1.0\n recall = 1.0\n return [precision, recall]\n\ndef fscore(precision, recall):\n if precision == 0.0 and recall == 0.0:\n return 0.0\n return 2.0 / (1.0 / precision + 1.0 / recall)\n\ndef average_fscore(founds, references):\n return np.mean([fscore(*get_precision_recall(found, reference))\n for found, reference in zip(founds, references)])\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"benchmark_output\")\n args = parser.parse_args(sys.argv[1:])\n\n with open(args.benchmark_output) as f:\n benchmark = json.load(f) \n\n num_perms = benchmark[\"num_perms\"]\n lsh_times = benchmark[\"lsh_times\"]\n linearscan_times = benchmark[\"linearscan_times\"]\n ground_truth_results = [[x[0] for x in r] for r in benchmark[\"ground_truth_results\"]]\n lsh_fscores = []\n for results in benchmark[\"lsh_results\"]:\n query_results = [[x[0] for x in r] for r in results]\n lsh_fscores.append(average_fscore(query_results, ground_truth_results))\n linearscan_fscores = []\n for results in benchmark[\"linearscan_results\"]:\n query_results = [[x[0] for x in r] for r in results]\n linearscan_fscores.append(average_fscore(query_results, ground_truth_results))\n\n lsh_times = np.array([np.percentile(ts, 90) \n for ts in lsh_times])*1000\n linearscan_times = np.array([np.percentile(ts, 90) \n for ts in linearscan_times])*1000\n\n fig, axes = plt.subplots(1, 2, figsize=(5*2, 4.5), sharex=True)\n # Plot query fscore vs. num perm\n axes[0].plot(num_perms, linearscan_fscores, marker=\"+\", label=\"Linearscan\")\n axes[0].plot(num_perms, lsh_fscores, marker=\"+\", label=\"LSH\")\n axes[0].set_ylabel(\"Average F-Score\")\n axes[0].set_xlabel(\"# of Permmutation Functions\")\n axes[0].grid()\n # Plot query time vs. num perm\n axes[1].plot(num_perms, linearscan_times, marker=\"+\", label=\"Linearscan\")\n axes[1].plot(num_perms, lsh_times, marker=\"+\", label=\"LSH\")\n axes[1].set_xlabel(\"# of Permutation Functions\")\n axes[1].set_ylabel(\"90 Percentile Query Time (ms)\")\n axes[1].grid()\n axes[1].legend(loc=\"center right\")\n fig.savefig(\"lsh_benchmark.png\", pad_inches=0.05, bbox_inches=\"tight\")\n",
"'''\nTest the accuracy of inclusion estimation using data sketches\nMust be using Python 2 as pyhash does not support Python 3\nHyperLogLog inclusion score is computed using cardinality estimate\nand inclusion-exclusion principle.\nMinHash inclusion score is computed using Jaccard estiamte,\ninclusion-exclusion principle, and the exact cardinality.\n'''\nimport time, logging, random, struct\nimport pyhash\nfrom datasketch.hyperloglog import HyperLogLog\nfrom datasketch.minhash import MinHash\n\nlogging.basicConfig(level=logging.INFO)\n\n# Produce some bytes\nint_bytes = lambda x : (\"a-%d-%d\" % (x, x)).encode('utf-8')\n\nclass Hash(object):\n def __init__(self, h):\n self.h = h\n def digest(self):\n return struct.pack('<I', self.h)\n\ndef _gen_data(size):\n return [int_bytes(i) for i in range(size)]\n\ndef _get_exact(A, B):\n (a_start, a_end) = A\n (b_start, b_end) = B\n overlap = min(a_end, b_end) - max(a_start, b_start)\n if overlap < 0:\n overlap = 0\n return float(overlap) / abs(a_start - a_end)\n\ndef _minhash_inclusion(m1, m2):\n c1 = m1.count()\n c2 = m2.count()\n j = m1.jaccard(m2)\n return (j / (j + 1.0)) * (1.0 + float(c2) / float(c1))\n\ndef _hyperloglog_inclusion(h1, h2):\n c1 = h1.count()\n if c1 == 0.0:\n return 1.0\n c2 = h2.count()\n uc = HyperLogLog.union(h1, h2).count()\n ic = c1 + c2 - uc\n return ic / c1\n\ndef _run_hyperloglog(A, B, data, seed, p):\n (a_start, a_end), (b_start, b_end) = A, B\n hasher = pyhash.murmur3_32()\n h1 = HyperLogLog(p=p, hashobj=Hash)\n h2 = HyperLogLog(p=p, hashobj=Hash)\n for i in xrange(a_start, a_end):\n h1.update(hasher(data[i], seed=seed))\n for i in xrange(b_start, b_end):\n h2.update(hasher(data[i], seed=seed))\n return _hyperloglog_inclusion(h1, h2)\n\ndef _run_minhash(A, B, data, seed, p):\n (a_start, a_end), (b_start, b_end) = A, B\n hasher = pyhash.murmur3_32()\n m1 = MinHash(num_perm=2**p, hashobj=Hash)\n m2 = MinHash(num_perm=2**p, hashobj=Hash)\n for i in xrange(a_start, a_end):\n m1.update(hasher(data[i], seed=seed))\n for i in xrange(b_start, b_end):\n m2.update(hasher(data[i], seed=seed))\n return _minhash_inclusion(m1, m2)\n\ndef _run_test(A, B, data, n, p):\n logging.info(\"Running HyperLogLog with p = %d\" % p)\n hll_runs = [_run_hyperloglog(A, B, data, i, p) for i in xrange(n)]\n logging.info(\"Running MinHash with num_perm = %d\" % 2**p)\n minhash_runs = [_run_minhash(A, B, data, i, p) for i in xrange(n)]\n return (hll_runs, minhash_runs)\n\n\ndef run_full_tests(A, B, data, n, p_list):\n logging.info(\"Run tests with A = (%d, %d), B = (%d, %d), n = %d\"\n % (A[0], A[1], B[0], B[1], n))\n return [_run_test(A, B, data, n, p) for p in p_list]\n\n\ndef plot_hist(ax, est_sims, bins, title, exact_sim):\n ax.hist(est_sims, bins, histtype='stepfilled', facecolor='g', alpha=0.75)\n ax.axvline(exact_sim, color='black', linestyle='--')\n ax.set_title(title)\n ax.set_xlabel(\"Estimation (Actual = %.4f)\" % exact_sim)\n\n\ndef plot(result, p_list, exact_sim, bins, save):\n import matplotlib\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n num_row = 2\n num_col = len(result)\n basesize = 5\n size = (basesize*num_col, basesize*num_row)\n fig, axes = plt.subplots(num_row, num_col, sharex=True, figsize=size)\n for i, (hll, minhash) in enumerate(result):\n title = \"HyperLogLog p = \" + r\"$2^{%d}$\" % p_list[i]\n plot_hist(axes[0][i], hll, bins, title, exact_sim)\n title = \"MinHash num_perm = \" + r\"$2^{%d}$\" % p_list[i]\n plot_hist(axes[1][i], minhash, bins, title, exact_sim)\n fig.savefig(save)\n\n\nif __name__ == \"__main__\":\n data = _gen_data(5000)\n A = (0, 3000)\n B = (2500, 5000)\n exps = [6, 8, 10]\n p_list = exps\n n = 100\n save = \"inclusion_benchmark.png\"\n bins = [i*0.02 for i in range(50)]\n exact_sim = _get_exact(A, B)\n result = run_full_tests(A, B, data, n, p_list)\n plot(result, p_list, exact_sim, bins, save)\n",
"'''\nBenchmarking the performance and accuracy of b-bi MinHash.\n'''\nimport time, logging, random\nlogging.basicConfig(level=logging.INFO)\nimport pyhash\nimport numpy as np\nfrom datasketch.minhash import MinHash\nfrom datasketch.b_bit_minhash import bBitMinHash\nfrom similarity_benchmark import _get_exact, _gen_data,\\\n Hash, _b_bit_minhash_jaccard\n\ndef _run_minhash(A, B, data, seed, bs, num_perm):\n (a_start, a_end), (b_start, b_end) = A, B\n hasher = pyhash.murmur3_32()\n m1 = MinHash(num_perm=num_perm, hashobj=Hash)\n m2 = MinHash(num_perm=num_perm, hashobj=Hash)\n for i in xrange(a_start, a_end):\n m1.update(hasher(data[i], seed=seed))\n for i in xrange(b_start, b_end):\n m2.update(hasher(data[i], seed=seed))\n return [m1.jaccard(m2)] + \\\n [_b_bit_minhash_jaccard(m1, m2, b) for b in bs]\n\ndef _run_test(A, B, data, n, bs, num_perm):\n logging.info(\"Run tests with A = (%d, %d), B = (%d, %d), n = %d\"\n % (A[0], A[1], B[0], B[1], n))\n runs = np.array([_run_minhash(A, B, data, i, bs, num_perm)\n for i in xrange(n)]).T\n return runs\n\ndef run_full_tests(attr_pairs, data, n, bs, num_perm):\n return [_run_test(A, B, data, n, bs, num_perm)\n for A, B in attr_pairs]\n\ndef plot(result, bs, exact_sims, num_perm, bins, save):\n import matplotlib\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n num_row = 1\n num_col = len(result)\n basesize = 5\n size = (basesize*num_col, basesize*num_row)\n fig, axes = plt.subplots(num_row, num_col, sharey=True,\n sharex=True, figsize=size)\n for i, runs in enumerate(result):\n minhash = sorted(runs[0])\n bbits = [sorted(r) for r in runs[1:]]\n exact_sim = exact_sims[i]\n ax = axes[i]\n l = ax.plot(minhash, label='MinHash')\n for b, run in zip(bs, bbits):\n l = ax.plot(run, label='%d-bit' % b)\n ax.axhline(exact_sim, color='black', linestyle='--', label='Exact')\n ax.set_title(\"%d perm funcs, exact = %.2f\" % (num_perm, exact_sim))\n ax.grid()\n ax.set_xlabel(\"Runs with random hash functions\")\n if i == 0:\n ax.set_ylabel('Jaccard')\n if i == num_col - 1:\n ax.legend(loc='lower right')\n fig.savefig(save)\n\n\nif __name__ == \"__main__\":\n data = _gen_data(5000)\n attr_pairs = [((0, 3000), (2000, 5000)),\n ((0, 3500), (1500, 5000)),\n ((0, 4500), (500, 5000))]\n num_perm = 128\n bs = [1, 2, 3]\n n = 100\n save = \"b_bit_minhash_benchmark.png\"\n bins = [i*0.02 for i in range(51)]\n exact_sims = [_get_exact(A, B) for A, B in attr_pairs]\n result = run_full_tests(attr_pairs, data, n, bs, num_perm)\n plot(result, bs, exact_sims, num_perm, bins, save)\n"
] |
[
[
"matplotlib.use",
"matplotlib.pyplot.subplots",
"numpy.percentile"
],
[
"matplotlib.use",
"matplotlib.pyplot.subplots"
],
[
"matplotlib.use",
"matplotlib.pyplot.subplots"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
scheng1992/Data_Assimilation
|
[
"2965ccf78951df11f8686282cd6814bae18afde5",
"2965ccf78951df11f8686282cd6814bae18afde5"
] |
[
"diagnostics/AE_time_loop_grad.py",
"src/VarDACAE/nn/CBAM.py"
] |
[
"import torch\nimport sys, os\n\nsys.path.append(os.getcwd()) #to import pipeline\n\nfrom pipeline.utils import ML_utils as ML\nfrom pipeline.AutoEncoders import ToyAE\nfrom pipeline import utils\n\nimport time\nimport matplotlib.pyplot as plt\n\ndef plot_time_w_output(outputs, inn, hidden, batch_sz, loop=True, no_batch=False):\n\n T_2s = []\n T_1s = []\n factors = []\n\n utils.set_seeds(42)\n input = torch.rand((Batch_sz, inn), requires_grad=True)\n if no_batch:\n input = input[0]\n\n for out_sz in outputs:\n model = ToyAE(inn, hidden, out_sz)\n model.gen_rand_weights()\n output = model.decode(input)\n t0 = time.time()\n if loop:\n jac_true = ML.jacobian_slow_torch(input, output)\n t1 = time.time()\n jac_expl = model.jac_explicit(input)\n t2 = time.time()\n T_1 = t1-t0\n T_2 = t2-t1\n\n try:\n factor = T_1 / T_2\n except ZeroDivisionError:\n factor = 0\n\n T_1s.append(T_1)\n T_2s.append(T_2)\n factors.append(factor)\n if loop:\n print(\"out = {}. Explicit x{:.1f} faster than loop method\".format(out_sz, factor))\n if loop:\n plt.plot(outputs, T_1s)\n plt.show()\n plt.plot(outputs, factors)\n plt.show()\n plt.plot(outputs, T_2s)\n plt.show()\n\n\nif __name__ == \"__main__\":\n INPUT = 32\n HIDDEN = 128\n Batch_sz = 64\n outputs = [2**x for x in range(8)]\n plot_time_w_output(outputs, INPUT, HIDDEN, Batch_sz, loop=True, no_batch=False)\n\n",
"\n\"\"\"\nImplementation of CBAM: Convolutional Block Attention Module\n(https://arxiv.org/pdf/1807.06521.pdf) for 3D case.\n\nThis is based on the following opensource implementation:\nhttps://github.com/Jongchan/attention-module/blob/master/MODELS/cbam.py\n\nReleased under MIT licence: https://github.com/Jongchan/attention-module/blob/master/LICENSE\n\"\"\"\n\nimport torch\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom VarDACAE.nn.helpers import get_activation\nfrom VarDACAE import nn as pnn\n\nclass BasicConv(nn.Module):\n \"\"\"This is edited so that it works for 3D case\"\"\"\n\n def __init__(self, encode, activation_constructor, in_planes, out_planes, kernel_size,\n stride=1, padding=0, dilation=1, groups=1, activation=True,\n bn=True, bias=False):\n super(BasicConv, self).__init__()\n self.out_channels = out_planes\n self.conv = nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size,\n stride=stride, padding=padding, dilation=dilation,\n groups=groups, bias=bias)\n self.bn = nn.BatchNorm3d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None\n self.act = activation_constructor(out_planes, not encode) if activation else None\n\n def forward(self, x):\n x = self.conv(x)\n if self.bn is not None:\n x = self.bn(x)\n if self.act is not None:\n x = self.act(x)\n return x\n\nclass Flatten(nn.Module):\n def forward(self, x):\n return x.view(x.size(0), -1)\n\nclass ChannelGate(nn.Module):\n def __init__(self, encode, activation_constructor, gate_channels,\n reduction_ratio=8, pool_types=['avg', 'max']):\n super(ChannelGate, self).__init__()\n self.gate_channels = gate_channels\n\n Cinner = gate_channels // reduction_ratio\n Cinner = Cinner if Cinner > 0 else 1\n self.mlp = nn.Sequential(\n Flatten(),\n nn.Linear(gate_channels, Cinner),\n activation_constructor(Cinner, not encode),\n nn.Linear(Cinner, gate_channels)\n )\n self.pool_types = pool_types\n def forward(self, x):\n\n channel_att_sum = None\n\n k_size = (x.size(2), x.size(3), x.size(4))\n for pool_type in self.pool_types:\n if pool_type=='avg':\n avg_pool = F.avg_pool3d( x, k_size, stride=k_size)\n\n channel_att_raw = self.mlp( avg_pool )\n elif pool_type=='max':\n max_pool = F.max_pool3d( x, k_size, stride=k_size)\n channel_att_raw = self.mlp( max_pool )\n elif pool_type=='lp':\n lp_pool = F.lp_pool3d( x, 2, k_size, stride=k_size)\n channel_att_raw = self.mlp( lp_pool )\n elif pool_type=='lse':\n # LSE pool only\n lse_pool = logsumexp_2d(x)\n channel_att_raw = self.mlp( lse_pool )\n\n if channel_att_sum is None:\n channel_att_sum = channel_att_raw\n else:\n channel_att_sum = channel_att_sum + channel_att_raw\n\n\n scale = torch.sigmoid( channel_att_sum ).unsqueeze(2).unsqueeze(3).unsqueeze(4).expand_as(x)\n\n return x * scale\n\ndef logsumexp_2d(tensor):\n\n tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), -1)\n s, _ = torch.max(tensor_flatten, dim=2, keepdim=True)\n outputs = s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log()\n return outputs\n\nclass ChannelPool(nn.Module):\n def forward(self, x):\n return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )\n\nclass SpatialGate(nn.Module):\n def __init__(self, encode, activation_constructor, kernel_size=7):\n super(SpatialGate, self).__init__()\n assert kernel_size % 2 == 1\n self.compress = ChannelPool()\n self.spatial = BasicConv(encode, activation_constructor, 2, 1, kernel_size,\n stride=1, padding=(kernel_size-1) // 2,\n activation=False)\n def forward(self, x):\n x_compress = self.compress(x)\n x_out = self.spatial(x_compress)\n scale = torch.sigmoid(x_out) # broadcasting\n return x * scale\n\nclass CBAM(nn.Module):\n def __init__(self, encode, activation_constructor, gate_channels, reduction_ratio=8,\n pool_types=['avg', 'max'], no_spatial=False, kernel_size=7):\n super(CBAM, self).__init__()\n if get_activation(activation_constructor) == \"GDN\":\n channel_act_constr = pnn.builder.NNBuilder.act_constr(\"prelu\")\n else:\n channel_act_constr = activation_constructor\n\n self.channelgate = ChannelGate(encode, channel_act_constr, gate_channels,\n reduction_ratio, pool_types)\n self.no_spatial=no_spatial\n if not no_spatial:\n self.spatialgate = SpatialGate(encode, activation_constructor, kernel_size)\n def forward(self, x):\n x_out = self.channelgate(x)\n if not self.no_spatial:\n x_out = self.spatialgate(x_out)\n return x_out\n\n\n\n\nif __name__ == \"__main__\":\n model = CBAM(activation_constructor, 32, reduction_ratio=16, pool_types=['avg', 'max'])\n print(model)\n num_params = sum(p.numel() for p in model.parameters())\n print(\"number params:\", num_params)"
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"torch.rand"
],
[
"torch.mean",
"torch.sigmoid",
"torch.max",
"torch.nn.functional.max_pool3d",
"torch.nn.Linear",
"torch.nn.Conv3d",
"torch.nn.functional.avg_pool3d",
"torch.nn.functional.lp_pool3d",
"torch.nn.BatchNorm3d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Omkar-Ranadive/Fine-Tuning-BERT
|
[
"b046092ec4007a4a59e1a478576cca7557c18d76"
] |
[
"src/train.py"
] |
[
"#!/usr/bin/env python\n\"\"\"\n Main training workflow\n\"\"\"\nfrom __future__ import division\n\nimport argparse\nimport glob\nimport os\nimport random\nimport signal\nimport time\n\nimport torch\nfrom pytorch_pretrained_bert import BertConfig\n\nimport distributed\nfrom models import data_loader, model_builder\nfrom models.data_loader import load_dataset\nfrom models.model_builder import Summarizer\nfrom models.trainer import build_trainer\nfrom others.logging import logger, init_logger\n\nimport matplotlib.pyplot as plt\nfrom src.utils import save_pickle\n\nmodel_flags = ['hidden_size', 'ff_size', 'heads', 'inter_layers','encoder','ff_actv', 'use_interval','rnn_size']\n\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\n\ndef multi_main(args):\n \"\"\" Spawns 1 process per GPU \"\"\"\n init_logger()\n\n nb_gpu = args.world_size\n mp = torch.multiprocessing.get_context('spawn')\n\n # Create a thread to listen for errors in the child processes.\n error_queue = mp.SimpleQueue()\n error_handler = ErrorHandler(error_queue)\n\n # Train with multiprocessing.\n procs = []\n for i in range(nb_gpu):\n device_id = i\n procs.append(mp.Process(target=run, args=(args,\n device_id, error_queue,), daemon=True))\n procs[i].start()\n logger.info(\" Starting process pid: %d \" % procs[i].pid)\n error_handler.add_child(procs[i].pid)\n for p in procs:\n p.join()\n\n\ndef run(args, device_id, error_queue):\n\n \"\"\" run process \"\"\"\n setattr(args, 'gpu_ranks', [int(i) for i in args.gpu_ranks])\n\n try:\n gpu_rank = distributed.multi_init(device_id, args.world_size, args.gpu_ranks)\n print('gpu_rank %d' %gpu_rank)\n if gpu_rank != args.gpu_ranks[device_id]:\n raise AssertionError(\"An error occurred in \\\n Distributed initialization\")\n\n train(args,device_id)\n except KeyboardInterrupt:\n pass # killed by parent, do nothing\n except Exception:\n # propagate exception to parent process, keeping original traceback\n import traceback\n error_queue.put((args.gpu_ranks[device_id], traceback.format_exc()))\n\n\nclass ErrorHandler(object):\n \"\"\"A class that listens for exceptions in children processes and propagates\n the tracebacks to the parent process.\"\"\"\n\n def __init__(self, error_queue):\n \"\"\" init error handler \"\"\"\n import signal\n import threading\n self.error_queue = error_queue\n self.children_pids = []\n self.error_thread = threading.Thread(\n target=self.error_listener, daemon=True)\n self.error_thread.start()\n signal.signal(signal.SIGUSR1, self.signal_handler)\n\n def add_child(self, pid):\n \"\"\" error handler \"\"\"\n self.children_pids.append(pid)\n\n def error_listener(self):\n \"\"\" error listener \"\"\"\n (rank, original_trace) = self.error_queue.get()\n self.error_queue.put((rank, original_trace))\n os.kill(os.getpid(), signal.SIGUSR1)\n\n def signal_handler(self, signalnum, stackframe):\n \"\"\" signal handler \"\"\"\n for pid in self.children_pids:\n os.kill(pid, signal.SIGINT) # kill children processes\n (rank, original_trace) = self.error_queue.get()\n msg = \"\"\"\\n\\n-- Tracebacks above this line can probably\n be ignored --\\n\\n\"\"\"\n msg += original_trace\n raise Exception(msg)\n\n\n\ndef wait_and_validate(args, device_id):\n\n timestep = 0\n if (args.test_all):\n print(\"In here!\")\n cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))\n cp_files.sort(key=os.path.getmtime)\n print(\"Cp files\", cp_files)\n xent_lst = []\n for i, cp in enumerate(cp_files):\n step = int(cp.split('.')[-2].split('_')[-1])\n xent = validate(args, device_id, cp, step)\n xent_lst.append((xent, cp))\n max_step = xent_lst.index(min(xent_lst))\n if (i - max_step > 10):\n break\n xent_lst = sorted(xent_lst, key=lambda x: x[0])[:3]\n logger.info('PPL %s' % str(xent_lst))\n for xent, cp in xent_lst:\n step = int(cp.split('.')[-2].split('_')[-1])\n test(args, device_id, cp, step)\n else:\n while (True):\n cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))\n cp_files.sort(key=os.path.getmtime)\n if (cp_files):\n cp = cp_files[-1]\n time_of_cp = os.path.getmtime(cp)\n if (not os.path.getsize(cp) > 0):\n time.sleep(60)\n continue\n if (time_of_cp > timestep):\n timestep = time_of_cp\n step = int(cp.split('.')[-2].split('_')[-1])\n validate(args, device_id, cp, step)\n test(args, device_id, cp, step)\n\n cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt')))\n cp_files.sort(key=os.path.getmtime)\n if (cp_files):\n cp = cp_files[-1]\n time_of_cp = os.path.getmtime(cp)\n if (time_of_cp > timestep):\n continue\n else:\n time.sleep(300)\n\n\ndef validate(args, device_id, pt, step):\n device = \"cpu\" if args.visible_gpus == '-1' else \"cuda\"\n if (pt != ''):\n test_from = pt\n else:\n test_from = args.test_from\n logger.info('Loading checkpoint from %s' % test_from)\n checkpoint = torch.load(test_from, map_location=lambda storage, loc: storage)\n opt = vars(checkpoint['opt'])\n for k in opt.keys():\n if (k in model_flags):\n setattr(args, k, opt[k])\n print(args)\n\n config = BertConfig.from_json_file(args.bert_config_path)\n model = Summarizer(args, device, load_pretrained_bert=False, bert_config = config)\n model.load_cp(checkpoint)\n model.eval()\n\n valid_iter =data_loader.Dataloader(args, load_dataset(args, 'valid', shuffle=False),\n args.batch_size, device,\n shuffle=False, is_test=False)\n trainer = build_trainer(args, device_id, model, None)\n stats = trainer.validate(valid_iter, step)\n print(\"Stats: {}\".format(stats.xent()))\n return stats.xent()\n\n\ndef test(args, device_id, pt, step):\n\n device = \"cpu\" if args.visible_gpus == '-1' else \"cuda\"\n if (pt != ''):\n test_from = pt\n else:\n test_from = args.test_from\n logger.info('Loading checkpoint from %s' % test_from)\n checkpoint = torch.load(test_from, map_location=lambda storage, loc: storage)\n opt = vars(checkpoint['opt'])\n for k in opt.keys():\n if (k in model_flags):\n setattr(args, k, opt[k])\n print(args)\n\n config = BertConfig.from_json_file(args.bert_config_path)\n model = Summarizer(args, device, load_pretrained_bert=False, bert_config = config)\n model.load_cp(checkpoint)\n model.eval()\n\n test_iter =data_loader.Dataloader(args, load_dataset(args, 'test', shuffle=False),\n args.batch_size, device,\n shuffle=False, is_test=True)\n trainer = build_trainer(args, device_id, model, None)\n trainer.test(test_iter,step)\n\n\ndef baseline(args, cal_lead=False, cal_oracle=False):\n\n test_iter =data_loader.Dataloader(args, load_dataset(args, 'test', shuffle=False),\n args.batch_size, device,\n shuffle=False, is_test=True)\n\n trainer = build_trainer(args, device_id, None, None)\n #\n if (cal_lead):\n trainer.test(test_iter, 0, cal_lead=True)\n elif (cal_oracle):\n trainer.test(test_iter, 0, cal_oracle=True)\n\n\ndef train(args, device_id):\n init_logger(args.log_file)\n\n device = \"cpu\" if args.visible_gpus == '-1' else \"cuda\"\n logger.info('Device ID %d' % device_id)\n logger.info('Device %s' % device)\n torch.manual_seed(args.seed)\n random.seed(args.seed)\n torch.backends.cudnn.deterministic = True\n\n if device_id >= 0:\n torch.cuda.set_device(device_id)\n torch.cuda.manual_seed(args.seed)\n\n\n torch.manual_seed(args.seed)\n random.seed(args.seed)\n torch.backends.cudnn.deterministic = True\n\n def train_iter_fct():\n return data_loader.Dataloader(args, load_dataset(args, 'train', shuffle=True), args.batch_size, device,\n shuffle=True, is_test=False)\n\n model = Summarizer(args, device, load_pretrained_bert=True)\n if args.train_from != '':\n logger.info('Loading checkpoint from %s' % args.train_from)\n checkpoint = torch.load(args.train_from,\n map_location=lambda storage, loc: storage)\n opt = vars(checkpoint['opt'])\n for k in opt.keys():\n if (k in model_flags):\n setattr(args, k, opt[k])\n model.load_cp(checkpoint)\n optim = model_builder.build_optim(args, model, checkpoint)\n else:\n optim = model_builder.build_optim(args, model, None)\n\n logger.info(model)\n trainer = build_trainer(args, device_id, model, optim)\n losses, n_docs = trainer.train(train_iter_fct, args.train_steps)\n\n save_pickle(losses, 'losses_classifier')\n save_pickle(n_docs, 'docs_classifier')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-encoder\", default='classifier', type=str, choices=['classifier','transformer','rnn','baseline', 'classifierDummy', 'gnn'])\n parser.add_argument(\"-mode\", default='train', type=str, choices=['train','validate','test'])\n parser.add_argument(\"-bert_data_path\", default='../bert_data/cnndm')\n parser.add_argument(\"-model_path\", default='../models/')\n parser.add_argument(\"-result_path\", default='../results/cnndm')\n parser.add_argument(\"-temp_dir\", default='../temp')\n parser.add_argument(\"-bert_config_path\", default='../bert_config_uncased_base.json')\n\n parser.add_argument(\"-batch_size\", default=1000, type=int)\n\n parser.add_argument(\"-use_interval\", type=str2bool, nargs='?',const=True,default=True)\n parser.add_argument(\"-hidden_size\", default=128, type=int)\n parser.add_argument(\"-ff_size\", default=512, type=int)\n parser.add_argument(\"-heads\", default=4, type=int)\n parser.add_argument(\"-inter_layers\", default=2, type=int)\n parser.add_argument(\"-rnn_size\", default=512, type=int)\n\n parser.add_argument(\"-param_init\", default=0, type=float)\n parser.add_argument(\"-param_init_glorot\", type=str2bool, nargs='?',const=True,default=True)\n parser.add_argument(\"-dropout\", default=0.1, type=float)\n parser.add_argument(\"-optim\", default='adam', type=str)\n parser.add_argument(\"-lr\", default=1, type=float)\n parser.add_argument(\"-beta1\", default= 0.9, type=float)\n parser.add_argument(\"-beta2\", default=0.999, type=float)\n parser.add_argument(\"-decay_method\", default='', type=str)\n parser.add_argument(\"-warmup_steps\", default=8000, type=int)\n parser.add_argument(\"-max_grad_norm\", default=0, type=float)\n\n parser.add_argument(\"-save_checkpoint_steps\", default=5, type=int)\n parser.add_argument(\"-accum_count\", default=1, type=int)\n parser.add_argument(\"-world_size\", default=1, type=int)\n parser.add_argument(\"-report_every\", default=1, type=int)\n parser.add_argument(\"-train_steps\", default=1000, type=int)\n parser.add_argument(\"-recall_eval\", type=str2bool, nargs='?',const=True,default=False)\n\n\n parser.add_argument('-visible_gpus', default='-1', type=str)\n parser.add_argument('-gpu_ranks', default='0', type=str)\n parser.add_argument('-log_file', default='../logs/cnndm.log')\n parser.add_argument('-dataset', default='')\n parser.add_argument('-seed', default=666, type=int)\n\n parser.add_argument(\"-test_all\", type=str2bool, nargs='?',const=True,default=False)\n parser.add_argument(\"-test_from\", default='')\n parser.add_argument(\"-train_from\", default='')\n parser.add_argument(\"-report_rouge\", type=str2bool, nargs='?',const=True,default=True)\n parser.add_argument(\"-block_trigram\", type=str2bool, nargs='?', const=True, default=True)\n\n args = parser.parse_args()\n args.gpu_ranks = [int(i) for i in args.gpu_ranks.split(',')]\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.visible_gpus\n\n init_logger(args.log_file)\n device = \"cpu\" if args.visible_gpus == '-1' else \"cuda\"\n device_id = 0 if device == \"cuda\" else -1\n\n if(args.world_size>1):\n multi_main(args)\n elif (args.mode == 'train'):\n train(args, device_id)\n elif (args.mode == 'validate'):\n wait_and_validate(args, device_id)\n elif (args.mode == 'lead'):\n baseline(args, cal_lead=True)\n elif (args.mode == 'oracle'):\n baseline(args, cal_oracle=True)\n elif (args.mode == 'test'):\n cp = args.test_from\n try:\n step = int(cp.split('.')[-2].split('_')[-1])\n except:\n step = 0\n test(args, device_id, cp, step)\n"
] |
[
[
"torch.cuda.manual_seed",
"torch.cuda.set_device",
"torch.load",
"torch.manual_seed",
"torch.multiprocessing.get_context"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Grant-Block/pylith
|
[
"f6338261b17551eba879da998a5aaf2d91f5f658"
] |
[
"tests/libtests/feassemble/data/obsolete/feutils.py"
] |
[
"#!/usr/bin/env python\n#\n# ----------------------------------------------------------------------\n#\n# Brad T. Aagaard, U.S. Geological Survey\n# Charles A. Williams, GNS Science\n# Matthew G. Knepley, University of Chicago\n#\n# This code was developed as part of the Computational Infrastructure\n# for Geodynamics (http://geodynamics.org).\n#\n# Copyright (c) 2010-2017 University of California, Davis\n#\n# See COPYING for license information.\n#\n# ----------------------------------------------------------------------\n#\n\n## @file tests/libtests/feassemble/data/feutils.py\n\n## @brief Python routines for doing simple finite-element related\n## calculations.\n\nimport numpy\n\n# ----------------------------------------------------------------------\ndef calculateJacobian(quadrature, vertices):\n \"\"\"\n Calculate jacobian, its determinant, and its inverse at quadrature\n points for a given cell.\n\n @param quadrature Quadrature information\n @param vertices Coordinates of cell's vertices\n \"\"\"\n (basis, basisDerivRef) = quadrature.calculateBasis()\n\n numQuadPts = quadrature.numQuadPts\n cellDim = quadrature.cellDim\n spaceDim = quadrature.spaceDim\n numBasis = quadrature.numBasis\n jacobian = numpy.zeros( (numQuadPts, spaceDim, cellDim),\n dtype=numpy.float64)\n jacobianInv = numpy.zeros( (numQuadPts, cellDim, spaceDim),\n dtype=numpy.float64)\n jacobianDet = numpy.zeros( (numQuadPts,), dtype=numpy.float64)\n basisDeriv = numpy.zeros( (numQuadPts, numBasis, spaceDim),\n dtype=numpy.float64)\n\n iQuad = 0\n for q in quadrature.quadPtsRef:\n # Jacobian at quadrature points\n deriv = basisDerivRef[iQuad]\n j = numpy.dot(vertices.transpose(), deriv)\n jacobian[iQuad] = j\n\n # Determinant of Jacobian and Jacobian inverse at quadrature points\n if spaceDim == cellDim:\n jacobianDet[iQuad] = numpy.linalg.det(j)\n jacobianInv[iQuad] = numpy.linalg.inv(j)\n else:\n det = numpy.linalg.det(numpy.dot(j.transpose(), j))**0.5\n jacobianDet[iQuad] = det\n\n if 1 == quadrature.cellDim:\n jacobianInv[iQuad] = 1.0 / j.transpose()\n elif 2 == quadrature.cellDim:\n minJacobian = 1.0e-06\n jj01 = j[[0,1],:]\n jj12 = j[[1,2],:]\n jj02 = j[[0,2],:]\n det01 = numpy.linalg.det(jj01)\n det12 = numpy.linalg.det(jj12)\n det02 = numpy.linalg.det(jj02)\n if abs(det01) > minJacobian:\n ij01 = numpy.linalg.inv(jj01)\n if abs(det12) > minJacobian:\n ij12 = numpy.linalg.inv(jj12)\n jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,1], ij12[0,1]],\n [ij01[1,0], ij01[1,1], ij12[1,1]] ],\n dtype=numpy.float64)\n elif abs(det02) > minJacobian:\n ij02 = numpy.linalg.inv(jj02)\n jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,0], ij02[0,1]],\n [ij01[1,0], ij11[1,1], ij02[1,1]] ],\n dtype=numpy.float64)\n else:\n jacobianInv[iQuad] = numpy.array([ [ij01[0,0], ij01[0,1], 0.0],\n [ij01[1,0], ij01[1,1], 0.0] ],\n dtype=numpy.float64)\n elif abs(det02) > minJacobian:\n ij02 = numpy.linalg.inv(jj02)\n if abs(det12) > minJacobian:\n ij12 = numpy.linalg.inv(jj12)\n jacobianInv[iQuad] = numpy.array([ [ij02[0,0], ij12[0,0], ij02[0,1]],\n [ij02[1,0], ij12[1,0], ij02[1,1]] ],\n dtype=numpy.float64)\n else:\n jacobianInv[iQuad] = numpy.array([ [ij02[0,0], 0.0, ij02[0,1]],\n [ij02[1,0], 0.0, ij02[1,1]] ],\n dtype=numpy.float64)\n elif abs(det12) > minJacobian:\n ij12 = numpy.linalg.inv(jj12)\n jacobianInv[iQuad] = numpy.array([ [0.0, ij12[0,0], ij12[0,1]],\n [0.0, ij12[1,0], ij12[1,1]] ],\n dtype=numpy.float64)\n else:\n raise ValueError(\"Could not find inverse of Jacobian.\")\n else:\n raise ValueError(\"Could not find inverse of Jacobian.\")\n\n # Compute derivatives of basis functions with respect to global\n # coordinates using derivatives of basis functions with respect\n # to local cell coordinates and inverse of Jacobian matrix\n for iBasis in xrange(numBasis):\n matBasis = numpy.array(basisDerivRef[iQuad,iBasis], dtype=numpy.float64)\n jInv = jacobianInv[iQuad]\n basisDeriv[iQuad,iBasis,:] = numpy.dot(matBasis, jInv)\n iQuad += 1\n return (jacobian, jacobianInv, jacobianDet, basisDeriv)\n \n\n# ----------------------------------------------------------------------\ndef assembleMat(globalMat, cellMat, cell, fiberDim):\n \"\"\"\n Assemble cell matrix into global matrix.\n \"\"\"\n (nrows, ncols) = cellMat.shape\n for iR in xrange(nrows/fiberDim):\n ibeginL = iR * fiberDim\n iendL = ibeginL + fiberDim\n ibeginG = cell[iR] * fiberDim\n iendG = ibeginG + fiberDim\n for iC in xrange(ncols/fiberDim):\n jbeginL = iC * fiberDim\n jendL = jbeginL + fiberDim\n jbeginG = cell[iC] * fiberDim\n jendG = jbeginG + fiberDim\n globalMat[ibeginG:iendG, jbeginG:jendG] += cellMat[ibeginL:iendL,\n jbeginL:jendL]\n return\n\n \n# ----------------------------------------------------------------------\ndef assembleVec(globalVec, cellVec, cell, fiberDim):\n \"\"\"\n Assemble cell vector into global vector.\n \"\"\"\n (nrows,) = cellVec.shape\n for iR in xrange(nrows/fiberDim):\n ibeginL = iR * fiberDim\n iendL = ibeginL + fiberDim\n ibeginG = cell[iR] * fiberDim\n iendG = ibeginG + fiberDim\n globalVec[ibeginG:iendG] += cellVec[ibeginL:iendL]\n return\n\n \n# End of file \n"
] |
[
[
"numpy.dot",
"numpy.linalg.inv",
"numpy.linalg.det",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
truongnhat-ryo/fsgan
|
[
"6d074c553a4b2d4ea8c4bc586e25f13486e2301b"
] |
[
"utils/video_renderer.py"
] |
[
"import numpy as np\nimport cv2\nimport torch\nimport torch.multiprocessing as mp\nfrom fsgan.utils.img_utils import tensor2bgr\nfrom fsgan.utils.bbox_utils import crop2img, scale_bbox, crop2img_smooth_version\n\nfrom fsgan.face_enhance.retinaface.retinaface_detection import RetinaFaceDetection\nfrom fsgan.face_enhance.face_model.face_gan import FaceGAN\nfrom fsgan.face_enhance.align_faces import warp_and_crop_face, get_reference_facial_points\nfrom skimage import transform as tf\n\nclass FaceEnhancement(object):\n def __init__(self, base_dir='/home/nhattruong/Project/FS/fsgan/face_enhance', size=512, model=None, channel_multiplier=2):\n self.facedetector = RetinaFaceDetection(base_dir)\n self.facegan = FaceGAN(base_dir, size, model, channel_multiplier)\n self.size = size\n self.threshold = 0.9\n\n # the mask for pasting restored faces back\n self.mask = np.zeros((512, 512), np.float32)\n cv2.rectangle(self.mask, (26, 26), (486, 486), (1, 1, 1), -1, cv2.LINE_AA)\n self.mask = cv2.GaussianBlur(self.mask, (101, 101), 11)\n self.mask = cv2.GaussianBlur(self.mask, (101, 101), 11)\n\n self.kernel = np.array((\n [0.0625, 0.125, 0.0625],\n [0.125, 0.25, 0.125],\n [0.0625, 0.125, 0.0625]), dtype=\"float32\")\n\n # get the reference 5 landmarks position in the crop settings\n default_square = True\n inner_padding_factor = 0.25\n outer_padding = (0, 0)\n self.reference_5pts = get_reference_facial_points(\n (self.size, self.size), inner_padding_factor, outer_padding, default_square)\n\n def process(self, img):\n facebs, landms = self.facedetector.detect(img)\n \n orig_faces, enhanced_faces = [], []\n height, width = img.shape[:2]\n full_mask = np.zeros((height, width), dtype=np.float32)\n full_img = np.zeros(img.shape, dtype=np.uint8)\n\n for i, (faceb, facial5points) in enumerate(zip(facebs, landms)):\n if faceb[4]<self.threshold: continue\n fh, fw = (faceb[3]-faceb[1]), (faceb[2]-faceb[0])\n\n facial5points = np.reshape(facial5points, (2, 5))\n\n of, tfm_inv = warp_and_crop_face(img, facial5points, reference_pts=self.reference_5pts, crop_size=(self.size, self.size))\n \n # enhance the face\n ef = self.facegan.process(of)\n \n orig_faces.append(of)\n enhanced_faces.append(ef)\n \n tmp_mask = self.mask\n tmp_mask = cv2.resize(tmp_mask, ef.shape[:2])\n tmp_mask = cv2.warpAffine(tmp_mask, tfm_inv, (width, height), flags=3)\n\n if min(fh, fw)<100: # gaussian filter for small faces\n ef = cv2.filter2D(ef, -1, self.kernel)\n \n tmp_img = cv2.warpAffine(ef, tfm_inv, (width, height), flags=3)\n\n mask = tmp_mask - full_mask\n full_mask[np.where(mask>0)] = tmp_mask[np.where(mask>0)]\n full_img[np.where(mask>0)] = tmp_img[np.where(mask>0)]\n\n full_mask = full_mask[:, :, np.newaxis]\n img = cv2.convertScaleAbs(img*(1-full_mask) + full_img*full_mask)\n\n return img, orig_faces, enhanced_faces\n\nclass VideoRenderer(mp.Process):\n \"\"\" Renders input video frames to both screen and video file.\n\n For more control on the rendering, this class should be inherited from and the on_render method overridden\n with an application specific implementation.\n\n Args:\n display (bool): If True, the rendered video will be displayed on screen\n verbose (int): Verbose level. Controls the amount of debug information in the rendering\n verbose_size (tuple of int): The rendered frame size for verbose level other than zero (width, height)\n output_crop (bool): If True, a cropped frame of size (resolution, resolution) will be rendered for\n verbose level zero\n resolution (int): Determines the size of cropped frames to be (resolution, resolution)\n crop_scale (float): Multiplier factor to scale tight bounding boxes\n encoder_codec (str): Encoder codec code\n separate_process (bool): If True, the renderer will be run in a separate process\n \"\"\"\n def __init__(self, display=False, verbose=0, verbose_size=None, output_crop=False, resolution=256, crop_scale=1.2,\n encoder_codec='avc1', separate_process=False, img2img=True):\n super(VideoRenderer, self).__init__()\n self._display = display\n self._verbose = verbose\n self._verbose_size = verbose_size\n self._output_crop = output_crop\n self._resolution = resolution\n self._crop_scale = crop_scale\n self._running = True\n self._input_queue = mp.Queue()\n self._reply_queue = mp.Queue()\n self._fourcc = cv2.VideoWriter_fourcc(*encoder_codec)\n self._separate_process = separate_process\n self._in_vid = None\n self._out_vid = None\n self._seq = None\n self._in_vid_path = None\n self._total_frames = None\n self._frame_count = 0\n self.img2img = img2img\n\n self.faceenhancer = FaceEnhancement(size=512, model='GPEN-512', channel_multiplier=2)\n\n def init(self, in_vid_path, seq, out_vid_path=None, **kwargs):\n \"\"\" Initialize the video render for a new video rendering job.\n\n Args:\n in_vid_path (str): Input video path\n seq (Sequence): Input sequence corresponding to the input video\n out_vid_path (str, optional): If specified, the rendering will be written to an output video in that path\n **kwargs (dict): Additional keyword arguments that will be added as members of the class. This allows\n inheriting classes to access those arguments from the new process\n \"\"\"\n if self._separate_process:\n self._input_queue.put([in_vid_path, seq, out_vid_path, kwargs])\n else:\n self._init_task(in_vid_path, seq, out_vid_path, kwargs)\n\n def write(self, out_path, *args):\n \"\"\" Add tensors for rendering.\n\n Args:\n *args (tuple of torch.Tensor): The tensors for rendering\n \"\"\"\n if self._separate_process:\n self._input_queue.put([a.cpu() for a in args])\n else:\n self._write_batch([a.cpu() for a in args], out_path)\n\n def finalize(self):\n if self._separate_process:\n self._input_queue.put(True)\n else:\n self._finalize_task()\n\n def wait_until_finished(self):\n \"\"\" Wait for the video renderer to finish the current video rendering job. \"\"\"\n if self._separate_process:\n return self._reply_queue.get()\n else:\n return True\n\n def on_render(self, *args):\n \"\"\" Given the input tensors this method produces a cropped rendered image.\n\n This method should be overridden by inheriting classes to customize the rendering. By default this method\n expects the first tensor to be a cropped image tensor of shape (B, 3, H, W) where B is the batch size,\n H is the height of the image and W is the width of the image.\n\n Args:\n *args (tuple of torch.Tensor): The tensors for rendering\n\n Returns:\n render_bgr (np.array): The cropped rendered image\n \"\"\"\n return tensor2bgr(args[0])\n\n def start(self):\n if self._separate_process:\n super(VideoRenderer, self).start()\n\n def kill(self):\n if self._separate_process:\n super(VideoRenderer, self).kill()\n\n def run(self):\n \"\"\" Main processing loop. Intended to be executed on a separate process. \"\"\"\n while self._running:\n task = self._input_queue.get()\n\n # Initialize new video rendering task\n if self._in_vid is None:\n self._init_task(*task[:3], task[3])\n continue\n\n # Finalize task\n if isinstance(task, bool):\n self._finalize_task()\n\n # Notify job is finished\n self._reply_queue.put(True)\n continue\n\n # Write a batch of frames\n self._write_batch(task)\n\n def _render(self, render_bgr, full_frame_bgr=None, bbox=None, out_path=None):\n if self._verbose == 0 and not self._output_crop and full_frame_bgr is not None:\n # import pdb; pdb.set_trace()\n render_bgr, orig_faces, enhanced_faces = self.faceenhancer.process(render_bgr)\n render_bgr = crop2img_smooth_version(full_frame_bgr, render_bgr, bbox)\n if self.img2img:\n cv2.imwrite(out_path, render_bgr)\n if self._out_vid is not None:\n self._out_vid.write(render_bgr)\n if self._display:\n cv2.imshow('render', render_bgr)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n self._running = False\n\n def _init_task(self, in_vid_path, seq, out_vid_path, additional_attributes):\n # print('_init_task start')\n self._in_vid_path, self._seq = in_vid_path, seq\n self._frame_count = 0\n\n # Add additional arguments as members\n for attr_name, attr_val in additional_attributes.items():\n setattr(self, attr_name, attr_val)\n\n # Open input video\n self._in_vid = cv2.VideoCapture(self._in_vid_path)\n assert self._in_vid.isOpened(), f'Failed to open video: \"{self._in_vid_path}\"'\n\n in_total_frames = int(self._in_vid.get(cv2.CAP_PROP_FRAME_COUNT))\n fps = self._in_vid.get(cv2.CAP_PROP_FPS)\n in_vid_width = int(self._in_vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n in_vid_height = int(self._in_vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n self._total_frames = in_total_frames if self._verbose == 0 else len(self._seq)\n # print(f'Debug: initializing video: \"{self._in_vid_path}\", total_frames={self._total_frames}')\n\n # Initialize output video\n if out_vid_path is not None:\n out_size = (in_vid_width, in_vid_height)\n if self._verbose <= 0 and self._output_crop:\n out_size = (self._resolution, self._resolution)\n elif self._verbose_size is not None:\n out_size = self._verbose_size\n if not self.img2img:\n self._out_vid = cv2.VideoWriter(out_vid_path, self._fourcc, fps, out_size)\n\n # Write frames as they are until the start of the sequence\n if self._verbose == 0:\n for i in range(self._seq.start_index):\n # Read frame\n ret, frame_bgr = self._in_vid.read()\n assert frame_bgr is not None, f'Failed to read frame {i} from input video: \"{self._in_vid_path}\"'\n self._render(frame_bgr) #uncmt for video rendering\n self._frame_count += 1\n\n def _write_batch(self, tensors, out_path):\n batch_size = tensors[0].shape[0]\n\n # For each frame in the current batch of tensors\n for b in range(batch_size):\n # Handle full frames if output_crop was not specified\n full_frame_bgr, bbox = None, None\n if self._verbose == 0 and not self._output_crop:\n # Read frame from input video\n ret, full_frame_bgr = self._in_vid.read()\n assert full_frame_bgr is not None, \\\n f'Failed to read frame {self._frame_count} from input video: \"{self._in_vid_path}\"'\n\n # Get bounding box from sequence\n det = self._seq[self._frame_count - self._seq.start_index]\n bbox = np.concatenate((det[:2], det[2:] - det[:2]))\n bbox = scale_bbox(bbox, self._crop_scale)\n\n render_bgr = self.on_render(*[t[b] for t in tensors])\n self._render(render_bgr, full_frame_bgr, bbox, out_path)\n self._frame_count += 1\n # print(f'Debug: Wrote frame: {self._frame_count}')\n\n def _finalize_task(self):\n if self._verbose == 0 and self._frame_count >= (self._seq.start_index + len(self._seq)):\n for i in range(self._seq.start_index + len(self._seq), self._total_frames):\n # Read frame\n ret, frame_bgr = self._in_vid.read()\n assert frame_bgr is not None, f'Failed to read frame {i} from input video: \"{self._in_vid_path}\"'\n self._render(frame_bgr) #uncmt for video rendering\n self._frame_count += 1\n # print(f'Debug: Wrote frame: {self._frame_count}')\n\n # if self._frame_count >= self._total_frames:\n # Clean up\n self._in_vid.release()\n # self._out_vid.release() # uncmt for video writer\n self._in_vid = None\n self._out_vid = None\n self._seq = None\n self._in_vid_path = None\n self._total_frames = None\n self._frame_count = 0\n"
] |
[
[
"torch.multiprocessing.Queue",
"numpy.reshape",
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
haoxins/GraphScope
|
[
"e1e22a425b5c33bed0dea930f8722e6159484153"
] |
[
"python/graphscope/nx/generators/random_graphs.py"
] |
[
"# -*- coding: utf-8 -*-\n#\n# This file random_graphs.py is referred and derived from project NetworkX,\n#\n# https://github.com/networkx/networkx/blob/master/networkx/generators/random_graphs.py\n#\n# which has the following license:\n#\n# Copyright (C) 2004-2020, NetworkX Developers\n# Aric Hagberg <[email protected]>\n# Dan Schult <[email protected]>\n# Pieter Swart <[email protected]>\n# All rights reserved.\n#\n# This file is part of NetworkX.\n#\n# NetworkX is distributed under a BSD license; see LICENSE.txt for more\n# information.\n#\n\"\"\"\nGenerators for random graphs.\n\n\"\"\"\n\nimport itertools\nimport math\nfrom collections import defaultdict\n\nimport networkx as nxa\nfrom networkx.utils import powerlaw_sequence\nfrom networkx.utils import py_random_state\n\nfrom graphscope import nx\nfrom graphscope.nx.generators.classic import complete_graph\nfrom graphscope.nx.generators.classic import empty_graph\nfrom graphscope.nx.generators.classic import path_graph\nfrom graphscope.nx.generators.degree_seq import degree_sequence_tree\nfrom graphscope.nx.utils.compat import patch_docstring\n\n__all__ = [\n \"fast_gnp_random_graph\",\n \"gnp_random_graph\",\n \"dense_gnm_random_graph\",\n \"gnm_random_graph\",\n \"erdos_renyi_graph\",\n \"binomial_graph\",\n \"newman_watts_strogatz_graph\",\n \"watts_strogatz_graph\",\n \"connected_watts_strogatz_graph\",\n \"random_regular_graph\",\n \"barabasi_albert_graph\",\n \"dual_barabasi_albert_graph\",\n \"extended_barabasi_albert_graph\",\n \"powerlaw_cluster_graph\",\n \"random_lobster\",\n \"random_shell_graph\",\n \"random_powerlaw_tree\",\n \"random_powerlaw_tree_sequence\",\n \"random_kernel_graph\",\n]\n\n# -------------------------------------------------------------------------\n# Some Famous Random Graphs\n# -------------------------------------------------------------------------\n\n\n@patch_docstring(nxa.fast_gnp_random_graph)\n@py_random_state(2)\ndef fast_gnp_random_graph(n, p, seed=None, directed=False):\n G = empty_graph(n)\n\n if p <= 0 or p >= 1:\n return nx.gnp_random_graph(n, p, seed=seed, directed=directed)\n\n w = -1\n lp = math.log(1.0 - p)\n\n if directed:\n G = nx.DiGraph(G)\n # Nodes in graph are from 0,n-1 (start with v as the first node index).\n v = 0\n while v < n:\n lr = math.log(1.0 - seed.random())\n w = w + 1 + int(lr / lp)\n if v == w: # avoid self loops\n w = w + 1\n while v < n <= w:\n w = w - n\n v = v + 1\n if v == w: # avoid self loops\n w = w + 1\n if v < n:\n G.add_edge(v, w)\n else:\n # Nodes in graph are from 0,n-1 (start with v as the second node index).\n v = 1\n while v < n:\n lr = math.log(1.0 - seed.random())\n w = w + 1 + int(lr / lp)\n while w >= v and v < n:\n w = w - v\n v = v + 1\n if v < n:\n G.add_edge(v, w)\n return G\n\n\n@patch_docstring(nxa.gnp_random_graph)\n@py_random_state(2)\ndef gnp_random_graph(n, p, seed=None, directed=False):\n if directed:\n edges = itertools.permutations(range(n), 2)\n G = nx.DiGraph()\n else:\n edges = itertools.combinations(range(n), 2)\n G = nx.Graph()\n G.add_nodes_from(range(n))\n if p <= 0:\n return G\n if p >= 1:\n return complete_graph(n, create_using=G)\n\n for e in edges:\n if seed.random() < p:\n G.add_edge(*e)\n return G\n\n\n# add some aliases to common names\nbinomial_graph = gnp_random_graph\nerdos_renyi_graph = gnp_random_graph\n\n\n@patch_docstring(nxa.dense_gnm_random_graph)\n@py_random_state(2)\ndef dense_gnm_random_graph(n, m, seed=None):\n mmax = n * (n - 1) / 2\n if m >= mmax:\n G = complete_graph(n)\n else:\n G = empty_graph(n)\n\n if n == 1 or m >= mmax:\n return G\n\n u = 0\n v = 1\n t = 0\n k = 0\n while True:\n if seed.randrange(mmax - t) < m - k:\n G.add_edge(u, v)\n k += 1\n if k == m:\n return G\n t += 1\n v += 1\n if v == n: # go to next row of adjacency matrix\n u += 1\n v = u + 1\n\n\n@patch_docstring(nxa.gnm_random_graph)\n@py_random_state(2)\ndef gnm_random_graph(n, m, seed=None, directed=False):\n if directed:\n G = nx.DiGraph()\n else:\n G = nx.Graph()\n G.add_nodes_from(range(n))\n\n if n == 1:\n return G\n max_edges = n * (n - 1)\n if not directed:\n max_edges /= 2.0\n if m >= max_edges:\n return complete_graph(n, create_using=G)\n\n nlist = list(G)\n edge_count = 0\n while edge_count < m:\n # generate random edge,u,v\n u = seed.choice(nlist)\n v = seed.choice(nlist)\n if u == v:\n continue\n else:\n G.add_edge(u, v)\n edge_count = edge_count + 1\n return G\n\n\n@patch_docstring(nxa.newman_watts_strogatz_graph)\n@py_random_state(3)\ndef newman_watts_strogatz_graph(n, k, p, seed=None):\n if k > n:\n raise nx.NetworkXError(\"k>=n, choose smaller k or larger n\")\n\n # If k == n the graph return is a complete graph\n if k == n:\n return nx.complete_graph(n)\n\n G = empty_graph(n)\n nlist = list(G.nodes())\n fromv = nlist\n # connect the k/2 neighbors\n for j in range(1, k // 2 + 1):\n tov = fromv[j:] + fromv[0:j] # the first j are now last\n for i, value in enumerate(fromv):\n G.add_edge(value, tov[i])\n # for each edge u-v, with probability p, randomly select existing\n # node w and add new edge u-w\n e = list(G.edges())\n for (u, v) in e:\n if seed.random() < p:\n w = seed.choice(nlist)\n # no self-loops and reject if edge u-w exists\n # is that the correct NWS model?\n while w == u or G.has_edge(u, w):\n w = seed.choice(nlist)\n if G.degree(u) >= n - 1:\n break # skip this rewiring\n else:\n G.add_edge(u, w)\n return G\n\n\n@patch_docstring(nxa.watts_strogatz_graph)\n@py_random_state(3)\ndef watts_strogatz_graph(n, k, p, seed=None):\n if k > n:\n raise nx.NetworkXError(\"k>n, choose smaller k or larger n\")\n\n # If k == n, the graph is complete not Watts-Strogatz\n if k == n:\n return nx.complete_graph(n)\n\n G = nx.Graph()\n nodes = list(range(n)) # nodes are labeled 0 to n-1\n # connect each node to k/2 neighbors\n for j in range(1, k // 2 + 1):\n targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list\n G.add_edges_from(zip(nodes, targets))\n # rewire edges from each node\n # loop over all nodes in order (label) and neighbors in order (distance)\n # no self loops or multiple edges allowed\n for j in range(1, k // 2 + 1): # outer loop is neighbors\n targets = nodes[j:] + nodes[0:j] # first j nodes are now last in list\n # inner loop in node order\n for u, v in zip(nodes, targets):\n if seed.random() < p:\n w = seed.choice(nodes)\n # Enforce no self-loops or multiple edges\n while w == u or G.has_edge(u, w):\n w = seed.choice(nodes)\n if G.degree(u) >= n - 1:\n break # skip this rewiring\n else:\n G.remove_edge(u, v)\n G.add_edge(u, w)\n return G\n\n\n@patch_docstring(nxa.connected_watts_strogatz_graph)\n@py_random_state(4)\ndef connected_watts_strogatz_graph(n, k, p, tries=100, seed=None):\n for i in range(tries):\n # seed is an RNG so should change sequence each call\n G = watts_strogatz_graph(n, k, p, seed)\n if nx.is_connected(G):\n return G\n raise nx.NetworkXError(\"Maximum number of tries exceeded\")\n\n\n@patch_docstring(nxa.random_regular_graph)\n@py_random_state(2)\ndef random_regular_graph(d, n, seed=None):\n if (n * d) % 2 != 0:\n raise nx.NetworkXError(\"n * d must be even\")\n\n if not 0 <= d < n:\n raise nx.NetworkXError(\"the 0 <= d < n inequality must be satisfied\")\n\n if d == 0:\n return empty_graph(n)\n\n def _suitable(edges, potential_edges):\n # Helper subroutine to check if there are suitable edges remaining\n # If False, the generation of the graph has failed\n if not potential_edges:\n return True\n for s1 in potential_edges:\n for s2 in potential_edges:\n # Two iterators on the same dictionary are guaranteed\n # to visit it in the same order if there are no\n # intervening modifications.\n if s1 == s2:\n # Only need to consider s1-s2 pair one time\n break\n if s1 > s2:\n s1, s2 = s2, s1\n if (s1, s2) not in edges:\n return True\n return False\n\n def _try_creation():\n # Attempt to create an edge set\n\n edges = set()\n stubs = list(range(n)) * d\n\n while stubs:\n potential_edges = defaultdict(lambda: 0)\n seed.shuffle(stubs)\n stubiter = iter(stubs)\n for s1, s2 in zip(stubiter, stubiter):\n if s1 > s2:\n s1, s2 = s2, s1\n if s1 != s2 and ((s1, s2) not in edges):\n edges.add((s1, s2))\n else:\n potential_edges[s1] += 1\n potential_edges[s2] += 1\n\n if not _suitable(edges, potential_edges):\n return None # failed to find suitable edge set\n\n stubs = [\n node\n for node, potential in potential_edges.items()\n for _ in range(potential)\n ]\n return edges\n\n # Even though a suitable edge set exists,\n # the generation of such a set is not guaranteed.\n # Try repeatedly to find one.\n edges = _try_creation()\n while edges is None:\n edges = _try_creation()\n\n G = nx.Graph()\n G.add_edges_from(edges)\n\n return G\n\n\ndef _random_subset(seq, m, rng):\n \"\"\"Return m unique elements from seq.\n\n This differs from random.sample which can return repeated\n elements if seq holds repeated elements.\n\n Note: rng is a random.Random or numpy.random.RandomState instance.\n \"\"\"\n targets = set()\n while len(targets) < m:\n x = rng.choice(seq)\n targets.add(x)\n return targets\n\n\n@patch_docstring(nxa.barabasi_albert_graph)\n@py_random_state(2)\ndef barabasi_albert_graph(n, m, seed=None, initial_graph=None):\n if m < 1 or m >= n:\n raise nx.NetworkXError(\n \"Barabási–Albert network must have m >= 1\"\n \" and m < n, m = %d, n = %d\" % (m, n)\n )\n\n if initial_graph is None:\n # Default initial graph : star graph on (m + 1) nodes\n G = nx.star_graph(m)\n else:\n if len(initial_graph) < m or len(initial_graph) > n:\n raise nx.NetworkXError(\n f\"Barabási–Albert initial graph needs between m={m} and n={n} nodes\"\n )\n G = initial_graph.copy()\n\n # List of existing nodes, with nodes repeated once for each adjacent edge\n repeated_nodes = [n for n, d in G.degree() for _ in range(d)]\n # Start adding the other n - m0 nodes.\n source = len(G)\n while source < n:\n # Now choose m unique nodes from the existing nodes\n # Pick uniformly from repeated_nodes (preferential attachment)\n targets = _random_subset(repeated_nodes, m, seed)\n # Add edges to m nodes from the source.\n G.add_edges_from(zip([source] * m, targets))\n # Add one node to the list for each new edge just created.\n repeated_nodes.extend(targets)\n # And the new node \"source\" has m edges to add to the list.\n repeated_nodes.extend([source] * m)\n\n source += 1\n return G\n\n\n@patch_docstring(nxa.dual_barabasi_albert_graph)\n@py_random_state(4)\ndef dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):\n if m1 < 1 or m1 >= n:\n raise nx.NetworkXError(\n \"Dual Barabási–Albert network must have m1 >= 1\"\n \" and m1 < n, m1 = %d, n = %d\" % (m1, n)\n )\n if m2 < 1 or m2 >= n:\n raise nx.NetworkXError(\n \"Dual Barabási–Albert network must have m2 >= 1\"\n \" and m2 < n, m2 = %d, n = %d\" % (m2, n)\n )\n if p < 0 or p > 1:\n raise nx.NetworkXError(\n \"Dual Barabási–Albert network must have 0 <= p <= 1,\" \"p = %f\" % p\n )\n\n # For simplicity, if p == 0 or 1, just return BA\n if p == 1:\n return barabasi_albert_graph(n, m1, seed)\n if p == 0:\n return barabasi_albert_graph(n, m2, seed)\n\n if initial_graph is None:\n # Default initial graph : empty graph on max(m1, m2) nodes\n G = nx.star_graph(max(m1, m2))\n else:\n if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:\n raise nx.NetworkXError(\n f\"Barabási–Albert initial graph must have between \"\n f\"max(m1, m2) = {max(m1, m2)} and n = {n} nodes\"\n )\n G = initial_graph.copy()\n\n # Target nodes for new edges\n targets = list(G)\n # List of existing nodes, with nodes repeated once for each adjacent edge\n repeated_nodes = [n for n, d in G.degree() for _ in range(d)]\n # Start adding the remaining nodes.\n source = len(G)\n while source < n:\n # Pick which m to use (m1 or m2)\n if seed.random() < p:\n m = m1\n else:\n m = m2\n # Now choose m unique nodes from the existing nodes\n # Pick uniformly from repeated_nodes (preferential attachment)\n targets = _random_subset(repeated_nodes, m, seed)\n # Add edges to m nodes from the source.\n G.add_edges_from(zip([source] * m, targets))\n # Add one node to the list for each new edge just created.\n repeated_nodes.extend(targets)\n # And the new node \"source\" has m edges to add to the list.\n repeated_nodes.extend([source] * m)\n\n source += 1\n return G\n\n\n@patch_docstring(nxa.extended_barabasi_albert_graph)\n@py_random_state(4)\ndef extended_barabasi_albert_graph(n, m, p, q, seed=None):\n if m < 1 or m >= n:\n msg = \"Extended Barabasi-Albert network needs m>=1 and m<n, m=%d, n=%d\"\n raise nx.NetworkXError(msg % (m, n))\n if p + q >= 1:\n msg = \"Extended Barabasi-Albert network needs p + q <= 1, p=%d, q=%d\"\n raise nx.NetworkXError(msg % (p, q))\n\n # Add m initial nodes (m0 in barabasi-speak)\n G = empty_graph(m)\n\n # List of nodes to represent the preferential attachment random selection.\n # At the creation of the graph, all nodes are added to the list\n # so that even nodes that are not connected have a chance to get selected,\n # for rewiring and adding of edges.\n # With each new edge, nodes at the ends of the edge are added to the list.\n attachment_preference = []\n attachment_preference.extend(range(m))\n\n # Start adding the other n-m nodes. The first node is m.\n new_node = m\n while new_node < n:\n a_probability = seed.random()\n\n # Total number of edges of a Clique of all the nodes\n clique_degree = len(G) - 1\n clique_size = (len(G) * clique_degree) / 2\n\n # Adding m new edges, if there is room to add them\n if a_probability < p and G.size() <= clique_size - m:\n # Select the nodes where an edge can be added\n elligible_nodes = [nd for nd, deg in G.degree() if deg < clique_degree]\n for i in range(m):\n # Choosing a random source node from elligible_nodes\n src_node = seed.choice(elligible_nodes)\n\n # Picking a possible node that is not 'src_node' or\n # neighbor with 'src_node', with preferential attachment\n prohibited_nodes = list(G[src_node])\n prohibited_nodes.append(src_node)\n # This will raise an exception if the sequence is empty\n dest_node = seed.choice(\n [nd for nd in attachment_preference if nd not in prohibited_nodes]\n )\n # Adding the new edge\n G.add_edge(src_node, dest_node)\n\n # Appending both nodes to add to their preferential attachment\n attachment_preference.append(src_node)\n attachment_preference.append(dest_node)\n\n # Adjusting the elligible nodes. Degree may be saturated.\n if G.degree(src_node) == clique_degree:\n elligible_nodes.remove(src_node)\n if (\n G.degree(dest_node) == clique_degree\n and dest_node in elligible_nodes\n ):\n elligible_nodes.remove(dest_node)\n\n # Rewiring m edges, if there are enough edges\n elif p <= a_probability < (p + q) and m <= G.size() < clique_size:\n # Selecting nodes that have at least 1 edge but that are not\n # fully connected to ALL other nodes (center of star).\n # These nodes are the pivot nodes of the edges to rewire\n elligible_nodes = [nd for nd, deg in G.degree() if 0 < deg < clique_degree]\n for i in range(m):\n # Choosing a random source node\n node = seed.choice(elligible_nodes)\n\n # The available nodes do have a neighbor at least.\n neighbor_nodes = list(G[node])\n\n # Choosing the other end that will get dettached\n src_node = seed.choice(neighbor_nodes)\n\n # Picking a target node that is not 'node' or\n # neighbor with 'node', with preferential attachment\n neighbor_nodes.append(node)\n dest_node = seed.choice(\n [nd for nd in attachment_preference if nd not in neighbor_nodes]\n )\n # Rewire\n G.remove_edge(node, src_node)\n G.add_edge(node, dest_node)\n\n # Adjusting the preferential attachment list\n attachment_preference.remove(src_node)\n attachment_preference.append(dest_node)\n\n # Adjusting the elligible nodes.\n # nodes may be saturated or isolated.\n if G.degree(src_node) == 0 and src_node in elligible_nodes:\n elligible_nodes.remove(src_node)\n if dest_node in elligible_nodes:\n if G.degree(dest_node) == clique_degree:\n elligible_nodes.remove(dest_node)\n else:\n if G.degree(dest_node) == 1:\n elligible_nodes.append(dest_node)\n\n # Adding new node with m edges\n else:\n # Select the edges' nodes by preferential attachment\n targets = _random_subset(attachment_preference, m, seed)\n G.add_edges_from(zip([new_node] * m, targets))\n\n # Add one node to the list for each new edge just created.\n attachment_preference.extend(targets)\n # The new node has m edges to it, plus itself: m + 1\n attachment_preference.extend([new_node] * (m + 1))\n new_node += 1\n return G\n\n\n@patch_docstring(nxa.powerlaw_cluster_graph)\n@py_random_state(3)\ndef powerlaw_cluster_graph(n, m, p, seed=None):\n if m < 1 or n < m:\n raise nx.NetworkXError(\n \"NetworkXError must have m>1 and m<n, m=%d,n=%d\" % (m, n)\n )\n\n if p > 1 or p < 0:\n raise nx.NetworkXError(\"NetworkXError p must be in [0,1], p=%f\" % (p))\n\n G = empty_graph(m) # add m initial nodes (m0 in barabasi-speak)\n repeated_nodes = list(G.nodes()) # list of existing nodes to sample from\n # with nodes repeated once for each adjacent edge\n source = m # next node is m\n while source < n: # Now add the other n-1 nodes\n possible_targets = _random_subset(repeated_nodes, m, seed)\n # do one preferential attachment for new node\n target = possible_targets.pop()\n G.add_edge(source, target)\n repeated_nodes.append(target) # add one node to list for each new link\n count = 1\n while count < m: # add m-1 more new links\n if seed.random() < p: # clustering step: add triangle\n neighborhood = [\n nbr\n for nbr in G.neighbors(target)\n if not G.has_edge(source, nbr) and not nbr == source\n ]\n if neighborhood: # if there is a neighbor without a link\n nbr = seed.choice(neighborhood)\n G.add_edge(source, nbr) # add triangle\n repeated_nodes.append(nbr)\n count = count + 1\n continue # go to top of while loop\n # else do preferential attachment step if above fails\n target = possible_targets.pop()\n G.add_edge(source, target)\n repeated_nodes.append(target)\n count = count + 1\n\n repeated_nodes.extend([source] * m) # add source node to list m times\n source += 1\n return G\n\n\n@patch_docstring(nxa.random_lobster)\n@py_random_state(3)\ndef random_lobster(n, p1, p2, seed=None):\n # a necessary ingredient in any self-respecting graph library\n llen = int(2 * seed.random() * n + 0.5)\n L = path_graph(llen)\n # build caterpillar: add edges to path graph with probability p1\n current_node = llen - 1\n for n in range(llen):\n if seed.random() < p1: # add fuzzy caterpillar parts\n current_node += 1\n L.add_edge(n, current_node)\n if seed.random() < p2: # add crunchy lobster bits\n current_node += 1\n L.add_edge(current_node - 1, current_node)\n return L # voila, un lobster!\n\n\n@patch_docstring(nxa.random_shell_graph)\n@py_random_state(1)\ndef random_shell_graph(constructor, seed=None):\n G = empty_graph(0)\n\n glist = []\n intra_edges = []\n nnodes = 0\n # create gnm graphs for each shell\n for (n, m, d) in constructor:\n inter_edges = int(m * d)\n intra_edges.append(m - inter_edges)\n g = nx.convert_node_labels_to_integers(\n gnm_random_graph(n, inter_edges, seed=seed), first_label=nnodes\n )\n glist.append(g)\n nnodes += n\n G = nx.operators.union(G, g)\n\n # connect the shells randomly\n for gi in range(len(glist) - 1):\n nlist1 = list(glist[gi])\n nlist2 = list(glist[gi + 1])\n total_edges = intra_edges[gi]\n edge_count = 0\n while edge_count < total_edges:\n u = seed.choice(nlist1)\n v = seed.choice(nlist2)\n if u == v or G.has_edge(u, v):\n continue\n else:\n G.add_edge(u, v)\n edge_count = edge_count + 1\n return G\n\n\n@patch_docstring(nxa.random_powerlaw_tree)\n@py_random_state(2)\ndef random_powerlaw_tree(n, gamma=3, seed=None, tries=100):\n # This call may raise a NetworkXError if the number of tries is succeeded.\n seq = random_powerlaw_tree_sequence(n, gamma=gamma, seed=seed, tries=tries)\n G = degree_sequence_tree(seq)\n return G\n\n\n@patch_docstring(nxa.random_powerlaw_tree_sequence)\n@py_random_state(2)\ndef random_powerlaw_tree_sequence(n, gamma=3, seed=None, tries=100):\n # get trial sequence\n z = powerlaw_sequence(n, exponent=gamma, seed=seed)\n # round to integer values in the range [0,n]\n zseq = [min(n, max(int(round(s)), 0)) for s in z]\n\n # another sequence to swap values from\n z = powerlaw_sequence(tries, exponent=gamma, seed=seed)\n # round to integer values in the range [0,n]\n swap = [min(n, max(int(round(s)), 0)) for s in z]\n\n for deg in swap:\n # If this degree sequence can be the degree sequence of a tree, return\n # it. It can be a tree if the number of edges is one fewer than the\n # number of nodes, or in other words, `n - sum(zseq) / 2 == 1`. We\n # use an equivalent condition below that avoids floating point\n # operations.\n if 2 * n - sum(zseq) == 2:\n return zseq\n index = seed.randint(0, n - 1)\n zseq[index] = swap.pop()\n\n raise nx.NetworkXError(\n \"Exceeded max (%d) attempts for a valid tree\" \" sequence.\" % tries\n )\n\n\n@patch_docstring(nxa.random_kernel_graph)\n@py_random_state(3)\ndef random_kernel_graph(n, kernel_integral, kernel_root=None, seed=None):\n if kernel_root is None:\n import scipy.optimize as optimize\n\n def kernel_root(y, a, r):\n def my_function(b):\n return kernel_integral(y, a, b) - r\n\n return optimize.brentq(my_function, a, 1)\n\n graph = nx.Graph()\n graph.add_nodes_from(range(n))\n (i, j) = (1, 1)\n while i < n:\n r = -math.log(1 - seed.random()) # (1-seed.random()) in (0, 1]\n if kernel_integral(i / n, j / n, 1) <= r:\n i, j = i + 1, i + 1\n else:\n j = int(math.ceil(n * kernel_root(i / n, j / n, r)))\n graph.add_edge(i - 1, j - 1)\n return graph\n"
] |
[
[
"scipy.optimize.brentq"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
JacobARose/genetic_algorithm
|
[
"de4c52637f6b928b96c0306b7da59a054322b56c"
] |
[
"genetic_algorithm/models/zoo/preprocess_c.py"
] |
[
"# Copyright 2019 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\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential, Model, Input\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import ReLU, Dense, Conv2D, Conv2DTranspose\nfrom tensorflow.keras.layers import DepthwiseConv2D, SeparableConv2D, Dropout\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Activation, BatchNormalization\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.optimizers import Adam, SGD\nfrom tensorflow.compat.v1.keras.initializers import glorot_uniform, he_normal\nfrom tensorflow.keras.callbacks import LearningRateScheduler\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import to_categorical\nimport tensorflow_datasets as tfds\nimport tensorflow.keras.backend as K\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom tfrecord_utils.img_utils import resize_repeat\nfrom boltons.funcutils import partial\n\nimport random\nimport math\nimport sys\n\n\ndef get_parse_example_func(target_size=(224,224,3), num_classes=10):\n resize = resize_repeat(target_size=tuple(target_size), training=False)\n one_hot = partial(tf.one_hot, depth=num_classes)\n def _parse_example(x, y):\n x = tf.image.convert_image_dtype(x, tf.float32)\n x = resize(x)\n y = one_hot(y)\n return x,y\n return _parse_example\n\n\n# def resize(self):\n# def preprocess_data(data: tf.data.Dataset, target_size=None, num_classes=None, batch_size=1, buffer_size=1024): #class_encoder=None):\n# parse_example = get_parse_example_func(target_size=target_size, num_classes=num_classes) #class_encoder=class_encoder)\n# return data.map(lambda x,y: parse_example(x, y), num_parallel_calls=-1) \\\n# .shuffle(buffer_size) \\\n# .batch(batch_size) \\\n# .prefetch(-1)\n\nclass Preprocess:\n ''' Preprocess base (super) class for Composable Models '''\n\n def __init__(self):\n \"\"\" Constructor\n \"\"\"\n pass\n\n ###\n # Preprocessing\n ###\n\n def normalization(self, x_train, x_test=None, centered=False):\n \"\"\" Normalize the input\n x_train : training images\n y_train : test images\n \"\"\"\n if x_train.dtype == np.uint8:\n if centered:\n x_train = ((x_train - 1) / 127.5).astype(np.float32)\n if x_test is not None:\n x_test = ((x_test - 1) / 127.5).astype(np.float32)\n else:\n x_train = (x_train / 255.0).astype(np.float32)\n if x_test is not None:\n x_test = (x_test / 255.0).astype(np.float32)\n return x_train, x_test\n\n def standardization(self, x_train, x_test=None):\n \"\"\" Standardize the input\n x_train : training images\n x_test : test images\n \"\"\"\n self.mean = np.mean(x_train)\n self.std = np.std(x_train)\n x_train = ((x_train - self.mean) / self.std).astype(np.float32)\n if x_test is not None:\n x_test = ((x_test - self.mean) / self.std).astype(np.float32)\n return x_train, x_test\n\n def label_smoothing(self, y_train, n_classes, factor=0.1):\n \"\"\" Convert a matrix of one-hot row-vector labels into smoothed versions. \n y_train : training labels\n n_classes: number of classes\n factor : smoothing factor (between 0 and 1)\n \"\"\"\n if 0 <= factor <= 1:\n # label smoothing ref: https://www.robots.ox.ac.uk/~vgg/rg/papers/reinception.pdf\n y_train *= 1 - factor\n y_train += factor / n_classes\n else:\n raise Exception('Invalid label smoothing factor: ' + str(factor))\n return y_train\n\n \n \n \n## class-Weighted label smoothing \n# def class_weight(labels_dict,mu=0.15):\n# total = np.sum(labels_dict.values())\n# keys = labels_dict.keys()\n# weight = dict()\n# for i in keys:\n# score = np.log(mu*total/float(labels_dict[i]))\n# weight[i] = score if score > 1 else 1\n# return weight\n# # random labels_dict\n# labels_dict = df[target_Y].value_counts().to_dict()\n# weights = class_weight(labels_dict)"
] |
[
[
"numpy.std",
"numpy.mean",
"tensorflow.image.convert_image_dtype"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
martinhoang11/pytorch_mpiigaze_demo
|
[
"26f9cd0c4278041ceb905ebb1ccbe5825f822d6f"
] |
[
"ptgaze/common/visualizer.py"
] |
[
"from typing import Optional, Tuple\n\nimport cv2\nimport numpy as np\nfrom scipy.spatial.transform import Rotation\n\nfrom .camera import Camera\nfrom .face import Face\n\nAXIS_COLORS = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]\n\n\nclass Visualizer:\n def __init__(self, camera: Camera, center_point_index: int):\n self._camera = camera\n self._center_point_index = center_point_index\n self.image: Optional[np.ndarray] = None\n\n def set_image(self, image: np.ndarray) -> None:\n self.image = image\n\n def draw_bbox(self,\n bbox: np.ndarray,\n color: Tuple[int, int, int] = (0, 255, 0),\n lw: int = 1) -> None:\n assert self.image is not None\n assert bbox.shape == (2, 2)\n bbox = np.round(bbox).astype(np.int).tolist()\n cv2.rectangle(self.image, tuple(bbox[0]), tuple(bbox[1]), color, lw)\n\n @staticmethod\n def _convert_pt(point: np.ndarray) -> Tuple[int, int]:\n return tuple(np.round(point).astype(np.int).tolist())\n\n def draw_points(self,\n points: np.ndarray,\n color: Tuple[int, int, int] = (0, 0, 255),\n size: int = 3) -> None:\n assert self.image is not None\n assert points.shape[1] == 2\n for pt in points:\n pt = self._convert_pt(pt)\n cv2.circle(self.image, pt, size, color, cv2.FILLED)\n\n def draw_3d_points(self,\n points3d: np.ndarray,\n color: Tuple[int, int, int] = (255, 0, 255),\n size=3) -> None:\n assert self.image is not None\n assert points3d.shape[1] == 3\n points2d = self._camera.project_points(points3d)\n self.draw_points(points2d, color=color, size=size)\n\n def draw_3d_line(self,\n point0: np.ndarray,\n point1: np.ndarray,\n color: Tuple[int, int, int] = (255, 255, 0),\n lw=2) -> None:\n assert self.image is not None\n assert point0.shape == point1.shape == (3, )\n points3d = np.vstack([point0, point1])\n points2d = self._camera.project_points(points3d)\n pt0 = self._convert_pt(points2d[0])\n pt1 = self._convert_pt(points2d[1])\n # cv2.line(self.image, pt0, pt1, color, lw, cv2.LINE_AA)\n cv2.arrowedLine(self.image, pt0, pt1, color, lw, cv2.LINE_AA)\n # cv2.arrowedLine(image_out, tuple(np.round(pos).astype(np.int32)),\n # tuple(np.round([pos[0] + dx, pos[1] + dy]).astype(int)), color,\n # thickness, cv2.LINE_AA, tipLength=0.2)\n\n def draw_model_axes(self, face: Face, length: float, lw: int = 2) -> None:\n assert self.image is not None\n assert face is not None\n assert face.head_pose_rot is not None\n assert face.head_position is not None\n assert face.landmarks is not None\n # Get the axes of the model coordinate system\n axes3d = np.eye(3, dtype=np.float) @ Rotation.from_euler(\n 'XYZ', [0, np.pi, 0]).as_matrix()\n axes3d = axes3d * length\n axes2d = self._camera.project_points(axes3d,\n face.head_pose_rot.as_rotvec(),\n face.head_position)\n center = face.landmarks[self._center_point_index]\n print(self._center_point_index)\n center = self._convert_pt(center)\n for pt, color in zip(axes2d, AXIS_COLORS):\n pt = self._convert_pt(pt)\n cv2.line(self.image, center, pt, color, lw, cv2.LINE_AA)\n \n def draw_info(self, name, attr, org: int, color: int = (255, 0, 0)) -> None:\n cv2.putText(self.image, f\"{name}: {attr}\", org, cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 1, cv2.LINE_AA)\n"
] |
[
[
"numpy.round",
"scipy.spatial.transform.Rotation.from_euler",
"numpy.eye",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.5",
"1.2",
"1.3",
"1.4"
],
"tensorflow": []
}
] |
erip/data
|
[
"9c6e5ddfcdf1061e3968ed5cd9d55754cc713965"
] |
[
"examples/vision/caltech101.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\nimport os.path\nimport re\n\nimport torch\nfrom torch.utils.data.datapipes.utils.decoder import imagehandler, mathandler\nfrom torchdata.datapipes.iter import (\n FileOpener,\n Filter,\n IterableWrapper,\n IterKeyZipper,\n Mapper,\n RoutedDecoder,\n TarArchiveReader,\n)\n\n\n# Download size is ~150 MB so fake data is provided\nURL = {\n \"images\": \"http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz\",\n \"annotations\": \"http://www.vision.caltech.edu/Image_Datasets/Caltech101/Annotations.tar\",\n}\n# We really shouldn't use MD5 anymore and switch to a more secure hash like SHA256 or\n# SHA512\nMD5 = {\n \"images\": \"b224c7392d521a49829488ab0f1120d9\",\n \"annotations\": \"f83eeb1f24d99cab4eb377263132c91\",\n}\n\nROOT = os.path.join(\"fakedata\", \"caltech101\")\n\nIMAGES_NAME_PATTERN = re.compile(r\"image_(?P<id>\\d+)[.]jpg\")\nANNS_NAME_PATTERN = re.compile(r\"annotation_(?P<id>\\d+)[.]mat\")\nANNS_CLASS_MAP = {\n \"Faces_2\": \"Faces\",\n \"Faces_3\": \"Faces_easy\",\n \"Motorbikes_16\": \"Motorbikes\",\n \"Airplanes_Side_2\": \"airplanes\",\n}\n\n\ndef is_ann(data):\n path, _ = data\n return bool(ANNS_NAME_PATTERN.match(os.path.basename(path)))\n\n\ndef collate_ann(data):\n path, ann = data\n\n cls = os.path.split(os.path.dirname(path))[1]\n if cls in ANNS_CLASS_MAP:\n cls = ANNS_CLASS_MAP[cls]\n\n return path, {\"cls\": cls, \"contour\": torch.as_tensor(ann[\"obj_contour\"])}\n\n\ndef is_not_background_image(data):\n path, _ = data\n return os.path.split(os.path.dirname(path))[1] != \"BACKGROUND_Google\"\n\n\ndef is_not_rogue_image(data) -> bool:\n path, _ = data\n return os.path.basename(path) != \"RENAME2\"\n\n\ndef extract_file_id(path, *, pattern):\n match = pattern.match(os.path.basename(path))\n return int(match.group(\"id\"))\n\n\ndef images_key_fn(data):\n path, _ = data\n cls = os.path.split(os.path.dirname(path))[1]\n id = extract_file_id(path, pattern=IMAGES_NAME_PATTERN)\n return cls, id\n\n\ndef anns_key_fn(data):\n path, ann = data\n id = extract_file_id(path, pattern=ANNS_NAME_PATTERN)\n return ann[\"cls\"], id\n\n\ndef collate_sample(data):\n (image_path, image), (ann_path, ann) = data\n return dict(ann, image_path=image_path, image=image, ann_path=ann_path)\n\n\ndef Caltech101(root=ROOT):\n anns_dp = IterableWrapper([os.path.join(root, \"Annotations.tar\")])\n anns_dp = FileOpener(anns_dp, mode=\"b\")\n anns_dp = TarArchiveReader(anns_dp)\n anns_dp = Filter(anns_dp, is_ann)\n anns_dp = RoutedDecoder(anns_dp, mathandler())\n anns_dp = Mapper(anns_dp, collate_ann)\n\n images_dp = IterableWrapper([os.path.join(root, \"101_ObjectCategories.tar.gz\")])\n images_dp = FileOpener(images_dp, mode=\"b\")\n images_dp = TarArchiveReader(images_dp)\n images_dp = Filter(images_dp, is_not_background_image)\n images_dp = Filter(images_dp, is_not_rogue_image)\n images_dp = RoutedDecoder(images_dp, imagehandler(\"pil\"))\n\n dp = IterKeyZipper(images_dp, anns_dp, images_key_fn, ref_key_fn=anns_key_fn, buffer_size=None)\n return Mapper(dp, collate_sample)\n\n\nif __name__ == \"__main__\":\n for _sample in Caltech101():\n pass\n"
] |
[
[
"torch.utils.data.datapipes.utils.decoder.mathandler",
"torch.utils.data.datapipes.utils.decoder.imagehandler",
"torch.as_tensor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
BookML/stylegan2-ada-pytorch
|
[
"d4b2afe9c27e3c305b721bc886d2cb5229458eba"
] |
[
"generate.py"
] |
[
"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# NVIDIA CORPORATION and its licensors retain all intellectual property\n# and proprietary rights in and to this software, related documentation\n# and any modifications thereto. Any use, reproduction, disclosure or\n# distribution of this software and related documentation without an express\n# license agreement from NVIDIA CORPORATION is strictly prohibited.\n\n\"\"\"Generate images using pretrained network pickle.\"\"\"\n\nimport os\nimport re\nfrom typing import List, Optional\n\nimport click\nimport dnnlib\nimport numpy as np\nimport PIL.Image\nimport torch\n\nimport legacy\n\n#----------------------------------------------------------------------------\n\ndef num_range(s: str) -> List[int]:\n '''Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints.'''\n\n range_re = re.compile(r'^(\\d+)-(\\d+)$')\n m = range_re.match(s)\n if m:\n return list(range(int(m.group(1)), int(m.group(2))+1))\n vals = s.split(',')\n return [int(x) for x in vals]\n\n#----------------------------------------------------------------------------\n\[email protected]()\[email protected]_context\[email protected]('--network', 'network_pkl', help='Network pickle filename', required=True)\[email protected]('--seeds', type=num_range, help='List of random seeds')\[email protected]('--trunc', 'truncation_psi', type=float, help='Truncation psi', default=1, show_default=True)\[email protected]('--class', 'class_idx', type=int, help='Class label (unconditional if not specified)')\[email protected]('--noise-mode', help='Noise mode', type=click.Choice(['const', 'random', 'none']), default='const', show_default=True)\[email protected]('--projected-w', help='Projection result file', type=str, metavar='FILE')\[email protected]('--outdir', help='Where to save the output images', type=str, required=True, metavar='DIR')\ndef generate_images(\n ctx: click.Context,\n network_pkl: str,\n seeds: Optional[List[int]],\n truncation_psi: float,\n noise_mode: str,\n outdir: str,\n class_idx: Optional[int],\n projected_w: Optional[str]\n):\n \"\"\"Generate images using pretrained network pickle.\n\n Examples:\n\n \\b\n # Generate curated MetFaces images without truncation (Fig.10 left)\n python generate.py --outdir=out --trunc=1 --seeds=85,265,297,849 \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl\n\n \\b\n # Generate uncurated MetFaces images with truncation (Fig.12 upper left)\n python generate.py --outdir=out --trunc=0.7 --seeds=600-605 \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl\n\n \\b\n # Generate class conditional CIFAR-10 images (Fig.17 left, Car)\n python generate.py --outdir=out --seeds=0-35 --class=1 \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/cifar10.pkl\n\n \\b\n # Render an image from projected W\n python generate.py --outdir=out --projected_w=projected_w.npz \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl\n \"\"\"\n\n print('Loading networks from \"%s\"...' % network_pkl)\n device = torch.device('cuda')\n with dnnlib.util.open_url(network_pkl) as f:\n G = legacy.load_network_pkl(f)['G_ema'].to(device) # type: ignore\n\n os.makedirs(outdir, exist_ok=True)\n\n # Synthesize the result of a W projection.\n if projected_w is not None:\n if seeds is not None:\n print ('warn: --seeds is ignored when using --projected-w')\n print(f'Generating images from projected W \"{projected_w}\"')\n ws = np.load(projected_w)['w']\n ws = torch.tensor(ws, device=device) # pylint: disable=not-callable\n assert ws.shape[1:] == (G.num_ws, G.w_dim)\n for idx, w in enumerate(ws):\n img = G.synthesis(w.unsqueeze(0), noise_mode=noise_mode)\n img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n img = PIL.Image.fromarray(img[0].cpu().numpy(), 'RGB').save(f'{outdir}/proj{idx:02d}.png')\n return\n\n if seeds is None:\n ctx.fail('--seeds option is required when not using --projected-w')\n\n # Labels.\n label = torch.zeros([1, G.c_dim], device=device)\n if G.c_dim != 0:\n if class_idx is None:\n ctx.fail('Must specify class label with --class when using a conditional network')\n label[:, class_idx] = 1\n else:\n if class_idx is not None:\n print ('warn: --class=lbl ignored when running on an unconditional network')\n\n # Generate images.\n for seed_idx, seed in enumerate(seeds):\n print('Generating image for seed %d (%d/%d) ...' % (seed, seed_idx, len(seeds)))\n z = torch.from_numpy(np.random.RandomState(seed).randn(1, G.z_dim)).to(device)\n img = G(z, label, truncation_psi=truncation_psi, noise_mode=noise_mode)\n img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n PIL.Image.fromarray(img[0].cpu().numpy(), 'RGB').save(f'{outdir}/seed{seed:04d}.png')\n\n\n#----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n generate_images() # pylint: disable=no-value-for-parameter\n\n#----------------------------------------------------------------------------\n"
] |
[
[
"torch.zeros",
"torch.tensor",
"torch.device",
"numpy.load",
"numpy.random.RandomState"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
anndvision/causal-bald
|
[
"4e58ef0afa4ba7c4e12342e6052b39a93c95c680"
] |
[
"causal_bald/application/workflows/active_learning.py"
] |
[
"import json\nimport numpy as np\nimport scipy.stats\n\nfrom copy import deepcopy\n\nfrom causal_bald.library import models\nfrom causal_bald.library import datasets\nfrom causal_bald.library import acquisitions\n\nfrom causal_bald.application.workflows import utils\n\n\ndef active_learner(model_name, config, experiment_dir, trial):\n # Set dataset seeds\n dataset_name = config.get(\"dataset_name\")\n config[\"ds_train\"][\"seed\"] = trial\n config[\"ds_valid\"][\"seed\"] = trial + 1 if dataset_name == \"synthetic\" else trial\n config[\"ds_test\"][\"seed\"] = trial + 2 if dataset_name == \"synthetic\" else trial\n # Get datasets\n ds_active = datasets.ActiveLearningDataset(\n datasets.DATASETS.get(dataset_name)(**config.get(\"ds_train\"))\n )\n ds_valid = datasets.DATASETS.get(dataset_name)(**config.get(\"ds_valid\"))\n # Set the trial dir\n experiment_dir = utils.DIRECTORIES[model_name](\n base_dir=experiment_dir, config=config\n )\n trial_dir = experiment_dir / f\"trial-{trial:03d}\"\n trial_dir.mkdir(parents=True, exist_ok=True)\n # Write config for downstream use\n config_path = trial_dir / \"config.json\"\n with config_path.open(mode=\"w\") as cp:\n json.dump(config, cp)\n # Get the acquisition function\n acquisition_function = acquisitions.FUNCTIONS.get(\n config.get(\"acquisition_function\")\n )\n # Train pi model if needed by acquisition\n pt = get_propensities(trial_dir=trial_dir, config=config)\n # Do active learning loop\n step_size = config.get(\"step_size\")\n warm_start_size = config.get(\"warm_start_size\")\n max_acquisitions = config.get(\"max_acquisitions\")\n temperature = config.get(\"temperature\")\n use_gumbel = config.get(\"use_gumbel\")\n for i in range(max_acquisitions):\n batch_size = warm_start_size if i == 0 else step_size\n acquisition_dir = trial_dir / f\"acquisition-{i:03d}\"\n acquired_path = acquisition_dir / \"aquired.json\"\n if not acquired_path.exists():\n if i == 0:\n scores = acquisitions.random(\n mu_0=None, mu_1=None, t=ds_active.dataset.t, pt=pt, temperature=None\n )[ds_active.pool_dataset.indices]\n else:\n # Predict pool set\n mu_0, mu_1 = utils.PREDICT_FUNCTIONS[model_name](\n dataset=ds_active.dataset,\n job_dir=trial_dir / f\"acquisition-{i-1:03d}\",\n config=config,\n )\n # Get acquisition scores\n scores = (\n acquisition_function(\n mu_0=mu_0,\n mu_1=mu_1,\n t=ds_active.dataset.t,\n pt=pt,\n temperature=temperature if temperature > 0.0 else 1.0,\n )\n )[ds_active.pool_dataset.indices]\n if temperature > 0.0:\n if use_gumbel:\n p = scores + scipy.stats.gumbel_r.rvs(\n loc=0, scale=1, size=len(scores), random_state=None,\n )\n idx = np.argpartition(p, -batch_size)[-batch_size:]\n else:\n scores = np.exp(scores)\n p = scores / scores.sum()\n idx = np.random.choice(\n range(len(p)), replace=False, p=p, size=batch_size,\n )\n else:\n idx = np.argsort(scores)[-batch_size:]\n ds_active.acquire(idx)\n # Train model\n utils.TRAIN_FUNCTIONS[model_name](\n ds_train=ds_active.training_dataset,\n ds_valid=ds_valid,\n job_dir=acquisition_dir,\n config=config,\n dim_input=ds_active.dataset.dim_input,\n )\n # Save acuired points\n with acquired_path.open(mode=\"w\") as ap:\n json.dump(\n {\"aquired_indices\": [int(a) for a in ds_active.acquired_indices]},\n ap,\n )\n\n\ndef get_propensities(trial_dir, config):\n dataset_name = config.get(\"dataset_name\")\n dim_hidden = config.get(\"dim_hidden\")\n depth = config.get(\"depth\")\n negative_slope = config.get(\"negative_slope\")\n dropout_rate = config.get(\"dropout_rate\")\n spectral_norm = config.get(\"spectral_norm\")\n learning_rate = config.get(\"learning_rate\")\n batch_size = config.get(\"batch_size\")\n epochs = config.get(\"epochs\")\n if config.get(\"acquisition_function\") in [\"pi\", \"mu-pi\"]:\n config_pi_train = deepcopy(config.get(\"ds_train\"))\n config_pi_train[\"mode\"] = \"pi\"\n ds_pi_train = datasets.DATASETS.get(dataset_name)(**config_pi_train)\n pi_dir = trial_dir / \"pi\"\n pi_model = models.NeuralNetwork(\n job_dir=pi_dir,\n architecture=\"resnet\",\n dim_input=ds_pi_train.dim_input,\n dim_hidden=dim_hidden,\n dim_output=1,\n depth=depth,\n negative_slope=negative_slope,\n batch_norm=False,\n spectral_norm=spectral_norm,\n dropout_rate=dropout_rate,\n weight_decay=(0.5 * (1 - config.get(\"dropout_rate\"))) / len(ds_pi_train),\n learning_rate=learning_rate,\n batch_size=batch_size,\n epochs=epochs,\n patience=10,\n num_workers=0,\n seed=config.get(\"seed\"),\n )\n if not (pi_dir / \"best_checkpoint.pt\").exists():\n config_pi_valid = deepcopy(config.get(\"ds_valid\"))\n config_pi_valid[\"mode\"] = \"pi\"\n ds_pi_valid = datasets.DATASETS.get(dataset_name)(**config_pi_valid)\n pi_model.fit(ds_pi_train, ds_pi_valid)\n pi_model.load()\n return pi_model.predict_mean(ds_pi_train).ravel()\n else:\n return None\n"
] |
[
[
"numpy.argsort",
"numpy.exp",
"numpy.argpartition"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
khiemledev/Basic_CNNs_TensorFlow2
|
[
"be2c90f2a63ae13b7586a1e4114c2bc42a825c83"
] |
[
"models/resnext_block.py"
] |
[
"import tensorflow as tf\n\nfrom models.group_convolution import get_group_conv\n\n\nclass ResNeXt_BottleNeck(tf.keras.layers.Layer):\n def __init__(self, filters, strides, groups):\n super(ResNeXt_BottleNeck, self).__init__()\n self.conv1 = tf.keras.layers.Conv2D(filters=filters,\n kernel_size=(1, 1),\n strides=1,\n padding=\"same\")\n self.bn1 = tf.keras.layers.BatchNormalization()\n # self.group_conv = tf.keras.layers.Conv2D(filters=filters,\n # kernel_size=(3, 3),\n # strides=strides,\n # padding=\"same\",\n # groups=groups)\n self.group_conv = get_group_conv(in_channels=filters,\n out_channels=filters,\n kernel_size=(3, 3),\n strides=strides,\n padding=\"same\",\n groups=groups)\n self.bn2 = tf.keras.layers.BatchNormalization()\n self.conv2 = tf.keras.layers.Conv2D(filters=2 * filters,\n kernel_size=(1, 1),\n strides=1,\n padding=\"same\")\n self.bn3 = tf.keras.layers.BatchNormalization()\n self.shortcut_conv = tf.keras.layers.Conv2D(filters=2 * filters,\n kernel_size=(1, 1),\n strides=strides,\n padding=\"same\")\n self.shortcut_bn = tf.keras.layers.BatchNormalization()\n\n def call(self, inputs, training=None, **kwargs):\n x = self.conv1(inputs)\n x = self.bn1(x, training=training)\n x = tf.nn.relu(x)\n x = self.group_conv(x)\n x = self.bn2(x, training=training)\n x = tf.nn.relu(x)\n x = self.conv2(x)\n x = self.bn3(x, training=training)\n\n shortcut = self.shortcut_conv(inputs)\n shortcut = self.shortcut_bn(shortcut, training=training)\n\n output = tf.nn.relu(tf.keras.layers.add([x, shortcut]))\n return output\n\n\ndef build_ResNeXt_block(filters, strides, groups, repeat_num):\n block = tf.keras.Sequential()\n block.add(ResNeXt_BottleNeck(filters=filters,\n strides=strides,\n groups=groups))\n for _ in range(1, repeat_num):\n block.add(ResNeXt_BottleNeck(filters=filters,\n strides=1,\n groups=groups))\n\n return block"
] |
[
[
"tensorflow.nn.relu",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.Sequential",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.add"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
SEMCOG/SEMCOG_ActSim
|
[
"cc18cce84b2e4b5f380f58c7919953d2cd03ee73",
"cc18cce84b2e4b5f380f58c7919953d2cd03ee73",
"cc18cce84b2e4b5f380f58c7919953d2cd03ee73"
] |
[
"activitysim/abm/models/util/trip.py",
"activitysim/core/input.py",
"activitysim/core/pipeline.py"
] |
[
"# ActivitySim\n# See full license in LICENSE.txt.\nimport logging\n\nimport numpy as np\n\nfrom activitysim.core.util import assign_in_place\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef failed_trip_cohorts(trips, failed):\n\n # outbound trips in a tour with a failed outbound trip\n bad_outbound_trips = \\\n trips.outbound & (trips.tour_id.isin(trips.tour_id[failed & trips.outbound]))\n\n # inbound trips in a tour with a failed inbound trip\n bad_inbound_trips = \\\n ~trips.outbound & (trips.tour_id.isin(trips.tour_id[failed & ~trips.outbound]))\n\n bad_trips = bad_outbound_trips | bad_inbound_trips\n\n return bad_trips\n\n\ndef flag_failed_trip_leg_mates(trips_df, col_name):\n \"\"\"\n set boolean flag column of specified name to identify failed trip leg_mates in place\n \"\"\"\n\n failed_trip_leg_mates = failed_trip_cohorts(trips_df, trips_df.failed) & ~trips_df.failed\n trips_df.loc[failed_trip_leg_mates, col_name] = True\n\n # handle outbound and inbound legs independently\n # for ob in [True, False]:\n # same_leg = (trips_df.outbound == ob)\n # # tour_ids of all tours with a failed trip in this (outbound or inbound) leg direction\n # bad_tours = trips_df.tour_id[trips_df.failed & same_leg].unique()\n # # not-failed leg_mates of all failed trips in this (outbound or inbound) leg direction\n # failed_trip_leg_mates = same_leg & (trips_df.tour_id.isin(bad_tours)) & ~trips_df.failed\n # # set the flag column\n # trips_df.loc[failed_trip_leg_mates, col_name] = True\n\n\ndef cleanup_failed_trips(trips):\n \"\"\"\n drop failed trips and cleanup fields in leg_mates:\n\n trip_num assign new ordinal trip num after failed trips are dropped\n trip_count assign new count of trips in leg, sans failed trips\n first update first flag as we may have dropped first trip (last trip can't fail)\n next_trip_id assign id of next trip in leg after failed trips are dropped\n \"\"\"\n\n if trips.failed.any():\n logger.warning(\"cleanup_failed_trips dropping %s failed trips\" % trips.failed.sum())\n\n trips['patch'] = False\n flag_failed_trip_leg_mates(trips, 'patch')\n\n # drop the original failures\n trips = trips[~trips.failed]\n\n # increasing trip_id order\n patch_trips = trips[trips.patch].sort_index()\n\n # recompute fields dependent on trip_num sequence\n grouped = patch_trips.groupby(['tour_id', 'outbound'])\n patch_trips['trip_num'] = grouped.cumcount() + 1\n patch_trips['trip_count'] = patch_trips['trip_num'] + grouped.cumcount(ascending=False)\n\n assign_in_place(trips, patch_trips[['trip_num', 'trip_count']])\n\n del trips['patch']\n\n del trips['failed']\n\n return trips\n\n\ndef generate_alternative_sizes(max_duration, max_trips):\n \"\"\"\n Builds a lookup Numpy array pattern sizes based on the\n number of trips in the leg and the duration available\n to the leg.\n :param max_duration:\n :param max_trips:\n :return:\n \"\"\"\n def np_shift(xs, n, fill_zero=True):\n if n >= 0:\n shift_array = np.concatenate((np.full(n, np.nan), xs[:-n]))\n else:\n shift_array = np.concatenate((xs[-n:], np.full(-n, np.nan)))\n return np.nan_to_num(shift_array, np.nan).astype(np.int) if fill_zero else shift_array\n\n levels = np.empty([max_trips, max_duration + max_trips])\n levels[0] = np.arange(1, max_duration + max_trips + 1)\n\n for level in np.arange(1, max_trips):\n levels[level] = np_shift(np.cumsum(np_shift(levels[level - 1], 1)), -1, fill_zero=False)\n\n return levels[:, :max_duration+1].astype(int)\n\n\ndef get_time_windows(residual, level):\n \"\"\"\n\n :param residual:\n :param level:\n :return:\n \"\"\"\n ranges = []\n\n for a in np.arange(residual + 1):\n if level > 1:\n windows = get_time_windows(residual - a, level - 1)\n width_dim = len(windows.shape) - 1\n ranges.append(np.vstack([np.repeat(a, windows.shape[width_dim]), windows]))\n else:\n return np.arange(residual + 1)\n return np.concatenate(ranges, axis=1)\n",
"# ActivitySim\n# See full license in LICENSE.txt.\n\nimport logging\nimport warnings\nimport os\n\nimport pandas as pd\n\nfrom activitysim.core import (\n inject,\n config,\n util,\n)\nfrom activitysim.core import mem\n\nlogger = logging.getLogger(__name__)\n\n\ndef read_input_table(tablename):\n \"\"\"Reads input table name and returns cleaned DataFrame.\n\n Uses settings found in input_table_list in global settings file\n\n Parameters\n ----------\n tablename : string\n\n Returns\n -------\n pandas DataFrame\n \"\"\"\n table_list = config.setting('input_table_list')\n assert table_list is not None, 'no input_table_list found in settings'\n\n table_info = None\n for info in table_list:\n if info['tablename'] == tablename:\n table_info = info\n\n assert table_info is not None, \\\n f\"could not find info for for tablename {tablename} in settings file\"\n\n return read_from_table_info(table_info)\n\n\ndef read_from_table_info(table_info):\n \"\"\"\n Read input text files and return cleaned up DataFrame.\n\n table_info is a dictionary that specifies the following input params.\n\n See input_table_list in settings.yaml in the example folder for a working example\n\n +--------------+----------------------------------------------------------+\n | key | description |\n +==============+=========================================+================+\n | tablename | name of pipeline table in which to store dataframe |\n +--------------+----------------------------------------------------------+\n | filename | name of csv file to read (in data_dir) |\n +--------------+----------------------------------------------------------+\n | column_map | list of input columns to rename from_name: to_name |\n +--------------+----------------------------------------------------------+\n | index_col | name of column to set as dataframe index column |\n +--------------+----------------------------------------------------------+\n | drop_columns | list of column names of columns to drop |\n +--------------+----------------------------------------------------------+\n | h5_tablename | name of target table in HDF5 file |\n +--------------+----------------------------------------------------------+\n\n \"\"\"\n input_store = config.setting('input_store', None)\n create_input_store = config.setting('create_input_store', default=False)\n\n tablename = table_info.get('tablename')\n data_filename = table_info.get('filename', input_store)\n h5_tablename = table_info.get('h5_tablename') or tablename\n drop_columns = table_info.get('drop_columns', None)\n column_map = table_info.get('column_map', None)\n keep_columns = table_info.get('keep_columns', None)\n rename_columns = table_info.get('rename_columns', None)\n index_col = table_info.get('index_col', None)\n\n assert tablename is not None, 'no tablename provided'\n assert data_filename is not None, 'no input file provided'\n\n data_file_path = config.data_file_path(data_filename)\n\n df = _read_input_file(data_file_path, h5_tablename=h5_tablename)\n\n # logger.debug('raw %s table columns: %s' % (tablename, df.columns.values))\n logger.debug('raw %s table size: %s' % (tablename, util.df_size(df)))\n\n if create_input_store:\n h5_filepath = config.output_file_path('input_data.h5')\n logger.info('writing %s to %s' % (h5_tablename, h5_filepath))\n df.to_hdf(h5_filepath, key=h5_tablename, mode='a')\n\n csv_dir = config.output_file_path('input_data')\n if not os.path.exists(csv_dir):\n os.makedirs(csv_dir) # make directory if needed\n df.to_csv(os.path.join(csv_dir, '%s.csv' % tablename), index=False)\n\n if drop_columns:\n logger.debug(\"dropping columns: %s\" % drop_columns)\n df.drop(columns=drop_columns, inplace=True, errors='ignore')\n\n if column_map:\n warnings.warn(\"table_inf option 'column_map' renamed 'rename_columns'\"\n \"Support for 'column_map' will be removed in future versions.\",\n FutureWarning)\n logger.debug(\"renaming columns: %s\" % column_map)\n df.rename(columns=column_map, inplace=True)\n\n # rename columns first, so keep_columns can be a stable list of expected/required columns\n if rename_columns:\n logger.debug(\"renaming columns: %s\" % rename_columns)\n df.rename(columns=rename_columns, inplace=True)\n\n # set index\n if index_col is not None:\n if index_col in df.columns:\n assert not df.duplicated(index_col).any()\n df.set_index(index_col, inplace=True)\n else:\n # FIXME not sure we want to do this. More likely they omitted index col than that they want to name it?\n # df.index.names = [index_col]\n logger.error(f\"index_col '{index_col}' specified in configs but not in {tablename} table!\")\n logger.error(f\"{tablename} columns are: {list(df.columns)}\")\n raise RuntimeError(f\"index_col '{index_col}' not in {tablename} table!\")\n\n if keep_columns:\n logger.debug(\"keeping columns: %s\" % keep_columns)\n if not set(keep_columns).issubset(set(df.columns)):\n logger.error(f\"Required columns missing from {tablename} table: \"\n f\"{list(set(keep_columns).difference(set(df.columns)))}\")\n logger.error(f\"{tablename} table has columns: {list(df.columns)}\")\n raise RuntimeError(f\"Required columns missing from {tablename} table\")\n\n df = df[keep_columns]\n\n if df.columns.duplicated().any():\n duplicate_column_names = df.columns[df.columns.duplicated(keep=False)].unique().to_list()\n assert not df.columns.duplicated().any(), f\"duplicate columns names in {tablename}: {duplicate_column_names}\"\n\n logger.debug('%s table columns: %s' % (tablename, df.columns.values))\n logger.debug('%s table size: %s' % (tablename, util.df_size(df)))\n logger.info('%s index name: %s' % (tablename, df.index.name))\n\n return df\n\n\ndef _read_input_file(filepath, h5_tablename=None):\n assert os.path.exists(filepath), 'input file not found: %s' % filepath\n\n if filepath.endswith('.csv'):\n return _read_csv_with_fallback_encoding(filepath)\n\n if filepath.endswith('.h5'):\n assert h5_tablename is not None, 'must provide a tablename to read HDF5 table'\n logger.info('reading %s table from %s' % (h5_tablename, filepath))\n return pd.read_hdf(filepath, h5_tablename)\n\n raise IOError(\n 'Unsupported file type: %s. '\n 'ActivitySim supports CSV and HDF5 files only' % filepath)\n\n\ndef _read_csv_with_fallback_encoding(filepath):\n \"\"\"read a CSV to a pandas DataFrame using default utf-8 encoding,\n but try alternate Windows-compatible cp1252 if unicode fails\n\n \"\"\"\n\n try:\n logger.info('Reading CSV file %s' % filepath)\n return pd.read_csv(filepath, comment='#')\n except UnicodeDecodeError:\n logger.warning(\n 'Reading %s with default utf-8 encoding failed, trying cp1252 instead', filepath)\n return pd.read_csv(filepath, comment='#', encoding='cp1252')\n",
"# ActivitySim\n# See full license in LICENSE.txt.\nfrom builtins import next\nfrom builtins import map\nfrom builtins import object\n\nimport os\nimport logging\nimport datetime as dt\n\nimport pandas as pd\n\nfrom . import orca\nfrom . import inject\nfrom . import config\nfrom . import random\nfrom . import tracing\nfrom . import mem\n\n\nfrom . import util\nfrom .tracing import print_elapsed_time\n\n\nlogger = logging.getLogger(__name__)\n\n# name of the checkpoint dict keys\n# (which are also columns in the checkpoints dataframe stored in hte pipeline store)\nTIMESTAMP = 'timestamp'\nCHECKPOINT_NAME = 'checkpoint_name'\nNON_TABLE_COLUMNS = [CHECKPOINT_NAME, TIMESTAMP]\n\n# name used for storing the checkpoints dataframe to the pipeline store\nCHECKPOINT_TABLE_NAME = 'checkpoints'\n\n# name of the first step/checkpoint created when teh pipeline is started\nINITIAL_CHECKPOINT_NAME = 'init'\n\n# special value for resume_after meaning last checkpoint\nLAST_CHECKPOINT = '_'\n\n# single character prefix for run_list model name to indicate that no checkpoint should be saved\nNO_CHECKPOINT_PREFIX = '_'\n\n\nclass Pipeline(object):\n def __init__(self):\n self.init_state()\n\n def init_state(self):\n\n # most recent checkpoint\n self.last_checkpoint = {}\n\n # array of checkpoint dicts\n self.checkpoints = []\n\n self.replaced_tables = {}\n\n self._rng = random.Random()\n\n self.open_files = {}\n\n self.pipeline_store = None\n\n self.is_open = False\n\n def rng(self):\n\n return self._rng\n\n\n_PIPELINE = Pipeline()\n\n\ndef be_open():\n\n if not _PIPELINE.is_open:\n raise RuntimeError(\"Pipeline is not open!\")\n\n\ndef pipeline_table_key(table_name, checkpoint_name):\n if checkpoint_name:\n key = \"%s/%s\" % (table_name, checkpoint_name)\n else:\n key = table_name\n return key\n\n\ndef close_on_exit(file, name):\n assert name not in _PIPELINE.open_files\n _PIPELINE.open_files[name] = file\n\n\ndef close_open_files():\n for name, file in _PIPELINE.open_files.items():\n print(\"Closing %s\" % name)\n file.close()\n _PIPELINE.open_files.clear()\n\n\ndef open_pipeline_store(overwrite=False):\n \"\"\"\n Open the pipeline checkpoint store\n\n Parameters\n ----------\n overwrite : bool\n delete file before opening (unless resuming)\n \"\"\"\n\n if _PIPELINE.pipeline_store is not None:\n raise RuntimeError(\"Pipeline store is already open!\")\n\n pipeline_file_path = config.pipeline_file_path(inject.get_injectable('pipeline_file_name'))\n\n if overwrite:\n try:\n if os.path.isfile(pipeline_file_path):\n logger.debug(\"removing pipeline store: %s\" % pipeline_file_path)\n os.unlink(pipeline_file_path)\n except Exception as e:\n print(e)\n logger.warning(\"Error removing %s: %s\" % (pipeline_file_path, e))\n\n _PIPELINE.pipeline_store = pd.HDFStore(pipeline_file_path, mode='a')\n\n logger.debug(\"opened pipeline_store\")\n\n\ndef get_pipeline_store():\n \"\"\"\n Return the open pipeline hdf5 checkpoint store or return None if it not been opened\n \"\"\"\n return _PIPELINE.pipeline_store\n\n\ndef get_rn_generator():\n \"\"\"\n Return the singleton random number object\n\n Returns\n -------\n activitysim.random.Random\n \"\"\"\n return _PIPELINE.rng()\n\n\ndef read_df(table_name, checkpoint_name=None):\n \"\"\"\n Read a pandas dataframe from the pipeline store.\n\n We store multiple versions of all simulation tables, for every checkpoint in which they change,\n so we need to know both the table_name and the checkpoint_name of hte desired table.\n\n The only exception is the checkpoints dataframe, which just has a table_name\n\n An error will be raised by HDFStore if the table is not found\n\n Parameters\n ----------\n table_name : str\n checkpoint_name : str\n\n Returns\n -------\n df : pandas.DataFrame\n the dataframe read from the store\n\n \"\"\"\n\n store = get_pipeline_store()\n df = store[pipeline_table_key(table_name, checkpoint_name)]\n\n return df\n\n\ndef write_df(df, table_name, checkpoint_name=None):\n \"\"\"\n Write a pandas dataframe to the pipeline store.\n\n We store multiple versions of all simulation tables, for every checkpoint in which they change,\n so we need to know both the table_name and the checkpoint_name to label the saved table\n\n The only exception is the checkpoints dataframe, which just has a table_name\n\n Parameters\n ----------\n df : pandas.DataFrame\n dataframe to store\n table_name : str\n also conventionally the orca table name\n checkpoint_name : str\n the checkpoint at which the table was created/modified\n \"\"\"\n\n # coerce column names to str as unicode names will cause PyTables to pickle them\n df.columns = df.columns.astype(str)\n\n store = get_pipeline_store()\n\n store[pipeline_table_key(table_name, checkpoint_name)] = df\n\n store.flush()\n\n\ndef rewrap(table_name, df=None):\n \"\"\"\n Add or replace an orca registered table as a unitary DataFrame-backed DataFrameWrapper table\n\n if df is None, then get the dataframe from orca (table_name should be registered, or\n an error will be thrown) which may involve evaluating added columns, etc.\n\n If the orca table already exists, deregister it along with any associated columns before\n re-registering it.\n\n The net result is that the dataframe is a registered orca DataFrameWrapper table with no\n computed or added columns.\n\n Parameters\n ----------\n table_name\n df\n\n Returns\n -------\n the underlying df of the rewrapped table\n \"\"\"\n\n logger.debug(\"rewrap table %s inplace=%s\" % (table_name, (df is None)))\n\n if orca.is_table(table_name):\n\n if df is None:\n # logger.debug(\"rewrap - orca.get_table(%s)\" % (table_name,))\n t = orca.get_table(table_name)\n df = t.to_frame()\n else:\n # logger.debug(\"rewrap - orca.get_raw_table(%s)\" % (table_name,))\n # don't trigger function call of TableFuncWrapper\n t = orca.get_raw_table(table_name)\n\n t.clear_cached()\n\n for column_name in orca.list_columns_for_table(table_name):\n # logger.debug(\"pop %s.%s: %s\" % (table_name, column_name, t.column_type(column_name)))\n # fixme\n orca._COLUMNS.pop((table_name, column_name), None)\n\n # remove from orca's table list\n orca._TABLES.pop(table_name, None)\n\n assert df is not None\n\n orca.add_table(table_name, df)\n\n return df\n\n\ndef add_checkpoint(checkpoint_name):\n \"\"\"\n Create a new checkpoint with specified name, write all data required to restore the simulation\n to its current state.\n\n Detect any changed tables , re-wrap them and write the current version to the pipeline store.\n Write the current state of the random number generator.\n\n Parameters\n ----------\n checkpoint_name : str\n \"\"\"\n timestamp = dt.datetime.now()\n\n logger.debug(\"add_checkpoint %s timestamp %s\" % (checkpoint_name, timestamp))\n\n for table_name in orca_dataframe_tables():\n\n # if we have not already checkpointed it or it has changed\n # FIXME - this won't detect if the orca table was modified\n if len(orca.list_columns_for_table(table_name)):\n # rewrap the changed orca table as a unitary DataFrame-backed DataFrameWrapper table\n df = rewrap(table_name)\n elif table_name not in _PIPELINE.last_checkpoint or table_name in _PIPELINE.replaced_tables:\n df = orca.get_table(table_name).to_frame()\n else:\n continue\n\n logger.debug(\"add_checkpoint '%s' table '%s' %s\" %\n (checkpoint_name, table_name, util.df_size(df)))\n write_df(df, table_name, checkpoint_name)\n\n # remember which checkpoint it was last written\n _PIPELINE.last_checkpoint[table_name] = checkpoint_name\n\n _PIPELINE.replaced_tables.clear()\n\n _PIPELINE.last_checkpoint[CHECKPOINT_NAME] = checkpoint_name\n _PIPELINE.last_checkpoint[TIMESTAMP] = timestamp\n\n # append to the array of checkpoint history\n _PIPELINE.checkpoints.append(_PIPELINE.last_checkpoint.copy())\n\n # create a pandas dataframe of the checkpoint history, one row per checkpoint\n\n checkpoints = pd.DataFrame(_PIPELINE.checkpoints)\n\n # convert empty values to str so PyTables doesn't pickle object types\n for c in checkpoints.columns:\n checkpoints[c] = checkpoints[c].fillna('')\n\n # write it to the store, overwriting any previous version (no way to simply extend)\n write_df(checkpoints, CHECKPOINT_TABLE_NAME)\n\n\ndef orca_dataframe_tables():\n \"\"\"\n Return a list of the neames of all currently registered dataframe tables\n \"\"\"\n return [name for name in orca.list_tables() if orca.table_type(name) == 'dataframe']\n\n\ndef checkpointed_tables():\n \"\"\"\n Return a list of the names of all checkpointed tables\n \"\"\"\n\n return [name for name, checkpoint_name in _PIPELINE.last_checkpoint.items()\n if checkpoint_name and name not in NON_TABLE_COLUMNS]\n\n\ndef load_checkpoint(checkpoint_name):\n \"\"\"\n Load dataframes and restore random number channel state from pipeline hdf5 file.\n This restores the pipeline state that existed at the specified checkpoint in a prior simulation.\n This allows us to resume the simulation after the specified checkpoint\n\n Parameters\n ----------\n checkpoint_name : str\n model_name of checkpoint to load (resume_after argument to open_pipeline)\n \"\"\"\n\n logger.info(\"load_checkpoint %s\" % (checkpoint_name))\n\n checkpoints = read_df(CHECKPOINT_TABLE_NAME)\n\n if checkpoint_name == LAST_CHECKPOINT:\n checkpoint_name = checkpoints[CHECKPOINT_NAME].iloc[-1]\n logger.info(\"loading checkpoint '%s'\" % checkpoint_name)\n\n try:\n # truncate rows after target checkpoint\n i = checkpoints[checkpoints[CHECKPOINT_NAME] == checkpoint_name].index[0]\n checkpoints = checkpoints.loc[:i]\n except IndexError:\n msg = \"Couldn't find checkpoint '%s' in checkpoints\" % (checkpoint_name,)\n print(checkpoints[CHECKPOINT_NAME])\n logger.error(msg)\n raise RuntimeError(msg)\n\n # convert pandas dataframe back to array of checkpoint dicts\n checkpoints = checkpoints.to_dict(orient='records')\n\n # drop tables with empty names\n for checkpoint in checkpoints:\n for key in list(checkpoint.keys()):\n if key not in NON_TABLE_COLUMNS and not checkpoint[key]:\n del checkpoint[key]\n\n # patch _CHECKPOINTS array of dicts\n _PIPELINE.checkpoints = checkpoints\n\n # patch _CHECKPOINTS dict with latest checkpoint info\n _PIPELINE.last_checkpoint.clear()\n _PIPELINE.last_checkpoint.update(_PIPELINE.checkpoints[-1])\n\n logger.info(\"load_checkpoint %s timestamp %s\"\n % (checkpoint_name, _PIPELINE.last_checkpoint['timestamp']))\n\n tables = checkpointed_tables()\n\n loaded_tables = {}\n for table_name in tables:\n # read dataframe from pipeline store\n df = read_df(table_name, checkpoint_name=_PIPELINE.last_checkpoint[table_name])\n logger.info(\"load_checkpoint table %s %s\" % (table_name, df.shape))\n # register it as an orca table\n rewrap(table_name, df)\n loaded_tables[table_name] = df\n\n # register for tracing in order that tracing.register_traceable_table wants us to register them\n traceable_tables = inject.get_injectable('traceable_tables', [])\n\n for table_name in traceable_tables:\n if table_name in loaded_tables:\n tracing.register_traceable_table(table_name, loaded_tables[table_name])\n\n # add tables of known rng channels\n rng_channels = inject.get_injectable('rng_channels', [])\n if rng_channels:\n logger.debug(\"loading random channels %s\" % rng_channels)\n for table_name in rng_channels:\n if table_name in loaded_tables:\n logger.debug(\"adding channel %s\" % (table_name,))\n _PIPELINE.rng().add_channel(table_name, loaded_tables[table_name])\n\n\ndef split_arg(s, sep, default=''):\n \"\"\"\n split str s in two at first sep, returning empty string as second result if no sep\n \"\"\"\n r = s.split(sep, 2)\n r = list(map(str.strip, r))\n\n arg = r[0]\n\n if len(r) == 1:\n val = default\n else:\n val = r[1]\n val = {'true': True, 'false': False}.get(val.lower(), val)\n\n return arg, val\n\n\ndef run_model(model_name):\n \"\"\"\n Run the specified model and add checkpoint for model_name\n\n Since we use model_name as checkpoint name, the same model may not be run more than once.\n\n Parameters\n ----------\n model_name : str\n model_name is assumed to be the name of a registered orca step\n \"\"\"\n\n if not _PIPELINE.is_open:\n raise RuntimeError(\"Pipeline not initialized! Did you call open_pipeline?\")\n\n # can't run same model more than once\n if model_name in [checkpoint[CHECKPOINT_NAME] for checkpoint in _PIPELINE.checkpoints]:\n raise RuntimeError(\"Cannot run model '%s' more than once\" % model_name)\n\n _PIPELINE.rng().begin_step(model_name)\n\n # check for args\n if '.' in model_name:\n step_name, arg_string = model_name.split('.', 1)\n args = dict((k, v)\n for k, v in (split_arg(item, \"=\", default=True)\n for item in arg_string.split(\";\")))\n else:\n step_name = model_name\n args = {}\n\n # check for no_checkpoint prefix\n if step_name[0] == NO_CHECKPOINT_PREFIX:\n step_name = step_name[1:]\n checkpoint = False\n else:\n checkpoint = True\n\n inject.set_step_args(args)\n\n t0 = print_elapsed_time()\n logger.info(f\"#run_model running step {step_name}\")\n orca.run([step_name])\n t0 = print_elapsed_time(\"#run_model completed step '%s'\" % model_name, t0, debug=True)\n\n inject.set_step_args(None)\n\n _PIPELINE.rng().end_step(model_name)\n if checkpoint:\n add_checkpoint(model_name)\n else:\n logger.info(\"##### skipping %s checkpoint for %s\" % (step_name, model_name))\n\n\ndef open_pipeline(resume_after=None):\n \"\"\"\n Start pipeline, either for a new run or, if resume_after, loading checkpoint from pipeline.\n\n If resume_after, then we expect the pipeline hdf5 file to exist and contain\n checkpoints from a previous run, including a checkpoint with name specified in resume_after\n\n Parameters\n ----------\n resume_after : str or None\n name of checkpoint to load from pipeline store\n \"\"\"\n\n logger.info(\"open_pipeline\")\n\n if _PIPELINE.is_open:\n raise RuntimeError(\"Pipeline is already open!\")\n\n _PIPELINE.init_state()\n _PIPELINE.is_open = True\n\n get_rn_generator().set_base_seed(inject.get_injectable('rng_base_seed', 0))\n\n if resume_after:\n # open existing pipeline\n logger.debug(\"open_pipeline - open existing pipeline\")\n open_pipeline_store(overwrite=False)\n load_checkpoint(resume_after)\n else:\n # open new, empty pipeline\n logger.debug(\"open_pipeline - new, empty pipeline\")\n open_pipeline_store(overwrite=True)\n # - not sure why I thought we needed this?\n # could have exogenous tables or prng instantiation under some circumstance??\n _PIPELINE.last_checkpoint[CHECKPOINT_NAME] = INITIAL_CHECKPOINT_NAME\n # empty table, in case they have turned off all checkpointing\n add_checkpoint(INITIAL_CHECKPOINT_NAME)\n\n logger.debug(\"open_pipeline complete\")\n\n\ndef last_checkpoint():\n \"\"\"\n\n Returns\n -------\n last_checkpoint: str\n name of last checkpoint\n \"\"\"\n\n be_open()\n\n return _PIPELINE.last_checkpoint[CHECKPOINT_NAME]\n\n\ndef close_pipeline():\n \"\"\"\n Close any known open files\n \"\"\"\n\n be_open()\n\n close_open_files()\n\n _PIPELINE.pipeline_store.close()\n\n _PIPELINE.init_state()\n\n logger.info(\"close_pipeline\")\n\n\ndef run(models, resume_after=None):\n \"\"\"\n run the specified list of models, optionally loading checkpoint and resuming after specified\n checkpoint.\n\n Since we use model_name as checkpoint name, the same model may not be run more than once.\n\n If resume_after checkpoint is specified and a model with that name appears in the models list,\n then we only run the models after that point in the list. This allows the user always to pass\n the same list of models, but specify a resume_after point if desired.\n\n Parameters\n ----------\n models : [str]\n list of model_names\n resume_after : str or None\n model_name of checkpoint to load checkpoint and AFTER WHICH to resume model run\n \"\"\"\n\n t0 = print_elapsed_time()\n\n open_pipeline(resume_after)\n t0 = print_elapsed_time('open_pipeline', t0)\n\n if resume_after == LAST_CHECKPOINT:\n resume_after = _PIPELINE.last_checkpoint[CHECKPOINT_NAME]\n\n if resume_after:\n logger.info(\"resume_after %s\" % resume_after)\n if resume_after in models:\n models = models[models.index(resume_after) + 1:]\n\n mem.init_trace(config.setting('mem_tick'), write_header=True)\n mem.trace_memory_info('#MEM pipeline.run before preload_injectables')\n\n # preload any bulky injectables (e.g. skims) not in pipeline\n if orca.is_injectable('preload_injectables'):\n orca.get_injectable('preload_injectables')\n t0 = print_elapsed_time('preload_injectables', t0)\n\n mem.trace_memory_info('#MEM pipeline.run before run_models')\n\n t0 = print_elapsed_time()\n for model in models:\n run_model(model)\n mem.trace_memory_info(f\"pipeline.run after {model}\")\n\n mem.trace_memory_info('#MEM pipeline.run after run_models')\n\n t0 = print_elapsed_time(\"run_model (%s models)\" % len(models), t0)\n\n # don't close the pipeline, as the user may want to read intermediate results from the store\n\n\ndef get_table(table_name, checkpoint_name=None):\n \"\"\"\n Return pandas dataframe corresponding to table_name\n\n if checkpoint_name is None, return the current (most recent) version of the table.\n The table can be a checkpointed table or any registered orca table (e.g. function table)\n\n if checkpoint_name is specified, return table as it was at that checkpoint\n (the most recently checkpointed version of the table at or before checkpoint_name)\n\n Parameters\n ----------\n table_name : str\n checkpoint_name : str or None\n\n Returns\n -------\n df : pandas.DataFrame\n \"\"\"\n\n be_open()\n\n # orca table not in checkpoints (e.g. a merged table)\n if table_name not in _PIPELINE.last_checkpoint and orca.is_table(table_name):\n if checkpoint_name is not None:\n raise RuntimeError(\"get_table: checkpoint_name ('%s') not supported\"\n \"for non-checkpointed table '%s'\" % (checkpoint_name, table_name))\n\n return orca.get_table(table_name).to_frame()\n\n # if they want current version of table, no need to read from pipeline store\n if checkpoint_name is None:\n\n if table_name not in _PIPELINE.last_checkpoint:\n raise RuntimeError(\"table '%s' never checkpointed.\" % table_name)\n\n if not _PIPELINE.last_checkpoint[table_name]:\n raise RuntimeError(\"table '%s' was dropped.\" % table_name)\n\n # return orca.get_table(table_name).local\n return orca.get_table(table_name).to_frame()\n\n # find the requested checkpoint\n checkpoint = \\\n next((x for x in _PIPELINE.checkpoints if x['checkpoint_name'] == checkpoint_name), None)\n if checkpoint is None:\n raise RuntimeError(\"checkpoint '%s' not in checkpoints.\" % checkpoint_name)\n\n # find the checkpoint that table was written to store\n last_checkpoint_name = checkpoint.get(table_name, None)\n\n if not last_checkpoint_name:\n raise RuntimeError(\"table '%s' not in checkpoint '%s'.\" % (table_name, checkpoint_name))\n\n # if this version of table is same as current\n if _PIPELINE.last_checkpoint.get(table_name, None) == last_checkpoint_name:\n return orca.get_table(table_name).to_frame()\n\n return read_df(table_name, last_checkpoint_name)\n\n\ndef get_checkpoints():\n \"\"\"\n Get pandas dataframe of info about all checkpoints stored in pipeline\n\n pipeline doesn't have to be open\n\n Returns\n -------\n checkpoints_df : pandas.DataFrame\n\n \"\"\"\n\n store = get_pipeline_store()\n\n if store is not None:\n df = store[CHECKPOINT_TABLE_NAME]\n else:\n pipeline_file_path = config.pipeline_file_path(orca.get_injectable('pipeline_file_name'))\n df = pd.read_hdf(pipeline_file_path, CHECKPOINT_TABLE_NAME)\n\n # non-table columns first (column order in df is random because created from a dict)\n table_names = [name for name in df.columns.values if name not in NON_TABLE_COLUMNS]\n\n df = df[NON_TABLE_COLUMNS + table_names]\n\n return df\n\n\ndef replace_table(table_name, df):\n \"\"\"\n Add or replace a orca table, removing any existing added orca columns\n\n The use case for this function is a method that calls to_frame on an orca table, modifies\n it and then saves the modified.\n\n orca.to_frame returns a copy, so no changes are saved, and adding multiple column with\n add_column adds them in an indeterminate order.\n\n Simply replacing an existing the table \"behind the pipeline's back\" by calling orca.add_table\n risks pipeline to failing to detect that it has changed, and thus not checkpoint the changes.\n\n Parameters\n ----------\n table_name : str\n orca/pipeline table name\n df : pandas DataFrame\n \"\"\"\n\n be_open()\n\n if df.columns.duplicated().any():\n logger.error(\"replace_table: dataframe '%s' has duplicate columns: %s\" %\n (table_name, df.columns[df.columns.duplicated()]))\n\n raise RuntimeError(\"replace_table: dataframe '%s' has duplicate columns: %s\" %\n (table_name, df.columns[df.columns.duplicated()]))\n\n rewrap(table_name, df)\n\n _PIPELINE.replaced_tables[table_name] = True\n\n\ndef extend_table(table_name, df, axis=0):\n \"\"\"\n add new table or extend (add rows) to an existing table\n\n Parameters\n ----------\n table_name : str\n orca/inject table name\n df : pandas DataFrame\n \"\"\"\n\n be_open()\n\n assert axis in [0, 1]\n\n if orca.is_table(table_name):\n\n table_df = orca.get_table(table_name).to_frame()\n\n if axis == 0:\n # don't expect indexes to overlap\n assert len(table_df.index.intersection(df.index)) == 0\n missing_df_str_columns = [c for c in table_df.columns\n if c not in df.columns and table_df[c].dtype == 'O']\n else:\n # expect indexes be same\n assert table_df.index.equals(df.index)\n new_df_columns = [c for c in df.columns if c not in table_df.columns]\n df = df[new_df_columns]\n\n # preserve existing column order\n df = pd.concat([table_df, df], sort=False, axis=axis)\n\n # backfill missing df columns that were str (object) type in table_df\n if axis == 0:\n for c in missing_df_str_columns:\n df[c] = df[c].fillna('')\n\n replace_table(table_name, df)\n\n return df\n\n\ndef drop_table(table_name):\n\n be_open()\n\n if orca.is_table(table_name):\n\n logger.debug(\"drop_table dropping orca table '%s'\" % table_name)\n\n # don't trigger function call of TableFuncWrapper\n t = orca.get_raw_table(table_name)\n t.clear_cached()\n\n for column_name in orca.list_columns_for_table(table_name):\n # logger.debug(\"pop %s.%s: %s\" % (table_name, column_name, t.column_type(column_name)))\n orca._COLUMNS.pop((table_name, column_name), None)\n\n # remove from orca's table list\n orca._TABLES.pop(table_name, None)\n\n if table_name in _PIPELINE.replaced_tables:\n\n logger.debug(\"drop_table forgetting replaced_tables '%s'\" % table_name)\n del _PIPELINE.replaced_tables[table_name]\n\n if table_name in _PIPELINE.last_checkpoint:\n\n logger.debug(\"drop_table removing table %s from last_checkpoint\" % table_name)\n\n _PIPELINE.last_checkpoint[table_name] = ''\n\n\ndef is_table(table_name):\n return orca.is_table(table_name)\n"
] |
[
[
"numpy.arange",
"numpy.nan_to_num",
"numpy.full",
"numpy.concatenate",
"numpy.repeat",
"numpy.empty"
],
[
"pandas.read_hdf",
"pandas.read_csv"
],
[
"pandas.read_hdf",
"pandas.concat",
"pandas.HDFStore",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
nickhuang1996/HJL-re-id
|
[
"107b25f31c961f360f69560cfddd78dfc0da3291",
"107b25f31c961f360f69560cfddd78dfc0da3291"
] |
[
"MDRSREID/Trainer/evaluation_creation/PGFA_Evaluation/extract_part_label.py",
"MDRSREID/DataLoaders/create_dataloader.py"
] |
[
"from MDRSREID.utils.data_utils.evaluations.PGFA.part_label import part_label_generate\nimport torch\n\n\ndef extract_part_label(item, cfg):\n imgnames, imgheights = item['test_pose_path'], item['height']\n N = len(imgnames)\n # part_label_batch = torch.FloatTensor(N, 1, cfg.model.num_parts).zero_()\n part_label_batch = torch.FloatTensor(N, cfg.model.num_parts).zero_()\n i = 0\n for imgname, height in zip(imgnames, imgheights):\n part_label = part_label_generate(imgname, cfg.model.num_parts, height.item())\n part_label = torch.from_numpy(part_label)\n # part_label = part_label.unsqueeze(0)\n part_label_batch[i] = part_label\n i += 1\n return part_label_batch\n",
"from MDRSREID.DataLoaders.create_dataset import create_dataset\nfrom MDRSREID.DataLoaders.Sampler import get_sampler\nfrom torch.utils.data import DataLoader as TorchDataLoader\n\n\ndef create_dataloader(cfg,\n mode=None,\n domain=None,\n name=None,\n authority=None,\n train_type=None,\n items=None):\n \"\"\"\n :param cfg:\n :param items:\n :return:\n\n create the dataset(search for the dataset class)\n init the sampler\n create the loader\n \"\"\"\n train_name_factory = {\n 'source': cfg.dataset.train.source,\n 'target': cfg.dataset.train.target,\n }\n if mode is 'train':\n name = train_name_factory[domain].name\n dataset = create_dataset(cfg,\n mode=mode,\n domain=domain,\n name=name,\n authority=authority,\n train_type=train_type,\n items=items)\n # from DataLoaders.Datasets.market1501 import Market1501\n # dataset = Market1501(cfg, items=items)\n sampler_factory = {\n 'train': cfg.dataloader.train,\n 'test': cfg.dataloader.test\n }\n sampler = get_sampler(cfg, dataset, sampler_factory[mode])\n\n data_loader = TorchDataLoader(\n dataset=dataset,\n batch_size=sampler_factory[mode].batch_size,\n sampler=sampler,\n num_workers=cfg.dataloader.num_workers,\n pin_memory=True,\n drop_last=sampler_factory[mode].drop_last,\n )\n return data_loader\n"
] |
[
[
"torch.FloatTensor",
"torch.from_numpy"
],
[
"torch.utils.data.DataLoader"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tanaydw/CenterNet
|
[
"91c2ccd2c8a063db8c8ec101adfd4c6830cd47eb"
] |
[
"src/lib/detectors/ddd.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport cv2\nimport numpy as np\nfrom progress.bar import Bar\nimport time\nimport torch\n\n\nfrom models.decode import ddd_decode\nfrom models.utils import flip_tensor\nfrom utils.image import get_affine_transform\nfrom utils.post_process import ddd_post_process\nfrom utils.debugger import Debugger\nfrom utils.ddd_utils import compute_box_3d, project_to_image, alpha2rot_y\nfrom utils.ddd_utils import draw_box_3d, unproject_2d_to_3d\n\nfrom .base_detector import BaseDetector\n\nclass DddDetector(BaseDetector):\n def __init__(self, opt):\n super(DddDetector, self).__init__(opt)\n self.calib = np.array([[707.0493, 0, 604.0814, 45.75831],\n [0, 707.0493, 180.5066, -0.3454157],\n [0, 0, 1., 0.004981016]], dtype=np.float32)\n\n\n def pre_process(self, image, scale, calib=None):\n height, width = image.shape[0:2]\n \n inp_height, inp_width = self.opt.input_h, self.opt.input_w\n c = np.array([width / 2, height / 2], dtype=np.float32)\n if self.opt.keep_res:\n s = np.array([inp_width, inp_height], dtype=np.int32)\n else:\n s = np.array([width, height], dtype=np.int32)\n\n trans_input = get_affine_transform(c, s, 0, [inp_width, inp_height])\n resized_image = image #cv2.resize(image, (width, height))\n inp_image = cv2.warpAffine(\n resized_image, trans_input, (inp_width, inp_height),\n flags=cv2.INTER_LINEAR)\n inp_image = (inp_image.astype(np.float32) / 255.)\n inp_image = (inp_image - self.mean) / self.std\n images = inp_image.transpose(2, 0, 1)[np.newaxis, ...]\n calib = np.array(calib, dtype=np.float32) if calib is not None \\\n else self.calib\n images = torch.from_numpy(images)\n meta = {'c': c, 's': s, \n 'out_height': inp_height // self.opt.down_ratio, \n 'out_width': inp_width // self.opt.down_ratio,\n 'calib': calib}\n return images, meta\n \n def process(self, images, return_time=False):\n with torch.no_grad():\n torch.cuda.synchronize()\n output = self.model(images)[-1]\n output['hm'] = output['hm'].sigmoid_()\n output['dep'] = 1. / (output['dep'].sigmoid() + 1e-6) - 1.\n wh = output['wh'] if self.opt.reg_bbox else None\n reg = output['reg'] if self.opt.reg_offset else None\n torch.cuda.synchronize()\n forward_time = time.time()\n \n dets = ddd_decode(output['hm'], output['rot'], output['dep'],\n output['dim'], wh=wh, reg=reg, K=self.opt.K)\n if return_time:\n return output, dets, forward_time\n else:\n return output, dets\n\n def post_process(self, dets, meta, scale=1):\n dets = dets.detach().cpu().numpy()\n detections = ddd_post_process(\n dets.copy(), [meta['c']], [meta['s']], [meta['calib']], self.opt)\n self.this_calib = meta['calib']\n return detections[0]\n\n def merge_outputs(self, detections):\n results = detections[0]\n for j in range(1, self.num_classes + 1):\n if len(results[j] > 0):\n keep_inds = (results[j][:, -1] > self.opt.peak_thresh)\n results[j] = results[j][keep_inds]\n return results\n\n def debug(self, debugger, images, dets, output, scale=1):\n dets = dets.detach().cpu().numpy()\n img = images[0].detach().cpu().numpy().transpose(1, 2, 0)\n img = ((img * self.std + self.mean) * 255).astype(np.uint8)\n pred = debugger.gen_colormap(output['hm'][0].detach().cpu().numpy())\n debugger.add_blend_img(img, pred, 'pred_hm')\n debugger.add_ct_detection(\n img, dets[0], show_box=self.opt.reg_bbox, \n center_thresh=self.opt.vis_thresh, img_id='det_pred')\n \n def show_results(self, debugger, image, results):\n debugger.add_3d_detection(\n image, results, self.this_calib,\n center_thresh=self.opt.vis_thresh, img_id='add_pred')\n debugger.add_bird_view(\n results, center_thresh=self.opt.vis_thresh, img_id='bird_pred')"
] |
[
[
"torch.cuda.synchronize",
"numpy.array",
"torch.no_grad",
"torch.from_numpy"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TomAugspurger/sunpy
|
[
"cad2d473f6aff05df5fe787c781cb7d004959b94"
] |
[
"sunpy/map/tests/test_map_factory.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 21 15:05:09 2013\n\n@author: stuart\n\"\"\"\nimport os\nimport tempfile\nimport pathlib\n\nimport pytest\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\n\nimport sunpy\nimport sunpy.map\nimport sunpy.data.test\n\n\nfilepath = sunpy.data.test.rootdir\na_list_of_many = [os.fspath(f) for f in pathlib.Path(filepath, \"EIT\").glob(\"*\")]\na_fname = a_list_of_many[0]\n\nAIA_171_IMAGE = os.path.join(filepath, 'aia_171_level1.fits')\nRHESSI_IMAGE = os.path.join(filepath, 'hsi_image_20101016_191218.fits')\n\n\n#==============================================================================\n# Map Factory Tests\n#==============================================================================\nclass TestMap:\n def test_mapsequence(self):\n # Test making a MapSequence\n sequence = sunpy.map.Map(a_list_of_many, sequence=True)\n assert isinstance(sequence, sunpy.map.MapSequence)\n\n def test_composite(self):\n # Test making a CompositeMap\n comp = sunpy.map.Map(AIA_171_IMAGE, RHESSI_IMAGE, composite=True)\n assert isinstance(comp, sunpy.map.CompositeMap)\n\n def test_patterns(self):\n # Test different Map pattern matching\n\n # File name\n eitmap = sunpy.map.Map(a_fname)\n assert isinstance(eitmap, sunpy.map.GenericMap)\n\n # Directory\n directory = pathlib.Path(filepath, \"EIT\")\n maps = sunpy.map.Map(os.fspath(directory))\n assert isinstance(maps, list)\n assert ([isinstance(amap, sunpy.map.GenericMap) for amap in maps])\n # Test that returned maps are sorted\n files_sorted = sorted(list(directory.glob('*')))\n maps_sorted = [sunpy.map.Map(os.fspath(f)) for f in files_sorted]\n assert all([m.date == m_s.date for m, m_s in zip(maps, maps_sorted)])\n\n # Pathlib\n path = pathlib.Path(a_fname)\n eitmap = sunpy.map.Map(path)\n assert isinstance(eitmap, sunpy.map.GenericMap)\n maps = sunpy.map.Map(directory)\n assert isinstance(maps, list)\n assert ([isinstance(amap, sunpy.map.GenericMap) for amap in maps])\n\n # Glob\n pattern = os.path.join(filepath, \"EIT\", \"*\")\n maps = sunpy.map.Map(pattern)\n assert isinstance(maps, list)\n assert ([isinstance(amap, sunpy.map.GenericMap) for amap in maps])\n # Test that returned maps are sorted\n files_sorted = sorted(list(pathlib.Path(pattern).parent.glob('*')))\n maps_sorted = [sunpy.map.Map(os.fspath(f)) for f in files_sorted]\n assert all([m.date == m_s.date for m, m_s in zip(maps, maps_sorted)])\n # Single character wildcard (?)\n pattern = os.path.join(filepath, \"EIT\", \"efz20040301.0?0010_s.fits\")\n maps = sunpy.map.Map(pattern)\n assert isinstance(maps, list)\n assert len(maps) == 7\n assert ([isinstance(amap, sunpy.map.GenericMap) for amap in maps])\n # Character ranges\n pattern = os.path.join(filepath, \"EIT\", \"efz20040301.0[2-6]0010_s.fits\")\n maps = sunpy.map.Map(pattern)\n assert isinstance(maps, list)\n assert len(maps) == 4\n assert ([isinstance(amap, sunpy.map.GenericMap) for amap in maps])\n\n # Already a Map\n amap = sunpy.map.Map(maps[0])\n assert isinstance(amap, sunpy.map.GenericMap)\n\n # A list of filenames\n maps = sunpy.map.Map(a_list_of_many)\n assert isinstance(maps, list)\n assert ([isinstance(amap, sunpy.map.GenericMap) for amap in maps])\n\n # Data-header pair in a tuple\n pair_map = sunpy.map.Map((amap.data, amap.meta))\n assert isinstance(pair_map, sunpy.map.GenericMap)\n\n # Data-header pair not in a tuple\n pair_map = sunpy.map.Map(amap.data, amap.meta)\n assert isinstance(pair_map, sunpy.map.GenericMap)\n\n # Data-wcs object pair in tuple\n pair_map = sunpy.map.Map((amap.data, WCS(AIA_171_IMAGE)))\n assert isinstance(pair_map, sunpy.map.GenericMap)\n\n # Data-wcs object pair not in a tuple\n pair_map = sunpy.map.Map(amap.data, WCS(AIA_171_IMAGE))\n assert isinstance(pair_map, sunpy.map.GenericMap)\n\n # Data-header from FITS\n with fits.open(a_fname) as hdul:\n data = hdul[0].data\n header = hdul[0].header\n pair_map = sunpy.map.Map((data, header))\n assert isinstance(pair_map, sunpy.map.GenericMap)\n pair_map, pair_map = sunpy.map.Map(((data, header), (data, header)))\n assert isinstance(pair_map, sunpy.map.GenericMap)\n pair_map = sunpy.map.Map(data, header)\n assert isinstance(pair_map, sunpy.map.GenericMap)\n\n # Custom Map\n data = np.arange(0, 100).reshape(10, 10)\n header = {'cdelt1': 10, 'cdelt2': 10,\n 'telescop': 'sunpy',\n 'cunit1': 'arcsec', 'cunit2': 'arcsec'}\n pair_map = sunpy.map.Map(data, header)\n assert isinstance(pair_map, sunpy.map.GenericMap)\n\n # requires dask array to run properly\n def test_dask_array(self):\n dask_array = pytest.importorskip('dask.array')\n amap = sunpy.map.Map(AIA_171_IMAGE)\n da = dask_array.from_array(amap.data, chunks=(1, 1))\n pair_map = sunpy.map.Map(da, amap.meta)\n assert isinstance(pair_map, sunpy.map.GenericMap)\n\n # requires sqlalchemy to run properly\n def test_databaseentry(self):\n sqlalchemy = pytest.importorskip('sqlalchemy')\n sunpy_database = pytest.importorskip('sunpy.database')\n db = sunpy_database.Database(url='sqlite://', default_waveunit='angstrom')\n db.add_from_file(a_fname)\n res = db.get_entry_by_id(1)\n db_map = sunpy.map.Map(res)\n assert isinstance(db_map, sunpy.map.GenericMap)\n\n @pytest.mark.remote_data\n def test_url_pattern(self):\n # A URL\n amap = sunpy.map.Map(\"http://data.sunpy.org/sample-data/AIA20110319_105400_0171.fits\")\n assert isinstance(amap, sunpy.map.GenericMap)\n\n def test_save(self):\n # Test save out\n eitmap = sunpy.map.Map(a_fname)\n afilename = tempfile.NamedTemporaryFile(suffix='fits').name\n eitmap.save(afilename, filetype='fits', overwrite=True)\n backin = sunpy.map.Map(afilename)\n assert isinstance(backin, sunpy.map.sources.EITMap)\n\n#==============================================================================\n# Sources Tests\n#==============================================================================\n def test_sdo(self):\n # Test an AIAMap\n aia = sunpy.map.Map(AIA_171_IMAGE)\n assert isinstance(aia, sunpy.map.sources.AIAMap)\n # TODO: Test a HMIMap\n\n def test_soho(self):\n # Test EITMap, LASCOMap & MDIMap\n eit = sunpy.map.Map(os.path.join(filepath, \"EIT\", \"efz20040301.000010_s.fits\"))\n assert isinstance(eit, sunpy.map.sources.EITMap)\n\n lasco = sunpy.map.Map(os.path.join(filepath, \"lasco_c2_25299383_s.fts\"))\n assert isinstance(lasco, sunpy.map.sources.LASCOMap)\n\n mdi_c = sunpy.map.Map(os.path.join(filepath, \"mdi_fd_Ic_6h_01d.5871.0000_s.fits\"))\n assert isinstance(mdi_c, sunpy.map.sources.MDIMap)\n\n mdi_m = sunpy.map.Map(os.path.join(filepath, \"mdi_fd_M_96m_01d.5874.0005_s.fits\"))\n assert isinstance(mdi_m, sunpy.map.sources.MDIMap)\n\n def test_stereo(self):\n # Test EUVIMap & CORMap & HIMap\n euvi = sunpy.map.Map(os.path.join(filepath, \"euvi_20090615_000900_n4euA_s.fts\"))\n assert isinstance(euvi, sunpy.map.sources.EUVIMap)\n\n cor = sunpy.map.Map(os.path.join(filepath, \"cor1_20090615_000500_s4c1A.fts\"))\n assert isinstance(cor, sunpy.map.sources.CORMap)\n\n hi = sunpy.map.Map(os.path.join(filepath, \"hi_20110910_114721_s7h2A.fts\"))\n assert isinstance(hi, sunpy.map.sources.HIMap)\n\n def test_rhessi(self):\n # Test RHESSIMap\n rhessi = sunpy.map.Map(RHESSI_IMAGE)\n assert isinstance(rhessi, sunpy.map.sources.RHESSIMap)\n\n def test_sot(self):\n # Test SOTMap\n sot = sunpy.map.Map(os.path.join(filepath, \"FGMG4_20110214_030443.7.fits\"))\n assert isinstance(sot, sunpy.map.sources.SOTMap)\n\n def test_swap(self):\n # Test SWAPMap\n swap = sunpy.map.Map(os.path.join(filepath, \"swap_lv1_20140606_000113.fits\"))\n assert isinstance(swap, sunpy.map.sources.SWAPMap)\n\n def test_xrt(self):\n # Test XRTMap\n xrt = sunpy.map.Map(os.path.join(filepath, \"HinodeXRT.fits\"))\n assert isinstance(xrt, sunpy.map.sources.XRTMap)\n\n # TODO: Test SXTMap\n"
] |
[
[
"numpy.arange"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gpu0/nnet
|
[
"0fd5c718c2d03cab91d4a4fd4963b12df241a9de"
] |
[
"conv_serial.py"
] |
[
"import multiprocessing\nimport numpy as np\n\nnumThreads = 8\nnumRows = 32000\nnumCols = 3\nnumOut = 2\n\nstride = numRows / numThreads\n\nX = np.ones((numRows, numCols))\nW = np.ones((numCols, numOut))\nB = np.ones((numRows, numOut))\n\ndef conv(idx):\n for i in range(100000):\n X[idx*stride:idx*stride+stride].dot(W) + B[idx*stride:idx*stride+stride]\n return X[idx*stride:idx*stride+stride].dot(W) + B[idx*stride:idx*stride+stride]\n\nif __name__=='__main__':\n for i in range(numThreads):\n conv(i)\n"
] |
[
[
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
REAM-lab/switch
|
[
"00af4508e34bdc460925950808dc7f87a0a064ff"
] |
[
"switch_model/wecc/get_inputs/post_process_steps/reserve_technologies.py"
] |
[
"\"\"\" This post-process selects which technologies can provide reserves\"\"\"\n# Standard packages\nimport os\nimport shutil\n\n# Third-party packages\nimport pandas as pd\n\nfrom switch_model.wecc.get_inputs.register_post_process import post_process_step\n\n\n@post_process_step(\n msg=\"Removing fossil fuels from reserves.\",\n)\ndef post_process(_):\n \"\"\"This function sets to zero the column that allows each candidate technology to\n provide\"\"\"\n\n fname = \"generation_projects_info.csv\"\n df = pd.read_csv(fname)\n\n # Energy sources to exclude from reserves\n filter_techs = [\"ResidualFuelOil\", \"Gas\", \"DistillateFuelOil\", \"Coal\"]\n\n # Set to zero column that allows technology to provide reserves\n df.loc[\n df[\"gen_energy_source\"].isin(filter_techs), \"gen_can_provide_cap_reserves\"\n ] = 0\n\n # Save file again\n df.to_csv(fname, index=False)\n"
] |
[
[
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
fokoa/byzantine_kmeans-msc_thesis
|
[
"b116cb2222cd0e1334db7df493ec453dd299b985"
] |
[
"code/main_vehicule.py"
] |
[
"#!usr/bin/python3\n# -*- coding : utf8 -*-\n\n\nimport sys;\nimport getopt;\nimport warnings;\nfrom mpi4py import MPI;\n\nimport numpy as np;\nimport pandas as pd;\nimport matplotlib.pyplot as plt;\nfrom mpl_toolkits.mplot3d import Axes3D;\n\nfrom sklearn import decomposition;\nfrom sklearn.cluster import KMeans;\n\nfrom kmeans_resilient import KMeansResilient as KMR;\nfrom functions import *;\n\npd.set_option('max_column', None);\nwarnings.filterwarnings('ignore');\n\n\n# MPI initialization\ncomm = MPI.COMM_WORLD;\nP = comm.Get_size();\nrank = comm.Get_rank();\n\n\ndef check_option(opt_arg):\n \"\"\" \n Check the arguments passed as parameters by the\n command prompt \n\n Parameters :\n -----------\n opt_arg : str\n Arguments and options passed by the command prompt\n\n Return :\n -------\n opts : list\n Argument list \n args : list\n Option list\n \"\"\"\n\n try:\n opts, args = opt_arg;\n\n except getopt.GetoptError as err:\n print(err);\n print(\"Use :\\t\", sys.argv[0], \"-b 5 \\n\\t\",\n \"or:\", sys.argv[0], \"--byzantine 5\");\n sys.exit(-1);\n\n for opt, val in opts:\n\n if opt in (\"-b\", \"--byzantine\"):\n if val.isdigit() == False:\n raise ValueError(\"Enter an integer as number\"\n \"of byzantine machines.\");\n\n elif opt in (\"-h\", \"--help\"):\n print(\"Use:\", sys.argv[0], \"-b 5\\n\",\n \"or:\", sys.argv[0], \"--byzantine 5\");\n sys.exit(-1);\n \n else:\n print(\"unhandled options\");\n sys.exit(-1);\n\n return opts, args;\n\n\n\ndef check_Nbyzan(opts, P):\n \"\"\" \n Check and get the number of Byzantine machines that\n we are going to simulate \n\n Parameters :\n -----------\n opts : str\n Options passed by the command prompt\n\n P : int\n Total number of machines (nodes or workers).\n 1 coodinator ans the ramaining are workers\n\n Return :\n -------\n n_byzantines : int (entire natural)\n Number of byzantine machines that we\n are going to simulate\n \"\"\"\n\n if len(opts) == 0:\n n_byzantines = 0;\n \n n_byzantines = int(opts[0][1]);\n \n if n_byzantines < 0 or n_byzantines > P - 1:\n raise ValueError(\"Number of byzantine must be an integer \"\n \"< number of workers or >= 0\");\n \n return n_byzantines;\n\n\n\ndef sort_centroides(centroids):\n \"\"\" \n Sort centroids according to their norms\n\n Parameters :\n -----------\n centroids : ndarray of shape (k, n_features)\n All centroids of clusters where k\n is number of clusters\n\n Return :\n -------\n tmp : ndarray of shape (k, n_features)\n Sorted centroids\n \"\"\"\n\n tmp = np.zeros((centroids.shape));\n normes = {};\n\n for centroid in range(0, centroids.shape[0]):\n norm = np.linalg.norm(centroids[centroid]);\n normes[norm] = centroid;\n\n i=0;\n for norm in sorted(normes):\n tmp[i] = centroids[normes[norm]];\n i = i + 1;\n\n return tmp;\n \n\n\ndef comparaison_cluster(X, label_km, label_by, label_co):\n \"\"\" \n Plot all the formed clusters \n\n Parameters :\n -----------\n X : ndarray of shape (n_samples, n_features)\n Samples to be clustered\n \n label_km : list of length 2\n The first is labels obtained with K-means\n The second is number of clusters\n\n label_by : list of length 2\n The first is labels obtained with byzantin K-means\n The second is number of byzantines\n\n label_co : ndarray of shape (n_samples, )\n Label obtained by correcting byzantines \n in byzantin K-means\n \"\"\"\n\n pca = decomposition.PCA(n_components = 3);\n X_reduced = pca.fit_transform(X);\n\n x_axis = [val[0] for val in X_reduced];\n y_axis = [val[1] for val in X_reduced];\n z_axis = [val[2] for val in X_reduced];\n\n fig = plt.figure(figsize=plt.figaspect(0.5), facecolor=\"w\");\n\n ax = fig.add_subplot(1, 3, 1, projection='3d');\n plt.title('%d-means'%(label_km[1]));\n ax.scatter(x_axis, y_axis, z_axis, c=label_km[0]);\n \n ax = fig.add_subplot(1, 3, 2, projection='3d');\n plt.title('%d Byzantines' % (label_by[1]));\n ax.scatter(x_axis, y_axis, z_axis, c=label_by[0]);\n\n ax = fig.add_subplot(1, 3, 3, projection='3d');\n ax.scatter(x_axis, y_axis, z_axis, c=label_co);\n plt.title('Correction');\n\n plt.show();\n\n\n\n\ndef main():\n\n # Check options and number of byzantines\n opts, arg = check_option(getopt.getopt(sys.argv[1:], \"b:\",\n [\"byzantine=\"]));\n n_byzantines = check_Nbyzan(opts, P);\n\n # Load dataset\n xaa = pd.read_csv(\"data/Statlog vehicule silhouette/xaa.dat\",\n header=None, sep='\\s+');\n xab = pd.read_csv(\"data/Statlog vehicule silhouette/xab.dat\",\n header=None, sep='\\s+');\n xac = pd.read_csv(\"data/Statlog vehicule silhouette/xac.dat\",\n header=None, sep='\\s+');\n xad = pd.read_csv(\"data/Statlog vehicule silhouette/xad.dat\",\n header=None, sep='\\s+');\n xae = pd.read_csv(\"data/Statlog vehicule silhouette/xae.dat\",\n header=None, sep='\\s+');\n xaf = pd.read_csv(\"data/Statlog vehicule silhouette/xaf.dat\",\n header=None, sep='\\s+');\n xag = pd.read_csv(\"data/Statlog vehicule silhouette/xag.dat\",\n header=None, sep='\\s+');\n xah = pd.read_csv(\"data/Statlog vehicule silhouette/xah.dat\",\n header=None, sep='\\s+');\n xai = pd.read_csv(\"data/Statlog vehicule silhouette/xai.dat\",\n header=None, sep='\\s+');\n\n # Concatate all data xa\n data = pd.concat([xaa, xab, xac, xad, xae, xaf, xag, xah, xai],\n ignore_index=True);\n \n # Column to fit\n cols = data.columns.difference([18]);\n X = data[cols].values;\n y = data[18].values;\n\n\n # Model\n km = KMR(n_clusters=4, n_init=10, n_iter=50, seed=2);\n by = KMR(n_clusters=4, n_init=10, n_iter=50, \n seed=2, n_byzantines=n_byzantines);\n co = KMR(n_clusters=4, n_init=10, n_iter=50,\n seed=2, n_byzantines=n_byzantines, correction=True);\n\n # Fit\n km.fit(X);\n by.fit(X);\n co.fit(X);\n\n # Sort centroides\n km.centroids_ = sort_centroides(km.centroids_);\n by.centroids_ = sort_centroides(by.centroids_);\n co.centroids_ = sort_centroides(co.centroids_);\n\n # Plot\n if rank == 0:\n\n # print('\\nKmeans centroids:\\n' , km.centroids_);\n # print('Byzantine centroids:\\n', by.centroids_);\n # print('Correct centroids:\\n', co.centroids_);\n\n print('\\nKmeans inertia:\\n', km.inertia_);\n print('\\nByzantine inertia:\\n', by.inertia_);\n print('\\nCorrection inertia:\\n', co.inertia_);\n\n # mis_1 = by.misclassified(X, km.labels_, by.labels_);\n # mis_2 = co.misclassified(X, km.labels_, co.labels_);\n\n # print('\\nByzantine has %d data point misclassified.' % (mis_1));\n # print('\\nCorrection has %d data point misclassified.' % (mis_2));\n \n comparaison_cluster(X, [km.labels_, km.n_clusters], [by.labels_,\n by.n_byzantines], co.labels_);\n\n\nif __name__ == \"__main__\":\n main();\n\n"
] |
[
[
"matplotlib.pyplot.figaspect",
"pandas.concat",
"pandas.read_csv",
"matplotlib.pyplot.title",
"numpy.linalg.norm",
"pandas.set_option",
"matplotlib.pyplot.show",
"numpy.zeros",
"sklearn.decomposition.PCA"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
liqile1/OCNet.pytorch
|
[
"5fb733adbf178ccc8040197057e3277896b3dc12",
"5fb733adbf178ccc8040197057e3277896b3dc12"
] |
[
"dataset/leadbang.py",
"cmp.py"
] |
[
"##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n## Created by: speedinghzl02\n## Modified by: RainbowSecret\n## Microsoft Research\n## [email protected]\n## Copyright (c) 2018\n##\n## This source code is licensed under the MIT-style license found in the\n## LICENSE file in the root directory of this source tree \n##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nimport cv2\nimport pdb\nimport collections\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport os.path as osp\nfrom PIL import Image, ImageOps, ImageFilter\nimport random\nimport torch\nimport torchvision\nfrom torch.utils import data\nimport torchvision.transforms as transforms\n\n\nclass LeadBangTrain(data.Dataset):\n def __init__(self, root, max_iters=None,\n scale=True, mirror=True, ignore_label=255, use_aug=False, network=\"resnet101\"):\n self.root = root\n # self.crop_h, self.crop_w = crop_size\n self.crop_h = 480\n self.crop_w = 480\n self.img_width = 512\n self.img_height = 512\n self.scale = scale\n self.ignore_label = ignore_label \n self.is_mirror = mirror\n self.use_aug = use_aug\n self.network = network\n self.files = []\n self.cache_img = {}\n self.cache_label = {}\n self.item_idx_list = []\n for item_idx in range(1, 1463):\n self.item_idx_list.append(item_idx)\n img_path = 'source/' + str(item_idx) + \".bmp\"\n label_path = 'label/' + str(item_idx) + \".bmp\"\n img_file = osp.join(self.root, img_path)\n label_file = osp.join(self.root, label_path)\n print('label file: ', label_file)\n self.files.append({\n \"img\": img_file,\n \"label\": label_file,\n \"name\": str(item_idx),\n \"weight\": 1\n })\n self.cache_img[item_idx] = cv2.imread(img_file)\n self.cache_label[item_idx] = 255 - cv2.imread(label_file, 0)\n \n print('{} images are loaded!'.format(1462))\n\n def __len__(self):\n return len(self.files)\n\n def generate_scale_label(self, image, label):\n f_scale = 0.5 + random.randint(0, 16) / 10.0\n image = cv2.resize(image, None, fx=f_scale, fy=f_scale, interpolation = cv2.INTER_LINEAR)\n label = cv2.resize(label, None, fx=f_scale, fy=f_scale, interpolation = cv2.INTER_NEAREST)\n return image, label\n \n def rescale(self, image, label):\n image = cv2.resize(image, (self.img_width, self.img_height))\n label = cv2.resize(label, (self.img_width, self.img_height))\n return image, label\n\n def id2trainId(self, label, reverse=False):\n label_copy = label.copy()\n if reverse:\n for v, k in self.id_to_trainid.items():\n label_copy[label == k] = v\n else:\n for k, v in self.id_to_trainid.items():\n label_copy[label == k] = v\n return label_copy\n\n def get_rotate_angle(self, angle_min, angle_max, angle_delta):\n count = int((angle_max - angle_min) / angle_delta)\n delta = random.random() * (count + 1) * angle_delta\n angle = angle_min + delta\n if angle < angle_min:\n angle = angle_min\n if angle > angle_max:\n angle = angle_max\n return angle\n\n def rotate(self, image, angle, border_value=None): \n center = (self.img_width // 2, self.img_height // 2)\n \n M = cv2.getRotationMatrix2D(center, angle, 1)\n if border_value is None:\n rotated = cv2.warpAffine(image, M, (self.img_width, self.img_height))\n else:\n rotated = cv2.warpAffine(image, M, (self.img_width, self.img_height), borderValue=(int(border_value),))\n return rotated\n def get_border_value(self, mat):\n r = mat.shape[0]\n c = mat.shape[1]\n return (mat[1][1] + mat[1][c - 2] + mat[r-2][1] + mat[r-2][c-2] + mat[2][2] + mat[2][c - 3] + mat[r-3][2] + mat[r-3][c-3]) / 8.0\n def rotate_img_lb(self, image, label, angle):\n b = image[0]\n g = image[1]\n r = image[2]\n # (102.9801, 115.9465, 122.7717)\n # b = self.rotate(b, angle, border_value=255 - 102.9801)\n # g = self.rotate(g, angle, border_value=255-115.9465)\n # r = self.rotate(r, angle, border_value=255-122.7717)\n b = self.rotate(b, angle, border_value=self.get_border_value(b))\n g = self.rotate(g, angle, border_value=self.get_border_value(g))\n r = self.rotate(r, angle, border_value=self.get_border_value(r))\n label = self.rotate(label, angle)\n image = np.asarray([b, g, r], dtype=np.float32)\n ret, label = cv2.threshold(label, 127, 255, cv2.THRESH_BINARY)\n return image, label\n\n def adv_img_lb(self, img, lb):\n\n # brightness\n img += (random.random() * 10 - 5)\n\n # rotate\n angle = self.get_rotate_angle(-180, 180, 5)\n img, lb = self.rotate_img_lb(img, lb, angle)\n \n # flip lr\n if random.random() < 0.5:\n img = img[:,:,::-1]\n lb = lb[:,::-1]\n # flip ud\n if random.random() < 0.5:\n img = img[:,::-1,:]\n lb = lb[::-1,:]\n\n return img, lb\n\n def __getitem__(self, index):\n datafiles = self.files[index]\n item_idx = self.item_idx_list[index]\n image = self.cache_img[item_idx].copy()\n label = self.cache_label[item_idx].copy()\n\n size = image.shape\n name = datafiles[\"name\"]\n image, label = self.rescale(image, label)\n\n image = np.array(image, dtype=np.float32)\n \n\n if self.network == \"resnet101\":\n # mean = (102.9801, 115.9465, 122.7717)\n # \"mean_value_b\" : 141.29403686523437,\n # \"mean_value_g\" : 123.58832550048828,\n # \"mean_value_r\" : 172.43679809570312,\n mean = (172.43679809570312, 123.58832550048828, 141.29403686523437)\n\n image = image[:,:,::-1]\n image -= mean\n elif self.network == \"mobilenetv2\":\n mean = (0.485, 0.456, 0.406)\n var = (0.229, 0.224, 0.225)\n # print(\"network: {}, mean: {}, var: {}\".format(self.network, mean, var))\n image = image[:,:,::-1]\n image /= 255\n image -= mean \n image /= var\n elif self.network == \"wide_resnet38\":\n mean = (0.41738699, 0.45732192, 0.46886091)\n var = (0.25685097, 0.26509955, 0.29067996)\n image = image[:,:,::-1]\n image /= 255\n image -= mean \n image /= var\n image = image.transpose((2, 0, 1))\n image, label = self.adv_img_lb(image, label)\n\n img_h, img_w = label.shape\n h_off = random.randint(0, img_h - self.crop_h)\n w_off = random.randint(0, img_w - self.crop_w)\n image = np.asarray(image[:,h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)\n label = np.asarray(label[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)\n\n # [0, 255] => [0, 1]\n ret, label = cv2.threshold(label, 127, 1, cv2.THRESH_BINARY)\n label = np.array(label, dtype=np.int64)\n return image.copy(), label.copy(), np.array(size), name\n\n\nclass LeadBangTest(data.Dataset):\n def __init__(self, root, max_iters=None,\n scale=True, mirror=True, ignore_label=255, network=\"resnet101\"):\n self.root = root\n # self.crop_h, self.crop_w = crop_size\n self.crop_h = 512\n self.crop_w = 512\n self.img_width = 512\n self.img_height = 512\n self.scale = scale\n self.ignore_label = ignore_label \n self.is_mirror = mirror\n self.network = network\n self.files = []\n self.cache_img = {}\n self.cache_label = {}\n self.item_idx_list = []\n for item_idx in range(1463, 2352):\n self.item_idx_list.append(item_idx)\n img_path = 'source/' + str(item_idx) + \".bmp\"\n label_path = 'label/' + str(item_idx) + \".bmp\"\n img_file = osp.join(self.root, img_path)\n label_file = osp.join(self.root, label_path)\n self.files.append({\n \"img\": img_file,\n \"label\": label_file,\n \"name\": str(item_idx),\n \"weight\": 1\n })\n print(\"label: \", label_file)\n self.cache_img[item_idx] = cv2.imread(img_file)\n self.cache_label[item_idx] = 255-cv2.imread(label_file, 0)\n \n print('{} images are loaded!'.format(2352-1463))\n\n def __len__(self):\n return len(self.files)\n\n def id2trainId(self, label, reverse=False):\n label_copy = label.copy()\n if reverse:\n for v, k in self.id_to_trainid.items():\n label_copy[label == k] = v\n else:\n for k, v in self.id_to_trainid.items():\n label_copy[label == k] = v\n return label_copy\n\n def rescale(self, image, label):\n image = cv2.resize(image, (self.img_width, self.img_height))\n label = cv2.resize(label, (self.img_width, self.img_height))\n return image, label\n def __getitem__(self, index):\n datafiles = self.files[index]\n item_idx = self.item_idx_list[index]\n image = self.cache_img[item_idx].copy()\n label = self.cache_label[item_idx].copy()\n\n size = image.shape\n name = datafiles[\"name\"]\n image, label = self.rescale(image, label)\n\n image = np.array(image, dtype=np.float32)\n \n\n if self.network == \"resnet101\":\n # mean = (102.9801, 115.9465, 122.7717)\n mean = (172.43679809570312, 123.58832550048828, 141.29403686523437)\n\n image = image[:,:,::-1]\n image -= mean\n elif self.network == \"mobilenetv2\":\n mean = (0.485, 0.456, 0.406)\n var = (0.229, 0.224, 0.225)\n # print(\"network: {}, mean: {}, var: {}\".format(self.network, mean, var))\n image = image[:,:,::-1]\n image /= 255\n image -= mean \n image /= var\n elif self.network == \"wide_resnet38\":\n mean = (0.41738699, 0.45732192, 0.46886091)\n var = (0.25685097, 0.26509955, 0.29067996)\n image = image[:,:,::-1]\n image /= 255\n image -= mean \n image /= var\n image = image.transpose((2, 0, 1))\n\n img_h, img_w = label.shape\n h_off = random.randint(0, img_h - self.crop_h)\n w_off = random.randint(0, img_w - self.crop_w)\n image = np.asarray(image[:,h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)\n label = np.asarray(label[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)\n\n # [0, 255] => [0, 1]\n ret, label = cv2.threshold(label, 127, 1, cv2.THRESH_BINARY)\n label = np.array(label, dtype=np.int64)\n label = np.asarray(label, dtype=np.int64) \n return image.copy(), label.copy(), np.array(size), name\n\n\ndef test_train_leadbang():\n \n dst = LeadBangTrain(\"./leadbang/\")\n trainloader = data.DataLoader(dst, batch_size=1, num_workers=0)\n\n with open(\"./list/cityscapes/trainval.lst\") as f:\n train_list = f.readlines()\n train_list = [x.strip() for x in train_list] \n\n f_w = open(\"./list/cityscapes/bus_truck_train.lst\", \"w\")\n \n for i, dt in enumerate(trainloader):\n imgs, labels, _, name = dt\n img = imgs.numpy()\n lb = labels.numpy()\n print(name)\n print(img.shape)\n print(lb.shape)\n name = name[0]\n img = np.transpose(img[0], (1,2,0))\n img += (172.43679809570312, 123.58832550048828, 141.29403686523437)\n img = img[:,:,::-1]\n img = np.array(img, dtype=np.uint8)\n lb = 255 - lb[0] * 255\n lb = np.asarray(lb, dtype=np.uint8)\n cv2.imshow( \"img\", img)\n cv2.imshow( \"lb\", lb)\n cv2.waitKey(0)\n\n\ndef test_test_leadbang():\n \n dst = LeadBangTest(\"./leadbang/\")\n trainloader = data.DataLoader(dst, batch_size=1, num_workers=0)\n\n with open(\"./list/cityscapes/trainval.lst\") as f:\n train_list = f.readlines()\n train_list = [x.strip() for x in train_list] \n\n f_w = open(\"./list/cityscapes/bus_truck_train.lst\", \"w\")\n \n for i, dt in enumerate(trainloader):\n imgs, labels, _, name = dt\n img = imgs.numpy()\n lb = labels.numpy()\n print(name)\n print(img.shape)\n print(lb.shape)\n name = name[0]\n img = np.transpose(img[0], (1,2,0))\n img += (172.43679809570312, 123.58832550048828, 141.29403686523437)\n img = img[:,:,::-1]\n img = np.array(img, dtype=np.uint8)\n lb = 255 - lb[0] * 255\n lb = np.asarray(lb, dtype=np.uint8)\n cv2.imshow( \"img\", img)\n cv2.imshow( \"lb\", lb)\n cv2.waitKey(0)\n\nif __name__ == '__main__':\n test_train_leadbang()\n # test_test_leadbang()\n",
"import os\nimport cv2\nimport numpy as np\n\nif __name__ == \"__main__\":\n mis_ok = 0\n mis_ng = 0\n ng = 0\n ok = 0\n for idx in range(1463, 2352):\n label = cv2.imread('dataset/leadbang/label/' + str(idx) + '.bmp', 0)\n result = cv2.imread('dataset/leadbang/test_result/' + str(idx) + '.bmp', 0)\n label_defect = len(np.where(label < 100)[0])\n result_defect = len(np.where(result < 100)[0])\n if label_defect > 0 and result_defect == 0:\n mis_ok += 1\n if label_defect == 0 and result_defect > 0:\n mis_ng += 1\n\n if label_defect > 0:\n ng += 1\n else:\n ok += 1\n print('mis ok: ', mis_ok, '/', ng)\n print('mis ng: ', mis_ng, '/', ok)\n"
] |
[
[
"numpy.asarray",
"numpy.array",
"torch.utils.data.DataLoader",
"numpy.transpose"
],
[
"numpy.where"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vstadnytskyi/sequence-server-wrapper
|
[
"1ee23638752a969f51b11a65a3b7652874efe8c5"
] |
[
"sequence_server_wrapper/examples/example_device.py"
] |
[
"#!/usr/bin/env python3\nfrom logging import debug, info, warning, error\nfrom time import sleep\n\nimport traceback\n\nclass DeviceExample():\n def __init__(self):\n self.io = None\n self.trajectory = None\n self.idle_value = 0.0\n\n def init(self):\n from time import sleep\n \"\"\"\n orderly initialization\n \"\"\"\n debug('Conducting orderly initialization of the Example Device')\n sleep(1)\n\n def parse_CMD(self,cmd):\n def linear(start=0,end=10,step=1):\n from numpy import arange\n return list(arange(start,end,step))\n try:\n lst = eval(cmd)\n except:\n lst = None\n if type(lst) is list:\n return {'flag':True, 'values':lst}\n else:\n return {'flag':False, 'values':[]}\n\n def set_VAL(self,value):\n self._VAL = value\n sleep(0.5)\n def get_VAL(self):\n return self._VAL\n VAL = property(get_VAL,set_VAL)\n\n def io_execute(self,pv_name, value):\n \"\"\"\n\n \"\"\"\n from time import sleep\n print(f'io_execute received: {pv_name},{value}')\n response = ''\n if pv_name == 'CMD':\n self.io_put(pv_name = 'ACK',value = 0)\n self.io_put(pv_name = 'values',value = [])\n\n reply = self.parse_CMD(value)\n response = \"\"+str(int(reply['flag']))\n self.trajectory = reply['values']\n if reply['flag'] == False:\n response += f\"{'failed to eval the command'}\"\n self.io_put(pv_name = 'values',value = reply['values'])\n sleep(1)\n self.io_put(pv_name = 'ACK',value = response)\n if pv_name == 'Nested_Indices':\n print(f'io_execute inside if pv_name == Nested_Indices: {\"Nested_Indices\"}')\n print(bytes(value))\n index = eval(bytes(value))['test.server']\n self.io_put(pv_name = 'ACK',value = 0)\n try:\n if self.trajectory is not None:\n self.VAL = self.trajectory[index]\n else:\n self.VAL = self.idle_value\n flag = True\n resp = ' '\n except:\n resp = traceback.format_exc()\n print(resp)\n flag = False\n print(self.VAL)\n response += resp\n self.io_put(pv_name = 'VAL',value = self.VAL)\n self.io_put(pv_name = 'message',value = response)\n self.io_put(pv_name = 'ACK',value = 1)\n\n\n print('response:',reply,response)\n\n def io_put(self,pv_name, value):\n print(f'DeviceExample.io_put: {pv_name},{value}')\n if self.io is not None:\n if pv_name == 'VAL':\n self.io.io_put_queue.put({pv_name: value})\n else:\n self.io.seq.io_put_queue.put({pv_name: value})\n\n\n\nif __name__ is '__main__':\n device = DeviceExample()\n device.init()\n"
] |
[
[
"numpy.arange"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
100kimch/ros_galapagos
|
[
"8f92cb93246c263b61199aef113e43cefc5f3939"
] |
[
"packages/galapagos_embedded/libs/lib_frontcam.py"
] |
[
"import cv2\nimport numpy as np\nimport rospy\nimport matplotlib.pyplot as plt\nimport sys\nfrom scheduler import SCHEDULER\nfrom constants import *\nimport os\nimport sys\n\n\n# * Variables\n\n# variables for matching\n# Initiate SIFT description detector\nOrb = cv2.ORB_create()\n# create BFMatcher object\nBf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\nref_images = {}\n\n# HSV Ranges used in each state\n\"\"\" before \nlower_blue = np.array([90, 80, 0])\nupper_blue = np.array([130, 255, 255])\n\"\"\"\n\nlower_blue = np.array([90, 110, 100])\nupper_blue = np.array([130, 200, 160])\nlower_red = np.array([0, 120, 100])\nupper_red = np.array([20, 180, 200])\nlower_green = np.array([60, 55, 50])\nupper_green = np.array([85, 255, 255])\n# lower_green = np.array([65, 60, 60])\n# upper_green = np.array([80, 255, 255])\n\nvalue_default = 1\n\n# * Methods\n\n\ndef init_ref_images():\n global ref_images\n\n for idx, key in enumerate(REF_IMAGE_PATH):\n image = cv2.imread(SCHEDULER.path + \"/images/\" + REF_IMAGE_PATH[key])\n try:\n image = cv2.medianBlur(cv2.GaussianBlur(image, (11, 11), 0), 11)\n except cv2.error as e:\n rospy.logfatal(\"[LIB_FRONT] ref image '\" + key +\n \"' not found in constants.py!\")\n rospy.signal_shutdown(\"Shutdown by fatal error.\")\n\n if SCHEDULER.debug_option[\"show_loaded_ref_images\"]:\n rospy.logdebug(\"[LIB_FRONT] {:8s} image loaded. ({})\".format(\n key, str(SCHEDULER.path + \"/\" + REF_IMAGE_PATH[key])))\n\n keypoints, descriptor = Orb.detectAndCompute(image, None)\n\n ref_images[key] = {\n \"image\": image,\n \"keypoints\": keypoints,\n \"descriptor\": descriptor\n }\n\n\ndef blob_parameter(state_type):\n ''' blob_parameter function for making detector for some blob shapes(circle or triangle)\n & setting parameter of detector\n * Input \n state_type : recognition type in recognition_list (ex : 'parking')\n * Output\n blob_detector : blob detector that has parameters setted by recognition type \n '''\n if state_type == 'traffic_light':\n # Setup SimpleBlobDetector parameters.\n params = cv2.SimpleBlobDetector_Params()\n params.minThreshold = 0\n params.maxThreshold = 256\n params.filterByArea = True\n params.minArea = 500\n params.maxArea = 2300\n params.filterByCircularity = True\n params.minCircularity = 0.4\n params.filterByConvexity = True\n params.minConvexity = 0.1\n params.filterByInertia = True\n params.minInertiaRatio = 0.01\n\n elif state_type == 'intersection' or state_type == 'construction' or state_type == 'turnel':\n # Setup SimpleBlobDetector parameters.\n params = cv2.SimpleBlobDetector_Params()\n params.minThreshold = 10\n params.maxThreshold = 200\n params.filterByArea = True\n params.minArea = 500\n params.filterByCircularity = True\n params.minCircularity = 0.1\n params.filterByConvexity = False\n params.minConvexity = 0.1\n params.filterByInertia = True\n params.minInertiaRatio = 0.01\n\n else:\n # Setup SimpleBlobDetector parameters.\n params = cv2.SimpleBlobDetector_Params()\n params.minThreshold = 0\n params.maxThreshold = 256\n params.filterByArea = True\n params.minArea = 1000\n params.maxArea = 35000\n params.filterByCircularity = True\n params.minCircularity = 0.5\n params.filterByConvexity = True\n params.minConvexity = 0.1\n params.filterByInertia = True\n params.minInertiaRatio = 0.01\n\n # Create a detector with the parameters\n ver = (cv2.__version__).split('.')\n\n if int(ver[0]) < 3:\n blob_detector = cv2.SimpleBlobDetector(params)\n else:\n blob_detector = cv2.SimpleBlobDetector_create(params)\n\n return blob_detector\n\n\ndef blob_detecting(image, blob_detector, state_type):\n ''' blob_detecting function for finding center point of ROI\n by HSV range thresholding & detecting specific blob shape\n * Input\n image : front camera image from pi camera --> BGR image\n blob_detector : HSV blob detector made by blob_parameter() function\n * Output\n blob_centers : center points of blob (specific blob shape -> potential ROI center point)\n centers : if `blob_centers` is detected, change the type of data to pt array\n '''\n #cv2.imshow(\"raw_image\", image)\n # cv2.waitKey(1)\n _hsv_maxThreshold = value_default\n _hsv_minThreshold = value_default\n if state_type == 'intersection' or state_type == 'construction' or state_type == 'turnel':\n _hsv_maxThreshold = upper_red\n _hsv_minThreshold = lower_red\n elif state_type == 'traffic_light':\n _hsv_maxThreshold = upper_green\n _hsv_minThreshold = lower_green\n else:\n _hsv_maxThreshold = upper_blue\n _hsv_minThreshold = lower_blue\n\n # thresholding process rgb_image to hsv_image by HSV Threshold\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # make mask and pre-image-processing : morphology (erode or dilate)\n kernel = np.ones((3, 3), np.uint8)\n mask = cv2.inRange(hsv, _hsv_minThreshold, _hsv_maxThreshold)\n mask = cv2.dilate(mask, kernel, iterations=5)\n #maks = cv2.erode(mask, kernel, iterations = 3)\n reversemask = 255 - mask\n\n # Detect specific blobshape and center point of blob\n if state_type == 'intersection' or state_type == 'turnel' or state_type == 'to_intersection':\n blob_centers = blob_detector.detect(mask)\n else:\n blob_centers = blob_detector.detect(reversemask)\n\n BGR_ROI = cv2.cvtColor(reversemask, cv2.COLOR_GRAY2BGR)\n\n # if IS_DEBUG_MODE == True:\n\n if SCHEDULER.debug_option[\"show_blob_detecting\"]:\n print(len(blob_centers))\n show_centers = cv2.drawKeypoints(reversemask, blob_centers, np.array(\n []), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n cv2.imshow('hsv', hsv)\n cv2.imshow('mask', mask)\n cv2.imshow('reverse', reversemask)\n cv2.imshow('result', show_centers)\n cv2.waitKey(0)\n\n if len(blob_centers) >= 1:\n centers = []\n for i in blob_centers:\n centers.append(i.pt)\n return centers\n else:\n return blob_centers\n\n\ndef signROI_detecting(image, state_type):\n ''' signROI_detecting function for detecting signROI\n using HSV range thresholding and specific blob shape detectiong, different by cases\n * Input \n image : front camera image from pi camera --> BGR image\n state_type : recognition type \n * Output\n signROI : sign detection result image --> BGR image\n True : thiere is singROI\n False : there is no signROI\n '''\n # image ROI detecting using HSV range\n #image = cv2.GaussianBlur(image, (5, 5), 0)\n sign_detector = blob_parameter(state_type)\n sign_centers = blob_detecting(image, sign_detector, state_type)\n # cv2.imshow('input', image) # ! code for debugging\n # cv2.waitKey() # ! code for debugging\n # print 'test' #! code for debugging\n # print len(sign_centers) #! code for debugging\n if len(sign_centers) >= 1:\n xx = int(sign_centers[0][0])\n yy = int(sign_centers[0][1])\n # print sign_centers[0][1], sign_centers[0][0] #! code for debugging\n if sign_centers[0][1] - 45 < 0 or sign_centers[0][0] < 45:\n if sign_centers[0][0] < sign_centers[0][1]:\n signROI_size = int(sign_centers[0][0])\n else:\n signROI_size = int(sign_centers[0][1])\n else:\n signROI_size = 45\n signROI = image[yy - signROI_size: yy +\n signROI_size, xx - signROI_size: xx + signROI_size]\n cv2.imshow('ROI', signROI) # ! code for debugging\n cv2.waitKey(1) # ! code for debugging\n # print(\"blob detected!!!!!\")\n # print(\"blob detected!!!!!\")\n # print(\"blob detected!!!!!\")\n return signROI, True\n else:\n # print(\"blob detected failed!!!!\")\n # print(\"blob detected failed!!!!\")\n # print(\"blob detected failed!!!!\")\n signROI = image\n return signROI, False\n\n\ndef ORB_matching(_roi, _ref_img, _ref_keypoints, _ref_descriptor):\n ''' ORB_matching function for matching two input image and output is matching result\n * Input\n _roi : sign ROI image --> BGR image\n _ref : sign ref image --> gray image\n * Output\n matches : ORB descriptor matching result \n '''\n\n global Orb\n global Bf\n\n # image pretreatment\n _roi = cv2.cvtColor(_roi, cv2.COLOR_BGR2GRAY)\n _roi = cv2.medianBlur(_roi, 5)\n\n # find the keypoints and descriptors with SIFT\n ROI_keypoints, ROI_descriptor = Orb.detectAndCompute(_roi, None)\n\n # Match descriptors.\n matches = Bf.match(ROI_descriptor, _ref_descriptor)\n\n # Sort them in the order of their distance.\n # Not use distance values yet, but can use it at thresholding\n matches = sorted(matches, key=lambda x: x.distance)\n\n if SCHEDULER.debug_option[\"show_orb_matching\"] == True:\n print(len(matches)) # ! code for debugging\n matching_image = cv2.drawMatches(\n _roi, ROI_keypoints, _ref_img, _ref_keypoints, matches, None, flags=2) # ! code for debugging\n cv2.imshow('matching', matching_image) # ! code for debugging\n cv2.waitKey() # ! code for debugging\n\n return matches\n\n\ndef check_if_left_or_right(image):\n \"\"\" \n Check direction where to go in intersection\n @Input: image - sign roi image from front pi camera image --> gray image\n @Output: direction where to go: [\"left\", \"right]\n \"\"\"\n\n\ndef left_or_right(_frontcam_roi):\n ''' left_or_right function for check direction of arrow sign\n * Input\n _frontcam_roi : sign roi image from front pi camera image --> gray image\n * Output\n direction left or right\n '''\n _frontcam_roi = cv2.cvtColor(_frontcam_roi, cv2.COLOR_BGR2GRAY)\n # Threshloding --> binary image by otsu's method\n # cv2.imwrite('gray_frontcam_roi.png', _frontcam_roi)\n _frontcam_roi = cv2.GaussianBlur(_frontcam_roi, (7, 7), 0)\n # cv2.imwrite('gaussian_gray_frontcam_roi.png', _frontcam_roi)\n tmp, binary_roi = cv2.threshold(\n _frontcam_roi, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n #height = np.size(binary_roi, 0)/2\n #width = np.size(binary_roi, 1)/2\n # cutting small ROI from under center point 40 X 20 box\n #small_roi = binary_roi[height:height+20, width-20:width+20]\n # compare sum of left pixels' value and right's one\n sum_left = 0\n sum_right = 0\n '''\n for j in range(20):\n for i in range(20):\n sum_left += small_roi[j, i]\n for i in range(20, 40):\n sum_right += small_roi[j, i]\n '''\n bin_roi_H = binary_roi.shape[0]\n bin_roi_W = binary_roi.shape[1]\n for j in range(bin_roi_H // 2):\n for i in range(bin_roi_W // 2):\n sum_left += binary_roi[j + bin_roi_H // 2, i]\n for i in range(bin_roi_W // 2):\n sum_right += binary_roi[j + bin_roi_H //\n 2, i + binary_roi.shape[1] // 2]\n print(\"=========================================\")\n print(\"sum left: \", sum_left / 255, \", sum right: \",\n sum_right / 255) # ! code for debugging\n print(\"==============sum printing================\")\n # cv2.imwrite('binary_roi.png', binary_roi) # ! code for debugging\n # cv2.imshow('small_roi',small_roi) #! code for debugging\n # cv2.waitKey(0) #! code for debugging\n if sum_left > sum_right:\n print(\"right detected!!!!\")\n print(\"right detected!!!!\")\n print(\"right detected!!!!\")\n return 'right'\n else:\n print(\"left detected!!!!\")\n print(\"left detected!!!!\")\n print(\"left detected!!!!\")\n return 'left'\n\n\ndef is_light_green(image):\n \"\"\" check the traffic_light's light\n image: front image\n return True if light is green\n return False if light is not green\n \"\"\"\n raw_data = np.fromstring(image.data, np.uint8)\n cv_img = cv2.imdecode(raw_data, cv2.IMREAD_COLOR)\n\n detector = blob_parameter('traffic_light')\n centers = blob_detecting(cv_img, detector, 'traffic_light')\n\n if len(centers) >= 1:\n return True\n else:\n return False\n\n\ndef is_intersection(image):\n \"\"\" check whether the image is intersection\n return True if intersection\n return False if not intersection\n \"\"\"\n\n ROI_img, ROI_OX = signROI_detecting(image, 'intersection')\n if ROI_OX != False:\n # matching & thresholding\n result_matching = ORB_matching(\n ROI_img, ref_intersection, ref_intersection_keypoints, ref_intersection_descriptor)\n if len(result_matching) >= threshold_intersection:\n return True\n else:\n return False\n else:\n return False\n\n\ndef is_parking(image):\n \"\"\" check whether the image is parking\n return True if parking\n return False if not parking\n \"\"\"\n\n ROI_img, ROI_OX = signROI_detecting(image, 'parking')\n\n if ROI_OX != False:\n # matching & thresholding\n result_matching = ORB_matching(\n ROI_img, ref_images[\"parking\"][\"images\"], ref_images[\"parking\"][\"keypoints\"], ref_images[\"parking\"][\"descriptor\"])\n\n if len(result_matching) >= threshold_parking:\n return True\n else:\n return False\n\n else:\n return False\n\n\ndef is_construction(image):\n raw_data = np.fromstring(image.data, np.uint8)\n cv_img = cv2.imdecode(raw_data, cv2.IMREAD_COLOR)\n\n ROI_img, ROI_OX = signROI_detecting(cv_img, 'construction')\n\n if ROI_OX != False:\n # matching & thresholding\n result_matching = ORB_matching(\n ROI_img, ref_images[\"construction\"][\"image\"], ref_images[\"construction\"][\"image\"], ref_images[\"construction\"][\"descriptor\"])\n\n if SCHEDULER.debug_option[\"show_image_matching\"]:\n rospy.logdebug(\"result matching : \" + str(len(result_matching)))\n\n if len(result_matching) >= THRESHOLDS[\"construction\"]:\n return True\n else:\n return False\n\n else:\n return False\n\n\ndef is_tunnel(image):\n ROI_img, ROI_OX = signROI_detecting(image, 'tunnel')\n\n if ROI_OX != False:\n # matching & thresholding\n result_matching = ORB_matching(\n ROI_img, ref_images[\"tunnel\"], ref_images[\"tunnel\"][\"keypoints\"], ref_images[\"tunnel\"][\"descriptor\"])\n\n if SCHEDULER.debug_option[\"show_image_matching\"] == True:\n rospy.logdebug(\"result matching : \" + str(len(result_matching)))\n\n if len(result_matching) >= threshold_tunnel:\n return True\n else:\n return False\n\n else:\n return False\n\n\ndef check_left_right_sign(image):\n \"\"\" check the sign of left or right sign\n return 'left' if the sign means 'left'\n return 'right' if the sign means 'right'\n return 'none' if there isn't a sign\n \"\"\"\n global threshold_lrmin\n global threshold_lrmax\n\n raw_data = np.fromstring(image.data, np.uint8)\n cv_img = cv2.imdecode(raw_data, cv2.IMREAD_COLOR)\n # NOTE: ROI Setting\n blob_ROI = cv_img[100:, :]\n\n ROI_img, ROI_OX = signROI_detecting(cv_img, 'left_or_right')\n\n if ROI_OX != False:\n # LEFT or RIGHT\n result_matching_left = ORB_matching(\n ROI_img, ref_images[\"left\"][\"image\"], ref_images[\"left\"][\"keypoints\"], ref_images[\"left\"][\"descriptor\"])\n result_matching_right = ORB_matching(\n ROI_img, ref_images[\"right\"][\"image\"], ref_images[\"right\"][\"keypoints\"], ref_images[\"right\"][\"descriptor\"])\n\n #print(\"left length: \",len(result_matching_left))\n #print(\"right length: \",len(result_matching_right))\n\n if len(result_matching_left) >= THRESHOLDS[\"left_right_min\"] and \\\n len(result_matching_left) <= THRESHOLDS[\"left_right_max\"] and \\\n len(result_matching_right) >= THRESHOLDS[\"left_right_min\"] and \\\n len(result_matching_right) <= THRESHOLDS[\"left_right_max\"]:\n return left_or_right(ROI_img)\n else:\n return 'none'\n\n else:\n return 'none'\n\n\ndef check_sign(image):\n \"\"\" check what the sign means\n image: front image\n return 'intersection' if the sign means 'intersection' state\n return 'construction' if the sign means 'construction' state\n return 'parking' if the sign means 'parking' state\n return 'tunnel' if the sign means 'tunnel' state\n return 'nothing' if there is no sign\n \"\"\"\n if(is_intersection(image) == True):\n return 'intersection'\n elif(is_parking(image) == True):\n return 'parking'\n else:\n return 'nothing'\n\n\ndef has_curve_in(distance, image):\n \"\"\" check if there is a curve in distance\"\"\"\n # TODO: future task\n return False\n\n\ndef is_straight_in(distance, image):\n \"\"\" check if the way is straight in distance\"\"\"\n # TODO: future task\n return False\n\n\ndef is_stopping_sign(image):\n \"\"\" check if the sign means 'stop \"\"\"\n # TODO: future task\n return False\n\n\ndef has_crossing_line(image):\n \"\"\" returns true if there is a crossing line from left to right\"\"\"\n # TODO: future task\n return False\n\n\n# reference image & keypoints & descriptors initialize\n# init_ref_images()\n'''\nfrom lib_frontcam import signROI_detecting\nimport cv2\nright_img = cv2.imread(\n \"/home/kusw-004/steamcup_2020/assets/images_final/image1.png\")\nleft_img = cv2.imread(\n \"/home/kusw-004/steamcup_2020/assets/images_final/image2.png\")\nref_left = cv2.imread(\n \"/home/kusw-004/steamcup_2020/packages/galapagos_v2/libs/left.png\")\nref_right = cv2.imread(\n \"/home/kusw-004/steamcup_2020/packages/galapagos_v2/libs/right.png\")\n'''\n"
] |
[
[
"numpy.fromstring",
"numpy.array",
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zeevikal/modin
|
[
"2128f80280092902c61d738d9d2ef551bc4ffaf4",
"2128f80280092902c61d738d9d2ef551bc4ffaf4"
] |
[
"modin/data_management/partitioning/remote_partition/pandas_on_python.py",
"modin/pandas/reshape.py"
] |
[
"import pandas\r\n\r\nfrom .utils import length_fn_pandas, width_fn_pandas\r\n\r\n\r\nclass PandasOnPythonRemotePartition(object):\r\n \"\"\"This abstract class holds the data and metadata for a single partition.\r\n The methods required for implementing this abstract class are listed in\r\n the section immediately following this.\r\n\r\n The API exposed by the children of this object is used in\r\n `BaseBlockPartitions`.\r\n\r\n Note: These objects are treated as immutable by `BaseBlockPartitions`\r\n subclasses. There is no logic for updating inplace.\r\n \"\"\"\r\n\r\n def __init__(self, data):\r\n self.data = data\r\n self.call_queue = []\r\n\r\n def get(self):\r\n \"\"\"Return the data.\r\n\r\n Note: Since this object is a simple wrapper, just return the data.\r\n\r\n Returns:\r\n The object that was `put`.\r\n \"\"\"\r\n return self.data.copy()\r\n\r\n def apply(self, func, **kwargs):\r\n \"\"\"Apply some callable function to the data in this partition.\r\n\r\n Note: It is up to the implementation how kwargs are handled. They are\r\n an important part of many implementations. As of right now, they\r\n are not serialized.\r\n\r\n Args:\r\n func: The lambda to apply (may already be correctly formatted)\r\n\r\n Returns:\r\n A new `BaseRemotePartition` containing the object that has had `func`\r\n applied to it.\r\n \"\"\"\r\n self.call_queue.append((func, kwargs))\r\n\r\n def call_queue_closure(data, call_queues):\r\n for func, kwargs in call_queues:\r\n try:\r\n data = func(data.copy(), **kwargs)\r\n except Exception as e:\r\n self.call_queue = []\r\n raise e\r\n return data\r\n\r\n new_data = call_queue_closure(self.data, self.call_queue)\r\n self.call_queue = []\r\n return PandasOnPythonRemotePartition(new_data)\r\n\r\n def add_to_apply_calls(self, func, **kwargs):\r\n \"\"\"Add the function to the apply function call stack.\r\n\r\n This function will be executed when apply is called. It will be executed\r\n in the order inserted; apply's func operates the last and return\r\n \"\"\"\r\n self.call_queue.append((func, kwargs))\r\n return self\r\n\r\n def to_pandas(self):\r\n \"\"\"Convert the object stored in this partition to a Pandas DataFrame.\r\n\r\n Note: If the underlying object is a Pandas DataFrame, this will likely\r\n only need to call `get`\r\n\r\n Returns:\r\n A Pandas DataFrame.\r\n \"\"\"\r\n return self.data\r\n\r\n @classmethod\r\n def put(cls, obj):\r\n \"\"\"A factory classmethod to format a given object.\r\n\r\n Args:\r\n obj: An object.\r\n\r\n Returns:\r\n A `RemotePartitions` object.\r\n \"\"\"\r\n return cls(obj)\r\n\r\n @classmethod\r\n def preprocess_func(cls, func):\r\n \"\"\"Preprocess a function before an `apply` call.\r\n\r\n Note: This is a classmethod because the definition of how to preprocess\r\n should be class-wide. Also, we may want to use this before we\r\n deploy a preprocessed function to multiple `BaseRemotePartition`\r\n objects.\r\n\r\n Args:\r\n func: The function to preprocess.\r\n\r\n Returns:\r\n An object that can be accepted by `apply`.\r\n \"\"\"\r\n return func\r\n\r\n @classmethod\r\n def length_extraction_fn(cls):\r\n \"\"\"The function to compute the length of the object in this partition.\r\n\r\n Returns:\r\n A callable function.\r\n \"\"\"\r\n return length_fn_pandas\r\n\r\n @classmethod\r\n def width_extraction_fn(cls):\r\n \"\"\"The function to compute the width of the object in this partition.\r\n\r\n Returns:\r\n A callable function.\r\n \"\"\"\r\n return width_fn_pandas\r\n\r\n _length_cache = None\r\n _width_cache = None\r\n\r\n def length(self):\r\n if self._length_cache is None:\r\n self._length_cache = type(self).width_extraction_fn()(self.data)\r\n return self._length_cache\r\n\r\n def width(self):\r\n if self._width_cache is None:\r\n self._width_cache = type(self).width_extraction_fn()(self.data)\r\n return self._width_cache\r\n\r\n @classmethod\r\n def empty(cls):\r\n return cls(pandas.DataFrame())\r\n",
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pandas\nfrom pandas.core.dtypes.common import is_list_like\n\nfrom .dataframe import DataFrame\n\n\ndef get_dummies(\n data,\n prefix=None,\n prefix_sep=\"_\",\n dummy_na=False,\n columns=None,\n sparse=False,\n drop_first=False,\n):\n \"\"\"Convert categorical variable into indicator variables.\n\n Args:\n data (array-like, Series, or DataFrame): data to encode.\n prefix (string, [string]): Prefix to apply to each encoded column\n label.\n prefix_sep (string, [string]): Separator between prefix and value.\n dummy_na (bool): Add a column to indicate NaNs.\n columns: Which columns to encode.\n sparse (bool): Not Implemented: If True, returns SparseDataFrame.\n drop_first (bool): Whether to remove the first level of encoded data.\n\n Returns:\n DataFrame or one-hot encoded data.\n \"\"\"\n if sparse:\n raise NotImplementedError(\n \"SparseDataFrame is not implemented. \"\n \"To contribute to Modin, please visit \"\n \"github.com/modin-project/modin.\"\n )\n if not isinstance(data, DataFrame):\n return pandas.get_dummies(\n data,\n prefix=prefix,\n prefix_sep=prefix_sep,\n dummy_na=dummy_na,\n columns=columns,\n sparse=sparse,\n drop_first=drop_first,\n )\n if isinstance(data, DataFrame):\n df = data\n elif is_list_like(data):\n df = DataFrame(data)\n\n new_manager = df._query_compiler.get_dummies(\n columns,\n prefix=prefix,\n prefix_sep=prefix_sep,\n dummy_na=dummy_na,\n drop_first=drop_first,\n )\n return DataFrame(query_compiler=new_manager)\n"
] |
[
[
"pandas.DataFrame"
],
[
"pandas.core.dtypes.common.is_list_like",
"pandas.get_dummies"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.24"
],
"scipy": [],
"tensorflow": []
}
] |
frahlg/npbench
|
[
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26",
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26",
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26",
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26",
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26",
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26",
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26",
"1bc4d9e2e22f3ca67fa2bc7f40e2e751a9c8dd26"
] |
[
"npbench/benchmarks/polybench/covariance/covariance.py",
"npbench/benchmarks/polybench/gemver/gemver_numba_n.py",
"npbench/benchmarks/deep_learning/lenet/lenet_numba_opr.py",
"npbench/benchmarks/polybench/symm/symm_numba_npr.py",
"npbench/benchmarks/polybench/floyd_warshall/floyd_warshall_numba_n.py",
"npbench/benchmarks/deep_learning/mlp/mlp_numba_n.py",
"npbench/benchmarks/polybench/cholesky/cholesky_dace.py",
"npbench/benchmarks/nbody/nbody.py"
] |
[
"# Copyright 2021 ETH Zurich and the NPBench authors. All rights reserved.\n\nimport numpy as np\n\n\ndef initialize(M, N, datatype=np.float64):\n float_n = datatype(N)\n data = np.fromfunction(lambda i, j: (i * j) / M, (N, M), dtype=datatype)\n\n return float_n, data\n",
"import numpy as np\nimport numba as nb\n\n\[email protected](nopython=True, parallel=False, fastmath=True)\ndef kernel(alpha, beta, A, u1, v1, u2, v2, w, x, y, z):\n\n A += np.outer(u1, v1) + np.outer(u2, v2)\n x += beta * y @ A + z\n w += alpha * A @ x\n",
"import numpy as np\nimport numba as nb\n\n\[email protected](nopython=False, forceobj=True, parallel=False, fastmath=True)\ndef relu(x):\n return np.maximum(x, 0)\n\n\n# Deep learning convolutional operator (stride = 1)\[email protected](nopython=False, forceobj=True, parallel=True, fastmath=True)\ndef conv2d(input, weights):\n K = weights.shape[0] # Assuming square kernel\n N = input.shape[0]\n H_out = input.shape[1] - K + 1\n W_out = input.shape[2] - K + 1\n C_out = weights.shape[3]\n output = np.empty((N, H_out, W_out, C_out), dtype=np.float32)\n\n # Loop structure adapted from https://github.com/SkalskiP/ILearnDeepLearning.py/blob/ba0b5ba589d4e656141995e8d1a06d44db6ce58d/01_mysteries_of_neural_networks/06_numpy_convolutional_neural_net/src/layers/convolutional.py#L88\n for i in nb.prange(H_out):\n for j in nb.prange(W_out):\n output[:, i, j, :] = np.sum(\n input[:, i:i + K, j:j + K, :, np.newaxis] *\n weights[np.newaxis, :, :, :],\n axis=(1, 2, 3),\n )\n\n return output\n\n\n# 2x2 maxpool operator, as used in LeNet-5\[email protected](nopython=False, forceobj=True, parallel=True, fastmath=True)\ndef maxpool2d(x):\n output = np.empty(\n [x.shape[0], x.shape[1] // 2, x.shape[2] // 2, x.shape[3]],\n dtype=x.dtype)\n for i in nb.prange(x.shape[1] // 2):\n for j in nb.prange(x.shape[2] // 2):\n output[:, i, j, :] = np.max(x[:, 2 * i:2 * i + 2,\n 2 * j:2 * j + 2, :],\n axis=(1, 2))\n return output\n\n\n# LeNet-5 Convolutional Neural Network (inference mode)\[email protected](nopython=False, forceobj=True, parallel=True, fastmath=True)\ndef lenet5(input, conv1, conv1bias, conv2, conv2bias, fc1w, fc1b, fc2w, fc2b,\n fc3w, fc3b, N, C_before_fc1):\n x = relu(conv2d(input, conv1) + conv1bias)\n x = maxpool2d(x)\n x = relu(conv2d(x, conv2) + conv2bias)\n x = maxpool2d(x)\n x = np.reshape(x, (N, C_before_fc1))\n x = relu(x @ fc1w + fc1b)\n x = relu(x @ fc2w + fc2b)\n return x @ fc3w + fc3b\n",
"import numpy as np\nimport numba as nb\n\n\[email protected](nopython=True, parallel=True, fastmath=True)\ndef kernel(alpha, beta, C, A, B):\n\n temp2 = np.empty((C.shape[1], ), dtype=C.dtype)\n C *= beta\n for i in range(C.shape[0]):\n for j in nb.prange(C.shape[1]):\n C[:i, j] += alpha * B[i, j] * A[i, :i]\n temp2[j] = B[:i, j] @ A[i, :i]\n C[i, :] += alpha * B[i, :] * A[i, i] + alpha * temp2\n",
"import numpy as np\nimport numba as nb\n\n\[email protected](nopython=True, parallel=False, fastmath=True)\ndef kernel(path):\n\n for k in range(path.shape[0]):\n # path[:] = np.minimum(path[:], np.add.outer(path[:, k], path[k, :]))\n for i in range(path.shape[0]):\n path[i, :] = np.minimum(path[i, :], path[i, k] + path[k, :])\n",
"import numpy as np\nimport numba as nb\n\n\[email protected](nopython=True, parallel=False, fastmath=True)\ndef relu(x):\n return np.maximum(x, 0)\n\n\n# Numerically-stable version of softmax\[email protected](nopython=True, parallel=False, fastmath=True)\ndef softmax(x):\n new_shape = (x.shape[0], 1)\n # tmp_max = np.max(x, axis=-1, keepdims=True)\n tmp_max = np.empty(new_shape, dtype=x.dtype)\n for i in range(x.shape[1]):\n tmp_max[:, 0] = np.max(x[:, i])\n tmp_out = np.exp(x - tmp_max)\n # tmp_sum = np.sum(tmp_out, axis=-1, keepdims=True)\n tmp_sum = np.reshape(np.sum(tmp_out, axis=-1), new_shape)\n return tmp_out / tmp_sum\n\n\n# 3-layer MLP\[email protected](nopython=True, parallel=False, fastmath=True)\ndef mlp(input, w1, b1, w2, b2, w3, b3):\n x = relu(input @ w1 + b1)\n x = relu(x @ w2 + b2)\n x = softmax(x @ w3 + b3) # Softmax call can be omitted if necessary\n return x\n",
"import numpy as np\nimport dace as dc\n\nM, N = (dc.symbol(s, dtype=dc.int64) for s in ('M', 'N'))\n\n\[email protected]\ndef kernel(A: dc.float64[N, N]):\n\n A[0, 0] = np.sqrt(A[0, 0])\n for i in range(1, N):\n for j in range(i):\n A[i, j] -= np.dot(A[i, :j], A[j, :j])\n A[i, j] /= A[j, j]\n A[i, i] -= np.dot(A[i, :i], A[i, :i])\n A[i, i] = np.sqrt(A[i, i])\n\n\n# def kernel2(A):\n# A[:] = np.linalg.cholesky(A) + np.triu(A, k=1)\n",
"# Copyright 2021 ETH Zurich and the NPBench authors. All rights reserved.\n\nimport numpy as np\n\n\ndef initialize(N, tEnd, dt):\n from numpy.random import default_rng\n rng = default_rng(42)\n mass = 20.0 * np.ones((N, 1)) / N # total mass of particles is 20\n pos = rng.random((N, 3)) # randomly selected positions and velocities\n vel = rng.random((N, 3))\n Nt = int(np.ceil(tEnd / dt))\n return mass, pos, vel, Nt\n"
] |
[
[
"numpy.fromfunction"
],
[
"numpy.outer"
],
[
"numpy.maximum",
"numpy.reshape",
"numpy.max",
"numpy.sum",
"numpy.empty"
],
[
"numpy.empty"
],
[
"numpy.minimum"
],
[
"numpy.maximum",
"numpy.max",
"numpy.exp",
"numpy.sum",
"numpy.empty"
],
[
"numpy.dot",
"numpy.sqrt"
],
[
"numpy.ceil",
"numpy.random.default_rng",
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
isabella232/dice_rl
|
[
"0e9e1a0963cb99ae3d995aa302fa19094c580d35"
] |
[
"estimators/neural_dual_dice.py"
] |
[
"# Copyright 2020 Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.policies import tf_policy\nfrom tf_agents.utils import common as tfagents_common\nfrom typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union\n\nimport dice_rl.data.dataset as dataset_lib\nimport dice_rl.utils.common as common_lib\nimport dice_rl.estimators.estimator as estimator_lib\n\n\nclass NeuralDualDice(object):\n \"\"\"Policy evaluation with DualDICE.\"\"\"\n\n def __init__(self, dataset_spec,\n nu_network,\n zeta_network,\n nu_optimizer,\n zeta_optimizer,\n gamma: Union[float, tf.Tensor],\n reward_fn: Optional[Callable] = None,\n solve_for_state_action_ratio: bool = True,\n f_exponent: float = 1.5,\n primal_form: bool = False,\n num_samples: Optional[int] = None,\n nu_regularizer: float = 0.,\n zeta_regularizer: float = 0.):\n \"\"\"Initializes the solver.\n\n Args:\n dataset_spec: The spec of the dataset that will be given.\n nu_network: The nu-value network.\n zeta_network: The zeta-value network.\n nu_optimizer: The optimizer to use for nu.\n zeta_optimizer: The optimizer to use for zeta.\n gamma: The discount factor to use.\n reward_fn: A function that takes in an EnvStep and returns the reward\n for that step. If not specified, defaults to just EnvStep.reward.\n solve_for_state_action_ratio: Whether to solve for state-action density\n ratio. Defaults to True.\n f_exponent: Exponent p to use for f(x) = |x|^p / p.\n primal_form: Whether to use primal form of DualDICE, which optimizes for\n nu independent of zeta. This form is biased in stochastic environments.\n Defaults to False, which uses the saddle-point formulation of DualDICE.\n num_samples: Number of samples to take from policy to estimate average\n next nu value. If actions are discrete, this defaults to computing\n average explicitly. If actions are not discrete, this defaults to using\n a single sample.\n nu_regularizer: Regularization coefficient on nu network.\n zeta_regularizer: Regularization coefficient on zeta network.\n \"\"\"\n self._dataset_spec = dataset_spec\n self._nu_network = nu_network\n self._nu_network.create_variables()\n self._zeta_network = zeta_network\n self._zeta_network.create_variables()\n\n self._nu_optimizer = nu_optimizer\n self._zeta_optimizer = zeta_optimizer\n self._nu_regularizer = nu_regularizer\n self._zeta_regularizer = zeta_regularizer\n\n self._gamma = gamma\n if reward_fn is None:\n reward_fn = lambda env_step: env_step.reward\n self._reward_fn = reward_fn\n self._num_samples = num_samples\n\n self._solve_for_state_action_ratio = solve_for_state_action_ratio\n if (not self._solve_for_state_action_ratio and\n not self._dataset_spec.has_log_probability()):\n raise ValueError('Dataset must contain log-probability when '\n 'solve_for_state_action_ratio is False.')\n\n if f_exponent <= 1:\n raise ValueError('Exponent for f must be greater than 1.')\n fstar_exponent = f_exponent / (f_exponent - 1)\n self._f_fn = lambda x: tf.abs(x) ** f_exponent / f_exponent\n self._fstar_fn = lambda x: tf.abs(x) ** fstar_exponent / fstar_exponent\n\n self._categorical_action = common_lib.is_categorical_spec(\n self._dataset_spec.action)\n if not self._categorical_action and self._num_samples is None:\n self._num_samples = 1\n\n self._primal_form = primal_form\n self._initialize()\n\n def _initialize(self):\n pass\n\n def _get_value(self, network, env_step):\n if self._solve_for_state_action_ratio:\n return network((env_step.observation, env_step.action))[0]\n else:\n return network(env_step.observation)[0]\n\n def _get_average_value(self, network, env_step, policy):\n if self._solve_for_state_action_ratio:\n tfagents_step = dataset_lib.convert_to_tfagents_timestep(env_step)\n if self._categorical_action and self._num_samples is None:\n action_weights = policy.distribution(\n tfagents_step).action.probs_parameter()\n action_dtype = self._dataset_spec.action.dtype\n batch_size = tf.shape(action_weights)[0]\n num_actions = tf.shape(action_weights)[-1]\n actions = ( # Broadcast actions\n tf.ones([batch_size, 1], dtype=action_dtype) *\n tf.range(num_actions, dtype=action_dtype)[None, :])\n else:\n batch_size = tf.shape(env_step.observation)[0]\n num_actions = self._num_samples\n action_weights = tf.ones([batch_size, num_actions]) / num_actions\n actions = tf.stack(\n [policy.action(tfagents_step).action\n for _ in range(num_actions)],\n axis=1)\n\n flat_actions = tf.reshape(actions, [batch_size * num_actions] +\n actions.shape[2:].as_list())\n flat_observations = tf.reshape(\n tf.tile(env_step.observation[:, None, ...],\n [1, num_actions] + [1] * len(env_step.observation.shape[1:])),\n [batch_size * num_actions] + env_step.observation.shape[1:].as_list())\n flat_values, _ = network((flat_observations, flat_actions))\n\n values = tf.reshape(flat_values, [batch_size, num_actions] +\n flat_values.shape[1:].as_list())\n return tf.reduce_sum(\n values * common_lib.reverse_broadcast(action_weights, values),\n axis=1)\n else:\n return network(env_step.observation)[0]\n\n def _orthogonal_regularization(self, network):\n reg = 0\n for layer in network.layers:\n if isinstance(layer, tf.keras.layers.Dense):\n prod = tf.matmul(tf.transpose(layer.kernel), layer.kernel)\n reg += tf.reduce_sum(\n tf.math.square(prod * (1 - tf.eye(prod.shape[0]))))\n return reg\n\n def train_loss(self, initial_env_step, env_step, next_env_step, policy):\n nu_values = self._get_value(self._nu_network, env_step)\n initial_nu_values = self._get_average_value(\n self._nu_network, initial_env_step, policy)\n next_nu_values = self._get_average_value(\n self._nu_network, next_env_step, policy)\n zeta_values = self._get_value(self._zeta_network, env_step)\n\n discounts = self._gamma * next_env_step.discount\n policy_ratio = 1.0\n if not self._solve_for_state_action_ratio:\n tfagents_step = dataset_lib.convert_to_tfagents_timestep(env_step)\n policy_log_probabilities = policy.distribution(\n tfagents_step).action.log_prob(env_step.action)\n policy_ratio = tf.exp(\n policy_log_probabilities - env_step.get_log_probability())\n\n bellman_residuals = (\n nu_values - common_lib.reverse_broadcast(\n discounts * policy_ratio, nu_values) * next_nu_values)\n\n zeta_loss = self._fstar_fn(zeta_values) - bellman_residuals * zeta_values\n if self._primal_form:\n nu_loss = (self._f_fn(bellman_residuals)\n - (1 - self._gamma) * initial_nu_values)\n else:\n nu_loss = -zeta_loss - (1 - self._gamma) * initial_nu_values\n\n return nu_loss, zeta_loss\n\n @tf.function\n def train_step(self,\n initial_env_step: dataset_lib.EnvStep,\n experience: dataset_lib.EnvStep,\n target_policy: tf_policy.TFPolicy):\n \"\"\"Performs a single training step based on batch.\n\n Args:\n initial_env_step: A batch of initial steps.\n experience: A batch of transitions. Elements must have shape\n [batch_size, 2, ...].\n target_policy: The policy whose value we want to estimate.\n\n Returns:\n The losses and the train op.\n \"\"\"\n env_step = tf.nest.map_structure(lambda t: t[:, 0, ...], experience)\n next_env_step = tf.nest.map_structure(lambda t: t[:, 1, ...], experience)\n\n with tf.GradientTape(watch_accessed_variables=False,\n persistent=True) as tape:\n tape.watch(self._nu_network.variables)\n tape.watch(self._zeta_network.variables)\n nu_loss, zeta_loss = self.train_loss(\n initial_env_step, env_step, next_env_step, target_policy)\n nu_loss += self._nu_regularizer * self._orthogonal_regularization(\n self._nu_network)\n zeta_loss += self._zeta_regularizer * self._orthogonal_regularization(\n self._zeta_network)\n\n nu_grads = tape.gradient(nu_loss, self._nu_network.variables)\n nu_grad_op = self._nu_optimizer.apply_gradients(\n zip(nu_grads, self._nu_network.variables))\n\n zeta_grads = tape.gradient(zeta_loss, self._zeta_network.variables)\n zeta_grad_op = self._zeta_optimizer.apply_gradients(\n zip(zeta_grads, self._zeta_network.variables))\n\n return (tf.reduce_mean(nu_loss), tf.reduce_mean(zeta_loss))\n\n def estimate_average_reward(self,\n dataset: dataset_lib.OffpolicyDataset,\n target_policy: tf_policy.TFPolicy):\n \"\"\"Estimates value (average per-step reward) of policy.\n\n Args:\n dataset: The dataset to sample experience from.\n target_policy: The policy whose value we want to estimate.\n\n Returns:\n Estimated average per-step reward of the target policy.\n \"\"\"\n def weight_fn(env_step):\n zeta = self._get_value(self._zeta_network, env_step)\n\n policy_ratio = 1.0\n if not self._solve_for_state_action_ratio:\n tfagents_timestep = dataset_lib.convert_to_tfagents_timestep(env_step)\n target_log_probabilities = target_policy.distribution(\n tfagents_timestep).action.log_prob(env_step.action)\n policy_ratio = tf.exp(\n target_log_probabilities -\n env_step.get_log_probability())\n\n return zeta * common_lib.reverse_broadcast(policy_ratio, zeta)\n\n return estimator_lib.get_fullbatch_average(\n dataset, limit=None, by_steps=True,\n reward_fn=self._reward_fn, weight_fn=weight_fn)\n"
] |
[
[
"tensorflow.compat.v2.nest.map_structure",
"tensorflow.compat.v2.transpose",
"tensorflow.compat.v2.GradientTape",
"tensorflow.compat.v2.reduce_mean",
"tensorflow.compat.v2.shape",
"tensorflow.compat.v2.range",
"tensorflow.compat.v2.ones",
"tensorflow.compat.v2.eye",
"tensorflow.compat.v2.abs"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Toroi0610/visualize_interactive
|
[
"8ddc8c248902ff59f1800d2418c697ffe1e5b472"
] |
[
"visualize.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport joblib\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, Button, RadioButtons\n\n\n# In[6]:\n\n\nwith open(\"model.pkl\", \"rb\") as f:\n model = joblib.load(f)\n\n\n# In[7]:\n\n\ndef pred(model, a, b, c, d):\n res = []\n for x in np.arange(-5.0, 5.0, 0.1):\n for y in np.arange(-5.0, 5.0, 0.1):\n res.append(model.predict([[x, y, a, b, c, d]]))\n return np.array(res).reshape([100, 100])\n\n\n# In[12]:\n\n\n\nfig, ax = plt.subplots(figsize=(12, 12))\nplt.subplots_adjust(left=0.25, bottom=0.35)\nx = np.arange(-5, 5, 0.1)\ny = np.arange(-5, 5, 0.1)\na = 0.2\nb = 0.2\nc = 0.2\nd = 0.2\n\ns = pred(model, a, b, c, d)\nim = plt.imshow(s)\nax.margins(x=0)\n\naxcolor = 'lightgoldenrodyellow'\naxa = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)\naxb = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)\naxc = plt.axes([0.25, 0.2, 0.65, 0.03], facecolor=axcolor)\naxd = plt.axes([0.25, 0.25, 0.65, 0.03], facecolor=axcolor)\n\nsa = Slider(axa, 'a', 0.0, 1.0, valinit=a)\nsb = Slider(axb, 'b', -1.0, 1.0, valinit=b)\nsc = Slider(axc, 'c', 0.0, 1.0, valinit=c)\nsd = Slider(axd, 'd', -1.0, 1.0, valinit=d)\n\n\ndef update(val):\n a = sa.val\n b = sb.val\n c = sc.val\n d = sd.val\n im.set_data(pred(model, a, b, c, d))\n fig.canvas.draw_idle()\n # amp = samp.val\n # freq = sfreq.val\n # l.set_ydata(amp*np.sin(2*np.pi*freq*t))\n # fig.canvas.draw_idle()\n\n\nsa.on_changed(update)\nsb.on_changed(update)\nsc.on_changed(update)\nsd.on_changed(update)\n\nresetax = plt.axes([0.8, 0.025, 0.1, 0.04])\nbutton = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')\n\n\ndef reset(event):\n sa.reset()\n sb.reset()\n sc.reset()\n sd.reset()\nbutton.on_clicked(reset)\n\n# rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)\n# radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)\n\n\n# def colorfunc(label):\n# im.set_color(label)\n# fig.canvas.draw_idle()\n# radio.on_clicked(colorfunc)\n\n# Initialize plot with correct initial active value\n# colorfunc(radio.value_selected)\n\nplt.show()\n\n\n# In[10]:\n\n\ns = pred(model, 0.1, 0.1, 0, 0)\n\n\n# In[11]:\n\n\nplt.imshow(s)\n\n\n# In[ ]:\n\n\n\n\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.widgets.Button",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.axes",
"matplotlib.widgets.Slider",
"matplotlib.pyplot.subplots_adjust",
"numpy.array",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bobeobibo/phigaro
|
[
"342a3454bb5324426b25feb4a4d1f640b58bf8f8"
] |
[
"phigaro/misc/vis.py"
] |
[
"import numpy as np\nfrom plotly import tools\nfrom plotly.graph_objs import Bar\nimport plotly.offline as py\n\nfrom phigaro.finder.v2 import calc_scores\n\n\ndef _make_coords_colors(data_len, real_phage_coords):\n colors = np.zeros(data_len)\n for begin, end in real_phage_coords:\n for i in range(begin, end + 1):\n colors[i] = 1\n return colors\n\n\ndef plot_scores(scores, title, real_phage_coords=None):\n indices = np.arange(len(scores))\n\n colors = None\n if real_phage_coords is not None:\n colors = _make_coords_colors(len(scores), real_phage_coords)\n data = Bar(\n x=indices, y=scores + 0.1, name=title, marker=dict(color=colors,)\n )\n\n return data\n\n\ndef plot_phage(phage, title):\n ind = np.arange(len(phage))\n int_phage = [c + 0.1 for c in phage]\n data = Bar(x=ind, y=int_phage, marker=dict(color='black',), name=title)\n return data\n\n\ndef _make_rects(coords, ymin, ymax, fillcolor, opacity):\n return [\n dict(\n type='rect',\n xref='x',\n yref='y',\n x0=x_begin,\n y0=ymin,\n x1=x_end,\n y1=ymax,\n fillcolor=fillcolor,\n opacity=opacity,\n line={'width': 0},\n )\n for (x_begin, x_end) in coords\n ]\n\n\ndef plot_scores_and_phage(\n phage, window_len, score_func=None, scan_func=None, real_phage_coords=None\n):\n score_func = score_func or score_tri\n fig = tools.make_subplots(rows=2, cols=1, shared_xaxes=True)\n title = 'Scores: window: {}'.format(window_len)\n scores = np.array(calc_scores(phage, window_len, score_func))\n\n ranges = []\n if scan_func is not None:\n ranges = scan_func(scores)\n\n score_fig = plot_scores(scores, title, real_phage_coords=None)\n phage_fig = plot_phage(phage, 'Phage')\n\n fig.append_trace(score_fig, 1, 1)\n fig.append_trace(phage_fig, 2, 1)\n\n ymax = window_len / 2\n if real_phage_coords is not None or ranges:\n fig['layout'].update(\n dict(\n shapes=_make_rects(ranges, ymax, 'rgb(50, 171, 96)', 0.5)\n + _make_rects(real_phage_coords or [], ymax, '#ff0000', 0.5)\n )\n )\n\n py.iplot(fig)\n\n\ndef plot_scores_and_phage2(\n phage,\n scores,\n found_phage_coords,\n real_phage_coords=None,\n filename='filename',\n):\n # real_phage_coords = real_phage_coords or []\n fig = tools.make_subplots(rows=2, cols=1, shared_xaxes=True)\n title = 'Scores'\n\n score_fig = plot_scores(scores, title, real_phage_coords=None)\n phage_fig = plot_phage(phage, 'Phage')\n\n fig.append_trace(score_fig, 1, 1)\n fig.append_trace(phage_fig, 2, 1)\n\n ymax = max(scores)\n # print(len(real_phage_coords), len(found_phage_coords))\n if (len(real_phage_coords) + len(found_phage_coords)) != 0:\n # print('got real coords')\n fig['layout'].update(\n dict(\n shapes=_make_rects(\n found_phage_coords, ymax * 0.5, ymax * 0.75, '#0000ff', 0.5\n )\n + _make_rects(\n real_phage_coords, ymax * 0.75, ymax, '#aaaa00', 0.5\n )\n )\n )\n\n py.plot(fig, filename=filename + '.html')\n"
] |
[
[
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jiaruonan/transferlearning
|
[
"17583db86db19709ff483a24590f0d5b88e25fe5",
"0360ba0b09df6c1033d466ddc65f0c870187331e",
"0360ba0b09df6c1033d466ddc65f0c870187331e"
] |
[
"code/deep/adarnn/base/loss/mutual_info.py",
"code/distance/coral_pytorch.py",
"code/deep/CSG/a-mnist/makedata.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Mine_estimator(nn.Module):\n def __init__(self, input_dim=2048, hidden_dim=512):\n super(Mine_estimator, self).__init__()\n self.mine_model = Mine(input_dim, hidden_dim)\n\n def forward(self, X, Y):\n Y_shffle = Y[torch.randperm(len(Y))]\n loss_joint = self.mine_model(X, Y)\n loss_marginal = self.mine_model(X, Y_shffle)\n ret = torch.mean(loss_joint) - \\\n torch.log(torch.mean(torch.exp(loss_marginal)))\n loss = -ret\n return loss\n\n\nclass Mine(nn.Module):\n def __init__(self, input_dim=2048, hidden_dim=512):\n super(Mine, self).__init__()\n self.fc1_x = nn.Linear(input_dim, hidden_dim)\n self.fc1_y = nn.Linear(input_dim, hidden_dim)\n self.fc2 = nn.Linear(hidden_dim, 1)\n\n def forward(self, x, y):\n h1 = F.leaky_relu(self.fc1_x(x)+self.fc1_y(y))\n h2 = self.fc2(h1)\n return h2",
"# Compute CORAL loss using pytorch\n# Reference: DCORAL: Correlation Alignment for Deep Domain Adaptation, ECCV-16.\n\nimport torch\n\ndef CORAL_loss(source, target):\n d = source.data.shape[1]\n ns, nt = source.data.shape[0], target.data.shape[0]\n # source covariance\n xm = torch.mean(source, 0, keepdim=True) - source\n xc = xm.t() @ xm / (ns - 1)\n\n # target covariance\n xmt = torch.mean(target, 0, keepdim=True) - target\n xct = xmt.t() @ xmt / (nt - 1)\n\n # frobenius norm between source and target\n loss = torch.mul((xc - xct), (xc - xct))\n loss = torch.sum(loss) / (4*d*d)\n return loss\n\n# Another implementation:\n# Two implementations are the same. Just different formulation format.\n# def CORAL(source, target):\n# d = source.size(1)\n# ns, nt = source.size(0), target.size(0)\n# # source covariance\n# tmp_s = torch.ones((1, ns)).to(DEVICE) @ source\n# cs = (source.t() @ source - (tmp_s.t() @ tmp_s) / ns) / (ns - 1)\n\n# # target covariance\n# tmp_t = torch.ones((1, nt)).to(DEVICE) @ target\n# ct = (target.t() @ target - (tmp_t.t() @ tmp_t) / nt) / (nt - 1)\n\n# # frobenius norm\n# loss = torch.norm(cs - ct, p='fro').pow(2)\n# loss = loss / (4 * d * d)\n# return loss",
"#!/usr/bin/env python3.6\n'''For generating MNIST-01 and its shifted interventional datasets.\n'''\nimport torch as tc\nimport torchvision as tv\nimport torchvision.transforms.functional as tvtf\nimport argparse\n\n__author__ = \"Chang Liu\"\n__email__ = \"[email protected]\"\n\ndef select_xy(dataset, selected_y = (0,1), piltransf = None, ytransf = None):\n dataset_selected = [(\n tvtf.to_tensor( img if piltransf is None else piltransf(img, label) ),\n label if ytransf is None else ytransf(label)\n ) for img, label in dataset if label in selected_y]\n xs, ys = tuple(zip(*dataset_selected))\n return tc.cat(xs, dim=0), tc.tensor(ys)\n\ndef get_shift_transf(pleft: list, distr: str, loc: float, scale: float):\n return lambda img, label: tvtf.affine(img, angle=0, translate=(\n scale * getattr(tc, distr)(()) + loc * (1. - 2. * tc.bernoulli(tc.tensor(pleft[label]))), 0.\n ), scale=1., shear=0, fillcolor=0)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"mode\", type = str, choices = {\"train\", \"test\"})\n parser.add_argument(\"--pleft\", type = float, nargs = '+', default = [0.5, 0.5])\n parser.add_argument(\"--distr\", type = str, choices = {\"randn\", \"rand\"})\n parser.add_argument(\"--loc\", type = float, default = 4.)\n parser.add_argument(\"--scale\", type = float, default = 1.)\n parser.add_argument(\"--procroot\", type = str, default = \"./data/MNIST/processed/\")\n ag = parser.parse_args()\n\n dataset = tv.datasets.MNIST(root=\"./data\", train = ag.mode==\"train\", download=True) # as PIL\n piltransf = get_shift_transf(ag.pleft, ag.distr, ag.loc, ag.scale)\n selected_y = tuple(range(len(ag.pleft)))\n shift_x, shift_y = select_xy(dataset, selected_y, piltransf)\n filename = ag.procroot + ag.mode + \"\".join(str(y) for y in selected_y) + (\n \"_\" + \"_\".join(f\"{p:.1f}\" for p in ag.pleft) +\n \"_\" + ag.distr + f\"_{ag.loc:.1f}_{ag.scale:.1f}.pt\" )\n tc.save((shift_x, shift_y), filename)\n print(\"Processed data saved to '\" + filename + \"'\")\n\n"
] |
[
[
"torch.exp",
"torch.nn.Linear",
"torch.mean"
],
[
"torch.mean",
"torch.mul",
"torch.sum"
],
[
"torch.tensor",
"torch.cat",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
taimur1871/plotly_examples
|
[
"04cccbc1c60963c4a6b5405614d9136de93846f6"
] |
[
"charts/random_coord.py"
] |
[
"import numpy as np\nimport pandas as pd\n\n# set coordinate range\nmax_lat = 41.986046\nmin_lat = 41.056583\nmax_long = -89.766294\nmin_long = -92.238217\n\n# random data\nfake_data = []\n\nfor i in range(10):\n rand_lat = np.random.uniform(min_lat, max_lat)\n rand_long = np.random.uniform(min_long, max_long)\n rand_dist = np.random.uniform(2500.00, 5500.00)\n well_name = 'well' + str(i)\n fake_data.append((well_name, rand_long, rand_lat, rand_dist))\n\ndf = pd.DataFrame(fake_data)\ndf.rename({0:'Well', 1:'Longitude', 2:'Latitude', 3:'Distance'}, axis=1, inplace=True)"
] |
[
[
"numpy.random.uniform",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
annelhote/fonduer
|
[
"bd5b1feebfb2860286ae8b5a520b24baa023b445"
] |
[
"tests/utils/test_utils_udf.py"
] |
[
"\"\"\"Fonduer UDF utils' unit tests.\"\"\"\nimport logging\n\nimport numpy as np\n\nfrom fonduer.utils.utils_udf import shift_label_matrix, unshift_label_matrix\n\n\ndef test_shift_label_matrix(caplog):\n \"\"\"Test the label matrix shifter and unshifter.\"\"\"\n caplog.set_level(logging.INFO)\n\n \"\"\"\n L is a dense label matrix (ABSTAIN as -1) with values:\n -1 0\n 1 -1\n \"\"\"\n L = np.array([[-1, 0], [1, -1]])\n \"\"\"\n L_sparse is a sparse label matrix (ABSTAIN as 0)\n 0 1\n 2 0\n \"\"\"\n L_sparse = shift_label_matrix(L)\n assert np.array_equal(L, unshift_label_matrix(L_sparse))\n assert L_sparse.count_nonzero() == 2\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
franciszhangkk/Cloud_computing
|
[
"e53e91199119ea72a434d7b7b424f9029a11451c"
] |
[
"Assignment2_spark_ML/CC_A2_code/cc_a2/matrix.py"
] |
[
"import seaborn as sn\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport math\n\n\n# def show_confusion_matrix(confusion, xlabels, ylabels):\n# plt.figure(figsize=(14, 11))\n# df_cm = pd.DataFrame(confusion, range(10), range(10))\n# df_cm.astype(int)\n#\n# sn.heatmap(df_cm, annot=True, xticklabels=xlabels, yticklabels=ylabels, vmin=0, vmax=8000, cmap=sn.cm.rocket_r,\n# fmt='.5g')\n# plt.show()\n# print('Fig. 3 Confusion Matrix of the test-data(X_axis is the predicted labels & Y_axis is the actual labels)')\n# return\n\nmatrix = []\nwith open('/Users/zekunzhang/Desktop/ML_A2/matrix/Confusion_MLP.csv') as training_label0:\n spamreader_label = csv.reader(training_label0, quotechar=',')\n for row in spamreader_label:\n arr=[]\n for k in row:\n arr.append(int(math.floor(float(k))))\n matrix.append(arr)\n\n\n\ndef statistic(confusion_test):\n re_list = []\n label = np.arange(0, 10)\n for i in label:\n TP = confusion_test[i, i]\n FN = np.sum(confusion_test[i]) - TP\n FP = np.sum(confusion_test[:, i]) - TP\n TN = np.sum(confusion_test) - TP - FN - FP\n precision = (TP / (TP + FP))\n recall = TP / (TP + FN)\n F_measure = TP / (2 * TP + FP + FN)\n Support = (TP + FN)\n row = [int(label[i]), round(float(precision), 3), round(float(recall), 3), round(float(F_measure), 3),\n round(float(Support), 0)]\n re_list.append(row)\n return re_list\n\n\nstatistic_list = statistic(matrix)\n\n"
] |
[
[
"numpy.arange",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
giorgiosavastano/casa
|
[
"8ecfdb121ec5b6814a5c15bc75d6879848c99ec9"
] |
[
"tests/test_classification_pipeline.py"
] |
[
"from pathlib import Path\nfrom unittest import TestCase\n\nimport numpy as np\nimport pytest\n\nfrom cassa.classification_pipeline import (\n eigen_decomposition,\n get_affinity_matrix,\n get_clusters_spectral,\n)\nfrom cassa.distance_matrix import DistanceMatrix\n\npath = Path(__file__)\n\n\nclass TestDistMatrix(TestCase):\n def setUp(self):\n pass\n\n @pytest.mark.unit\n def test_distance_matrix(self):\n matrix_arrays = np.random.random((100, 10, 50))\n dmatrix = DistanceMatrix(matrix_arrays)\n dist_matr = dmatrix.compute_distance_matrix(parallel=True)\n self.assertEqual(matrix_arrays.shape[0], dist_matr.shape[0])\n\n aff_matrix = get_affinity_matrix(dist_matr)\n self.assertEqual(aff_matrix.shape, dist_matr.shape)\n\n n_cl = eigen_decomposition(aff_matrix)[0]\n self.assertGreater(n_cl, 0)\n\n l_labels, cl_colors, clusterer = get_clusters_spectral(\n dist_matr, ncl=n_cl, self_tuned=True\n )\n self.assertEqual(len(l_labels), len(cl_colors))\n\n @pytest.mark.unit\n def test_distance_matrix_parallel(self):\n matrix_arrays = np.random.random((100, 10, 50))\n dmatrix = DistanceMatrix(matrix_arrays)\n\n dist_matr_1 = dmatrix.compute_distance_matrix(parallel=True)\n dist_matr_2 = dmatrix.compute_distance_matrix(parallel=False)\n\n self.assertTrue((dist_matr_1 == dist_matr_2).all())\n\n @pytest.mark.unit\n def test_classify_new_data(self):\n matrix_arrays = np.random.random((1000, 10, 50))\n new_data = matrix_arrays[269]\n\n dmatrix = DistanceMatrix(matrix_arrays)\n dmatrix.k_step_new_data = int(matrix_arrays.shape[0] / 5)\n indexes_arr, dists_arr = dmatrix.classify_new_data(new_data=new_data)\n\n self.assertEqual(indexes_arr[0], 269)\n self.assertEqual(np.argmin(dists_arr), indexes_arr[0])\n self.assertEqual(len(dists_arr[dists_arr == 0]), 1)\n\n def tearDown(self):\n pass\n"
] |
[
[
"numpy.random.random",
"numpy.argmin"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mostafamahdieh/ClusteringFaultPronenessTCP
|
[
"567184740d24f464cde7d623f84ec3a6d989d401"
] |
[
"results/aggregate_results.py"
] |
[
"import pandas as pd\r\nfrom pandas import Categorical\r\nimport numpy as np\r\nfrom numpy import std, mean, sqrt\r\nimport os\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport scipy.stats as stats\r\nimport itertools as it\r\n\r\n\r\ndef effect_size(lst1, lst2):\r\n return improvement(lst1, lst2)\r\n\r\n\r\ndef improvement(x, y):\r\n n = len(x)\r\n a = 0\r\n for i in range(0, n):\r\n# print(\"x\",x[i],\"y\",y[i],\"x-y\",x[i]-y[i])\r\n a = a + (x[i] - y[i])\r\n improvement = (a/n)\r\n return improvement\r\n\r\n\r\ndef read_results(file_names, project, from_version, to_version):\r\n first_fail = pd.DataFrame(columns=['version'])\r\n apfd = pd.DataFrame(columns=['version'])\r\n\r\n for version_number in range(from_version, to_version):\r\n data_path = \"../../WTP-data/%s/%d\" % (project, version_number)\r\n results_dict_first_fail = {'version': version_number}\r\n results_dict_apfd = {'version': version_number}\r\n skipped = False\r\n\r\n for file_name in file_names:\r\n file_path = '%s/%s' % (data_path, file_name)\r\n\r\n if os.path.isfile(file_path):\r\n print(\"Reading %s\" % file_path)\r\n results = pd.read_csv(file_path, delimiter=',')\r\n\r\n for i, row in results.iterrows():\r\n results_dict_first_fail[row['alg']] = row['first_fail'] * 100\r\n results_dict_apfd[row['alg']] = row['apfd']\r\n else:\r\n print(\"Skipping %s\" % file_path)\r\n skipped = True\r\n\r\n if not skipped:\r\n first_fail = first_fail.append(results_dict_first_fail, ignore_index=True)\r\n apfd = apfd.append(results_dict_apfd, ignore_index=True)\r\n\r\n return first_fail, apfd\r\n\r\n\r\ndef main():\r\n# projects = ['Chart', 'Closure', 'Lang', 'Math', 'Time']\r\n# from_version = [1, 1, 1, 1, 1]\r\n# to_version = [26, 119, 65, 106, 26]\r\n projects = ['Chart', 'Closure', 'Lang', 'Math', 'Time']\r\n from_version = [1, 1, 1, 1, 1]\r\n to_version = [13, 50, 33, 50, 14]\r\n\r\n results_path = '../../WTP-data/aggregate/first_fail/a11'\r\n try:\r\n os.stat(results_path)\r\n except:\r\n os.mkdir(results_path) \r\n\r\n matplotlib.rcParams.update({'font.size': 14})\r\n pd.set_option('display.max_columns', 1000)\r\n\r\n data_vals_stats = pd.DataFrame()\r\n improvement_stats = pd.DataFrame(columns=[\"project\", \"improvement_clustering\", \"improvement_clustering_fp\"])\r\n first_fail_all = pd.DataFrame()\r\n\r\n for index, project in enumerate(projects):\r\n first_fail, apfd = read_results(['std2.csv', 'agg11_4.csv', 'std2_c95.csv', 'agg11_c95.csv'],\r\n project, from_version[index], to_version[index] + 1)\r\n\r\n plt.close('all')\r\n\r\n # 'fp2_1__1_aa': 'fp_0_aa' --> c_dp1=1.0, c_dp2=0\r\n\r\n# first_fail = first_fail.rename(columns={\"a12_3_c0_200_tt\":\"Clustering\",\"a12_3_c0999_200_tt\":\"Clustering+FP\",\r\n# \"add_c0\":\"Additional\",\"tot_c0\":\"Total\",\r\n# \"add_c0999\":'Additional+FP', \"tot_c0999\":\"Total+FP\"})\r\n\r\n first_fail = first_fail.rename(columns={\"a11_4_c0_at\": \"Clustering\", \"a11_c95_at\": \"Clustering+FP\",\r\n \"add_c0\":\"Additional\",\"tot_c0\":\"Total\",\r\n \"add_c95\":'Additional+FP', \"tot_c95\":\"Total+FP\"})\r\n# print(first_fail)\r\n# print(apfd)\r\n\r\n improvement_clustering = improvement(first_fail[['Additional', 'Total']].min(axis=1), first_fail[\"Clustering\"])\r\n improvement_clustering_fp = improvement(first_fail[['Additional+FP', 'Total+FP']].min(axis=1), first_fail[\"Clustering+FP\"])\r\n print(\"improvement_clustering\", improvement_clustering)\r\n print(\"improvement_clustering_fp\", improvement_clustering_fp)\r\n improvement_stats.add([project, improvement_clustering, improvement_clustering_fp])\r\n\r\n if index == 0:\r\n first_fail_all = first_fail\r\n else:\r\n first_fail_all = first_fail_all.append(first_fail)\r\n first_fail_mean = first_fail.mean()\r\n first_fail_mean = first_fail_mean.drop('version')\r\n\r\n data_vals_stats = data_vals_stats.append(first_fail_mean, ignore_index=True)\r\n\r\n columns = ['Total', 'Additional', 'Clustering', 'Total+FP', 'Additional+FP', 'Clustering+FP']\r\n\r\n plot1 = first_fail.boxplot(column=columns)\r\n plot1.set_ylabel('First Fail (%)')\r\n plot1.set_ylim(0, 100)\r\n\r\n #plot1.set_title(project)\r\n\r\n fig1 = plot1.get_figure()\r\n fig1.autofmt_xdate(rotation=32)\r\n #fig1.savefig('%s/first_fail/%s.first_fail.boxplot.png' % (results_path, project), bbox_inches='tight')\r\n fig1.savefig('%s/%s.first_fail.boxplot.png' % (results_path, project))\r\n\r\n plt.close('all')\r\n\r\n first_fail_all = first_fail_all.reset_index()\r\n print(first_fail_all)\r\n print(\"first_fail_total\", stats.wilcoxon(first_fail_all[\"Total\"],first_fail_all[\"Clustering\"]))\r\n print(\"first_fail_additional\", stats.wilcoxon(first_fail_all[\"Additional\"],first_fail_all[\"Clustering\"]))\r\n print(\"first_fail_tolal+fp\", stats.wilcoxon(first_fail_all[\"Total+FP\"],first_fail_all[\"Clustering+FP\"]))\r\n print(\"first_fail_additional+fp\", stats.wilcoxon(first_fail_all[\"Additional+FP\"],first_fail_all[\"Clustering+FP\"]))\r\n\r\n data_vals_stats.insert(0, 'project', projects)\r\n data_vals_stats.to_csv(results_path+'/stats.csv')\r\n\r\nmain()\r\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame",
"scipy.stats.wilcoxon",
"matplotlib.rcParams.update",
"matplotlib.pyplot.close",
"pandas.set_option"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
cambel/rlpyt
|
[
"96e231d6c77ba5ff06dd09f6e9c8837f0abb1a89",
"96e231d6c77ba5ff06dd09f6e9c8837f0abb1a89"
] |
[
"rlpyt/utils/tensor.py",
"rlpyt/algos/qpg/ddpg.py"
] |
[
"\nimport torch\n\n\ndef select_at_indexes(indexes, tensor):\n \"\"\"Leading dimensions of tensor must match dimensions of indexes.\"\"\"\n dim = len(indexes.shape)\n assert indexes.shape == tensor.shape[:dim]\n num = indexes.numel()\n t_flat = tensor.view((num,) + tensor.shape[dim:])\n s_flat = t_flat[torch.arange(num), indexes.view(-1)]\n return s_flat.view(tensor.shape[:dim] + tensor.shape[dim + 1:])\n\n\ndef to_onehot(indexes, num, dtype=None):\n \"\"\"Dimension of size num added to the end of indexes.shape.\"\"\"\n if dtype is None:\n dtype = indexes.dtype\n onehot = torch.zeros(indexes.shape + (num,),\n dtype=dtype, device=indexes.device)\n onehot.scatter_(-1, indexes.unsqueeze(-1).type(torch.long), 1)\n return onehot\n\n\ndef from_onehot(onehot, dim=-1, dtype=None):\n \"\"\"Selected dimension of onehot is removed by argmax.\"\"\"\n indexes = torch.argmax(onehot, dim=dim)\n if dtype is not None:\n indexes = indexes.type(dtype)\n return indexes\n\n\ndef valid_mean(tensor, valid=None, dim=None):\n dim = () if dim is None else dim\n if valid is None:\n return tensor.mean(dim=dim)\n valid = valid.type(tensor.dtype) # Convert as needed.\n return (tensor * valid).sum(dim=dim) / valid.sum(dim=dim)\n\n\ndef infer_leading_dims(tensor, dim):\n \"\"\"Param 'dim': number of non-leading dimensions in tensor.\n Returns:\n lead_dim: int --number of leading dims found.\n T: int --size of first leading dim, if two leading dims, o/w 1.\n B: int --size of first leading dim if one, second leading dim if two, o/w 1.\n shape: tensor shape after leading dims.\n \"\"\"\n lead_dim = tensor.dim() - dim\n assert lead_dim in (0, 1, 2)\n if lead_dim == 2:\n T, B = tensor.shape[:2]\n else:\n T = 1\n B = 1 if lead_dim == 0 else tensor.shape[0]\n shape = tensor.shape[-dim:]\n return lead_dim, T, B, shape\n\n\ndef restore_leading_dims(tensors, lead_dim, T=1, B=1):\n \"\"\"Assume tensors have leading Batch dimension (might need removed).\"\"\"\n is_seq = isinstance(tensors, (tuple, list))\n tensors = tensors if is_seq else (tensors,)\n if lead_dim == 2: # (Put T dim.)\n tensors = tuple(t.view((T, B) + t.shape[1:]) for t in tensors)\n if lead_dim == 0: # (Remove B=1 dim.)\n assert B == 1\n tensors = tuple(t.squeeze(0) for t in tensors)\n return tensors if is_seq else tensors[0]\n",
"\nimport torch\nfrom collections import namedtuple\n\nfrom rlpyt.algos.base import RlAlgorithm\nfrom rlpyt.utils.quick_args import save__init__args\nfrom rlpyt.utils.logging import logger\nfrom rlpyt.replays.non_sequence.uniform import (UniformReplayBuffer,\n AsyncUniformReplayBuffer)\nfrom rlpyt.replays.non_sequence.time_limit import (TlUniformReplayBuffer,\n AsyncTlUniformReplayBuffer)\nfrom rlpyt.utils.collections import namedarraytuple\nfrom rlpyt.utils.tensor import valid_mean\nfrom rlpyt.algos.utils import valid_from_done\n\nOptInfo = namedtuple(\"OptInfo\",\n [\"muLoss\", \"qLoss\", \"muGradNorm\", \"qGradNorm\"])\nSamplesToBuffer = namedarraytuple(\"SamplesToBuffer\",\n [\"observation\", \"action\", \"reward\", \"done\", \"timeout\"])\n\n\nclass DDPG(RlAlgorithm):\n\n opt_info_fields = tuple(f for f in OptInfo._fields) # copy\n\n def __init__(\n self,\n discount=0.99,\n batch_size=64,\n min_steps_learn=int(1e4),\n replay_size=int(1e6),\n replay_ratio=64, # data_consumption / data_generation\n target_update_tau=0.01,\n target_update_interval=1,\n policy_update_interval=1,\n learning_rate=1e-4,\n q_learning_rate=1e-3,\n OptimCls=torch.optim.Adam,\n optim_kwargs=None,\n initial_optim_state_dict=None,\n clip_grad_norm=1e8,\n q_target_clip=1e6,\n n_step_return=1,\n updates_per_sync=1, # For async mode only.\n bootstrap_timelimit=True,\n ):\n if optim_kwargs is None:\n optim_kwargs = dict()\n self._batch_size = batch_size\n del batch_size # Property.\n save__init__args(locals())\n\n def initialize(self, agent, n_itr, batch_spec, mid_batch_reset, examples,\n world_size=1, rank=0):\n \"\"\"Used in basic or synchronous multi-GPU runners, not async.\"\"\"\n self.agent = agent\n self.n_itr = n_itr\n self.mid_batch_reset = mid_batch_reset\n self.sampler_bs = sampler_bs = batch_spec.size\n self.updates_per_optimize = max(1, round(self.replay_ratio * sampler_bs /\n self.batch_size))\n logger.log(f\"From sampler batch size {sampler_bs}, training \"\n f\"batch size {self.batch_size}, and replay ratio \"\n f\"{self.replay_ratio}, computed {self.updates_per_optimize} \"\n f\"updates per iteration.\")\n self.min_itr_learn = int(self.min_steps_learn // sampler_bs)\n # Agent give min itr learn.?\n self.initialize_replay_buffer(examples, batch_spec)\n self.optim_initialize(rank)\n\n def async_initialize(self, agent, sampler_n_itr, batch_spec, mid_batch_reset,\n examples, world_size=1):\n \"\"\"Used in async runner only.\"\"\"\n self.agent = agent\n self.n_itr = sampler_n_itr\n self.initialize_replay_buffer(examples, batch_spec, async_=True)\n self.mid_batch_reset = mid_batch_reset\n self.sampler_bs = sampler_bs = batch_spec.size\n self.updates_per_optimize = self.updates_per_sync\n self.min_itr_learn = int(self.min_steps_learn // sampler_bs)\n return self.replay_buffer\n\n def optim_initialize(self, rank=0):\n \"\"\"Called by async runner.\"\"\"\n self.rank = rank\n self.mu_optimizer = self.OptimCls(self.agent.mu_parameters(),\n lr=self.learning_rate, **self.optim_kwargs)\n self.q_optimizer = self.OptimCls(self.agent.q_parameters(),\n lr=self.q_learning_rate, **self.optim_kwargs)\n if self.initial_optim_state_dict is not None:\n self.q_optimizer.load_state_dict(self.initial_optim_state_dict[\"q\"])\n self.mu_optimizer.load_state_dict(self.initial_optim_state_dict[\"mu\"])\n\n def initialize_replay_buffer(self, examples, batch_spec, async_=False):\n example_to_buffer = SamplesToBuffer(\n observation=examples[\"observation\"],\n action=examples[\"action\"],\n reward=examples[\"reward\"],\n done=examples[\"done\"],\n timeout=getattr(examples[\"env_info\"], \"timeout\", None)\n )\n replay_kwargs = dict(\n example=example_to_buffer,\n size=self.replay_size,\n B=batch_spec.B,\n n_step_return=self.n_step_return,\n )\n if not self.bootstrap_timelimit:\n ReplayCls = AsyncUniformReplayBuffer if async_ else UniformReplayBuffer\n else:\n ReplayCls = AsyncTlUniformReplayBuffer if async_ else TlUniformReplayBuffer\n self.replay_buffer = ReplayCls(**replay_kwargs)\n\n def optimize_agent(self, itr, samples=None, sampler_itr=None):\n itr = itr if sampler_itr is None else sampler_itr # Async uses sampler_itr.\n if samples is not None:\n samples_to_buffer = self.samples_to_buffer(samples)\n self.replay_buffer.append_samples(samples_to_buffer)\n opt_info = OptInfo(*([] for _ in range(len(OptInfo._fields))))\n if itr < self.min_itr_learn:\n return opt_info\n for _ in range(self.updates_per_optimize):\n samples_from_replay = self.replay_buffer.sample_batch(self.batch_size)\n if self.mid_batch_reset and not self.agent.recurrent:\n valid = torch.ones_like(samples_from_replay.done, dtype=torch.float)\n else:\n valid = valid_from_done(samples_from_replay.done)\n if self.bootstrap_timelimit:\n # To avoid non-use of bootstrap when environment is 'done' due to\n # time-limit, turn off training on these samples.\n valid *= (1 - samples_from_replay.timeout_n.float())\n self.q_optimizer.zero_grad()\n q_loss = self.q_loss(samples_from_replay, valid)\n q_loss.backward()\n q_grad_norm = torch.nn.utils.clip_grad_norm_(\n self.agent.q_parameters(), self.clip_grad_norm)\n self.q_optimizer.step()\n opt_info.qLoss.append(q_loss.item())\n opt_info.qGradNorm.append(q_grad_norm)\n self.update_counter += 1\n if self.update_counter % self.policy_update_interval == 0:\n self.mu_optimizer.zero_grad()\n mu_loss = self.mu_loss(samples_from_replay, valid)\n mu_loss.backward()\n mu_grad_norm = torch.nn.utils.clip_grad_norm_(\n self.agent.mu_parameters(), self.clip_grad_norm)\n self.mu_optimizer.step()\n opt_info.muLoss.append(mu_loss.item())\n opt_info.muGradNorm.append(mu_grad_norm)\n if self.update_counter % self.target_update_interval == 0:\n self.agent.update_target(self.target_update_tau)\n return opt_info\n\n def samples_to_buffer(self, samples):\n return SamplesToBuffer(\n observation=samples.env.observation,\n action=samples.agent.action,\n reward=samples.env.reward,\n done=samples.env.done,\n timeout=getattr(samples.env.env_info, \"timeout\", None)\n )\n\n def mu_loss(self, samples, valid):\n mu_losses = self.agent.q_at_mu(*samples.agent_inputs)\n mu_loss = valid_mean(mu_losses, valid) # valid can be None.\n return -mu_loss\n\n def q_loss(self, samples, valid):\n \"\"\"Samples have leading batch dimension [B,..] (but not time).\"\"\"\n q = self.agent.q(*samples.agent_inputs, samples.action)\n with torch.no_grad():\n target_q = self.agent.target_q_at_mu(*samples.target_inputs)\n disc = self.discount ** self.n_step_return\n y = samples.return_ + (1 - samples.done_n.float()) * disc * target_q\n y = torch.clamp(y, -self.q_target_clip, self.q_target_clip)\n q_losses = 0.5 * (y - q) ** 2\n q_loss = valid_mean(q_losses, valid) # valid can be None.\n return q_loss\n\n def optim_state_dict(self):\n return dict(q=self.q_optimizer.state_dict(),\n mu=self.mu_optimizer.state_dict())\n\n def load_optim_state_dict(self, state_dict):\n self.q_optimizer.load_state_dict(state_dict[\"q\"])\n self.mu_optimizer.load_state_dict(state_dict[\"mu\"])\n"
] |
[
[
"torch.argmax",
"torch.arange",
"torch.zeros"
],
[
"torch.clamp",
"torch.no_grad",
"torch.ones_like"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DanielMabadeje/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
|
[
"6988f1f3ccfa4f6794ce269f056422da4ce9baf6",
"6017441f2d476f9c6c568dd886da43c6c0fd89bd",
"6017441f2d476f9c6c568dd886da43c6c0fd89bd",
"6988f1f3ccfa4f6794ce269f056422da4ce9baf6",
"6017441f2d476f9c6c568dd886da43c6c0fd89bd"
] |
[
"deep-learning/GANs and Variational Autoencoders/BigGAN-PyTorch/train.py",
"sympy/register.py",
"quantum gravity/Getting Started/readligo.py",
"deep-learning/GANs and Variational Autoencoders/BigGAN-PyTorch/sample.py",
"deep-learning/CapsNET/TensorFlow_Implementation/capsNet.py"
] |
[
"\"\"\" BigGAN: The Authorized Unofficial PyTorch release\n Code by A. Brock and A. Andonian\n This code is an unofficial reimplementation of\n \"Large-Scale GAN Training for High Fidelity Natural Image Synthesis,\"\n by A. Brock, J. Donahue, and K. Simonyan (arXiv 1809.11096).\n\n Let's go.\n\"\"\"\n\nimport os\nimport functools\nimport math\nimport numpy as np\nfrom tqdm import tqdm, trange\n\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.nn import Parameter as P\nimport torchvision\n\n# Import my stuff\nimport inception_utils\nimport utils\nimport losses\nimport train_fns\nfrom sync_batchnorm import patch_replication_callback\n\n# The main training file. Config is a dictionary specifying the configuration\n# of this training run.\ndef run(config):\n\n # Update the config dict as necessary\n # This is for convenience, to add settings derived from the user-specified\n # configuration into the config-dict (e.g. inferring the number of classes\n # and size of the images from the dataset, passing in a pytorch object\n # for the activation specified as a string)\n config['resolution'] = utils.imsize_dict[config['dataset']]\n config['n_classes'] = utils.nclass_dict[config['dataset']]\n config['G_activation'] = utils.activation_dict[config['G_nl']]\n config['D_activation'] = utils.activation_dict[config['D_nl']]\n # By default, skip init if resuming training.\n if config['resume']:\n print('Skipping initialization for training resumption...')\n config['skip_init'] = True\n config = utils.update_config_roots(config)\n device = 'cuda'\n \n # Seed RNG\n utils.seed_rng(config['seed'])\n\n # Prepare root folders if necessary\n utils.prepare_root(config)\n\n # Setup cudnn.benchmark for free speed\n torch.backends.cudnn.benchmark = True\n\n # Import the model--this line allows us to dynamically select different files.\n model = __import__(config['model'])\n experiment_name = (config['experiment_name'] if config['experiment_name']\n else utils.name_from_config(config))\n print('Experiment name is %s' % experiment_name)\n\n # Next, build the model\n G = model.Generator(**config).to(device)\n D = model.Discriminator(**config).to(device)\n \n # If using EMA, prepare it\n if config['ema']:\n print('Preparing EMA for G with decay of {}'.format(config['ema_decay']))\n G_ema = model.Generator(**{**config, 'skip_init':True, \n 'no_optim': True}).to(device)\n ema = utils.ema(G, G_ema, config['ema_decay'], config['ema_start'])\n else:\n ema = None\n \n # FP16?\n if config['G_fp16']:\n print('Casting G to float16...')\n G = G.half()\n if config['ema']:\n G_ema = G_ema.half()\n if config['D_fp16']:\n print('Casting D to fp16...')\n D = D.half()\n # Consider automatically reducing SN_eps?\n GD = model.G_D(G, D)\n print(G)\n print(D)\n print('Number of params in G: {} D: {}'.format(\n *[sum([p.data.nelement() for p in net.parameters()]) for net in [G,D]]))\n # Prepare state dict, which holds things like epoch # and itr #\n state_dict = {'itr': 0, 'epoch': 0, 'save_num': 0, 'save_best_num': 0,\n 'best_IS': 0, 'best_FID': 999999, 'config': config}\n\n # If loading from a pre-trained model, load weights\n if config['resume']:\n print('Loading weights...')\n utils.load_weights(G, D, state_dict,\n config['weights_root'], experiment_name, \n config['load_weights'] if config['load_weights'] else None,\n G_ema if config['ema'] else None)\n\n # If parallel, parallelize the GD module\n if config['parallel']:\n GD = nn.DataParallel(GD)\n if config['cross_replica']:\n patch_replication_callback(GD)\n\n # Prepare loggers for stats; metrics holds test metrics,\n # lmetrics holds any desired training metrics.\n test_metrics_fname = '%s/%s_log.jsonl' % (config['logs_root'],\n experiment_name)\n train_metrics_fname = '%s/%s' % (config['logs_root'], experiment_name)\n print('Inception Metrics will be saved to {}'.format(test_metrics_fname))\n test_log = utils.MetricsLogger(test_metrics_fname, \n reinitialize=(not config['resume']))\n print('Training Metrics will be saved to {}'.format(train_metrics_fname))\n train_log = utils.MyLogger(train_metrics_fname, \n reinitialize=(not config['resume']),\n logstyle=config['logstyle'])\n # Write metadata\n utils.write_metadata(config['logs_root'], experiment_name, config, state_dict)\n # Prepare data; the Discriminator's batch size is all that needs to be passed\n # to the dataloader, as G doesn't require dataloading.\n # Note that at every loader iteration we pass in enough data to complete\n # a full D iteration (regardless of number of D steps and accumulations)\n D_batch_size = (config['batch_size'] * config['num_D_steps']\n * config['num_D_accumulations'])\n loaders = utils.get_data_loaders(**{**config, 'batch_size': D_batch_size,\n 'start_itr': state_dict['itr']})\n\n # Prepare inception metrics: FID and IS\n get_inception_metrics = inception_utils.prepare_inception_metrics(config['dataset'], config['parallel'], config['no_fid'])\n\n # Prepare noise and randomly sampled label arrays\n # Allow for different batch sizes in G\n G_batch_size = max(config['G_batch_size'], config['batch_size'])\n z_, y_ = utils.prepare_z_y(G_batch_size, G.dim_z, config['n_classes'],\n device=device, fp16=config['G_fp16'])\n # Prepare a fixed z & y to see individual sample evolution throghout training\n fixed_z, fixed_y = utils.prepare_z_y(G_batch_size, G.dim_z,\n config['n_classes'], device=device,\n fp16=config['G_fp16']) \n fixed_z.sample_()\n fixed_y.sample_()\n # Loaders are loaded, prepare the training function\n if config['which_train_fn'] == 'GAN':\n train = train_fns.GAN_training_function(G, D, GD, z_, y_, \n ema, state_dict, config)\n # Else, assume debugging and use the dummy train fn\n else:\n train = train_fns.dummy_training_function()\n # Prepare Sample function for use with inception metrics\n sample = functools.partial(utils.sample,\n G=(G_ema if config['ema'] and config['use_ema']\n else G),\n z_=z_, y_=y_, config=config)\n\n print('Beginning training at epoch %d...' % state_dict['epoch'])\n # Train for specified number of epochs, although we mostly track G iterations.\n for epoch in range(state_dict['epoch'], config['num_epochs']): \n # Which progressbar to use? TQDM or my own?\n if config['pbar'] == 'mine':\n pbar = utils.progress(loaders[0],displaytype='s1k' if config['use_multiepoch_sampler'] else 'eta')\n else:\n pbar = tqdm(loaders[0])\n for i, (x, y) in enumerate(pbar):\n # Increment the iteration counter\n state_dict['itr'] += 1\n # Make sure G and D are in training mode, just in case they got set to eval\n # For D, which typically doesn't have BN, this shouldn't matter much.\n G.train()\n D.train()\n if config['ema']:\n G_ema.train()\n if config['D_fp16']:\n x, y = x.to(device).half(), y.to(device)\n else:\n x, y = x.to(device), y.to(device)\n metrics = train(x, y)\n train_log.log(itr=int(state_dict['itr']), **metrics)\n \n # Every sv_log_interval, log singular values\n if (config['sv_log_interval'] > 0) and (not (state_dict['itr'] % config['sv_log_interval'])):\n train_log.log(itr=int(state_dict['itr']), \n **{**utils.get_SVs(G, 'G'), **utils.get_SVs(D, 'D')})\n\n # If using my progbar, print metrics.\n if config['pbar'] == 'mine':\n print(', '.join(['itr: %d' % state_dict['itr']] \n + ['%s : %+4.3f' % (key, metrics[key])\n for key in metrics]), end=' ')\n\n # Save weights and copies as configured at specified interval\n if not (state_dict['itr'] % config['save_every']):\n if config['G_eval_mode']:\n print('Switchin G to eval mode...')\n G.eval()\n if config['ema']:\n G_ema.eval()\n train_fns.save_and_sample(G, D, G_ema, z_, y_, fixed_z, fixed_y, \n state_dict, config, experiment_name)\n\n # Test every specified interval\n if not (state_dict['itr'] % config['test_every']):\n if config['G_eval_mode']:\n print('Switchin G to eval mode...')\n G.eval()\n train_fns.test(G, D, G_ema, state_dict, config, sample,\n get_inception_metrics, experiment_name, test_log)\n # Increment epoch counter at end of epoch\n state_dict['epoch'] += 1\n\n\ndef main():\n # parse command line and run\n parser = utils.prepare_parser()\n config = vars(parser.parse_args())\n print(config)\n run(config)\n\nif __name__ == '__main__':\n main()",
"import numpy as np\nimport numpy.random as random\nimport matplotlib.pyplot as plt\n\n\nclass QuantumRegister(object):\n def __init__(self, n_qubits):\n self.n_qubits = n_qubits\n self.n_states = 2 ** n_qubits\n self.qubits = np.zeros(self.n_states, dtype=complex)\n self.qubits[0] = 1.0\n\n def reset(self):\n self.qubits = np.zeros(self.n_states, dtype=complex)\n self.qubits[0] = 1.0\n\n # REGISER MANIPULATION\n\n def isset(self, state, n):\n return state & 1 << (self.n_qubits - 1 - n) != 0\n\n def flip(self, state, n):\n return state ^ 1 << (self.n_qubits - 1 - n)\n\n def set_qubit(self, n, a, b): # a|0>+b|1>\n tmp_qubits = np.zeros(self.n_states, dtype=complex)\n for state in range(self.n_states):\n current_amplitude = self.qubits[state] + self.qubits[self.flip(state, n)]\n if self.isset(state, n):\n tmp_qubits[state] = current_amplitude * b\n else:\n tmp_qubits[state] = current_amplitude * a\n self.qubits = tmp_qubits\n\n # MEASUREMENT OPERATIONS\n\n def measure(self):\n probabilities = np.absolute(self.qubits)**2\n return random.choice(len(probabilities), p=probabilities.flatten())\n\n def probability(self, qubits):\n assert len(qubits) == self.n_qubits\n probability = 0.0\n for state in range(self.n_states):\n selected = True\n for i in range(self.n_qubits):\n if qubits[i] is not None:\n selected &= (self.isset(state, i) == qubits[i])\n if selected:\n probability += np.absolute(self.qubits[i])**2\n print(state, selected, probability)\n return probability\n\n # QUANTUM GATES\n\n def hadamar(self, qubits=None):\n if qubits is None:\n qubits = [1] * self.n_qubits\n H = 1. / np.sqrt(2) * np.array([[1., 1.], [1., -1.]])\n m = np.array([1])\n for indicator in reversed(qubits):\n m = np.kron(H, m) if indicator else np.kron(np.eye(2), m)\n self.qubits = m.dot(self.qubits)\n return self\n\n def hadamar_alternative(self):\n hadamar = np.zeros((self.n_states, self.n_states))\n for target in range(self.n_states):\n for state in range(self.n_states):\n hadamar[target, state] = (2.**(-self.n_qubits / 2.))*(-1)**bin(state & target).count(\"1\")\n self.qubits = hadamar.dot(self.qubits)\n return self\n\n def cswap(self, c, a, b):\n cswap = np.zeros((self.n_states, self.n_states))\n for state in range(self.n_states):\n if self.isset(state, c):\n if self.isset(state, a) != self.isset(state, b):\n flipstate = self.flip(self.flip(state, b), a)\n cswap[state, flipstate] = 1.0\n else:\n cswap[state, state] = 1.0\n else:\n cswap[state, state] = 1.0\n self.qubits = cswap.dot(self.qubits)\n return self\n\n # IMPLEMENTATION ESSENTIALS\n\n def __str__(self):\n string = \"\"\n for state in range(self.n_states):\n string += \"{0:0>3b}\".format(state) + \" => {:.2f}\".format(self.qubits[state]) + \"\\n\"\n return string[:-1]\n\n def plot(self):\n plt.bar(range(self.n_states), np.absolute(self.qubits), color='k')\n plt.title(str(self.n_qubits) + ' qubit register')\n plt.axis([0, self.n_states, 0.0, 1.0])\n plt.show()\n\n def savefig(self, name):\n plt.bar(range(self.n_states), np.absolute(self.qubits), color='k')\n plt.title(str(self.n_qubits) + ' qubit register')\n plt.axis([0, self.n_states, 0.0, 1.0])\n plt.savefig(\"img/\" + name + \".pdf\")\n\n def plot2(self, save=None, name=None):\n cols = 2 ** (self.n_qubits / 2) # integer division!\n rows = 2 ** (self.n_qubits - (self.n_qubits / 2))\n\n x = []\n y = []\n c = []\n\n for i in range(self.n_states):\n x.append(i % cols)\n y.append(i / cols)\n c.append(np.absolute(self.qubits[i]))\n\n plt.xlim(-0.5, cols-0.5)\n plt.ylim(-0.5, rows-0.5)\n\n plt.axes().set_aspect('equal')\n\n plt.scatter(x, y, s=2e3, c=c, linewidths=2, vmin=0, vmax=1, cmap=plt.get_cmap('jet'))\n\n if save is None:\n plt.show()\n else:\n plt.axis('off')\n plt.title('('+name+')')\n\n fig = plt.gcf()\n fig.set_size_inches(cols, rows)\n fig.savefig(\"img/\" + save + \".pdf\", transparent=True, pad_inches=0)",
"\"\"\"\nreadligo.py\n\nupdated: January 15, 2018\nby: Agata Trovato\nwhat has been modified: minor corrections to make it usable with python 3 \n(tab replaced with spaces, argument of 'reshape' integer, forced the integer conversion also for slices)\n\nVersion 0.3\nJanuary 10, 2017\nJonah Kanner, Roy Williams, and Alan Weinstein\n\nUpdates in this version:\n * Should now work with both Python 2 and Python 3\n\nThis module provides tools for reading LIGO data\nfiles. Data along with supporting documentation\ncan be downloaded from the losc web site:\nhttps://losc.ligo.org\n\nSome possible use cases are shown below.\n\nExample #0:\nTo load all data from a single file:\nstrain, time, dq = rl.loaddata('ligo_data/H-H1_LOSC_4_V1-842653696-4096.hdf5', 'H1')\n\nExample #1: \nsegList = getsegs(842657792, 842658792, 'H1')\nfor (start, stop) in segList:\n strain, meta, dq = getstrain(start, stop, 'H1')\n # -- Analysis code here\n ...\n\nThis default configuration assumes that the needed LIGO data \nfiles are available in the current working directory or a \nsubdirectory. LIGO data between the input GPS times is loaded\ninto STRAIN. META is a dictionary of gps start, gps stop, and the \nsample time. DQ is a dictionary of data quality flags.\n\nExample #2\nsegList = SegmentList('H1_segs.txt')\n\nIn Example 2, 'H1_segs.txt' is a segment list downloaded from the\nLOSC web site using the Timeline application. This may be used in the same\nmanner as segList in example 1.\n\nExample #3\nfilelist = FileList(directory='/home/ligodata')\nsegList = getsegs(842657792, 842658792, 'H1', filelist=filelist)\nfor start, stop in segList:\n strain, meta, dq = getstrain(start, stop, 'H1', filelist=filelist)\n # -- Analysis code here\n\nIn this example, the first command searches the indicated directory and \nsub-directories for LIGO data files. This list of data files is then \nused to construct a segment list and load the requested data. \n\n-- SEGMENT LISTS --\n\nSegment lists may be downloaded from the LOSC web site\nusing the Timeline Query Form or constructed directly\nfrom the data files. \n\nRead in a segment list downloaded from the Timeline \napplication on the LOSC web site with SegmentList:\n>> seglist = SegmentList('H1_segs.txt')\nOR\nConstruct a segment list directly from the LIGO\ndata files with getsegs():\n>> seglist = getsegs(842657792, 842658792, 'H1', flag='DATA', filelist=None)\n\n\"\"\"\n\nimport numpy as np\nimport os\nimport fnmatch\n\ndef read_frame(filename, ifo, readstrain=True):\n \"\"\"\n Helper function to read frame files\n \"\"\"\n try:\n import Fr\n except:\n from pylal import Fr\n\n if ifo is None:\n raise TypeError(\"\"\"To read GWF data, ifo must be 'H1', 'H2', or 'L1'.\n def loaddata(filename, ifo=None):\"\"\")\n\n #-- Read strain channel\n strain_name = ifo + ':LOSC-STRAIN'\n if readstrain:\n sd = Fr.frgetvect(filename, strain_name) \n strain = sd[0]\n gpsStart = sd[1] \n ts = sd[3][0]\n else:\n ts = 1\n strain = 0\n \n #-- Read DQ channel\n dq_name = ifo + ':LOSC-DQMASK'\n qd = Fr.frgetvect(filename, dq_name)\n gpsStart = qd[1]\n qmask = np.array(qd[0])\n dq_ts = qd[3][0]\n shortnameList_wbit = qd[5].split()\n shortnameList = [name.split(':')[1] for name in shortnameList_wbit]\n\n #-- Read Injection channel\n inj_name = ifo + ':LOSC-INJMASK'\n injdata = Fr.frgetvect(filename, inj_name)\n injmask = injdata[0]\n injnamelist_bit = injdata[5].split()\n injnamelist = [name.split(':')[1] for name in injnamelist_bit]\n\n return strain, gpsStart, ts, qmask, shortnameList, injmask, injnamelist\n \ndef read_hdf5(filename, readstrain=True):\n \"\"\"\n Helper function to read HDF5 files\n \"\"\"\n import h5py\n dataFile = h5py.File(filename, 'r')\n\n #-- Read the strain\n if readstrain:\n strain = dataFile['strain']['Strain'][...]\n else:\n strain = 0\n\n ts = dataFile['strain']['Strain'].attrs['Xspacing']\n \n #-- Read the DQ information\n dqInfo = dataFile['quality']['simple']\n qmask = dqInfo['DQmask'][...]\n shortnameArray = dqInfo['DQShortnames'].value\n shortnameList = list(shortnameArray)\n \n # -- Read the INJ information\n injInfo = dataFile['quality/injections']\n injmask = injInfo['Injmask'][...]\n injnameArray = injInfo['InjShortnames'].value\n injnameList = list(injnameArray)\n \n #-- Read the meta data\n meta = dataFile['meta']\n gpsStart = meta['GPSstart'].value \n \n dataFile.close()\n return strain, gpsStart, ts, qmask, shortnameList, injmask, injnameList\n\ndef loaddata(filename, ifo=None, tvec=True, readstrain=True):\n \"\"\"\n The input filename should be a LOSC .hdf5 file or a LOSC .gwf\n file. The file type will be determined from the extenstion. \n The detector should be H1, H2, or L1.\n\n The return value is: \n STRAIN, TIME, CHANNEL_DICT\n\n STRAIN is a vector of strain values\n TIME is a vector of time values to match the STRAIN vector\n unless the flag tvec=False. In that case, TIME is a\n dictionary of meta values.\n CHANNEL_DICT is a dictionary of data quality channels \n \"\"\"\n\n # -- Check for zero length file\n try:\n if os.stat(filename).st_size == 0:\n return None, None, None\n except:\n return None,None,None\n\n file_ext = os.path.splitext(filename)[1] \n if (file_ext.upper() == '.GWF'):\n strain, gpsStart, ts, qmask, shortnameList, injmask, injnameList = read_frame(filename, ifo, readstrain)\n else:\n strain, gpsStart, ts, qmask, shortnameList, injmask, injnameList = read_hdf5(filename, readstrain)\n \n #-- Create the time vector\n gpsEnd = gpsStart + len(qmask)\n if tvec:\n time = np.arange(gpsStart, gpsEnd, ts)\n else:\n meta = {}\n meta['start'] = gpsStart\n meta['stop'] = gpsEnd\n meta['dt'] = ts\n\n #-- Create 1 Hz DQ channel for each DQ and INJ channel\n channel_dict = {} #-- 1 Hz, mask\n slice_dict = {} #-- sampling freq. of stain, a list of slices\n final_one_hz = np.zeros(qmask.shape, dtype='int32')\n for flag in shortnameList:\n bit = shortnameList.index(flag)\n # Special check for python 3\n if isinstance(flag, bytes): flag = flag.decode(\"utf-8\") \n \n channel_dict[flag] = (qmask >> bit) & 1\n\n for flag in injnameList:\n bit = injnameList.index(flag)\n # Special check for python 3\n if isinstance(flag, bytes): flag = flag.decode(\"utf-8\") \n \n channel_dict[flag] = (injmask >> bit) & 1\n \n #-- Calculate the DEFAULT channel\n try:\n channel_dict['DEFAULT'] = ( channel_dict['DATA'] )\n except:\n print(\"Warning: Failed to calculate DEFAULT data quality channel\")\n\n if tvec:\n return strain, time, channel_dict\n else:\n return strain, meta, channel_dict\n\n\ndef dq2segs(channel, gps_start):\n \"\"\"\n This function takes a DQ CHANNEL (as returned by loaddata or getstrain) and \n the GPS_START time of the channel and returns a segment\n list. The DQ Channel is assumed to be a 1 Hz channel.\n\n Returns of a list of segment GPS start and stop times.\n \"\"\"\n #-- Check if the user input a dictionary\n if type(channel) == dict:\n try:\n channel = channel['DEFAULT']\n except:\n print(\"ERROR: Could not find DEFAULT channel in dictionary\")\n raise\n\n #-- Create the segment list\n segments = dq_channel_to_seglist(channel, fs=1)\n t0 = gps_start\n segList = [(int(seg.start+t0), int(seg.stop+t0)) for seg in segments]\n return SegmentList(segList)\n \ndef dq_channel_to_seglist(channel, fs=4096):\n \"\"\"\n WARNING: \n This function is designed to work the output of the low level function\n LOADDATA, not the output from the main data loading function GETSTRAIN.\n\n Takes a data quality 1 Hz channel, as returned by\n loaddata, and returns a segment list. The segment\n list is really a list of slices for the strain \n associated strain vector. \n\n If CHANNEL is a dictionary instead of a single channel,\n an attempt is made to return a segment list for the DEFAULT\n channel. \n\n Returns a list of slices which can be used directly with the \n strain and time outputs of LOADDATA.\n \"\"\"\n #-- Check if the user input a dictionary\n if type(channel) == dict:\n try:\n channel = channel['DEFAULT']\n except:\n print(\"ERROR: Could not find DEFAULT channel in dictionary\")\n raise\n\n # -- Create the segment list\n condition = channel > 0\n boundaries = np.where(np.diff(condition) == True)[0]\n # -- Need to +1 due to how np.diff works \n boundaries = boundaries + 1\n # if the array \"begins\" True, we need to complete the first segment\n if condition[0]:\n boundaries = np.append(0,boundaries)\n # if the array \"ends\" True, we need to complete the last segment\n if condition[-1]:\n boundaries = np.append(boundaries,len(condition))\n\n # -- group the segment boundaries two by two\n segments = boundaries.reshape( ( len(boundaries) // 2, 2 ) ) #// for python 3\n # -- Account for sampling frequency and return a slice\n segment_list = [slice(start*fs, stop*fs) for (start,stop) in segments]\n \n return segment_list\n\nclass FileList():\n \"\"\"\n Class for lists of LIGO data files.\n \n When a FileList instance is created, DIRECTORY will \n be searched for LIGO data files. Sub-directories\n will be searched as well. By default, the current\n working directory is searched. \n \"\"\"\n def __init__(self, directory=None, cache=None):\n\n # -- Set default directory\n if directory is None:\n if os.path.isdir('/archive/losc/strain-gwf'):\n directory='/archive/losc/strain-gwf'\n else:\n directory='.'\n\n print(\"Using data directory {0} ...\".format(directory))\n self.directory = directory\n self.cache = cache\n if cache is None:\n self.list = self.searchdir(directory)\n else:\n self.readcache()\n\n def searchdir(self, directory='.'):\n frameList = []\n hdfList = []\n for root, dirnames, filenames in os.walk(directory):\n for filename in fnmatch.filter(filenames, '*.gwf'):\n frameList.append(os.path.join(root, filename))\n for filename in fnmatch.filter(filenames, '*.hdf5'):\n hdfList.append(os.path.join(root, filename))\n return frameList + hdfList\n\n def writecache(self, cacheName):\n outfile = open(cacheName, 'w')\n for file in self.list:\n outfile.write(file + '\\n')\n outfile.close()\n\n def readcache(self):\n infile = open(self.cache, 'r')\n self.list = infile.read().split()\n infile.close()\n \n def findfile(self, gps, ifo):\n start_gps = gps - (gps % 4096)\n filenamelist = fnmatch.filter(self.list, '*' + '-' + ifo + '*' + '-' + str(start_gps) + '-' + '*')\n if len(filenamelist) == 0:\n print(\"WARNING! No file found for GPS {0} and IFO {1}\".format(gps, ifo))\n return None\n else:\n return filenamelist[0]\n \ndef getstrain(start, stop, ifo, filelist=None):\n \"\"\"\n START should be the starting gps time of the data to be loaded.\n STOP should be the end gps time of the data to be loaded.\n IFO should be 'H1', 'H2', or 'L1'.\n FILELIST is an optional argument that is a FileList() instance.\n\n The return value is (strain, meta, dq)\n \n STRAIN: The data as a strain time series\n META: A dictionary of meta data, especially the start time, stop time, \n and sample time\n DQ: A dictionary of the data quality flags\n \"\"\"\n\n if filelist is None:\n filelist = FileList()\n\n # -- Check if this is a science segment\n segList = getsegs(start, stop, ifo, flag='DATA', filelist=filelist)\n sl = segList.seglist\n if (sl[0][0] == start) and (sl[0][1] == stop):\n pass\n else:\n raise TypeError(\"\"\"Error in getstrain.\n Requested times include times where the data file was not found\n or instrument not in SCIENCE mode.\n Use readligo.getsegs() to construct a segment list.\n The science mode segment list for the requested time range is: \n {0}\"\"\".format(segList))\n\n # -- Construct list of expected file start times\n first = start - (start % 4096)\n gpsList = np.arange(first, stop, 4096)\n\n m_strain = np.array([])\n m_dq = None\n # -- Loop over needed files\n for time in gpsList:\n filename = filelist.findfile(time, ifo)\n print(\"Loading {0}\".format(filename))\n\n #-- Read in data\n strain, meta, dq = loaddata(filename, ifo, tvec=False)\n if len(m_strain) == 0:\n m_start = meta['start']\n dt = meta['dt']\n m_stop = meta['stop']\n m_strain = np.append(m_strain, strain)\n if m_dq is None:\n m_dq = dq\n else:\n for key in dq.keys():\n m_dq[key] = np.append(m_dq[key], dq[key])\n\n # -- Trim the data\n lndx = np.abs(start - m_start)*(1.0/dt)\n rndx = np.abs(stop - m_start)*(1.0/dt)\n\n m_strain = m_strain[int(lndx):int(rndx)] # slice indices must be integers\n for key in m_dq.keys():\n m_dq[key] = m_dq[key][int(lndx*dt):int(rndx*dt)]# slice indices must be integers\n\n meta['start'] = start\n meta['stop'] = stop\n meta['dt'] = dt\n\n return m_strain, meta, m_dq\n\nclass SegmentList():\n def __init__(self, filename, numcolumns=3):\n\n if type(filename) is str:\n try:\n if numcolumns == 4:\n number, start, stop, duration = np.loadtxt(filename, dtype='int',unpack=True)\n elif numcolumns == 2:\n start, stop = np.loadtxt(filename, dtype='int',unpack=True)\n elif numcolumns == 3:\n start, stop, duration = np.loadtxt(filename, dtype='int',unpack=True)\n if isinstance(start, int): \n self.seglist = [[start, stop]]\n else:\n self.seglist = zip(start, stop)\n except:\n self.seglist = []\n elif type(filename) is list:\n self.seglist = filename\n else:\n raise TypeError(\"SegmentList() expects the name of a segmentlist file from the LOSC website Timeline\")\n\n def __repr__(self):\n return 'SegmentList( {0} )'.format(self.seglist)\n def __iter__(self):\n return iter(self.seglist)\n def __getitem__(self, key):\n return self.seglist[key]\n \ndef getsegs(start, stop, ifo, flag='DATA', filelist=None):\n \"\"\"\n Method for constructing a segment list from \n LOSC data files. By default, the method uses\n files in the current working directory to \n construct a segment list. \n\n If a FileList is passed in the flag FILELIST,\n then those files will be searched for segments\n passing the DQ flag passed as the FLAG argument.\n \"\"\"\n\n if filelist is None:\n filelist = FileList()\n\n # -- Construct list of expected file start times\n first = start - (start % 4096)\n gpsList = np.arange(first, stop, 4096)\n m_dq = None\n \n # -- Initialize segment list\n segList = []\n\n # -- Loop over needed files\n for time in gpsList:\n filename = filelist.findfile(time, ifo)\n\n #-- Read in data\n if filename is None:\n print(\"WARNING! No file found with GPS start time {0}\".format(time))\n print(\"Segment list may contain errors due to missing files.\")\n continue\n else:\n try:\n strain, meta, dq = loaddata(filename, ifo, tvec=False, readstrain=False) \n except:\n print(\"WARNING! Failed to load file {0}\".format(filename))\n print(\"Segment list may contain errors due to corrupt files.\")\n continue\n\n if dq is None:\n print(\"Warning! Found zero length file {0}\".format(filename))\n print(\"Segment list may contain errors.\")\n continue\n\n #-- Add segments to list on a file-by-file basis\n chan = dq[flag]\n indxlist = dq_channel_to_seglist(chan, fs=1.0)\n i_start = meta['start']\n i_seglist = [(indx.start+i_start, indx.stop+i_start) for indx in indxlist]\n i_seglist = [(int(begin), int(end)) for begin, end in i_seglist] \n segList = segList + i_seglist\n \n # -- Sort segments\n segList.sort()\n \n # -- Merge overlapping segments\n for i in range(0, len(segList)-1):\n seg1 = segList[i]\n seg2 = segList[i+1]\n \n if seg1[1] == seg2[0]:\n segList[i] = None\n segList[i+1] = (seg1[0], seg2[1]) \n # -- Remove placeholder segments\n segList = [seg for seg in segList if seg is not None]\n\n # -- Trim segment list to fit within requested start/stop times\n for seg in segList:\n idx = segList.index(seg)\n if (seg[1] < start):\n segList[idx] = None\n elif (seg[0] > stop):\n segList[idx] = None\n elif (seg[0] < start) and (seg[1] > stop):\n segList[idx] = (start, stop)\n elif (seg[0] < start):\n segList[idx] = (start, seg[1])\n elif (seg[1] > stop):\n segList[idx] = (seg[0], stop)\n # -- Remove placeholder segments\n segList = [seg for seg in segList if seg is not None]\n\n return SegmentList(segList)",
"''' Sample\n This script loads a pretrained net and a weightsfile and sample '''\nimport functools\nimport math\nimport numpy as np\nfrom tqdm import tqdm, trange\n\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.nn import Parameter as P\nimport torchvision\n\n# Import my stuff\nimport inception_utils\nimport utils\nimport losses\nimport model\n\n\ndef run(config):\n # Prepare state dict, which holds things like epoch # and itr #\n state_dict = {'itr': 0, 'epoch': 0, 'save_num': 0, 'save_best_num': 0,\n 'best_IS': 0, 'best_FID': 999999, 'config': config}\n \n # Optionally, get the configuration from the state dict. This allows for\n # recovery of the config provided only a state dict and experiment name,\n # and can be convenient for writing less verbose sample shell scripts.\n if config['config_from_name']:\n utils.load_weights(None, None, state_dict, config['weights_root'], \n config['experiment_name'], config['load_weights'], None,\n strict=False, load_optim=False)\n # Ignore items which we might want to overwrite from the command line\n for item in state_dict['config']:\n if item not in ['z_var', 'base_root', 'batch_size', 'G_batch_size', 'use_ema', 'G_eval_mode']:\n config[item] = state_dict['config'][item]\n \n # update config (see train.py for explanation)\n config['resolution'] = utils.imsize_dict[config['dataset']]\n config['n_classes'] = utils.nclass_dict[config['dataset']]\n config['G_activation'] = utils.activation_dict[config['G_nl']]\n config['D_activation'] = utils.activation_dict[config['D_nl']]\n config = utils.update_config_roots(config)\n config['skip_init'] = True\n config['no_optim'] = True\n device = 'cuda'\n \n # Seed RNG\n utils.seed_rng(config['seed'])\n \n # Setup cudnn.benchmark for free speed\n torch.backends.cudnn.benchmark = True\n \n # Import the model--this line allows us to dynamically select different files.\n model = __import__(config['model'])\n experiment_name = (config['experiment_name'] if config['experiment_name']\n else utils.name_from_config(config))\n print('Experiment name is %s' % experiment_name)\n \n G = model.Generator(**config).cuda()\n utils.count_parameters(G)\n \n # Load weights\n print('Loading weights...')\n # Here is where we deal with the ema--load ema weights or load normal weights\n utils.load_weights(G if not (config['use_ema']) else None, None, state_dict, \n config['weights_root'], experiment_name, config['load_weights'],\n G if config['ema'] and config['use_ema'] else None,\n strict=False, load_optim=False)\n # Update batch size setting used for G\n G_batch_size = max(config['G_batch_size'], config['batch_size']) \n z_, y_ = utils.prepare_z_y(G_batch_size, G.dim_z, config['n_classes'],\n device=device, fp16=config['G_fp16'], \n z_var=config['z_var'])\n \n if config['G_eval_mode']:\n print('Putting G in eval mode..')\n G.eval()\n else:\n print('G is in %s mode...' % ('training' if G.training else 'eval'))\n \n #Sample function\n sample = functools.partial(utils.sample, G=G, z_=z_, y_=y_, config=config) \n if config['accumulate_stats']:\n print('Accumulating standing stats across %d accumulations...' % config['num_standing_accumulations'])\n utils.accumulate_standing_stats(G, z_, y_, config['n_classes'],\n config['num_standing_accumulations'])\n \n \n # Sample a number of images and save them to an NPZ, for use with TF-Inception\n if config['sample_npz']:\n # Lists to hold images and labels for images\n x, y = [], []\n print('Sampling %d images and saving them to npz...' % config['sample_num_npz'])\n for i in trange(int(np.ceil(config['sample_num_npz'] / float(G_batch_size)))):\n with torch.no_grad():\n images, labels = sample()\n x += [np.uint8(255 * (images.cpu().numpy() + 1) / 2.)]\n y += [labels.cpu().numpy()]\n x = np.concatenate(x, 0)[:config['sample_num_npz']]\n y = np.concatenate(y, 0)[:config['sample_num_npz']] \n print('Images shape: %s, Labels shape: %s' % (x.shape, y.shape))\n npz_filename = '%s/%s/samples.npz' % (config['samples_root'], experiment_name)\n print('Saving npz to %s...' % npz_filename)\n np.savez(npz_filename, **{'x' : x, 'y' : y})\n \n # Prepare sample sheets\n if config['sample_sheets']:\n print('Preparing conditional sample sheets...')\n utils.sample_sheet(G, classes_per_sheet=utils.classes_per_sheet_dict[config['dataset']], \n num_classes=config['n_classes'], \n samples_per_class=10, parallel=config['parallel'],\n samples_root=config['samples_root'], \n experiment_name=experiment_name,\n folder_number=config['sample_sheet_folder_num'],\n z_=z_,)\n # Sample interp sheets\n if config['sample_interps']:\n print('Preparing interp sheets...')\n for fix_z, fix_y in zip([False, False, True], [False, True, False]):\n utils.interp_sheet(G, num_per_sheet=16, num_midpoints=8,\n num_classes=config['n_classes'], \n parallel=config['parallel'], \n samples_root=config['samples_root'], \n experiment_name=experiment_name,\n folder_number=config['sample_sheet_folder_num'], \n sheet_number=0,\n fix_z=fix_z, fix_y=fix_y, device='cuda')\n # Sample random sheet\n if config['sample_random']:\n print('Preparing random sample sheet...')\n images, labels = sample() \n torchvision.utils.save_image(images.float(),\n '%s/%s/random_samples.jpg' % (config['samples_root'], experiment_name),\n nrow=int(G_batch_size**0.5),\n normalize=True)\n\n # Get Inception Score and FID\n get_inception_metrics = inception_utils.prepare_inception_metrics(config['dataset'], config['parallel'], config['no_fid'])\n # Prepare a simple function get metrics that we use for trunc curves\n def get_metrics():\n sample = functools.partial(utils.sample, G=G, z_=z_, y_=y_, config=config) \n IS_mean, IS_std, FID = get_inception_metrics(sample, config['num_inception_images'], num_splits=10, prints=False)\n # Prepare output string\n outstring = 'Using %s weights ' % ('ema' if config['use_ema'] else 'non-ema')\n outstring += 'in %s mode, ' % ('eval' if config['G_eval_mode'] else 'training')\n outstring += 'with noise variance %3.3f, ' % z_.var\n outstring += 'over %d images, ' % config['num_inception_images']\n if config['accumulate_stats'] or not config['G_eval_mode']:\n outstring += 'with batch size %d, ' % G_batch_size\n if config['accumulate_stats']:\n outstring += 'using %d standing stat accumulations, ' % config['num_standing_accumulations']\n outstring += 'Itr %d: PYTORCH UNOFFICIAL Inception Score is %3.3f +/- %3.3f, PYTORCH UNOFFICIAL FID is %5.4f' % (state_dict['itr'], IS_mean, IS_std, FID)\n print(outstring)\n if config['sample_inception_metrics']: \n print('Calculating Inception metrics...')\n get_metrics()\n \n # Sample truncation curve stuff. This is basically the same as the inception metrics code\n if config['sample_trunc_curves']:\n start, step, end = [float(item) for item in config['sample_trunc_curves'].split('_')]\n print('Getting truncation values for variance in range (%3.3f:%3.3f:%3.3f)...' % (start, step, end))\n for var in np.arange(start, end + step, step): \n z_.var = var\n # Optionally comment this out if you want to run with standing stats\n # accumulated at one z variance setting\n if config['accumulate_stats']:\n utils.accumulate_standing_stats(G, z_, y_, config['n_classes'],\n config['num_standing_accumulations'])\n get_metrics()\ndef main():\n # parse command line and run \n parser = utils.prepare_parser()\n parser = utils.add_sample_parser(parser)\n config = vars(parser.parse_args())\n print(config)\n run(config)\n \nif __name__ == '__main__': \n main()",
"import tensorflow as tf\n\nfrom config import cfg\nfrom utils import get_batch_data\nfrom capsLayer import CapsConv\n\n\nclass CapsNet(object):\n def __init__(self, is_training=True):\n self.graph = tf.Graph()\n with self.graph.as_default():\n if is_training:\n self.X, self.Y = get_batch_data()\n\n self.build_arch()\n self.loss()\n\n # t_vars = tf.trainable_variables()\n self.optimizer = tf.train.AdamOptimizer()\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\n self.train_op = self.optimizer.minimize(self.total_loss, global_step=self.global_step) # var_list=t_vars)\n else:\n self.X = tf.placeholder(tf.float32,\n shape=(cfg.batch_size, 28, 28, 1))\n self.build_arch()\n\n tf.logging.info('Seting up the main structure')\n\n def build_arch(self):\n with tf.variable_scope('Conv1_layer'):\n # Conv1, [batch_size, 20, 20, 256]\n conv1 = tf.contrib.layers.conv2d(self.X, num_outputs=256,\n kernel_size=9, stride=1,\n padding='VALID')\n assert conv1.get_shape() == [cfg.batch_size, 20, 20, 256]\n\n # TODO: Rewrite the 'CapsConv' class as a function, the capsLay\n # function should be encapsulated into tow function, one like conv2d\n # and another is fully_connected in Tensorflow.\n # Primary Capsules, [batch_size, 1152, 8, 1]\n with tf.variable_scope('PrimaryCaps_layer'):\n primaryCaps = CapsConv(num_units=8, with_routing=False)\n caps1 = primaryCaps(conv1, num_outputs=32, kernel_size=9, stride=2)\n assert caps1.get_shape() == [cfg.batch_size, 1152, 8, 1]\n\n # DigitCaps layer, [batch_size, 10, 16, 1]\n with tf.variable_scope('DigitCaps_layer'):\n digitCaps = CapsConv(num_units=16, with_routing=True)\n self.caps2 = digitCaps(caps1, num_outputs=10)\n\n # Decoder structure in Fig. 2\n # 1. Do masking, how:\n with tf.variable_scope('Masking'):\n # a). calc ||v_c||, then do softmax(||v_c||)\n # [batch_size, 10, 16, 1] => [batch_size, 10, 1, 1]\n self.v_length = tf.sqrt(tf.reduce_sum(tf.square(self.caps2),\n axis=2, keep_dims=True))\n self.softmax_v = tf.nn.softmax(self.v_length, dim=1)\n assert self.softmax_v.get_shape() == [cfg.batch_size, 10, 1, 1]\n\n # b). pick out the index of max softmax val of the 10 caps\n # [batch_size, 10, 1, 1] => [batch_size] (index)\n argmax_idx = tf.argmax(self.softmax_v, axis=1, output_type=tf.int32)\n assert argmax_idx.get_shape() == [cfg.batch_size, 1, 1]\n\n # c). indexing\n # It's not easy to understand the indexing process with argmax_idx\n # as we are 3-dim animal\n masked_v = []\n argmax_idx = tf.reshape(argmax_idx, shape=(cfg.batch_size, ))\n for batch_size in range(cfg.batch_size):\n v = self.caps2[batch_size][argmax_idx[batch_size], :]\n masked_v.append(tf.reshape(v, shape=(1, 1, 16, 1)))\n\n self.masked_v = tf.concat(masked_v, axis=0)\n assert self.masked_v.get_shape() == [cfg.batch_size, 1, 16, 1]\n\n # 2. Reconstructe the MNIST images with 3 FC layers\n # [batch_size, 1, 16, 1] => [batch_size, 16] => [batch_size, 512]\n with tf.variable_scope('Decoder'):\n vector_j = tf.reshape(self.masked_v, shape=(cfg.batch_size, -1))\n fc1 = tf.contrib.layers.fully_connected(vector_j, num_outputs=512)\n assert fc1.get_shape() == [cfg.batch_size, 512]\n fc2 = tf.contrib.layers.fully_connected(fc1, num_outputs=1024)\n assert fc2.get_shape() == [cfg.batch_size, 1024]\n self.decoded = tf.contrib.layers.fully_connected(fc2, num_outputs=784, activation_fn=tf.sigmoid)\n\n def loss(self):\n # 1. The margin loss\n\n # [batch_size, 10, 1, 1]\n # max_l = max(0, m_plus-||v_c||)^2\n max_l = tf.square(tf.maximum(0., cfg.m_plus - self.v_length))\n # max_r = max(0, ||v_c||-m_minus)^2\n max_r = tf.square(tf.maximum(0., self.v_length - cfg.m_minus))\n assert max_l.get_shape() == [cfg.batch_size, 10, 1, 1]\n\n # reshape: [batch_size, 10, 1, 1] => [batch_size, 10]\n max_l = tf.reshape(max_l, shape=(cfg.batch_size, -1))\n max_r = tf.reshape(max_r, shape=(cfg.batch_size, -1))\n\n # calc T_c: [batch_size, 10]\n # T_c = Y, is my understanding correct? Try it.\n T_c = self.Y\n # [batch_size, 10], element-wise multiply\n L_c = T_c * max_l + cfg.lambda_val * (1 - T_c) * max_r\n\n self.margin_loss = tf.reduce_mean(tf.reduce_sum(L_c, axis=1))\n\n # 2. The reconstruction loss\n orgin = tf.reshape(self.X, shape=(cfg.batch_size, -1))\n squared = tf.square(self.decoded - orgin)\n self.reconstruction_err = tf.reduce_mean(squared)\n\n # 3. Total loss\n self.total_loss = self.margin_loss + 0.0005 * self.reconstruction_err\n\n # Summary\n tf.summary.scalar('margin_loss', self.margin_loss)\n tf.summary.scalar('reconstruction_loss', self.reconstruction_err)\n tf.summary.scalar('total_loss', self.total_loss)\n recon_img = tf.reshape(self.decoded, shape=(cfg.batch_size, 28, 28, 1))\n tf.summary.image('reconstruction_img', recon_img)\n self.merged_sum = tf.summary.merge_all()"
] |
[
[
"torch.nn.DataParallel"
],
[
"numpy.absolute",
"numpy.sqrt",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"numpy.eye",
"numpy.kron",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.axis",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show"
],
[
"numpy.abs",
"numpy.arange",
"numpy.append",
"numpy.diff",
"numpy.array",
"numpy.zeros",
"numpy.loadtxt"
],
[
"numpy.concatenate",
"numpy.arange",
"numpy.savez",
"torch.no_grad"
],
[
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.Graph",
"tensorflow.Variable",
"tensorflow.summary.image",
"tensorflow.square",
"tensorflow.argmax",
"tensorflow.placeholder",
"tensorflow.contrib.layers.conv2d",
"tensorflow.logging.info",
"tensorflow.summary.merge_all",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.contrib.layers.fully_connected",
"tensorflow.variable_scope"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
Sanyambansal76/MLAlgorithms
|
[
"829c74cf7d79307fc6ca1d849e65b959fb10e5de"
] |
[
"mla/base/base.py"
] |
[
"import numpy as np\n\n\nclass BaseEstimator(object):\n X = None\n y = None\n y_required = True\n\n def _setup_input(self, X, y=None):\n \"\"\"Ensure inputs to an estimator are in the expected format.\n\n Ensures X and y are stored as numpy ndarrays by converting from an\n array-like object if necessary. Enables estimators to define whether\n they require a set of y target values or not with y_required, e.g.\n kmeans clustering requires no target labels and is fit against only X.\n\n Parameters\n ----------\n X : array-like\n Feature dataset.\n y : array-like\n Target values. By default is required, but if y_required = false\n then may be omitted.\n \"\"\"\n if not isinstance(X, np.ndarray):\n X = np.array(X)\n\n if X.size == 0:\n raise ValueError('Number of features must be > 0')\n\n if X.ndim == 1:\n self.n_samples, self.n_features = 1, X.shape\n else:\n self.n_samples, self.n_features = X.shape[0], np.prod(X.shape[1:])\n\n self.X = X\n\n if self.y_required:\n if y is None:\n raise ValueError('Missed required argument y')\n\n if not isinstance(y, np.ndarray):\n y = np.array(y)\n\n if y.size == 0:\n raise ValueError('Number of targets must be > 0')\n\n self.y = y\n\n def fit(self, X, y=None):\n self._setup_input(X, y)\n\n def predict(self, X=None):\n if not isinstance(X, np.ndarray):\n X = np.array(X)\n\n if self.X is not None:\n return self._predict(X)\n else:\n raise ValueError('You must call `fit` before `predict`')\n\n def _predict(self, X=None):\n raise NotImplementedError()\n"
] |
[
[
"numpy.array",
"numpy.prod"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lywong92/garage
|
[
"96cb8887fcae90531a645d540653010e7fe10fcc"
] |
[
"src/garage/experiment/local_tf_runner.py"
] |
[
"\"\"\"\nThe local runner for tensorflow algorithms.\n\nA runner setup context for algorithms during initialization and\npipelines data between sampler and algorithm during training.\n\"\"\"\nimport copy\nimport time\nfrom types import SimpleNamespace\n\nfrom dowel import logger, tabular\nimport tensorflow as tf\n\nfrom garage.experiment import snapshotter\n\n# Note: Optional module should be imported ad hoc to break circular dependency.\n\n\nclass LocalRunner:\n \"\"\"This class implements a local runner for tensorflow algorithms.\n\n A local runner provides a default tensorflow session using python context.\n This is useful for those experiment components (e.g. policy) that require a\n tensorflow session during construction.\n\n Use Runner.setup(algo, env) to setup algorithm and environement for runner\n and Runner.train() to start training.\n\n Examples:\n with LocalRunner() as runner:\n env = gym.make('CartPole-v1')\n policy = CategoricalMLPPolicy(\n env_spec=env.spec,\n hidden_sizes=(32, 32))\n algo = TRPO(\n env=env,\n policy=policy,\n baseline=baseline,\n max_path_length=100,\n discount=0.99,\n max_kl_step=0.01)\n runner.setup(algo, env)\n runner.train(n_epochs=100, batch_size=4000)\n\n \"\"\"\n\n def __init__(self, sess=None, max_cpus=1):\n \"\"\"Create a new local runner.\n\n Args:\n max_cpus(int): The maximum number of parallel sampler workers.\n sess(tf.Session): An optional tensorflow session.\n A new session will be created immediately if not provided.\n\n Note:\n The local runner will set up a joblib task pool of size max_cpus\n possibly later used by BatchSampler. If BatchSampler is not used,\n the processes in the pool will remain dormant.\n\n This setup is required to use tensorflow in a multiprocess\n environment before a tensorflow session is created\n because tensorflow is not fork-safe.\n\n See https://github.com/tensorflow/tensorflow/issues/2448.\n\n \"\"\"\n if max_cpus > 1:\n from garage.sampler import singleton_pool\n singleton_pool.initialize(max_cpus)\n self.sess = sess or tf.Session()\n self.sess_entered = False\n self.has_setup = False\n self.plot = False\n\n self.setup_args = None\n self.train_args = None\n\n def __enter__(self):\n \"\"\"Set self.sess as the default session.\n\n Returns:\n This local runner.\n\n \"\"\"\n if tf.get_default_session() is not self.sess:\n self.sess.__enter__()\n self.sess_entered = True\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Leave session.\"\"\"\n if tf.get_default_session() is self.sess and self.sess_entered:\n self.sess.__exit__(exc_type, exc_val, exc_tb)\n self.sess_entered = False\n\n def setup(self, algo, env, sampler_cls=None, sampler_args=None):\n \"\"\"Set up runner for algorithm and environment.\n\n This method saves algo and env within runner and creates a sampler.\n\n Note:\n After setup() is called all variables in session should have been\n initialized. setup() respects existing values in session so\n policy weights can be loaded before setup().\n\n Args:\n algo (garage.np.algos.RLAlgorithm): An algorithm instance.\n env (garage.envs.GarageEnv): An environement instance.\n sampler_cls (garage.sampler.Sampler): A sampler class.\n sampler_args (dict): Arguments to be passed to sampler constructor.\n\n \"\"\"\n self.algo = algo\n self.env = env\n self.policy = self.algo.policy\n\n if sampler_args is None:\n sampler_args = {}\n\n if sampler_cls is None:\n from garage.tf.algos.batch_polopt import BatchPolopt\n if isinstance(algo, BatchPolopt):\n if self.policy.vectorized:\n from garage.tf.samplers import OnPolicyVectorizedSampler\n sampler_cls = OnPolicyVectorizedSampler\n else:\n from garage.tf.samplers import BatchSampler\n sampler_cls = BatchSampler\n else:\n from garage.tf.samplers import OffPolicyVectorizedSampler\n sampler_cls = OffPolicyVectorizedSampler\n\n self.sampler = sampler_cls(algo, env, **sampler_args)\n\n self.initialize_tf_vars()\n logger.log(self.sess.graph)\n self.has_setup = True\n\n self.setup_args = SimpleNamespace(\n sampler_cls=sampler_cls, sampler_args=sampler_args)\n\n def initialize_tf_vars(self):\n \"\"\"Initialize all uninitialized variables in session.\"\"\"\n with tf.name_scope('initialize_tf_vars'):\n uninited_set = [\n e.decode()\n for e in self.sess.run(tf.report_uninitialized_variables())\n ]\n self.sess.run(\n tf.variables_initializer([\n v for v in tf.global_variables()\n if v.name.split(':')[0] in uninited_set\n ]))\n\n def _start_worker(self):\n \"\"\"Start Plotter and Sampler workers.\"\"\"\n self.sampler.start_worker()\n if self.plot:\n from garage.tf.plotter import Plotter\n self.plotter = Plotter(self.env, self.policy)\n self.plotter.start()\n\n def _shutdown_worker(self):\n \"\"\"Shutdown Plotter and Sampler workers.\"\"\"\n self.sampler.shutdown_worker()\n if self.plot:\n self.plotter.close()\n\n def obtain_samples(self, itr, batch_size):\n \"\"\"Obtain one batch of samples.\n\n Args:\n itr(int): Index of iteration (epoch).\n batch_size(int): Number of steps in batch.\n This is a hint that the sampler may or may not respect.\n\n Returns:\n One batch of samples.\n\n \"\"\"\n if self.train_args.n_epoch_cycles == 1:\n logger.log('Obtaining samples...')\n return self.sampler.obtain_samples(itr, batch_size)\n\n def save(self, epoch, paths=None):\n \"\"\"Save snapshot of current batch.\n\n Args:\n itr(int): Index of iteration (epoch).\n paths(dict): Batch of samples after preprocessed. If None,\n no paths will be logged to the snapshot.\n\n \"\"\"\n assert self.has_setup\n\n logger.log('Saving snapshot...')\n\n params = dict()\n # Save arguments\n params['setup_args'] = self.setup_args\n params['train_args'] = self.train_args\n\n # Save states\n params['env'] = self.env\n params['algo'] = self.algo\n if paths:\n params['paths'] = paths\n params['last_epoch'] = epoch\n snapshotter.save_itr_params(epoch, params)\n\n logger.log('Saved')\n\n def restore(self, snapshot_dir, from_epoch='last'):\n \"\"\"Restore experiment from snapshot.\n\n Args:\n snapshot_dir(str): Directory of snapshot.\n from_epoch(str or int): The epoch to restore from.\n Can be 'first', 'last' or a number.\n Not applicable when snapshot_mode='last'.\n\n Returns:\n A SimpleNamespace for train()'s arguments.\n\n Examples:\n 1. Resume experiment immediately.\n with LocalRunner() as runner:\n runner.restore(snapshot_dir)\n runner.resume()\n\n 2. Resume experiment with modified training arguments.\n with LocalRunner() as runner:\n runner.restore(snapshot_dir, resume_now=False)\n runner.resume(n_epochs=20)\n\n Note:\n When resume via command line, new snapshots will be\n saved into the SAME directory if not specified.\n\n When resume programmatically, snapshot directory should be\n specify manually or through run_experiment() interface.\n\n \"\"\"\n snapshotter.snapshot_dir = snapshot_dir\n saved = snapshotter.load(from_epoch)\n\n self.setup_args = saved['setup_args']\n self.train_args = saved['train_args']\n\n self.setup(\n env=saved['env'],\n algo=saved['algo'],\n sampler_cls=self.setup_args.sampler_cls,\n sampler_args=self.setup_args.sampler_args)\n\n n_epochs = self.train_args.n_epochs\n last_epoch = saved['last_epoch']\n n_epoch_cycles = self.train_args.n_epoch_cycles\n batch_size = self.train_args.batch_size\n store_paths = self.train_args.store_paths\n pause_for_plot = self.train_args.pause_for_plot\n\n fmt = '{:<20} {:<15}'\n logger.log('Restore from snapshot saved in %s' % snapshot_dir)\n logger.log(fmt.format('Train Args', 'Value'))\n logger.log(fmt.format('n_epochs', n_epochs))\n logger.log(fmt.format('last_epoch', last_epoch))\n logger.log(fmt.format('n_epoch_cycles', n_epoch_cycles))\n logger.log(fmt.format('batch_size', batch_size))\n logger.log(fmt.format('store_paths', store_paths))\n logger.log(fmt.format('pause_for_plot', pause_for_plot))\n\n self.train_args.start_epoch = last_epoch + 1\n return copy.copy(self.train_args)\n\n def log_diagnostics(self, pause_for_plot=False):\n \"\"\"Log diagnostics.\n\n Args:\n pause_for_plot(bool): Pause for plot.\n\n \"\"\"\n logger.log('Time %.2f s' % (time.time() - self._start_time))\n logger.log('EpochTime %.2f s' % (time.time() - self._itr_start_time))\n logger.log(tabular)\n if self.plot:\n self.plotter.update_plot(self.policy, self.algo.max_path_length)\n if pause_for_plot:\n input('Plotting evaluation run: Press Enter to \" \"continue...')\n\n def train(self,\n n_epochs,\n batch_size,\n n_epoch_cycles=1,\n plot=False,\n store_paths=False,\n pause_for_plot=False):\n \"\"\"Start training.\n\n Args:\n n_epochs(int): Number of epochs.\n batch_size(int): Number of environment steps in one batch.\n n_epoch_cycles(int): Number of batches of samples in each epoch.\n This is only useful for off-policy algorithm.\n For on-policy algorithm this value should always be 1.\n plot(bool): Visualize policy by doing rollout after each epoch.\n store_paths(bool): Save paths in snapshot.\n pause_for_plot(bool): Pause for plot.\n\n Returns:\n The average return in last epoch cycle.\n\n \"\"\"\n assert self.has_setup, ('Use Runner.setup() to setup runner before '\n 'training.')\n\n # Save arguments for restore\n self.train_args = SimpleNamespace(\n n_epochs=n_epochs,\n n_epoch_cycles=n_epoch_cycles,\n batch_size=batch_size,\n plot=plot,\n store_paths=store_paths,\n pause_for_plot=pause_for_plot,\n start_epoch=0)\n\n self.plot = plot\n\n return self.algo.train(self, batch_size)\n\n def step_epochs(self):\n \"\"\"Generator for training.\n\n This function serves as a generator. It is used to separate\n services such as snapshotting, sampler control from the actual\n training loop. It is used inside train() in each algorithm.\n\n The generator initializes two variables: `self.step_itr` and\n `self.step_path`. To use the generator, these two have to be\n updated manually in each epoch, as the example shows below.\n\n Yields:\n int: The next training epoch.\n\n Examples:\n for epoch in runner.step_epochs():\n runner.step_path = runner.obtain_samples(...)\n self.train_once(...)\n runner.step_itr += 1\n\n \"\"\"\n try:\n self._start_worker()\n self._start_time = time.time()\n self.step_itr = (\n self.train_args.start_epoch * self.train_args.n_epoch_cycles)\n self.step_path = None\n\n for epoch in range(self.train_args.start_epoch,\n self.train_args.n_epochs):\n self._itr_start_time = time.time()\n with logger.prefix('epoch #%d | ' % epoch):\n yield epoch\n save_path = (self.step_path\n if self.train_args.store_paths else None)\n self.save(epoch, save_path)\n self.log_diagnostics(self.train_args.pause_for_plot)\n logger.dump_all(self.step_itr)\n tabular.clear()\n finally:\n self._shutdown_worker()\n\n def resume(self,\n n_epochs=None,\n batch_size=None,\n n_epoch_cycles=None,\n plot=None,\n store_paths=None,\n pause_for_plot=None):\n \"\"\"Resume from restored experiment.\n\n This method provides the same interface as train().\n\n If not specified, an argument will default to the\n saved arguments from the last call to train().\n\n Returns:\n The average return in last epoch cycle.\n\n \"\"\"\n assert self.train_args is not None, (\n 'You must call restore() before resume().')\n\n self.train_args.n_epochs = n_epochs or self.train_args.n_epochs\n self.train_args.batch_size = batch_size or self.train_args.batch_size\n self.train_args.n_epoch_cycles = (n_epoch_cycles\n or self.train_args.n_epoch_cycles)\n\n if plot is not None:\n self.train_args.plot = plot\n if store_paths is not None:\n self.train_args.store_paths = store_paths\n if pause_for_plot is not None:\n self.train_args.pause_for_plot = pause_for_plot\n\n return self.algo.train(self, batch_size)\n"
] |
[
[
"tensorflow.get_default_session",
"tensorflow.global_variables",
"tensorflow.report_uninitialized_variables",
"tensorflow.name_scope",
"tensorflow.Session"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
jacv050/hyperfuture
|
[
"54288230656c7a8cc0b825f9e397d690408d9e42"
] |
[
"backbone/hyrnn_nets.py"
] |
[
"\"\"\"\nNetwork definitions from https://github.com/ferrine/hyrnn\n\"\"\"\n\nimport geoopt\nimport geoopt.manifolds.stereographic.math as gmath\nimport numpy as np\nimport torch.nn\nimport torch.nn.functional\nfrom torch.cuda.amp import autocast\n\n\ndef mobius_linear(\n input,\n weight,\n bias=None,\n hyperbolic_input=True,\n hyperbolic_bias=True,\n nonlin=None,\n k=-1.0,\n):\n k = torch.tensor(k)\n if hyperbolic_input:\n output = mobius_matvec(weight, input, k=k)\n else:\n output = torch.nn.functional.linear(input, weight)\n output = gmath.expmap0(output, k=k)\n if bias is not None:\n if not hyperbolic_bias:\n bias = gmath.expmap0(bias, k=k)\n output = gmath.mobius_add(output, bias.unsqueeze(0).expand_as(output), k=k)\n if nonlin is not None:\n output = gmath.mobius_fn_apply(nonlin, output, k=k)\n output = gmath.project(output, k=k)\n return output\n\n\ndef mobius_matvec(m: torch.Tensor, x: torch.Tensor, *, k: torch.Tensor, dim=-1):\n return _mobius_matvec(m, x, k, dim=dim)\n\n\ndef _mobius_matvec(m: torch.Tensor, x: torch.Tensor, k: torch.Tensor, dim: int = -1):\n if m.dim() > 2 and dim != -1:\n raise RuntimeError(\n \"broadcasted Möbius matvec is supported for the last dim only\"\n )\n x_norm = x.norm(dim=dim, keepdim=True, p=2).clamp_min(1e-15)\n if dim != -1 or m.dim() == 2:\n # mx = torch.tensordot(x, m, [dim], [1])\n mx = torch.matmul(m, x.transpose(1, 0)).transpose(1, 0)\n else:\n mx = torch.matmul(m, x.unsqueeze(-1)).squeeze(-1)\n mx_norm = mx.norm(dim=dim, keepdim=True, p=2).clamp_min(1e-15)\n res_c = gmath.tan_k(mx_norm / x_norm * gmath.artan_k(x_norm, k), k) * (mx / mx_norm)\n cond = (mx == 0).prod(dim=dim, keepdim=True, dtype=torch.uint8)\n res_0 = torch.zeros(1, dtype=res_c.dtype, device=res_c.device)\n res = torch.where(cond, res_0, res_c)\n return res\n\n\ndef one_rnn_transform(W, h, U, x, b, k):\n W_otimes_h = gmath.mobius_matvec(W, h, k=k)\n U_otimes_x = gmath.mobius_matvec(U, x, k=k)\n Wh_plus_Ux = gmath.mobius_add(W_otimes_h, U_otimes_x, k=k)\n return gmath.mobius_add(Wh_plus_Ux, b, k=k)\n\n\ndef mobius_gru_cell(\n input: torch.Tensor,\n hx: torch.Tensor,\n weight_ih: torch.Tensor,\n weight_hh: torch.Tensor,\n bias: torch.Tensor,\n k: torch.Tensor,\n nonlin=None,\n):\n W_ir, W_ih, W_iz = weight_ih.chunk(3)\n b_r, b_h, b_z = bias\n W_hr, W_hh, W_hz = weight_hh.chunk(3)\n\n z_t = gmath.logmap0(one_rnn_transform(W_hz, hx, W_iz, input, b_z, k), k=k).sigmoid()\n r_t = gmath.logmap0(one_rnn_transform(W_hr, hx, W_ir, input, b_r, k), k=k).sigmoid()\n\n rh_t = gmath.mobius_pointwise_mul(r_t, hx, k=k)\n h_tilde = one_rnn_transform(W_hh, rh_t, W_ih, input, b_h, k)\n\n if nonlin is not None:\n h_tilde = gmath.mobius_fn_apply(nonlin, h_tilde, k=k)\n delta_h = gmath.mobius_add(-hx, h_tilde, k=k)\n h_out = gmath.mobius_add(hx, gmath.mobius_pointwise_mul(z_t, delta_h, k=k), k=k)\n return h_out\n\n\ndef mobius_gru_loop(\n input: torch.Tensor,\n h0: torch.Tensor,\n weight_ih: torch.Tensor,\n weight_hh: torch.Tensor,\n bias: torch.Tensor,\n k: torch.Tensor,\n batch_sizes=None,\n hyperbolic_input: bool = False,\n hyperbolic_hidden_state0: bool = False,\n nonlin=None,\n):\n if not hyperbolic_hidden_state0:\n hx = gmath.expmap0(h0, k=k)\n else:\n hx = h0\n if not hyperbolic_input:\n input = gmath.expmap0(input, k=k)\n outs = []\n if batch_sizes is None:\n input_unbinded = input.unbind(0)\n for t in range(input.size(0)):\n hx = mobius_gru_cell(\n input=input_unbinded[t],\n hx=hx,\n weight_ih=weight_ih,\n weight_hh=weight_hh,\n bias=bias,\n nonlin=nonlin,\n k=k,\n )\n outs.append(hx)\n outs = torch.stack(outs)\n h_last = hx\n else:\n h_last = []\n T = len(batch_sizes) - 1\n for i, t in enumerate(range(batch_sizes.size(0))):\n ix, input = input[: batch_sizes[t]], input[batch_sizes[t]:]\n hx = mobius_gru_cell(\n input=ix,\n hx=hx,\n weight_ih=weight_ih,\n weight_hh=weight_hh,\n bias=bias,\n nonlin=nonlin,\n k=k,\n )\n outs.append(hx)\n if t < T:\n hx, ht = hx[: batch_sizes[t + 1]], hx[batch_sizes[t + 1]:]\n h_last.append(ht)\n else:\n h_last.append(hx)\n h_last.reverse()\n h_last = torch.cat(h_last)\n outs = torch.cat(outs)\n return outs, h_last\n\n\nclass MobiusLinear(torch.nn.Linear):\n def __init__(\n self,\n *args,\n hyperbolic_input=True,\n hyperbolic_bias=True,\n nonlin=None,\n k=-1.0,\n fp64_hyper=True,\n **kwargs\n ):\n k = torch.tensor(k)\n super().__init__(*args, **kwargs)\n if self.bias is not None:\n if hyperbolic_bias:\n self.ball = manifold = geoopt.PoincareBall(c=k.abs())\n self.bias = geoopt.ManifoldParameter(self.bias, manifold=manifold)\n with torch.no_grad():\n # self.bias.set_(gmath.expmap0(self.bias.normal_() / 4, k=k))\n self.bias.set_(gmath.expmap0(self.bias.normal_() / 400, k=k))\n with torch.no_grad():\n # 1e-2 was the original value in the code. The updated one is from HNN++\n std = 1 / np.sqrt(2 * self.weight.shape[0] * self.weight.shape[1])\n # Actually, we divide that by 100 so that it starts really small and far from the border\n std = std / 100\n self.weight.normal_(std=std)\n self.hyperbolic_bias = hyperbolic_bias\n self.hyperbolic_input = hyperbolic_input\n self.nonlin = nonlin\n self.k = k\n self.fp64_hyper = fp64_hyper\n\n def forward(self, input):\n if self.fp64_hyper:\n input = input.double()\n else:\n input = input.float()\n with autocast(enabled=False): # Do not use fp16\n return mobius_linear(\n input,\n weight=self.weight,\n bias=self.bias,\n hyperbolic_input=self.hyperbolic_input,\n nonlin=self.nonlin,\n hyperbolic_bias=self.hyperbolic_bias,\n k=self.k,\n )\n\n def extra_repr(self):\n info = super().extra_repr()\n info += \"c={}, hyperbolic_input={}\".format(self.ball.c, self.hyperbolic_input)\n if self.bias is not None:\n info = \", hyperbolic_bias={}\".format(self.hyperbolic_bias)\n return info\n\n\nclass MobiusDist2Hyperplane(torch.nn.Module):\n def __init__(self, in_features, out_features, k=-1.0, fp64_hyper=True):\n k = torch.tensor(k)\n super().__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.ball = ball = geoopt.PoincareBall(c=k.abs())\n self.sphere = sphere = geoopt.manifolds.Sphere()\n self.scale = torch.nn.Parameter(torch.zeros(out_features))\n point = torch.randn(out_features, in_features) / 4\n point = gmath.expmap0(point, k=k)\n tangent = torch.randn(out_features, in_features)\n self.point = geoopt.ManifoldParameter(point, manifold=ball)\n self.fp64_hyper = fp64_hyper\n with torch.no_grad():\n self.tangent = geoopt.ManifoldParameter(tangent, manifold=sphere).proj_()\n\n def forward(self, input):\n if self.fp64_hyper:\n input = input.double()\n else:\n input = input.float()\n with autocast(enabled=False): # Do not use fp16\n input = input.unsqueeze(-2)\n distance = gmath.dist2plane(\n x=input, p=self.point, a=self.tangent, k=self.ball.c, signed=True\n )\n return distance * self.scale.exp()\n\n def extra_repr(self):\n return (\n \"in_features={in_features}, out_features={out_features}\"\n # \"c={ball.c}\".format(\n # **self.__dict__\n # )\n )\n"
] |
[
[
"numpy.sqrt",
"torch.cuda.amp.autocast"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tianhm/tensorflow
|
[
"ec8216568d8cd9810004067558041c11a8356685",
"ec8216568d8cd9810004067558041c11a8356685"
] |
[
"tensorflow/contrib/eager/python/datasets.py",
"tensorflow/python/keras/_impl/keras/layers/wrappers.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\"\"\"Support for tf.contrib.data when eager execution is enabled.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\n\nfrom tensorflow.contrib.data.python.util import nest\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import gen_dataset_ops\nfrom tensorflow.python.ops import resource_variable_ops\n\n_uid_counter = 0\n_uid_lock = threading.Lock()\n\n\ndef _iterator_shared_name():\n with _uid_lock:\n global _uid_counter\n uid = _uid_counter\n _uid_counter += 1\n return \"eager_iterator_{}\".format(uid)\n\n\nclass Iterator(object):\n \"\"\"An iterator producing tf.Tensor objects from a tf.contrib.data.Dataset.\"\"\"\n\n def __init__(self, dataset):\n \"\"\"Creates a new iterator over the given dataset.\n\n For example:\n ```python\n dataset = tf.contrib.data.Dataset.range(4)\n for x in Iterator(dataset):\n print(x)\n ```\n\n Args:\n dataset: A `tf.contrib.data.Dataset` object.\n\n Raises:\n RuntimeError: When invoked without eager execution enabled.\n \"\"\"\n\n if not context.in_eager_mode():\n raise RuntimeError(\n \"{} objects only make sense when eager execution is enabled\".format(\n type(self)))\n ds_variant = dataset.make_dataset_resource()\n self._output_types = dataset.output_types\n self._flat_output_types = nest.flatten(dataset.output_types)\n self._flat_output_shapes = nest.flatten(dataset.output_shapes)\n self._resource = gen_dataset_ops.iterator(\n container=\"\",\n shared_name=_iterator_shared_name(),\n output_types=self._flat_output_types,\n output_shapes=self._flat_output_shapes)\n gen_dataset_ops.make_iterator(ds_variant, self._resource)\n\n def __del__(self):\n if self._resource is not None:\n resource_variable_ops.destroy_resource_op(self._resource)\n self._resource = None\n\n def __iter__(self):\n return self\n\n def __next__(self): # For Python 3 compatibility\n return self.next()\n\n def next(self):\n \"\"\"Return the next tf.Tensor from the dataset.\"\"\"\n try:\n ret = gen_dataset_ops.iterator_get_next(\n self._resource,\n output_types=self._flat_output_types,\n output_shapes=self._flat_output_shapes)\n return nest.pack_sequence_as(self._output_types, ret)\n except errors.OutOfRangeError:\n raise StopIteration\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# pylint: disable=protected-access\n\"\"\"Wrapper layers: layers that augment the functionality of another layer.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\n\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras._impl.keras import backend as K\nfrom tensorflow.python.keras._impl.keras.engine import InputSpec\nfrom tensorflow.python.keras._impl.keras.engine import Layer\nfrom tensorflow.python.keras._impl.keras.utils.generic_utils import has_arg\nfrom tensorflow.python.layers import base as tf_base_layers\n\n\nclass Wrapper(Layer):\n \"\"\"Abstract wrapper base class.\n\n Wrappers take another layer and augment it in various ways.\n Do not use this class as a layer, it is only an abstract base class.\n Two usable wrappers are the `TimeDistributed` and `Bidirectional` wrappers.\n\n Arguments:\n layer: The layer to be wrapped.\n \"\"\"\n\n def __init__(self, layer, **kwargs):\n self.layer = layer\n # Tracks mapping of Wrapper inputs to inner layer inputs. Useful when\n # the inner layer has update ops that depend on its inputs (as opposed\n # to the inputs to the Wrapper layer).\n self._input_map = {}\n super(Wrapper, self).__init__(**kwargs)\n\n def build(self, input_shape=None):\n self.built = True\n\n @property\n def activity_regularizer(self):\n if hasattr(self.layer, 'activity_regularizer'):\n return self.layer.activity_regularizer\n else:\n return None\n\n @property\n def trainable_weights(self):\n return self.layer.trainable_weights\n\n @property\n def non_trainable_weights(self):\n return self.layer.non_trainable_weights\n\n @property\n def updates(self):\n if hasattr(self.layer, 'updates'):\n return self.layer.updates\n return []\n\n def get_updates_for(self, inputs=None):\n # If the wrapper modifies the inputs, use the modified inputs to\n # get the updates from the inner layer.\n inner_inputs = inputs\n if inputs is not None:\n uid = tf_base_layers._object_list_uid(inputs)\n if uid in self._input_map:\n inner_inputs = self._input_map[uid]\n\n updates = self.layer.get_updates_for(inner_inputs)\n updates += super(Wrapper, self).get_updates_for(inputs)\n return updates\n\n @property\n def losses(self):\n if hasattr(self.layer, 'losses'):\n return self.layer.losses\n return []\n\n def get_losses_for(self, inputs=None):\n if inputs is None:\n losses = self.layer.get_losses_for(None)\n return losses + super(Wrapper, self).get_losses_for(None)\n return super(Wrapper, self).get_losses_for(inputs)\n\n @property\n def constraints(self):\n return self.layer.constraints\n\n def get_weights(self):\n return self.layer.get_weights()\n\n def set_weights(self, weights):\n self.layer.set_weights(weights)\n\n def get_config(self):\n config = {\n 'layer': {\n 'class_name': self.layer.__class__.__name__,\n 'config': self.layer.get_config()\n }\n }\n base_config = super(Wrapper, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n from tensorflow.python.keras._impl.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top\n layer = deserialize_layer(\n config.pop('layer'), custom_objects=custom_objects)\n return cls(layer, **config)\n\n\nclass TimeDistributed(Wrapper):\n \"\"\"This wrapper allows to apply a layer to every temporal slice of an input.\n\n The input should be at least 3D, and the dimension of index one\n will be considered to be the temporal dimension.\n\n Consider a batch of 32 samples,\n where each sample is a sequence of 10 vectors of 16 dimensions.\n The batch input shape of the layer is then `(32, 10, 16)`,\n and the `input_shape`, not including the samples dimension, is `(10, 16)`.\n\n You can then use `TimeDistributed` to apply a `Dense` layer\n to each of the 10 timesteps, independently:\n\n ```python\n # as the first layer in a model\n model = Sequential()\n model.add(TimeDistributed(Dense(8), input_shape=(10, 16)))\n # now model.output_shape == (None, 10, 8)\n ```\n\n The output will then have shape `(32, 10, 8)`.\n\n In subsequent layers, there is no need for the `input_shape`:\n\n ```python\n model.add(TimeDistributed(Dense(32)))\n # now model.output_shape == (None, 10, 32)\n ```\n\n The output will then have shape `(32, 10, 32)`.\n\n `TimeDistributed` can be used with arbitrary layers, not just `Dense`,\n for instance with a `Conv2D` layer:\n\n ```python\n model = Sequential()\n model.add(TimeDistributed(Conv2D(64, (3, 3)),\n input_shape=(10, 299, 299, 3)))\n ```\n\n Arguments:\n layer: a layer instance.\n \"\"\"\n\n def __init__(self, layer, **kwargs):\n super(TimeDistributed, self).__init__(layer, **kwargs)\n self.supports_masking = True\n\n def build(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n assert len(input_shape) >= 3\n self.input_spec = InputSpec(shape=input_shape)\n child_input_shape = [input_shape[0]] + input_shape[2:]\n if not self.layer.built:\n self.layer.build(child_input_shape)\n self.layer.built = True\n super(TimeDistributed, self).build()\n self.built = True\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n child_input_shape = tensor_shape.TensorShape([input_shape[0]] +\n input_shape[2:])\n child_output_shape = self.layer._compute_output_shape( # pylint: disable=protected-access\n child_input_shape).as_list()\n timesteps = input_shape[1]\n return tensor_shape.TensorShape([child_output_shape[0], timesteps] +\n child_output_shape[1:])\n\n def call(self, inputs, training=None, mask=None):\n kwargs = {}\n if has_arg(self.layer.call, 'training'):\n kwargs['training'] = training\n uses_learning_phase = False # pylint: disable=redefined-outer-name\n\n input_shape = K.int_shape(inputs)\n if input_shape[0]:\n # batch size matters, use rnn-based implementation\n def step(x, _):\n global uses_learning_phase # pylint: disable=global-variable-undefined\n output = self.layer.call(x, **kwargs)\n if hasattr(output, '_uses_learning_phase'):\n uses_learning_phase = (output._uses_learning_phase or\n uses_learning_phase)\n return output, []\n\n _, outputs, _ = K.rnn(\n step,\n inputs,\n initial_states=[],\n unroll=False)\n y = outputs\n else:\n # No batch size specified, therefore the layer will be able\n # to process batches of any size.\n # We can go with reshape-based implementation for performance.\n input_length = input_shape[1]\n if not input_length:\n input_length = K.shape(inputs)[1]\n # Shape: (num_samples * timesteps, ...). And track the\n # transformation in self._input_map.\n input_uid = tf_base_layers._object_list_uid(inputs)\n inputs = K.reshape(inputs, (-1,) + input_shape[2:])\n self._input_map[input_uid] = inputs\n # (num_samples * timesteps, ...)\n y = self.layer.call(inputs, **kwargs)\n if hasattr(y, '_uses_learning_phase'):\n uses_learning_phase = y._uses_learning_phase\n # Shape: (num_samples, timesteps, ...)\n output_shape = self._compute_output_shape(input_shape).as_list()\n y = K.reshape(y, (-1, input_length) + tuple(output_shape[2:]))\n\n # Apply activity regularizer if any:\n if (hasattr(self.layer, 'activity_regularizer') and\n self.layer.activity_regularizer is not None):\n regularization_loss = self.layer.activity_regularizer(y)\n self.add_loss(regularization_loss, inputs)\n\n if uses_learning_phase:\n y._uses_learning_phase = True\n return y\n\n\nclass Bidirectional(Wrapper):\n \"\"\"Bidirectional wrapper for RNNs.\n\n Arguments:\n layer: `Recurrent` instance.\n merge_mode: Mode by which outputs of the\n forward and backward RNNs will be combined.\n One of {'sum', 'mul', 'concat', 'ave', None}.\n If None, the outputs will not be combined,\n they will be returned as a list.\n\n Raises:\n ValueError: In case of invalid `merge_mode` argument.\n\n Examples:\n\n ```python\n model = Sequential()\n model.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5,\n 10)))\n model.add(Bidirectional(LSTM(10)))\n model.add(Dense(5))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop')\n ```\n \"\"\"\n\n def __init__(self, layer, merge_mode='concat', weights=None, **kwargs):\n super(Bidirectional, self).__init__(layer, **kwargs)\n if merge_mode not in ['sum', 'mul', 'ave', 'concat', None]:\n raise ValueError('Invalid merge mode. '\n 'Merge mode should be one of '\n '{\"sum\", \"mul\", \"ave\", \"concat\", None}')\n self.forward_layer = copy.copy(layer)\n config = layer.get_config()\n config['go_backwards'] = not config['go_backwards']\n self.backward_layer = layer.__class__.from_config(config)\n self.forward_layer.name = 'forward_' + self.forward_layer.name\n self.backward_layer.name = 'backward_' + self.backward_layer.name\n self.merge_mode = merge_mode\n if weights:\n nw = len(weights)\n self.forward_layer.initial_weights = weights[:nw // 2]\n self.backward_layer.initial_weights = weights[nw // 2:]\n self.stateful = layer.stateful\n self.return_sequences = layer.return_sequences\n self.supports_masking = True\n\n def get_weights(self):\n return self.forward_layer.get_weights() + self.backward_layer.get_weights()\n\n def set_weights(self, weights):\n nw = len(weights)\n self.forward_layer.set_weights(weights[:nw // 2])\n self.backward_layer.set_weights(weights[nw // 2:])\n\n def _compute_output_shape(self, input_shape):\n input_shape = tuple(tensor_shape.TensorShape(input_shape).as_list())\n if self.merge_mode in ['sum', 'ave', 'mul']:\n return self.forward_layer._compute_output_shape(input_shape) # pylint: disable=protected-access\n elif self.merge_mode == 'concat':\n shape = self.forward_layer._compute_output_shape(input_shape).as_list() # pylint: disable=protected-access\n shape[-1] *= 2\n return tensor_shape.TensorShape(shape)\n elif self.merge_mode is None:\n shape = self.forward_layer._compute_output_shape(input_shape) # pylint: disable=protected-access\n return [shape, copy.copy(shape)]\n\n def call(self, inputs, training=None, mask=None):\n kwargs = {}\n if has_arg(self.layer.call, 'training'):\n kwargs['training'] = training\n if has_arg(self.layer.call, 'mask'):\n kwargs['mask'] = mask\n\n y = self.forward_layer.call(inputs, **kwargs)\n y_rev = self.backward_layer.call(inputs, **kwargs)\n if self.return_sequences:\n y_rev = K.reverse(y_rev, 1)\n if self.merge_mode == 'concat':\n output = K.concatenate([y, y_rev])\n elif self.merge_mode == 'sum':\n output = y + y_rev\n elif self.merge_mode == 'ave':\n output = (y + y_rev) / 2\n elif self.merge_mode == 'mul':\n output = y * y_rev\n elif self.merge_mode is None:\n output = [y, y_rev]\n\n # Properly set learning phase\n if 0 < self.layer.dropout + self.layer.recurrent_dropout:\n if self.merge_mode is None:\n for out in output:\n out._uses_learning_phase = True\n else:\n output._uses_learning_phase = True\n return output\n\n def reset_states(self):\n self.forward_layer.reset_states()\n self.backward_layer.reset_states()\n\n def build(self, input_shape):\n with K.name_scope(self.forward_layer.name):\n self.forward_layer.build(input_shape)\n with K.name_scope(self.backward_layer.name):\n self.backward_layer.build(input_shape)\n self.built = True\n\n def compute_mask(self, inputs, mask):\n if self.return_sequences:\n if not self.merge_mode:\n return [mask, mask]\n else:\n return mask\n else:\n return None\n\n @property\n def trainable_weights(self):\n if hasattr(self.forward_layer, 'trainable_weights'):\n return (self.forward_layer.trainable_weights +\n self.backward_layer.trainable_weights)\n return []\n\n @property\n def non_trainable_weights(self):\n if hasattr(self.forward_layer, 'non_trainable_weights'):\n return (self.forward_layer.non_trainable_weights +\n self.backward_layer.non_trainable_weights)\n return []\n\n @property\n def updates(self):\n if hasattr(self.forward_layer, 'updates'):\n return self.forward_layer.updates + self.backward_layer.updates\n return []\n\n @property\n def losses(self):\n if hasattr(self.forward_layer, 'losses'):\n return self.forward_layer.losses + self.backward_layer.losses\n return []\n\n @property\n def constraints(self):\n constraints = {}\n if hasattr(self.forward_layer, 'constraints'):\n constraints.update(self.forward_layer.constraints)\n constraints.update(self.backward_layer.constraints)\n return constraints\n\n def get_config(self):\n config = {'merge_mode': self.merge_mode}\n base_config = super(Bidirectional, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n"
] |
[
[
"tensorflow.contrib.data.python.util.nest.pack_sequence_as",
"tensorflow.contrib.data.python.util.nest.flatten",
"tensorflow.python.ops.resource_variable_ops.destroy_resource_op",
"tensorflow.python.ops.gen_dataset_ops.iterator_get_next",
"tensorflow.python.eager.context.in_eager_mode",
"tensorflow.python.ops.gen_dataset_ops.make_iterator"
],
[
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.keras._impl.keras.backend.name_scope",
"tensorflow.python.keras._impl.keras.engine.InputSpec",
"tensorflow.python.keras._impl.keras.backend.rnn",
"tensorflow.python.keras._impl.keras.backend.shape",
"tensorflow.python.keras._impl.keras.backend.concatenate",
"tensorflow.python.layers.base._object_list_uid",
"tensorflow.python.keras._impl.keras.backend.reverse",
"tensorflow.python.keras._impl.keras.backend.int_shape",
"tensorflow.python.keras._impl.keras.utils.generic_utils.has_arg",
"tensorflow.python.keras._impl.keras.backend.reshape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.2",
"2.9",
"1.5",
"1.7",
"2.5",
"2.8",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Hourout/tensordata
|
[
"cbef6742ee0d3bfc4b886358fc01618bb5b63603"
] |
[
"tensordata/report/p2peye/_p2peye.py"
] |
[
"import io\nimport time\nimport datetime\n\nimport requests\nimport pandas as pd\n\n__all__ =['rating', 'problem_platform']\n\ndef rating(date=None):\n \"\"\"P2peye comprehensive rating and display results.\n \n from https://www.p2peye.com\n \n Args:\n date: if None, download latest data, if like '201812', that download month data.\n Returns:\n DataFrame\n \"\"\"\n start = time.time()\n if date is None:\n date = str(pd.to_datetime(datetime.datetime.now())-pd.DateOffset(months=1))[:7].replace('-', '')\n assert (isinstance(date, str) and len(date)==6), \"`date` shoule format '201812' or None\"\n url_txt = 'https://raw.githubusercontent.com/Hourout/datasets/master/report/p2peye/rating/p2peye_rating'+date+'.txt'\n s = requests.get(url_txt).content\n data = pd.read_csv(io.StringIO(s.decode('utf-8')))\n print('p2peye rating dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60))\n return data\n\ndef problem_platform(date=None, days=7):\n \"\"\"P2peye problem platform and display results.\n \n from https://www.p2peye.com\n \n Args:\n date: if None, download latest data, if like '2018-12-01', that download month data.\n days: latest (date-days) day data.\n Returns:\n DataFrame\n \"\"\"\n start = time.time()\n if date is None:\n date = str(pd.to_datetime(datetime.datetime.now()).floor('d'))[:10]\n assert (isinstance(date, str) and len(date)==10), \"`date` shoule format '2018-12-01' or None\"\n date = pd.to_datetime(date)\n update = date-pd.DateOffset(days=days)\n url_txt = 'https://raw.githubusercontent.com/Hourout/datasets/master/report/p2peye/problem_platform/problem_platform.txt'\n s = requests.get(url_txt).content\n data = pd.read_csv(io.StringIO(s.decode('utf-8')), parse_dates=['问题发生时间'])\n data = data[(data['问题发生时间']<=date)&(data['问题发生时间']>update)].reset_index(drop=True)\n print('p2peye problem platform dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60))\n return data\n"
] |
[
[
"pandas.to_datetime",
"pandas.DateOffset"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"0.19",
"0.24",
"0.20",
"1.0",
"0.25"
],
"scipy": [],
"tensorflow": []
}
] |
trisct/DeepSDF
|
[
"85e0cf413544244737fe2237f9549c0d4e946745"
] |
[
"pyrender_render.py"
] |
[
"import numpy as np\nimport trimesh\nimport pyrender\nimport matplotlib.pyplot as plt\nimport math\nfrom tqdm import tqdm\nimport os\nimport torch\nimport torchvision\nimport glob\n\ndef render_one(mesh_list, steps, save_name, save_path, resolution, need_video=False):\n \"\"\"\n mesh: pyrender.mesh.Mesh\n A pyrender.mesh.Mesh object\n steps: int\n number of steps in one horizontal revolution\n save_path: str\n path to save color and depth image (saved as numpy arrays).\n mode: str, either 'light' or 'albedo'\n if 'light', then render with light objects\n if 'albedo', then render with only ambient lights\n resolution: tuple of 2: (res_h, res_w)\n\n ----\n file saving:\n This files save the color image, the depth image, the camera pose and the camera projection matrix\n \n color image: saved as\n [save_path]/[save_name]/[save_name]_[rotate_deg]_color.npy\n depth image: saved as\n [save_path]/[save_name]/[save_name]_[rotate_deg]_depth.npy\n camera pose: saved as\n [save_path]/[save_name]/[save_name]_[rotate_deg]_campose.npy\n projection matrix: saved as\n [save_path]/[save_name]/[save_name]_projection.npy\n \"\"\"\n print(f'Starting to render one, which will be saved to {os.path.join(save_path, save_name)}.')\n if not os.path.exists(os.path.join(save_path, save_name)):\n os.system(f'mkdir -p {os.path.join(save_path, save_name)}')\n\n # resolution\n res_h, res_w = resolution\n\n # creating nodes\n # mesh\n node_mesh_list = []\n for mesh in mesh_list:\n #mesh = pyrender.Mesh.from_trimesh(mesh)\n node_mesh_list.append( pyrender.Node(mesh=mesh, matrix=np.eye(4)) )\n\n # directional light\n dir_light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=2.0)\n node_light = pyrender.Node(light=dir_light, matrix=np.eye(4))\n\n # perspective cameras\n pers_cam = pyrender.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1)\n node_cam = pyrender.Node(camera=pers_cam, matrix=np.eye(4))\n\n # scene\n scene = pyrender.Scene(ambient_light=[1., 1., 1.], bg_color=[1., 1., 1.])\n for node_mesh in node_mesh_list:\n scene.add_node(node_mesh)\n scene.add_node(node_light)\n scene.add_node(node_cam)\n \n\n offscr_renderer = pyrender.OffscreenRenderer(viewport_width=res_h, viewport_height=res_w, point_size=3.)\n \n \n # for outputting video\n if need_video:\n color_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8)\n depth_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8)\n albedo_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8)\n \n deg_interval = 720 / steps\n \n for i, angle_i in enumerate(range(steps)):\n print(f'Showing angle {angle_i}')\n angle_deg = int(deg_interval * angle_i)\n angle_rad = angle_deg * math.pi / 180\n\n s = math.sin(angle_rad)\n c = math.cos(angle_rad)\n\n camera_pose = np.array([\n [ c, 0.0, s, 2*s],\n [0.0, -1.0, 0.0, 0.0],\n [ s, 0.0, -c, -2*c],\n [0.0, 0.0, 0.0, 1.0]])\n\n pitch_angle_rad = 30 * math.pi / 180\n s_pitch = math.sin(pitch_angle_rad)\n c_pitch = math.cos(pitch_angle_rad)\n\n\n # rendering\n scene.set_pose(node_cam, pose=camera_pose)\n color, depth = offscr_renderer.render(scene) \n scene.remove_node(node_light)\n albedo, _ = offscr_renderer.render(scene)\n scene.add_node(node_light)\n\t\t\n #plt.imshow(color)\n #plt.show()\n\t\t\n # making video\n if need_video:\n color_video[i] = torch.from_numpy(color.copy())\n \n depth_pt = torch.from_numpy(depth.copy())\n depth_scaled = (depth_pt - depth_pt[depth_pt !=0].min()) / (depth_pt[depth_pt != 0].max() - depth_pt[depth_pt != 0].min()) * 255\n depth_scaled = torch.where(depth_pt != 0., depth_scaled, torch.zeros_like(depth_scaled))\n \n depth_video[i] = depth_scaled.int().unsqueeze(dim=-1).expand(-1, -1, 3)\n albedo_video[i] = torch.from_numpy(albedo.copy())\n\n \n #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_color'), color)\n #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_depth'), depth)\n #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_albedo'), albedo)\n #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_campose'), camera_pose)\n\n #plt.imshow(color)\n #plt.savefig(f'{save_name}_color_{angle_i}.png', bbox_inches='tight')\n #plt.clf()\n #plt.show()\n\n #plt.imshow(depth)\n #plt.show()\n \n #plt.imshow(albedo)\n #plt.show()\n \n \n #np.save( os.path.join(save_path, save_name, f'{save_name}_projection'), node_cam.camera.get_projection_matrix())\n #print(node_cam.camera.get_projection_matrix())\n \n if need_video:\n final_video = torch.cat([color_video, depth_video], dim=2)\n torchvision.io.write_video( os.path.join(save_path, save_name, f'{save_name}_rendervideo_color.mp4'), color_video, fps=30)\n torchvision.io.write_video( os.path.join(save_path, save_name, f'{save_name}_rendervideo_depth.mp4'), depth_video, fps=30)\n \n \n\n\nif __name__ == '__main__':\n # headless rendering\n os.environ['PYOPENGL_PLATFORM']='egl'\n source_folder = '02691156'\n\n # steps\n steps = 180\n\n file_list = ['0676', '0775', '1314', '0411', '0447', '1441', '0993', '0671']\n \n for frame_id in file_list:\n file_name = glob.glob(f'*{frame_id}*.ply')[0]\n os.system(f'python ~/.dev_apps/simplemesh/simplemesh.py --input {file_name} -n.85 --output {file_name[:-4]+\"_norm.ply\"}')\n pcd = trimesh.load(file_name[:-4]+\"_norm.ply\")\n\t\n pcd_pyr = pyrender.Mesh.from_points(pcd.vertices, colors=pcd.colors)\n \n \n render_one([pcd_pyr], steps=steps, save_name=file_name[:-4]+'_render', save_path='videos', resolution=(512, 512), need_video=True)\n"
] |
[
[
"torch.cat",
"torch.zeros",
"numpy.eye",
"torch.zeros_like",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tlambert-forks/pyclesperanto_prototype
|
[
"aea964a75e691f19b7753040daa8b276d57ccf36",
"65bc3035d3b2b61a2722c93b95bae310bfbd190e"
] |
[
"pyclesperanto_prototype/_tier0/_pycl.py",
"tests/test_copy_slice.py"
] |
[
"import os\nimport sys\n\nimport numpy as np\nimport pyopencl as cl\nfrom pyopencl import characterize\nfrom pyopencl import array\nfrom ._device import get_device\n\n\"\"\" Below here, vendored from GPUtools\nCopyright (c) 2016, Martin Weigert\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of gputools nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\n\n\n\n\ncl_image_datatype_dict = {\n cl.channel_type.FLOAT: np.float32,\n cl.channel_type.UNSIGNED_INT8: np.uint8,\n cl.channel_type.UNSIGNED_INT16: np.uint16,\n cl.channel_type.SIGNED_INT8: np.int8,\n cl.channel_type.SIGNED_INT16: np.int16,\n cl.channel_type.SIGNED_INT32: np.int32,\n}\n\ncl_image_datatype_dict.update(\n {dtype: cltype for cltype, dtype in list(cl_image_datatype_dict.items())}\n)\n\ncl_buffer_datatype_dict = {\n np.bool: \"bool\",\n np.uint8: \"uchar\",\n np.uint16: \"ushort\",\n np.uint32: \"uint\",\n np.uint64: \"ulong\",\n np.int8: \"char\",\n np.int16: \"short\",\n np.int32: \"int\",\n np.int64: \"long\",\n np.float32: \"float\",\n np.complex64: \"cfloat_t\",\n}\n\n\nif characterize.has_double_support(get_device().device):\n cl_buffer_datatype_dict[np.float64] = \"double\"\n\n\ndef abspath(myPath):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n\n try:\n # PyInstaller creates a temp folder and stores path in _MEIPASS\n base_path = sys._MEIPASS\n return os.path.join(base_path, os.path.basename(myPath))\n except Exception:\n base_path = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(base_path, myPath)\n\n\ndef assert_supported_ndarray_type(dtype):\n # make sure it works for e.g. np.float32 and np.dtype(np.float32)\n dtype = getattr(dtype, \"type\", dtype)\n if dtype not in cl_buffer_datatype_dict:\n raise KeyError(\"dtype %s not supported \" % dtype)\n\n\ndef assert_bufs_type(mytype, *bufs):\n if not all([b.dtype.type == mytype for b in bufs]):\n raise TypeError(\n \"all data type of buffer(s) should be %s! but are %s\"\n % (mytype, str([b.dtype.type for b in bufs]))\n )\n\n\ndef _wrap_OCLArray(cls):\n \"\"\"\n WRAPPER\n \"\"\"\n\n def prepare(arr):\n return np.require(arr, None, \"C\")\n\n @classmethod\n def from_array(cls, arr, *args, **kwargs):\n assert_supported_ndarray_type(arr.dtype.type)\n queue = get_device().queue\n return array.to_device(queue, prepare(arr), *args, **kwargs)\n\n @classmethod\n def empty(cls, shape, dtype=np.float32):\n assert_supported_ndarray_type(dtype)\n queue = get_device().queue\n return array.empty(queue, shape, dtype)\n\n @classmethod\n def empty_like(cls, arr):\n assert_supported_ndarray_type(arr.dtype.type)\n return cls.empty(arr.shape, arr.dtype.type)\n\n @classmethod\n def zeros(cls, shape, dtype=np.float32):\n assert_supported_ndarray_type(dtype)\n queue = get_device().queue\n return array.zeros(queue, shape, dtype)\n\n @classmethod\n def zeros_like(cls, arr):\n assert_supported_ndarray_type(arr.dtype.type)\n queue = get_device().queue\n return array.zeros(queue, arr.shape, arr.dtype.type)\n\n def copy_buffer(self, buf, **kwargs):\n queue = get_device().queue\n return cl.enqueue_copy(queue, self.data, buf.data, **kwargs)\n\n def write_array(self, arr, **kwargs):\n assert_supported_ndarray_type(arr.dtype.type)\n queue = get_device().queue\n return cl.enqueue_copy(queue, self.data, prepare(arr), **kwargs)\n\n def copy_image(self, img, **kwargs):\n queue = get_device().queue\n return cl.enqueue_copy(\n queue,\n self.data,\n img,\n offset=0,\n origin=(0,) * len(img.shape),\n region=img.shape,\n **kwargs,\n )\n\n def wrap_module_func(mod, f):\n def func(self, *args, **kwargs):\n return getattr(mod, f)(self, *args, **kwargs)\n\n return func\n\n cls.from_array = from_array\n cls.empty = empty\n cls.empty_like = empty_like\n cls.zeros = zeros\n cls.zeros_like = zeros_like\n cls.copy_buffer = copy_buffer\n cls.copy_image = copy_image\n cls.write_array = write_array\n\n cls.__array__ = cls.get\n\n def add(x1, x2):\n if isinstance(x2, (int, float)) :\n from .._tier1 import add_image_and_scalar\n return add_image_and_scalar(x1, scalar=x2)\n else:\n from .._tier1 import add_images_weighted\n return add_images_weighted(x1, x2)\n cls.__add__ = add\n\n def iadd(x1, x2):\n from .._tier1 import copy\n temp = copy(x1)\n if isinstance(x2, (int, float)) :\n from .._tier1 import add_image_and_scalar\n return add_image_and_scalar(temp, x1, scalar=x2)\n else:\n from .._tier1 import add_images_weighted\n return add_images_weighted(temp, x2, x1)\n cls.__iadd__ = iadd\n\n def sub(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import add_image_and_scalar\n return add_image_and_scalar(x1, scalar=-x2)\n else:\n from .._tier1 import add_images_weighted\n return add_images_weighted(x1, x2, factor2=-1)\n cls.__sub__ = sub\n\n def isub(x1, x2):\n from .._tier1 import copy\n temp = copy(x1)\n if isinstance(x2, (int, float)) :\n from .._tier1 import add_image_and_scalar\n return add_image_and_scalar(temp, x1, scalar=-x2)\n else:\n from .._tier1 import add_images_weighted\n return add_images_weighted(temp, x2, x1, factor2=-1)\n cls.__isub__ = isub\n\n def mul(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import multiply_image_and_scalar\n return multiply_image_and_scalar(x1, scalar=x2)\n else:\n from .._tier1 import multiply_images\n return multiply_images(x1, x2)\n cls.__mul__ = mul\n\n def imul(x1, x2):\n from .._tier1 import copy\n temp = copy(x1)\n if isinstance(x2, (int, float)):\n from .._tier1 import multiply_image_and_scalar\n return multiply_image_and_scalar(temp, x1, scalar=x2)\n else:\n from .._tier1 import multiply_images\n return multiply_images(temp, x2, x1)\n\n cls.__imul__ = imul\n\n def div(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import multiply_image_and_scalar\n return multiply_image_and_scalar(x1, scalar=1.0 / x2)\n else:\n from .._tier1 import divide_images\n return divide_images(x1, x2)\n cls.__div__ = div\n cls.__truediv__ = div\n\n def idiv(x1, x2):\n from .._tier1 import copy\n temp = copy(x1)\n if isinstance(x2, (int, float)):\n from .._tier1 import multiply_image_and_scalar\n return multiply_image_and_scalar(temp, x1, scalar=1.0 / x2)\n else:\n from .._tier1 import divide_images\n return divide_images(temp, x2, x1)\n cls.__idiv__ = idiv\n cls.__itruediv__ = idiv\n\n def gt(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import greater_constant\n return greater_constant(x1, constant=x2)\n else:\n from .._tier1 import greater\n return greater(x1, x2)\n cls.__gt__ = gt\n\n def ge(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import greater_or_equal_constant\n return greater_or_equal_constant(x1, constant=x2)\n else:\n from .._tier1 import greater_or_equal\n return greater_or_equal(x1, x2)\n cls.__ge__ = ge\n\n def lt(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import smaller_constant\n return smaller_constant(x1, constant=x2)\n else:\n from .._tier1 import smaller\n return smaller(x1, x2)\n cls.__lt__ = lt\n\n def le(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import smaller_or_equal_constant\n return smaller_or_equal_constant(x1, constant=x2)\n else:\n from .._tier1 import smaller_or_equal\n return smaller_or_equal(x1, x2)\n cls.__le__ = le\n\n def eq(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import equal_constant\n return equal_constant(x1, constant=x2)\n else:\n from .._tier1 import equal\n return equal(x1, x2)\n cls.__eq__ = eq\n\n def ne(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import not_equal_constant\n return not_equal_constant(x1, constant=x2)\n else:\n from .._tier1 import not_equal\n return not_equal(x1, x2)\n cls.__ne__ = ne\n\n def pos(x1):\n from .._tier1 import copy\n return copy(x1)\n cls.__pos__ = pos\n\n def neg(x1):\n from .._tier1 import subtract_image_from_scalar\n return subtract_image_from_scalar(x1, scalar=0)\n cls.__neg__ = neg\n\n def pow(x1, x2):\n if isinstance(x2, (int, float)):\n from .._tier1 import power\n return power(x1, exponent=x2)\n else:\n from .._tier1 import power_images\n return power_images(x1, x2)\n cls.__pow__ = pow\n\n def ipow(x1, x2):\n from .._tier1 import copy\n temp = copy(x1)\n if isinstance(x2, (int, float)):\n from .._tier1 import power\n return power(temp, x1, exponent=x2)\n else:\n from .._tier1 import power_images\n return power_images(temp, x2, x1)\n cls.__ipow__ = ipow\n\n def min(self, axis=None, out=None):\n from .._tier2 import minimum_of_all_pixels\n from .._tier1 import minimum_x_projection\n from .._tier1 import minimum_y_projection\n from .._tier1 import minimum_z_projection\n\n if axis==0:\n result = minimum_z_projection(self)\n elif axis==1:\n result = minimum_y_projection(self)\n elif axis==2:\n result = minimum_x_projection(self)\n elif axis is None:\n result = minimum_of_all_pixels(self)\n else:\n raise ValueError(\"Axis \" + axis + \" not supported\")\n if out is not None:\n np.copyto(out, result.get().astype(out.dtype))\n return result\n cls.min = min\n\n def max(self, axis=None, out=None):\n from .._tier2 import maximum_of_all_pixels\n from .._tier1 import maximum_x_projection\n from .._tier1 import maximum_y_projection\n from .._tier1 import maximum_z_projection\n\n if axis==0:\n result = maximum_z_projection(self)\n elif axis==1:\n result = maximum_y_projection(self)\n elif axis==2:\n result = maximum_x_projection(self)\n elif axis is None:\n result = maximum_of_all_pixels(self)\n else:\n raise ValueError(\"Axis \" + axis + \" not supported\")\n if out is not None:\n np.copyto(out, result.get().astype(out.dtype))\n return result\n cls.max = max\n\n def sum(self, axis=None, out=None):\n from .._tier2 import sum_of_all_pixels\n from .._tier1 import sum_x_projection\n from .._tier1 import sum_y_projection\n from .._tier1 import sum_z_projection\n\n if axis==0:\n result = sum_z_projection(self)\n elif axis==1:\n result = sum_y_projection(self)\n elif axis==2:\n result = sum_x_projection(self)\n elif axis is None:\n result = sum_of_all_pixels(self)\n else:\n raise ValueError(\"Axis \" + axis + \" not supported\")\n if out is not None:\n np.copyto(out, result.get().astype(out.dtype))\n return result\n cls.sum = sum\n\n cls._former_get = cls._get\n def _cust_get(self, queue=None, ary=None, async_=None, **kwargs):\n if not isinstance(queue, cl.CommandQueue):\n queue = None\n return self._former_get(queue, ary, async_, **kwargs)\n cls._get = _cust_get\n\n cls._former_get_item = cls.__getitem__\n\n def _cust_get_item(self, index):\n try:\n return self._former_get_item(index)\n except IndexError:\n raise IndexError(\"Accessing individual GPU-backed pixels is not fully supported. If you work in napari, use the menu Plugins > clEsperanto > Make labels editable. If you work in python, use numpy.asarray(image) to retrieve a fully accessible copy of the image.\")\n cls.__getitem__ = _cust_get_item\n\n # todo:\n # __floordiv__(x1, x2)\n # __mod__(x1, x2)\n # __matmul__(x1, x2)\n # __inv__(x1, x2)\n # __invert__(x1, x2)\n # __lshift__(x1, x2)\n # __rshift__(x1, x2)\n # and, or, xor\n\n for f in [\"dot\", \"vdot\"]:\n setattr(cls, f, wrap_module_func(array, f))\n\n # for f in dir(cl_math):\n # if callable(getattr(cl.cl_math, f)):\n # setattr(cls, f, wrap_module_func(cl.cl_math, f))\n\n # cls.sum = sum\n cls.__name__ = str(\"OCLArray\")\n return cls\n\n\nOCLArray = _wrap_OCLArray(array.Array)\n\nclass _OCLImage:\n def __init__(self, cl_image : cl.Image):\n self.data = cl_image\n self.shape = cl_image.shape[::-1]\n self.dtype = cl_image.dtype\n",
"import pyclesperanto_prototype as cle\nimport numpy as np\n\ndef test_copy_slice_from_3d():\n\n test1 = cle.push(np.asarray([\n [\n [1, 4],\n [0, 4]\n ],\n [\n [1, 3],\n [1, 2]\n ]\n ]).T)\n\n test2 = cle.create((2, 2))\n cle.copy_slice(test1, test2, 0)\n\n print(test2)\n a = cle.pull(test2)\n assert (np.min(a) == 0)\n assert (np.max(a) == 1)\n assert (np.mean(a) == 0.75)\n\n\ndef test_copy_slice_to_3d():\n test1 = cle.push(np.asarray([\n [3, 4],\n [4, 5]\n ]))\n\n test2 = cle.create((2, 2, 2))\n cle.set(test2, 0)\n cle.copy_slice(test1, test2, 0)\n\n print(test2)\n a = cle.pull(test2)\n assert (np.min(a) == 0)\n assert (np.max(a) == 5)\n assert (np.mean(a) == 2)\n\ndef test_copy_slice_to3d_with_one_slice():\n test1 = cle.push(np.asarray([\n [3, 4, 6],\n [4, 5, 2]\n ]))\n\n print(test1)\n print(\"shape test1 \" + str(test1.shape))\n\n test2 = cle.create((1, 2, 3))\n print(\"shape test2 \" + str(test2.shape))\n print(test2)\n\n cle.copy_slice(test1, test2, 0)\n print(test2)\n\n a = cle.pull(test2)\n assert (np.min(a) == 2)\n assert (np.max(a) == 6)\n assert (np.mean(a) == 4)\n\ndef test_copy_slice_to3d_with_one_slice_zyx():\n test1 = cle.push(np.asarray([\n [3, 4, 6],\n [4, 5, 2]\n ]))\n\n print(test1)\n print(\"shape test1 \" + str(test1.shape))\n\n test2 = cle.create((1, 2, 3))\n print(\"shape test2 \" + str(test2.shape))\n print(test2)\n\n cle.copy_slice(test1, test2, 0)\n print(test2)\n\n a = cle.pull(test2)\n assert (np.min(a) == 2)\n assert (np.max(a) == 6)\n assert (np.mean(a) == 4)\n\ndef test_copy_slice_mini_y():\n np_input = np.asarray([[1], [2], [3], [4]])\n\n gpu_input = cle.push(np_input)\n gpu_output = cle.create((1, 4, 1))\n\n cle.copy_slice(gpu_input, gpu_output, 0)\n print(gpu_output)\n\n a = cle.pull(gpu_output)\n assert (np.min(a) == 1)\n assert (np.max(a) == 4)\n assert (np.mean(a) == 2.5)\n\ndef test_copy_slice_mini_x():\n np_input = np.asarray([[1, 2, 3, 4]])\n\n gpu_input = cle.push(np_input)\n gpu_output = cle.create((1, 1, 4))\n\n cle.copy_slice(gpu_input, gpu_output, 0)\n print(gpu_output)\n\n a = cle.pull(gpu_output)\n assert (np.min(a) == 1)\n assert (np.max(a) == 4)\n assert (np.mean(a) == 2.5)\n"
] |
[
[
"numpy.require"
],
[
"numpy.asarray",
"numpy.max",
"numpy.mean",
"numpy.min"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vlkit/vlk
|
[
"0fc79b39972356af1ca921eab5fce5d671366725"
] |
[
"test/test_optimal_transport.py"
] |
[
"import os.path as osp\nTEST_DIR = osp.dirname(__file__)\nimport sys, os\nsys.path.insert(0, osp.abspath(osp.join(TEST_DIR, \"../\")))\nfrom vlkit.optimal_transport import sinkhorn\n\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n\nimport torch\nimport numpy as np\nimport ot\nimport ot.plot\nfrom ot.datasets import make_1D_gauss as gauss\n\n\nsavedir = osp.join(osp.dirname(__file__), \"../data/test\")\nos.makedirs(savedir, exist_ok=True)\n\n\n\nn = 100 # nb bins\n# bin positions\nx = np.arange(n, dtype=np.float64)\n# Gaussian distributions\na = gauss(n, m=20, s=5) # m= mean, s= std\nb = gauss(n, m=60, s=8)\n\nd1, d2 = a.shape[0], b.shape[0]\n\n# loss matrix\nM = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)))\nM /= M.max()\n\nlambd = 1e-3\nT_ot = ot.sinkhorn(a, b, M, lambd, verbose=False)\n\n\nT = sinkhorn(\n torch.from_numpy(a).view(1, -1),\n torch.from_numpy(b).view(1, -1),\n torch.from_numpy(M).unsqueeze(dim=0),\n num_iters=1000,\n error_thres=1e-9,\n reg=lambd,\n)\n\nplt.figure(figsize=(20, 10))\ngs = gridspec.GridSpec(3, 6)\n\nax1 = plt.subplot(gs[0, 1:3])\nplt.plot(np.arange(b.size), b, 'r', label='Target distribution')\nax2 = plt.subplot(gs[1:, 0])\nplt.plot(b, x, 'b', label='Source distribution')\nplt.gca().invert_xaxis()\nplt.gca().invert_yaxis()\nplt.subplot(gs[1:3, 1:3], sharex=ax1, sharey=ax2)\nplt.imshow(T_ot)\nplt.axis('off')\n\nax1 = plt.subplot(gs[0, 4:])\nplt.plot(np.arange(b.size), b, 'r', label='Target distribution')\nax2 = plt.subplot(gs[1:, 3])\nplt.plot(b, x, 'b', label='Source distribution')\nplt.gca().invert_xaxis()\nplt.gca().invert_yaxis()\nplt.subplot(gs[1:3, 4:], sharex=ax1, sharey=ax2)\nplt.imshow(T.squeeze(dim=0).numpy())\nplt.axis('off')\n\nplt.tight_layout()\nplt.subplots_adjust(wspace=0., hspace=0.2)\nplt.savefig(osp.join(savedir, 'pth_sinkhorm.pdf'))"
] |
[
[
"matplotlib.pyplot.gca",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.tight_layout",
"matplotlib.use",
"numpy.arange",
"torch.from_numpy",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Conxz/nipype
|
[
"1281723ae56eacd103597ff4081a205583706e62",
"1281723ae56eacd103597ff4081a205583706e62",
"1281723ae56eacd103597ff4081a205583706e62"
] |
[
"nipype/algorithms/tests/test_overlap.py",
"nipype/algorithms/tests/test_mesh_ops.py",
"nipype/algorithms/rapidart.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\nimport os\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\n\nfrom nipype.testing import (example_data)\n\nimport numpy as np\n\n\ndef test_overlap():\n from nipype.algorithms.metrics import Overlap\n\n def check_close(val1, val2):\n import numpy.testing as npt\n return npt.assert_almost_equal(val1, val2, decimal=3)\n\n tempdir = mkdtemp()\n in1 = example_data('segmentation0.nii.gz')\n in2 = example_data('segmentation1.nii.gz')\n\n cwd = os.getcwd()\n os.chdir(tempdir)\n overlap = Overlap()\n overlap.inputs.volume1 = in1\n overlap.inputs.volume2 = in1\n res = overlap.run()\n yield check_close, res.outputs.jaccard, 1.0\n overlap = Overlap()\n overlap.inputs.volume1 = in1\n overlap.inputs.volume2 = in2\n res = overlap.run()\n\n yield check_close, res.outputs.jaccard, 0.99705\n\n overlap = Overlap()\n overlap.inputs.volume1 = in1\n overlap.inputs.volume2 = in2\n overlap.inputs.vol_units = 'mm'\n res = overlap.run()\n\n yield check_close, res.outputs.jaccard, 0.99705\n yield (check_close, res.outputs.roi_voldiff,\n np.array([0.0063086, -0.0025506, 0.0]))\n\n os.chdir(cwd)\n rmtree(tempdir)\n",
"# -*- coding: utf-8 -*-\n# coding: utf-8\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\nimport os\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\n\nfrom nipype.testing import (assert_equal, assert_raises, skipif,\n assert_almost_equal, example_data)\nimport numpy as np\nfrom nipype.algorithms import mesh as m\nfrom ...interfaces import vtkbase as VTKInfo\n\n\ndef test_ident_distances():\n tempdir = mkdtemp()\n curdir = os.getcwd()\n os.chdir(tempdir)\n\n if VTKInfo.no_tvtk():\n yield assert_raises, ImportError, m.ComputeMeshWarp\n else:\n in_surf = example_data('surf01.vtk')\n dist_ident = m.ComputeMeshWarp()\n dist_ident.inputs.surface1 = in_surf\n dist_ident.inputs.surface2 = in_surf\n dist_ident.inputs.out_file = os.path.join(tempdir, 'distance.npy')\n res = dist_ident.run()\n yield assert_equal, res.outputs.distance, 0.0\n\n dist_ident.inputs.weighting = 'area'\n res = dist_ident.run()\n yield assert_equal, res.outputs.distance, 0.0\n\n os.chdir(curdir)\n rmtree(tempdir)\n\n\ndef test_trans_distances():\n tempdir = mkdtemp()\n curdir = os.getcwd()\n os.chdir(tempdir)\n\n if VTKInfo.no_tvtk():\n yield assert_raises, ImportError, m.ComputeMeshWarp\n else:\n from ...interfaces.vtkbase import tvtk\n\n in_surf = example_data('surf01.vtk')\n warped_surf = os.path.join(tempdir, 'warped.vtk')\n\n inc = np.array([0.7, 0.3, -0.2])\n\n r1 = tvtk.PolyDataReader(file_name=in_surf)\n vtk1 = VTKInfo.vtk_output(r1)\n r1.update()\n vtk1.points = np.array(vtk1.points) + inc\n\n writer = tvtk.PolyDataWriter(file_name=warped_surf)\n VTKInfo.configure_input_data(writer, vtk1)\n writer.write()\n\n dist = m.ComputeMeshWarp()\n dist.inputs.surface1 = in_surf\n dist.inputs.surface2 = warped_surf\n dist.inputs.out_file = os.path.join(tempdir, 'distance.npy')\n res = dist.run()\n yield assert_almost_equal, res.outputs.distance, np.linalg.norm(inc), 4\n dist.inputs.weighting = 'area'\n res = dist.run()\n yield assert_almost_equal, res.outputs.distance, np.linalg.norm(inc), 4\n\n os.chdir(curdir)\n rmtree(tempdir)\n\n\ndef test_warppoints():\n tempdir = mkdtemp()\n curdir = os.getcwd()\n os.chdir(tempdir)\n\n if VTKInfo.no_tvtk():\n yield assert_raises, ImportError, m.WarpPoints\n\n # TODO: include regression tests for when tvtk is installed\n\n os.chdir(curdir)\n rmtree(tempdir)\n\n\ndef test_meshwarpmaths():\n tempdir = mkdtemp()\n curdir = os.getcwd()\n os.chdir(tempdir)\n\n if VTKInfo.no_tvtk():\n yield assert_raises, ImportError, m.MeshWarpMaths\n\n # TODO: include regression tests for when tvtk is installed\n\n os.chdir(curdir)\n rmtree(tempdir)\n",
"# -*- coding: utf-8 -*-\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\"\nThe rapidart module provides routines for artifact detection and region of\ninterest analysis.\n\nThese functions include:\n\n * ArtifactDetect: performs artifact detection on functional images\n\n * StimulusCorrelation: determines correlation between stimuli\n schedule and movement/intensity parameters\n\n Change directory to provide relative paths for doctests\n >>> import os\n >>> filepath = os.path.dirname( os.path.realpath( __file__ ) )\n >>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data'))\n >>> os.chdir(datadir)\n\"\"\"\nfrom __future__ import print_function, division, unicode_literals, absolute_import\nfrom builtins import open, range, str, bytes\n\nimport os\nfrom copy import deepcopy\n\nfrom nibabel import load, funcs, Nifti1Image\nimport numpy as np\nfrom scipy import signal\nimport scipy.io as sio\n\nfrom ..interfaces.base import (BaseInterface, traits, InputMultiPath,\n OutputMultiPath, TraitedSpec, File,\n BaseInterfaceInputSpec, isdefined)\nfrom ..utils.filemanip import filename_to_list, save_json, split_filename\nfrom ..utils.misc import find_indices\nfrom .. import logging, config\niflogger = logging.getLogger('interface')\n\n\ndef _get_affine_matrix(params, source):\n \"\"\"Return affine matrix given a set of translation and rotation parameters\n\n params : np.array (upto 12 long) in native package format\n source : the package that generated the parameters\n supports SPM, AFNI, FSFAST, FSL, NIPY\n \"\"\"\n if source == 'FSL':\n params = params[[3, 4, 5, 0, 1, 2]]\n elif source in ('AFNI', 'FSFAST'):\n params = params[np.asarray([4, 5, 3, 1, 2, 0]) + (len(params) > 6)]\n params[3:] = params[3:] * np.pi / 180.\n if source == 'NIPY':\n # nipy does not store typical euler angles, use nipy to convert\n from nipy.algorithms.registration import to_matrix44\n return to_matrix44(params)\n # process for FSL, SPM, AFNI and FSFAST\n rotfunc = lambda x: np.array([[np.cos(x), np.sin(x)],\n [-np.sin(x), np.cos(x)]])\n q = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0])\n if len(params) < 12:\n params = np.hstack((params, q[len(params):]))\n params.shape = (len(params),)\n # Translation\n T = np.eye(4)\n T[0:3, -1] = params[0:3]\n # Rotation\n Rx = np.eye(4)\n Rx[1:3, 1:3] = rotfunc(params[3])\n Ry = np.eye(4)\n Ry[(0, 0, 2, 2), (0, 2, 0, 2)] = rotfunc(params[4]).ravel()\n Rz = np.eye(4)\n Rz[0:2, 0:2] = rotfunc(params[5])\n # Scaling\n S = np.eye(4)\n S[0:3, 0:3] = np.diag(params[6:9])\n # Shear\n Sh = np.eye(4)\n Sh[(0, 0, 1), (1, 2, 2)] = params[9:12]\n if source in ('AFNI', 'FSFAST'):\n return np.dot(T, np.dot(Ry, np.dot(Rx, np.dot(Rz, np.dot(S, Sh)))))\n return np.dot(T, np.dot(Rx, np.dot(Ry, np.dot(Rz, np.dot(S, Sh)))))\n\n\ndef _calc_norm(mc, use_differences, source, brain_pts=None):\n \"\"\"Calculates the maximum overall displacement of the midpoints\n of the faces of a cube due to translation and rotation.\n\n Parameters\n ----------\n mc : motion parameter estimates\n [3 translation, 3 rotation (radians)]\n use_differences : boolean\n brain_pts : [4 x n_points] of coordinates\n\n Returns\n -------\n\n norm : at each time point\n displacement : euclidean distance (mm) of displacement at each coordinate\n\n \"\"\"\n\n if brain_pts is None:\n respos = np.diag([70, 70, 75])\n resneg = np.diag([-70, -110, -45])\n all_pts = np.vstack((np.hstack((respos, resneg)), np.ones((1, 6))))\n displacement = None\n else:\n all_pts = brain_pts\n n_pts = all_pts.size - all_pts.shape[1]\n newpos = np.zeros((mc.shape[0], n_pts))\n if brain_pts is not None:\n displacement = np.zeros((mc.shape[0], int(n_pts / 3)))\n for i in range(mc.shape[0]):\n affine = _get_affine_matrix(mc[i, :], source)\n newpos[i, :] = np.dot(affine,\n all_pts)[0:3, :].ravel()\n if brain_pts is not None:\n displacement[i, :] = \\\n np.sqrt(np.sum(np.power(np.reshape(newpos[i, :],\n (3, all_pts.shape[1])) -\n all_pts[0:3, :],\n 2),\n axis=0))\n # np.savez('displacement.npz', newpos=newpos, pts=all_pts)\n normdata = np.zeros(mc.shape[0])\n if use_differences:\n newpos = np.concatenate((np.zeros((1, n_pts)),\n np.diff(newpos, n=1, axis=0)), axis=0)\n for i in range(newpos.shape[0]):\n normdata[i] = \\\n np.max(np.sqrt(np.sum(np.reshape(np.power(np.abs(newpos[i, :]), 2),\n (3, all_pts.shape[1])), axis=0)))\n else:\n newpos = np.abs(signal.detrend(newpos, axis=0, type='constant'))\n normdata = np.sqrt(np.mean(np.power(newpos, 2), axis=1))\n return normdata, displacement\n\n\ndef _nanmean(a, axis=None):\n \"\"\"Return the mean excluding items that are nan\n\n >>> a = [1, 2, np.nan]\n >>> _nanmean(a)\n 1.5\n\n \"\"\"\n if axis:\n return np.nansum(a, axis) / np.sum(1 - np.isnan(a), axis)\n else:\n return np.nansum(a) / np.sum(1 - np.isnan(a))\n\n\nclass ArtifactDetectInputSpec(BaseInterfaceInputSpec):\n realigned_files = InputMultiPath(File(exists=True),\n desc=\"Names of realigned functional data files\",\n mandatory=True)\n realignment_parameters = InputMultiPath(File(exists=True), mandatory=True,\n desc=(\"Names of realignment parameters\"\n \"corresponding to the functional data files\"))\n parameter_source = traits.Enum(\"SPM\", \"FSL\", \"AFNI\", \"NiPy\", \"FSFAST\",\n desc=\"Source of movement parameters\",\n mandatory=True)\n use_differences = traits.ListBool([True, False], minlen=2, maxlen=2,\n usedefault=True,\n desc=(\"Use differences between successive motion (first element)\"\n \"and intensity paramter (second element) estimates in order\"\n \"to determine outliers. (default is [True, False])\"))\n use_norm = traits.Bool(True, requires=['norm_threshold'],\n desc=(\"Uses a composite of the motion parameters in \"\n \"order to determine outliers.\"),\n usedefault=True)\n norm_threshold = traits.Float(desc=(\"Threshold to use to detect motion-rela\"\n \"ted outliers when composite motion is \"\n \"being used\"), mandatory=True,\n xor=['rotation_threshold',\n 'translation_threshold'])\n rotation_threshold = traits.Float(mandatory=True, xor=['norm_threshold'],\n desc=(\"Threshold (in radians) to use to detect rotation-related \"\n \"outliers\"))\n translation_threshold = traits.Float(mandatory=True, xor=['norm_threshold'],\n desc=(\"Threshold (in mm) to use to detect translation-related \"\n \"outliers\"))\n zintensity_threshold = traits.Float(mandatory=True,\n desc=(\"Intensity Z-threshold use to detection images that deviate \"\n \"from the mean\"))\n mask_type = traits.Enum('spm_global', 'file', 'thresh',\n desc=(\"Type of mask that should be used to mask the functional \"\n \"data. *spm_global* uses an spm_global like calculation to \"\n \"determine the brain mask. *file* specifies a brain mask \"\n \"file (should be an image file consisting of 0s and 1s). \"\n \"*thresh* specifies a threshold to use. By default all voxels\"\n \"are used, unless one of these mask types are defined.\"),\n mandatory=True)\n mask_file = File(exists=True,\n desc=\"Mask file to be used if mask_type is 'file'.\")\n mask_threshold = traits.Float(desc=(\"Mask threshold to be used if mask_type\"\n \" is 'thresh'.\"))\n intersect_mask = traits.Bool(True,\n desc=(\"Intersect the masks when computed from \"\n \"spm_global.\"))\n save_plot = traits.Bool(True, desc=\"save plots containing outliers\",\n usedefault=True)\n plot_type = traits.Enum('png', 'svg', 'eps', 'pdf',\n desc=\"file type of the outlier plot\",\n usedefault=True)\n bound_by_brainmask = traits.Bool(False, desc=(\"use the brain mask to \"\n \"determine bounding box\"\n \"for composite norm (works\"\n \"for SPM and Nipy - currently\"\n \"inaccurate for FSL, AFNI\"),\n usedefault=True)\n global_threshold = traits.Float(8.0, desc=(\"use this threshold when mask \"\n \"type equal's spm_global\"),\n usedefault=True)\n\n\nclass ArtifactDetectOutputSpec(TraitedSpec):\n outlier_files = OutputMultiPath(File(exists=True),\n desc=(\"One file for each functional run containing a list of \"\n \"0-based indices corresponding to outlier volumes\"))\n intensity_files = OutputMultiPath(File(exists=True),\n desc=(\"One file for each functional run containing the global \"\n \"intensity values determined from the brainmask\"))\n norm_files = OutputMultiPath(File,\n desc=(\"One file for each functional run containing the composite \"\n \"norm\"))\n statistic_files = OutputMultiPath(File(exists=True),\n desc=(\"One file for each functional run containing information \"\n \"about the different types of artifacts and if design info is\"\n \" provided then details of stimulus correlated motion and a \"\n \"listing or artifacts by event type.\"))\n plot_files = OutputMultiPath(File,\n desc=(\"One image file for each functional run containing the \"\n \"detected outliers\"))\n mask_files = OutputMultiPath(File,\n desc=(\"One image file for each functional run containing the mask\"\n \"used for global signal calculation\"))\n displacement_files = OutputMultiPath(File,\n desc=(\"One image file for each functional run containing the voxel\"\n \"displacement timeseries\"))\n\n\nclass ArtifactDetect(BaseInterface):\n \"\"\"Detects outliers in a functional imaging series\n\n Uses intensity and motion parameters to infer outliers. If `use_norm` is\n True, it computes the movement of the center of each face a cuboid centered\n around the head and returns the maximal movement across the centers.\n\n\n Examples\n --------\n\n >>> ad = ArtifactDetect()\n >>> ad.inputs.realigned_files = 'functional.nii'\n >>> ad.inputs.realignment_parameters = 'functional.par'\n >>> ad.inputs.parameter_source = 'FSL'\n >>> ad.inputs.norm_threshold = 1\n >>> ad.inputs.use_differences = [True, False]\n >>> ad.inputs.zintensity_threshold = 3\n >>> ad.run() # doctest: +SKIP\n \"\"\"\n\n input_spec = ArtifactDetectInputSpec\n output_spec = ArtifactDetectOutputSpec\n\n def __init__(self, **inputs):\n super(ArtifactDetect, self).__init__(**inputs)\n\n def _get_output_filenames(self, motionfile, output_dir):\n \"\"\"Generate output files based on motion filenames\n\n Parameters\n ----------\n\n motionfile: file/string\n Filename for motion parameter file\n output_dir: string\n output directory in which the files will be generated\n \"\"\"\n if isinstance(motionfile, (str, bytes)):\n infile = motionfile\n elif isinstance(motionfile, list):\n infile = motionfile[0]\n else:\n raise Exception(\"Unknown type of file\")\n _, filename, ext = split_filename(infile)\n artifactfile = os.path.join(output_dir, ''.join(('art.', filename,\n '_outliers.txt')))\n intensityfile = os.path.join(output_dir, ''.join(('global_intensity.',\n filename, '.txt')))\n statsfile = os.path.join(output_dir, ''.join(('stats.', filename,\n '.txt')))\n normfile = os.path.join(output_dir, ''.join(('norm.', filename,\n '.txt')))\n plotfile = os.path.join(output_dir, ''.join(('plot.', filename, '.',\n self.inputs.plot_type)))\n displacementfile = os.path.join(output_dir, ''.join(('disp.',\n filename, ext)))\n maskfile = os.path.join(output_dir, ''.join(('mask.', filename, ext)))\n return (artifactfile, intensityfile, statsfile, normfile, plotfile,\n displacementfile, maskfile)\n\n def _list_outputs(self):\n outputs = self._outputs().get()\n outputs['outlier_files'] = []\n outputs['intensity_files'] = []\n outputs['statistic_files'] = []\n outputs['mask_files'] = []\n if isdefined(self.inputs.use_norm) and self.inputs.use_norm:\n outputs['norm_files'] = []\n if self.inputs.bound_by_brainmask:\n outputs['displacement_files'] = []\n if isdefined(self.inputs.save_plot) and self.inputs.save_plot:\n outputs['plot_files'] = []\n for i, f in enumerate(filename_to_list(self.inputs.realigned_files)):\n (outlierfile, intensityfile, statsfile, normfile, plotfile,\n displacementfile, maskfile) = \\\n self._get_output_filenames(f, os.getcwd())\n outputs['outlier_files'].insert(i, outlierfile)\n outputs['intensity_files'].insert(i, intensityfile)\n outputs['statistic_files'].insert(i, statsfile)\n outputs['mask_files'].insert(i, maskfile)\n if isdefined(self.inputs.use_norm) and self.inputs.use_norm:\n outputs['norm_files'].insert(i, normfile)\n if self.inputs.bound_by_brainmask:\n outputs['displacement_files'].insert(i, displacementfile)\n if isdefined(self.inputs.save_plot) and self.inputs.save_plot:\n outputs['plot_files'].insert(i, plotfile)\n return outputs\n\n def _plot_outliers_with_wave(self, wave, outliers, name):\n import matplotlib.pyplot as plt\n plt.plot(wave)\n plt.ylim([wave.min(), wave.max()])\n plt.xlim([0, len(wave) - 1])\n if len(outliers):\n plt.plot(np.tile(outliers[:, None], (1, 2)).T,\n np.tile([wave.min(), wave.max()], (len(outliers), 1)).T,\n 'r')\n plt.xlabel('Scans - 0-based')\n plt.ylabel(name)\n\n def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None):\n \"\"\"\n Core routine for detecting outliers\n \"\"\"\n if not cwd:\n cwd = os.getcwd()\n\n # read in functional image\n if isinstance(imgfile, (str, bytes)):\n nim = load(imgfile)\n elif isinstance(imgfile, list):\n if len(imgfile) == 1:\n nim = load(imgfile[0])\n else:\n images = [load(f) for f in imgfile]\n nim = funcs.concat_images(images)\n\n # compute global intensity signal\n (x, y, z, timepoints) = nim.shape\n\n data = nim.get_data()\n affine = nim.affine\n g = np.zeros((timepoints, 1))\n masktype = self.inputs.mask_type\n if masktype == 'spm_global': # spm_global like calculation\n iflogger.debug('art: using spm global')\n intersect_mask = self.inputs.intersect_mask\n if intersect_mask:\n mask = np.ones((x, y, z), dtype=bool)\n for t0 in range(timepoints):\n vol = data[:, :, :, t0]\n # Use an SPM like approach\n mask_tmp = vol > \\\n (_nanmean(vol) / self.inputs.global_threshold)\n mask = mask * mask_tmp\n for t0 in range(timepoints):\n vol = data[:, :, :, t0]\n g[t0] = _nanmean(vol[mask])\n if len(find_indices(mask)) < (np.prod((x, y, z)) / 10):\n intersect_mask = False\n g = np.zeros((timepoints, 1))\n if not intersect_mask:\n iflogger.info('not intersect_mask is True')\n mask = np.zeros((x, y, z, timepoints))\n for t0 in range(timepoints):\n vol = data[:, :, :, t0]\n mask_tmp = vol > \\\n (_nanmean(vol) / self.inputs.global_threshold)\n mask[:, :, :, t0] = mask_tmp\n g[t0] = np.nansum(vol * mask_tmp) / np.nansum(mask_tmp)\n elif masktype == 'file': # uses a mask image to determine intensity\n maskimg = load(self.inputs.mask_file)\n mask = maskimg.get_data()\n affine = maskimg.affine\n mask = mask > 0.5\n for t0 in range(timepoints):\n vol = data[:, :, :, t0]\n g[t0] = _nanmean(vol[mask])\n elif masktype == 'thresh': # uses a fixed signal threshold\n for t0 in range(timepoints):\n vol = data[:, :, :, t0]\n mask = vol > self.inputs.mask_threshold\n g[t0] = _nanmean(vol[mask])\n else:\n mask = np.ones((x, y, z))\n g = _nanmean(data[mask > 0, :], 1)\n\n # compute normalized intensity values\n gz = signal.detrend(g, axis=0) # detrend the signal\n if self.inputs.use_differences[1]:\n gz = np.concatenate((np.zeros((1, 1)), np.diff(gz, n=1, axis=0)),\n axis=0)\n gz = (gz - np.mean(gz)) / np.std(gz) # normalize the detrended signal\n iidx = find_indices(abs(gz) > self.inputs.zintensity_threshold)\n\n # read in motion parameters\n mc_in = np.loadtxt(motionfile)\n mc = deepcopy(mc_in)\n\n (artifactfile, intensityfile, statsfile, normfile, plotfile,\n displacementfile, maskfile) = self._get_output_filenames(imgfile, cwd)\n mask_img = Nifti1Image(mask.astype(np.uint8), affine)\n mask_img.to_filename(maskfile)\n\n if self.inputs.use_norm:\n brain_pts = None\n if self.inputs.bound_by_brainmask:\n voxel_coords = np.nonzero(mask)\n coords = np.vstack((voxel_coords[0],\n np.vstack((voxel_coords[1],\n voxel_coords[2])))).T\n brain_pts = np.dot(affine,\n np.hstack((coords,\n np.ones((coords.shape[0], 1)))).T)\n # calculate the norm of the motion parameters\n normval, displacement = _calc_norm(mc,\n self.inputs.use_differences[0],\n self.inputs.parameter_source,\n brain_pts=brain_pts)\n tidx = find_indices(normval > self.inputs.norm_threshold)\n ridx = find_indices(normval < 0)\n if displacement is not None:\n dmap = np.zeros((x, y, z, timepoints), dtype=np.float)\n for i in range(timepoints):\n dmap[voxel_coords[0],\n voxel_coords[1],\n voxel_coords[2], i] = displacement[i, :]\n dimg = Nifti1Image(dmap, affine)\n dimg.to_filename(displacementfile)\n else:\n if self.inputs.use_differences[0]:\n mc = np.concatenate((np.zeros((1, 6)),\n np.diff(mc_in, n=1, axis=0)),\n axis=0)\n traval = mc[:, 0:3] # translation parameters (mm)\n rotval = mc[:, 3:6] # rotation parameters (rad)\n tidx = find_indices(np.sum(abs(traval) >\n self.inputs.translation_threshold, 1) >\n 0)\n ridx = find_indices(np.sum(abs(rotval) >\n self.inputs.rotation_threshold, 1) > 0)\n\n outliers = np.unique(np.union1d(iidx, np.union1d(tidx, ridx)))\n\n # write output to outputfile\n np.savetxt(artifactfile, outliers, fmt=b'%d', delimiter=' ')\n np.savetxt(intensityfile, g, fmt=b'%.2f', delimiter=' ')\n if self.inputs.use_norm:\n np.savetxt(normfile, normval, fmt=b'%.4f', delimiter=' ')\n\n if isdefined(self.inputs.save_plot) and self.inputs.save_plot:\n import matplotlib\n matplotlib.use(config.get(\"execution\", \"matplotlib_backend\"))\n import matplotlib.pyplot as plt\n fig = plt.figure()\n if isdefined(self.inputs.use_norm) and self.inputs.use_norm:\n plt.subplot(211)\n else:\n plt.subplot(311)\n self._plot_outliers_with_wave(gz, iidx, 'Intensity')\n if isdefined(self.inputs.use_norm) and self.inputs.use_norm:\n plt.subplot(212)\n self._plot_outliers_with_wave(normval, np.union1d(tidx, ridx),\n 'Norm (mm)')\n else:\n diff = ''\n if self.inputs.use_differences[0]:\n diff = 'diff'\n plt.subplot(312)\n self._plot_outliers_with_wave(traval, tidx,\n 'Translation (mm)' + diff)\n plt.subplot(313)\n self._plot_outliers_with_wave(rotval, ridx,\n 'Rotation (rad)' + diff)\n plt.savefig(plotfile)\n plt.close(fig)\n\n motion_outliers = np.union1d(tidx, ridx)\n stats = [{'motion_file': motionfile,\n 'functional_file': imgfile},\n {'common_outliers': len(np.intersect1d(iidx, motion_outliers)),\n 'intensity_outliers': len(np.setdiff1d(iidx,\n motion_outliers)),\n 'motion_outliers': len(np.setdiff1d(motion_outliers, iidx)),\n },\n {'motion': [{'using differences': self.inputs.use_differences[0]},\n {'mean': np.mean(mc_in, axis=0).tolist(),\n 'min': np.min(mc_in, axis=0).tolist(),\n 'max': np.max(mc_in, axis=0).tolist(),\n 'std': np.std(mc_in, axis=0).tolist()},\n ]},\n {'intensity': [{'using differences': self.inputs.use_differences[1]},\n {'mean': np.mean(gz, axis=0).tolist(),\n 'min': np.min(gz, axis=0).tolist(),\n 'max': np.max(gz, axis=0).tolist(),\n 'std': np.std(gz, axis=0).tolist()},\n ]},\n ]\n if self.inputs.use_norm:\n stats.insert(3, {'motion_norm':\n {'mean': np.mean(normval, axis=0).tolist(),\n 'min': np.min(normval, axis=0).tolist(),\n 'max': np.max(normval, axis=0).tolist(),\n 'std': np.std(normval, axis=0).tolist(),\n }})\n save_json(statsfile, stats)\n\n def _run_interface(self, runtime):\n \"\"\"Execute this module.\n \"\"\"\n funcfilelist = filename_to_list(self.inputs.realigned_files)\n motparamlist = filename_to_list(self.inputs.realignment_parameters)\n for i, imgf in enumerate(funcfilelist):\n self._detect_outliers_core(imgf, motparamlist[i], i,\n cwd=os.getcwd())\n return runtime\n\n\nclass StimCorrInputSpec(BaseInterfaceInputSpec):\n realignment_parameters = InputMultiPath(File(exists=True), mandatory=True,\n desc=('Names of realignment parameters corresponding to the functional '\n 'data files'))\n intensity_values = InputMultiPath(File(exists=True), mandatory=True,\n desc='Name of file containing intensity values')\n spm_mat_file = File(exists=True, mandatory=True,\n desc='SPM mat file (use pre-estimate SPM.mat file)')\n concatenated_design = traits.Bool(mandatory=True,\n desc='state if the design matrix contains concatenated sessions')\n\n\nclass StimCorrOutputSpec(TraitedSpec):\n stimcorr_files = OutputMultiPath(File(exists=True),\n desc='List of files containing correlation values')\n\n\nclass StimulusCorrelation(BaseInterface):\n \"\"\"Determines if stimuli are correlated with motion or intensity\n parameters.\n\n Currently this class supports an SPM generated design matrix and requires\n intensity parameters. This implies that one must run\n :ref:`ArtifactDetect <nipype.algorithms.rapidart.ArtifactDetect>`\n and :ref:`Level1Design <nipype.interfaces.spm.model.Level1Design>` prior to running this or\n provide an SPM.mat file and intensity parameters through some other means.\n\n Examples\n --------\n\n >>> sc = StimulusCorrelation()\n >>> sc.inputs.realignment_parameters = 'functional.par'\n >>> sc.inputs.intensity_values = 'functional.rms'\n >>> sc.inputs.spm_mat_file = 'SPM.mat'\n >>> sc.inputs.concatenated_design = False\n >>> sc.run() # doctest: +SKIP\n\n \"\"\"\n\n input_spec = StimCorrInputSpec\n output_spec = StimCorrOutputSpec\n\n def _get_output_filenames(self, motionfile, output_dir):\n \"\"\"Generate output files based on motion filenames\n\n Parameters\n ----------\n motionfile: file/string\n Filename for motion parameter file\n output_dir: string\n output directory in which the files will be generated\n \"\"\"\n (_, filename) = os.path.split(motionfile)\n (filename, _) = os.path.splitext(filename)\n corrfile = os.path.join(output_dir, ''.join(('qa.', filename,\n '_stimcorr.txt')))\n return corrfile\n\n def _stimcorr_core(self, motionfile, intensityfile, designmatrix, cwd=None):\n \"\"\"\n Core routine for determining stimulus correlation\n\n \"\"\"\n if not cwd:\n cwd = os.getcwd()\n # read in motion parameters\n mc_in = np.loadtxt(motionfile)\n g_in = np.loadtxt(intensityfile)\n g_in.shape = g_in.shape[0], 1\n dcol = designmatrix.shape[1]\n mccol = mc_in.shape[1]\n concat_matrix = np.hstack((np.hstack((designmatrix, mc_in)), g_in))\n cm = np.corrcoef(concat_matrix, rowvar=0)\n corrfile = self._get_output_filenames(motionfile, cwd)\n # write output to outputfile\n file = open(corrfile, 'w')\n file.write(\"Stats for:\\n\")\n file.write(\"Stimulus correlated motion:\\n%s\\n\" % motionfile)\n for i in range(dcol):\n file.write(\"SCM.%d:\" % i)\n for v in cm[i, dcol + np.arange(mccol)]:\n file.write(\" %.2f\" % v)\n file.write('\\n')\n file.write(\"Stimulus correlated intensity:\\n%s\\n\" % intensityfile)\n for i in range(dcol):\n file.write(\"SCI.%d: %.2f\\n\" % (i, cm[i, -1]))\n file.close()\n\n def _get_spm_submatrix(self, spmmat, sessidx, rows=None):\n \"\"\"\n Parameters\n ----------\n spmmat: scipy matlab object\n full SPM.mat file loaded into a scipy object\n sessidx: int\n index to session that needs to be extracted.\n \"\"\"\n designmatrix = spmmat['SPM'][0][0].xX[0][0].X\n U = spmmat['SPM'][0][0].Sess[0][sessidx].U[0]\n if rows is None:\n rows = spmmat['SPM'][0][0].Sess[0][sessidx].row[0] - 1\n cols = spmmat['SPM'][0][0].Sess[0][sessidx].col[0][list(range(len(U)))] - 1\n outmatrix = designmatrix.take(rows.tolist(), axis=0).take(cols.tolist(),\n axis=1)\n return outmatrix\n\n def _run_interface(self, runtime):\n \"\"\"Execute this module.\n \"\"\"\n motparamlist = self.inputs.realignment_parameters\n intensityfiles = self.inputs.intensity_values\n spmmat = sio.loadmat(self.inputs.spm_mat_file, struct_as_record=False)\n nrows = []\n for i in range(len(motparamlist)):\n sessidx = i\n rows = None\n if self.inputs.concatenated_design:\n sessidx = 0\n mc_in = np.loadtxt(motparamlist[i])\n rows = np.sum(nrows) + np.arange(mc_in.shape[0])\n nrows.append(mc_in.shape[0])\n matrix = self._get_spm_submatrix(spmmat, sessidx, rows)\n self._stimcorr_core(motparamlist[i], intensityfiles[i],\n matrix, os.getcwd())\n return runtime\n\n def _list_outputs(self):\n outputs = self._outputs().get()\n files = []\n for i, f in enumerate(self.inputs.realignment_parameters):\n files.insert(i, self._get_output_filenames(f, os.getcwd()))\n if files:\n outputs['stimcorr_files'] = files\n return outputs\n"
] |
[
[
"numpy.testing.assert_almost_equal",
"numpy.array"
],
[
"numpy.array",
"numpy.linalg.norm"
],
[
"numpy.diag",
"numpy.dot",
"numpy.asarray",
"numpy.vstack",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.mean",
"numpy.hstack",
"numpy.reshape",
"numpy.arange",
"numpy.eye",
"scipy.io.loadmat",
"numpy.sin",
"numpy.intersect1d",
"numpy.std",
"numpy.nansum",
"numpy.diff",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.nonzero",
"numpy.power",
"numpy.isnan",
"numpy.min",
"numpy.union1d",
"matplotlib.pyplot.savefig",
"numpy.corrcoef",
"numpy.savetxt",
"numpy.array",
"numpy.sum",
"scipy.signal.detrend",
"matplotlib.pyplot.ylabel",
"numpy.abs",
"numpy.cos",
"numpy.tile",
"numpy.ones",
"numpy.setdiff1d",
"numpy.prod",
"matplotlib.pyplot.xlabel",
"numpy.loadtxt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
amrzv/federated
|
[
"d8ac0d5f8d52541860fba881e87ccdd44c5d5b9b",
"d8ac0d5f8d52541860fba881e87ccdd44c5d5b9b",
"d8ac0d5f8d52541860fba881e87ccdd44c5d5b9b"
] |
[
"tensorflow_federated/python/core/impl/executors/eager_tf_executor_multi_gpu_test.py",
"tensorflow_federated/python/core/impl/intrinsic_factory_test.py",
"tensorflow_federated/python/core/impl/executors/federating_executor_test.py"
] |
[
"# Copyright 2019, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.common_libs import test_utils\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.impl import computation_impl\nfrom tensorflow_federated.python.core.impl.executors import eager_tf_executor\n\n\nclass MultiGPUTest(tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n test_utils.create_logical_multi_gpus()\n\n def test_check_dataset_reduce_in_multi_gpu_no_reduce_no_raise(self):\n with tf.Graph().as_default() as graph:\n tf.data.Dataset.range(10).map(lambda x: x + 1)\n eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def())\n\n def test_check_dataset_reduce_in_multi_gpu(self):\n with tf.Graph().as_default() as graph:\n tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q)\n with self.assertRaisesRegex(\n ValueError, 'Detected dataset reduce op in multi-GPU TFF simulation.*'):\n eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def())\n\n def test_check_dataset_reduce_in_multi_gpu_tf_device_no_raise(self):\n logical_gpus = tf.config.list_logical_devices('GPU')\n with tf.Graph().as_default() as graph:\n with tf.device(logical_gpus[0].name):\n tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q)\n eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def())\n\n def test_get_no_arg_wrapped_function_check_dataset_reduce_in_multi_gpu(self):\n\n @computations.tf_computation\n def comp():\n return tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q)\n\n with self.assertRaisesRegex(\n ValueError, 'Detected dataset reduce op in multi-GPU TFF simulation.*'):\n eager_tf_executor._get_wrapped_function_from_comp(\n computation_impl.ComputationImpl.get_proto(comp),\n must_pin_function_to_cpu=False,\n param_type=None,\n device=None)\n\n def test_get_no_arg_wrapped_function_multi_gpu_no_reduce(self):\n\n @computations.tf_computation\n @tf.function\n def comp():\n value = tf.constant(0, dtype=tf.int64)\n for d in iter(tf.data.Dataset.range(10)):\n value += d\n return value\n\n wrapped_fn = eager_tf_executor._get_wrapped_function_from_comp(\n computation_impl.ComputationImpl.get_proto(comp),\n must_pin_function_to_cpu=False,\n param_type=None,\n device=None)\n self.assertEqual(wrapped_fn(), np.int64(45))\n\n def test_get_no_arg_wrapped_function_multi_gpu_tf_device(self):\n\n logical_gpus = tf.config.list_logical_devices('GPU')\n\n @computations.tf_computation\n def comp():\n with tf.device(logical_gpus[0].name):\n return tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q)\n\n wrapped_fn = eager_tf_executor._get_wrapped_function_from_comp(\n computation_impl.ComputationImpl.get_proto(comp),\n must_pin_function_to_cpu=False,\n param_type=None,\n device=None)\n self.assertEqual(wrapped_fn(), np.int64(45))\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom absl.testing import absltest\nimport numpy as np\n\nfrom tensorflow_federated.python.core.api import intrinsics\nfrom tensorflow_federated.python.core.impl.context_stack import context_stack_impl\nfrom tensorflow_federated.python.core.impl.federated_context import federated_computation_context\nfrom tensorflow_federated.python.core.impl.types import placement_literals\n\n\nclass FederatedSecureSumTest(absltest.TestCase):\n\n def run(self, result=None):\n fc_context = federated_computation_context.FederatedComputationContext(\n context_stack_impl.context_stack)\n with context_stack_impl.context_stack.install(fc_context):\n super(FederatedSecureSumTest, self).run(result)\n\n def test_type_signature_with_int(self):\n value = intrinsics.federated_value(1, placement_literals.CLIENTS)\n bitwidth = 8\n\n intrinsic = intrinsics.federated_secure_sum(value, bitwidth)\n\n self.assertEqual(intrinsic.type_signature.compact_representation(),\n 'int32@SERVER')\n\n def test_type_signature_with_structure_of_ints(self):\n value = intrinsics.federated_value([1, [1, 1]], placement_literals.CLIENTS)\n bitwidth = [8, [4, 2]]\n\n intrinsic = intrinsics.federated_secure_sum(value, bitwidth)\n\n self.assertEqual(intrinsic.type_signature.compact_representation(),\n '<int32,<int32,int32>>@SERVER')\n\n def test_type_signature_with_structure_of_ints_scalar_bitwidth(self):\n value = intrinsics.federated_value([1, [1, 1]], placement_literals.CLIENTS)\n bitwidth = 8\n\n intrinsic = intrinsics.federated_secure_sum(value, bitwidth)\n\n self.assertEqual(intrinsic.type_signature.compact_representation(),\n '<int32,<int32,int32>>@SERVER')\n\n def test_type_signature_with_one_tensor_and_bitwidth(self):\n value = intrinsics.federated_value(\n np.ndarray(shape=(5, 37), dtype=np.int16), placement_literals.CLIENTS)\n bitwidth = 2\n\n intrinsic = intrinsics.federated_secure_sum(value, bitwidth)\n\n self.assertEqual(intrinsic.type_signature.compact_representation(),\n 'int16[5,37]@SERVER')\n\n def test_type_signature_with_structure_of_tensors_and_bitwidths(self):\n np_array = np.ndarray(shape=(5, 37), dtype=np.int16)\n value = intrinsics.federated_value((np_array, np_array),\n placement_literals.CLIENTS)\n bitwidth = (2, 2)\n\n intrinsic = intrinsics.federated_secure_sum(value, bitwidth)\n\n self.assertEqual(intrinsic.type_signature.compact_representation(),\n '<int16[5,37],int16[5,37]>@SERVER')\n\n def test_raises_type_error_with_value_float(self):\n value = intrinsics.federated_value(1.0, placement_literals.CLIENTS)\n bitwidth = intrinsics.federated_value(1, placement_literals.SERVER)\n\n with self.assertRaises(TypeError):\n intrinsics.federated_secure_sum(value, bitwidth)\n\n def test_raises_type_error_with_bitwith_int_at_server(self):\n value = intrinsics.federated_value(1, placement_literals.CLIENTS)\n bitwidth = intrinsics.federated_value(1, placement_literals.SERVER)\n\n with self.assertRaises(TypeError):\n intrinsics.federated_secure_sum(value, bitwidth)\n\n def test_raises_type_error_with_different_structures(self):\n value = intrinsics.federated_value([1, [1, 1]], placement_literals.CLIENTS)\n bitwidth = [8, 4, 2]\n\n with self.assertRaises(TypeError):\n intrinsics.federated_secure_sum(value, bitwidth)\n\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Copyright 2019, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Any, Iterable, List, Tuple, Type\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow_federated.proto.v0 import computation_pb2 as pb\nfrom tensorflow_federated.python.common_libs import structure\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.impl import computation_impl\nfrom tensorflow_federated.python.core.impl.compiler import intrinsic_defs\nfrom tensorflow_federated.python.core.impl.context_stack import context_stack_impl\nfrom tensorflow_federated.python.core.impl.executors import eager_tf_executor\nfrom tensorflow_federated.python.core.impl.executors import executor_test_utils\nfrom tensorflow_federated.python.core.impl.executors import executor_value_base\nfrom tensorflow_federated.python.core.impl.executors import federated_resolving_strategy\nfrom tensorflow_federated.python.core.impl.executors import federating_executor\nfrom tensorflow_federated.python.core.impl.executors import reference_resolving_executor\nfrom tensorflow_federated.python.core.impl.types import placement_literals\nfrom tensorflow_federated.python.core.impl.types import type_serialization\n\n\ndef all_isinstance(objs: Iterable[Any], classinfo: Type[Any]) -> bool:\n return all(isinstance(x, classinfo) for x in objs)\n\n\ndef create_test_executor(\n number_of_clients: int = 3) -> federating_executor.FederatingExecutor:\n\n def create_bottom_stack():\n executor = eager_tf_executor.EagerTFExecutor()\n return reference_resolving_executor.ReferenceResolvingExecutor(executor)\n\n factory = federated_resolving_strategy.FederatedResolvingStrategy.factory({\n placement_literals.SERVER:\n create_bottom_stack(),\n placement_literals.CLIENTS: [\n create_bottom_stack() for _ in range(number_of_clients)\n ],\n })\n return federating_executor.FederatingExecutor(factory, create_bottom_stack())\n\n\ndef get_named_parameters_for_supported_intrinsics() -> List[Tuple[str, Any]]:\n # pyformat: disable\n return [\n ('intrinsic_def_federated_aggregate',\n *executor_test_utils.create_dummy_intrinsic_def_federated_aggregate()),\n ('intrinsic_def_federated_apply',\n *executor_test_utils.create_dummy_intrinsic_def_federated_apply()),\n ('intrinsic_def_federated_broadcast',\n *executor_test_utils.create_dummy_intrinsic_def_federated_broadcast()),\n ('intrinsic_def_federated_collect',\n *executor_test_utils.create_dummy_intrinsic_def_federated_collect()),\n ('intrinsic_def_federated_eval_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_clients()),\n ('intrinsic_def_federated_eval_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_server()),\n ('intrinsic_def_federated_map',\n *executor_test_utils.create_dummy_intrinsic_def_federated_map()),\n ('intrinsic_def_federated_map_all_equal',\n *executor_test_utils.create_dummy_intrinsic_def_federated_map_all_equal()),\n ('intrinsic_def_federated_mean',\n *executor_test_utils.create_dummy_intrinsic_def_federated_mean()),\n ('intrinsic_def_federated_sum',\n *executor_test_utils.create_dummy_intrinsic_def_federated_sum()),\n ('intrinsic_def_federated_reduce',\n *executor_test_utils.create_dummy_intrinsic_def_federated_reduce()),\n ('intrinsic_def_federated_value_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_value_at_clients()),\n ('intrinsic_def_federated_value_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_value_at_server()),\n ('intrinsic_def_federated_weighted_mean',\n *executor_test_utils.create_dummy_intrinsic_def_federated_weighted_mean()),\n ('intrinsic_def_federated_zip_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_zip_at_clients()),\n ('intrinsic_def_federated_zip_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_zip_at_server()),\n ]\n # pyformat: enable\n\n\nclass FederatingExecutorInitTest(executor_test_utils.AsyncTestCase):\n\n def test_raises_type_error_with_no_target_executor_unplaced(self):\n factory = federated_resolving_strategy.FederatedResolvingStrategy.factory({\n placement_literals.SERVER: eager_tf_executor.EagerTFExecutor(),\n placement_literals.CLIENTS: eager_tf_executor.EagerTFExecutor(),\n })\n\n with self.assertRaises(TypeError):\n federating_executor.FederatingExecutor(factory, None)\n\n\nclass FederatingExecutorCreateValueTest(executor_test_utils.AsyncTestCase,\n parameterized.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('placement_literal',\n *executor_test_utils.create_dummy_placement_literal()),\n ('computation_intrinsic',\n *executor_test_utils.create_dummy_computation_intrinsic()),\n ('computation_lambda',\n *executor_test_utils.create_dummy_computation_lambda_empty()),\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_empty()),\n ('federated_type_at_clients',\n *executor_test_utils.create_dummy_value_at_clients()),\n ('federated_type_at_clients_all_equal',\n *executor_test_utils.create_dummy_value_at_clients_all_equal()),\n ('federated_type_at_server',\n *executor_test_utils.create_dummy_value_at_server()),\n ('unplaced_type',\n *executor_test_utils.create_dummy_value_unplaced()),\n ] + get_named_parameters_for_supported_intrinsics())\n # pyformat: enable\n def test_returns_value_with_value_and_type(self, value, type_signature):\n executor = create_test_executor()\n\n result = self.run_sync(executor.create_value(value, type_signature))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.compact_representation())\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('placement_literal',\n *executor_test_utils.create_dummy_placement_literal()),\n ('computation_intrinsic',\n *executor_test_utils.create_dummy_computation_intrinsic()),\n ('computation_lambda',\n *executor_test_utils.create_dummy_computation_lambda_empty()),\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_empty()),\n ])\n # pyformat: enable\n def test_returns_value_with_value_only(self, value, type_signature):\n executor = create_test_executor()\n\n result = self.run_sync(executor.create_value(value))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.compact_representation())\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('computation_intrinsic',\n *executor_test_utils.create_dummy_computation_intrinsic()),\n ('computation_lambda',\n *executor_test_utils.create_dummy_computation_lambda_empty()),\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_empty()),\n ])\n # pyformat: enable\n def test_returns_value_with_computation_impl(self, proto, type_signature):\n executor = create_test_executor()\n value = computation_impl.ComputationImpl(proto,\n context_stack_impl.context_stack)\n\n result = self.run_sync(executor.create_value(value, type_signature))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.compact_representation())\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('federated_type_at_clients',\n *executor_test_utils.create_dummy_value_at_clients()),\n ('federated_type_at_clients_all_equal',\n *executor_test_utils.create_dummy_value_at_clients_all_equal()),\n ('federated_type_at_server',\n *executor_test_utils.create_dummy_value_at_server()),\n ('unplaced_type',\n *executor_test_utils.create_dummy_value_unplaced()),\n ] + get_named_parameters_for_supported_intrinsics())\n # pyformat: enable\n def test_raises_type_error_with_value_only(self, value, type_signature):\n del type_signature # Unused.\n executor = create_test_executor()\n\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_value(value))\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('placement_literal',\n *executor_test_utils.create_dummy_placement_literal()),\n ('computation_call',\n *executor_test_utils.create_dummy_computation_call()),\n ('computation_intrinsic',\n *executor_test_utils.create_dummy_computation_intrinsic()),\n ('computation_lambda',\n *executor_test_utils.create_dummy_computation_lambda_empty()),\n ('computation_selection',\n *executor_test_utils.create_dummy_computation_selection()),\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_empty()),\n ('computation_tuple',\n *executor_test_utils.create_dummy_computation_tuple()),\n ('federated_type_at_clients',\n *executor_test_utils.create_dummy_value_at_clients()),\n ('federated_type_at_clients_all_equal',\n *executor_test_utils.create_dummy_value_at_clients_all_equal()),\n ('federated_type_at_server',\n *executor_test_utils.create_dummy_value_at_server()),\n ('unplaced_type',\n *executor_test_utils.create_dummy_value_unplaced()),\n ] + get_named_parameters_for_supported_intrinsics())\n # pyformat: enable\n def test_raises_type_error_with_value_and_bad_type(self, value,\n type_signature):\n del type_signature # Unused.\n executor = create_test_executor()\n bad_type_signature = computation_types.TensorType(tf.string)\n\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_value(value, bad_type_signature))\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('computation_call',\n *executor_test_utils.create_dummy_computation_call()),\n ('computation_placement',\n *executor_test_utils.create_dummy_computation_placement()),\n ('computation_reference',\n *executor_test_utils.create_dummy_computation_reference()),\n ('computation_selection',\n *executor_test_utils.create_dummy_computation_selection()),\n ('computation_tuple',\n *executor_test_utils.create_dummy_computation_tuple()),\n ])\n # pyformat: enable\n def test_raises_value_error_with_value(self, value, type_signature):\n executor = create_test_executor()\n\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_value(value, type_signature))\n\n def test_raises_value_error_with_unrecognized_computation_intrinsic(self):\n executor = create_test_executor()\n type_signature = computation_types.TensorType(tf.int32)\n # A `ValueError` will be raised because `create_value` can not recognize the\n # following intrinsic, because it has not been added to the intrinsic\n # registry.\n type_signature = computation_types.TensorType(tf.int32)\n value = pb.Computation(\n type=type_serialization.serialize_type(type_signature),\n intrinsic=pb.Intrinsic(uri='unregistered_intrinsic'))\n\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_value(value, type_signature))\n\n def test_raises_value_error_with_unrecognized_computation_selection(self):\n executor = create_test_executor()\n source, _ = executor_test_utils.create_dummy_computation_tuple()\n type_signature = computation_types.StructType([])\n # A `ValueError` will be raised because `create_value` can not handle the\n # following `pb.Selection`, because does not set either a name or an index\n # field.\n value = pb.Computation(\n type=type_serialization.serialize_type(type_signature),\n selection=pb.Selection(source=source))\n\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_value(value, type_signature))\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('intrinsic_def_federated_broadcast',\n *executor_test_utils.create_dummy_intrinsic_def_federated_broadcast()),\n ('intrinsic_def_federated_eval_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_clients()),\n ('intrinsic_def_federated_map',\n *executor_test_utils.create_dummy_intrinsic_def_federated_map()),\n ('intrinsic_def_federated_map_all_equal',\n *executor_test_utils.create_dummy_intrinsic_def_federated_map_all_equal()),\n ('intrinsic_def_federated_value_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_value_at_clients()),\n ('federated_type_at_clients_all_equal',\n *executor_test_utils.create_dummy_value_at_clients_all_equal()),\n ('federated_type_at_clients',\n *executor_test_utils.create_dummy_value_at_clients())\n ])\n # pyformat: enable\n def test_raises_value_error_with_no_target_executor_clients(\n self, value, type_signature):\n factory = federated_resolving_strategy.FederatedResolvingStrategy.factory({\n placement_literals.SERVER: eager_tf_executor.EagerTFExecutor(),\n })\n executor = federating_executor.FederatingExecutor(\n factory, eager_tf_executor.EagerTFExecutor())\n\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_value(value, type_signature))\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('intrinsic_def_federated_aggregate',\n *executor_test_utils.create_dummy_intrinsic_def_federated_aggregate()),\n ('intrinsic_def_federated_apply',\n *executor_test_utils.create_dummy_intrinsic_def_federated_apply()),\n ('intrinsic_def_federated_collect',\n *executor_test_utils.create_dummy_intrinsic_def_federated_collect()),\n ('intrinsic_def_federated_eval_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_server()),\n ('intrinsic_def_federated_mean',\n *executor_test_utils.create_dummy_intrinsic_def_federated_mean()),\n ('intrinsic_def_federated_sum',\n *executor_test_utils.create_dummy_intrinsic_def_federated_sum()),\n ('intrinsic_def_federated_reduce',\n *executor_test_utils.create_dummy_intrinsic_def_federated_reduce()),\n ('intrinsic_def_federated_value_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_value_at_server()),\n ('intrinsic_def_federated_weighted_mean',\n *executor_test_utils.create_dummy_intrinsic_def_federated_weighted_mean()),\n ('intrinsic_def_federated_zip_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_zip_at_server()),\n ('federated_type_at_server',\n *executor_test_utils.create_dummy_value_at_server()),\n ])\n # pyformat: enable\n def test_raises_value_error_with_no_target_executor_server(\n self, value, type_signature):\n factory = federated_resolving_strategy.FederatedResolvingStrategy.factory({\n placement_literals.CLIENTS: eager_tf_executor.EagerTFExecutor(),\n })\n executor = federating_executor.FederatingExecutor(\n factory, eager_tf_executor.EagerTFExecutor())\n value, type_signature = executor_test_utils.create_dummy_value_at_server()\n\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_value(value, type_signature))\n\n def test_raises_value_error_with_unexpected_federated_type_at_clients(self):\n executor = create_test_executor()\n value = [10, 20]\n type_signature = computation_types.at_clients(tf.int32)\n\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_value(value, type_signature))\n\n def test_raises_type_error_with_unexpected_federated_type_at_clients_all_equal(\n self):\n executor = create_test_executor()\n value = [10] * 3\n type_signature = computation_types.at_clients(tf.int32, all_equal=True)\n\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_value(value, type_signature))\n\n\nclass FederatingExecutorCreateCallTest(executor_test_utils.AsyncTestCase,\n parameterized.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('intrinsic_def_federated_aggregate',\n *executor_test_utils.create_dummy_intrinsic_def_federated_aggregate(),\n [executor_test_utils.create_dummy_value_at_clients(),\n executor_test_utils.create_dummy_value_unplaced(),\n executor_test_utils.create_dummy_computation_tensorflow_add(),\n executor_test_utils.create_dummy_computation_tensorflow_add(),\n executor_test_utils.create_dummy_computation_tensorflow_identity()],\n 43.0),\n ('intrinsic_def_federated_apply',\n *executor_test_utils.create_dummy_intrinsic_def_federated_apply(),\n [executor_test_utils.create_dummy_computation_tensorflow_identity(),\n executor_test_utils.create_dummy_value_at_server()],\n 10.0),\n ('intrinsic_def_federated_broadcast',\n *executor_test_utils.create_dummy_intrinsic_def_federated_broadcast(),\n [executor_test_utils.create_dummy_value_at_server()],\n 10.0),\n ('intrinsic_def_federated_collect',\n *executor_test_utils.create_dummy_intrinsic_def_federated_collect(),\n [executor_test_utils.create_dummy_value_at_clients()],\n tf.data.Dataset.from_tensor_slices([10.0, 11.0, 12.0])),\n ('intrinsic_def_federated_eval_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_clients(),\n [executor_test_utils.create_dummy_computation_tensorflow_constant()],\n [10.0] * 3),\n ('intrinsic_def_federated_eval_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_server(),\n [executor_test_utils.create_dummy_computation_tensorflow_constant()],\n 10.0),\n ('intrinsic_def_federated_map',\n *executor_test_utils.create_dummy_intrinsic_def_federated_map(),\n [executor_test_utils.create_dummy_computation_tensorflow_identity(),\n executor_test_utils.create_dummy_value_at_clients()],\n [10.0, 11.0, 12.0]),\n ('intrinsic_def_federated_map_all_equal',\n *executor_test_utils.create_dummy_intrinsic_def_federated_map_all_equal(),\n [executor_test_utils.create_dummy_computation_tensorflow_identity(),\n executor_test_utils.create_dummy_value_at_clients_all_equal()],\n 10.0),\n ('intrinsic_def_federated_mean',\n *executor_test_utils.create_dummy_intrinsic_def_federated_mean(),\n [executor_test_utils.create_dummy_value_at_clients()],\n 11.0),\n ('intrinsic_def_federated_sum',\n *executor_test_utils.create_dummy_intrinsic_def_federated_sum(),\n [executor_test_utils.create_dummy_value_at_clients()],\n 33.0),\n ('intrinsic_def_federated_reduce',\n *executor_test_utils.create_dummy_intrinsic_def_federated_reduce(),\n [executor_test_utils.create_dummy_value_at_clients(),\n executor_test_utils.create_dummy_value_unplaced(),\n executor_test_utils.create_dummy_computation_tensorflow_add()],\n 43.0),\n ('intrinsic_def_federated_value_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_value_at_clients(),\n [executor_test_utils.create_dummy_value_unplaced()],\n 10.0),\n ('intrinsic_def_federated_value_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_value_at_server(),\n [executor_test_utils.create_dummy_value_unplaced()],\n 10.0),\n ('intrinsic_def_federated_weighted_mean',\n *executor_test_utils.create_dummy_intrinsic_def_federated_weighted_mean(),\n [executor_test_utils.create_dummy_value_at_clients(),\n executor_test_utils.create_dummy_value_at_clients()],\n 11.060606),\n ('intrinsic_def_federated_zip_at_clients',\n *executor_test_utils.create_dummy_intrinsic_def_federated_zip_at_clients(),\n [executor_test_utils.create_dummy_value_at_clients(),\n executor_test_utils.create_dummy_value_at_clients()],\n [structure.Struct([(None, 10.0), (None, 10.0)]),\n structure.Struct([(None, 11.0), (None, 11.0)]),\n structure.Struct([(None, 12.0), (None, 12.0)])]),\n ('intrinsic_def_federated_zip_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_zip_at_server(),\n [executor_test_utils.create_dummy_value_at_server(),\n executor_test_utils.create_dummy_value_at_server()],\n structure.Struct([(None, 10.0), (None, 10.0)])),\n ('computation_intrinsic',\n *executor_test_utils.create_dummy_computation_intrinsic(),\n [executor_test_utils.create_dummy_computation_tensorflow_constant()],\n 10.0),\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_identity(),\n [executor_test_utils.create_dummy_value_unplaced()],\n 10.0),\n ])\n # pyformat: enable\n def test_returns_value_with_comp_and_arg(self, comp, comp_type, args,\n expected_result):\n executor = create_test_executor()\n\n comp = self.run_sync(executor.create_value(comp, comp_type))\n elements = [self.run_sync(executor.create_value(*x)) for x in args]\n if len(elements) > 1:\n arg = self.run_sync(executor.create_struct(elements))\n else:\n arg = elements[0]\n result = self.run_sync(executor.create_call(comp, arg))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n comp_type.result.compact_representation())\n actual_result = self.run_sync(result.compute())\n if (all_isinstance([actual_result, expected_result], list) or\n all_isinstance([actual_result, expected_result], tf.data.Dataset)):\n for actual_element, expected_element in zip(actual_result,\n expected_result):\n self.assertEqual(actual_element, expected_element)\n else:\n self.assertEqual(actual_result, expected_result)\n\n def test_returns_value_with_intrinsic_def_federated_eval_at_clients_and_random(\n self):\n executor = create_test_executor(number_of_clients=3)\n comp, comp_type = executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_clients(\n )\n arg, arg_type = executor_test_utils.create_dummy_computation_tensorflow_random(\n )\n\n comp = self.run_sync(executor.create_value(comp, comp_type))\n arg = self.run_sync(executor.create_value(arg, arg_type))\n result = self.run_sync(executor.create_call(comp, arg))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n comp_type.result.compact_representation())\n actual_result = self.run_sync(result.compute())\n unique_results = set([x.numpy() for x in actual_result])\n if len(actual_result) != len(unique_results):\n self.fail(\n 'Expected the result to contain different random numbers, found {}.'\n .format(actual_result))\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_empty()),\n ])\n # pyformat: enable\n def test_returns_value_with_comp_only(self, comp, comp_type):\n executor = create_test_executor()\n\n comp = self.run_sync(executor.create_value(comp, comp_type))\n result = self.run_sync(executor.create_call(comp))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n comp_type.result.compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = []\n self.assertCountEqual(actual_result, expected_result)\n\n def test_raises_type_error_with_unembedded_comp(self):\n executor = create_test_executor()\n comp, _ = executor_test_utils.create_dummy_computation_tensorflow_identity()\n arg, arg_type = executor_test_utils.create_dummy_value_unplaced()\n\n arg = self.run_sync(executor.create_value(arg, arg_type))\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_call(comp, arg))\n\n def test_raises_type_error_with_unembedded_arg(self):\n executor = create_test_executor()\n comp, comp_type = executor_test_utils.create_dummy_computation_tensorflow_identity(\n )\n arg, _ = executor_test_utils.create_dummy_value_unplaced()\n\n comp = self.run_sync(executor.create_value(comp, comp_type))\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_call(comp, arg))\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('computation_intrinsic',\n *executor_test_utils.create_dummy_computation_intrinsic()),\n ('computation_lambda',\n *executor_test_utils.create_dummy_computation_lambda_identity()),\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_identity()),\n ] + get_named_parameters_for_supported_intrinsics())\n # pyformat: enable\n def test_raises_type_error_with_comp_and_bad_arg(self, comp, comp_type):\n executor = create_test_executor()\n bad_arg = 'string'\n bad_arg_type = computation_types.TensorType(tf.string)\n\n comp = self.run_sync(executor.create_value(comp, comp_type))\n arg = self.run_sync(executor.create_value(bad_arg, bad_arg_type))\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_call(comp, arg))\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('computation_lambda',\n *executor_test_utils.create_dummy_computation_lambda_empty()),\n ('federated_type_at_clients',\n *executor_test_utils.create_dummy_value_at_clients()),\n ('federated_type_at_clients_all_equal',\n *executor_test_utils.create_dummy_value_at_clients_all_equal()),\n ('federated_type_at_server',\n *executor_test_utils.create_dummy_value_at_server()),\n ('unplaced_type',\n *executor_test_utils.create_dummy_value_unplaced()),\n ])\n # pyformat: enable\n def test_raises_value_error_with_comp(self, comp, comp_type):\n executor = create_test_executor()\n\n comp = self.run_sync(executor.create_value(comp, comp_type))\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_call(comp))\n\n def test_raises_not_implemented_error_with_intrinsic_def_federated_secure_sum(\n self):\n executor = create_test_executor()\n comp, comp_type = executor_test_utils.create_dummy_intrinsic_def_federated_secure_sum(\n )\n arg_1 = [10, 11, 12]\n arg_1_type = computation_types.at_clients(tf.int32, all_equal=False)\n arg_2 = 10\n arg_2_type = computation_types.TensorType(tf.int32)\n\n comp = self.run_sync(executor.create_value(comp, comp_type))\n arg_1 = self.run_sync(executor.create_value(arg_1, arg_1_type))\n arg_2 = self.run_sync(executor.create_value(arg_2, arg_2_type))\n args = self.run_sync(executor.create_struct([arg_1, arg_2]))\n with self.assertRaises(NotImplementedError):\n self.run_sync(executor.create_call(comp, args))\n\n def test_raises_not_implemented_error_with_unimplemented_intrinsic(self):\n executor = create_test_executor()\n dummy_intrinsic = intrinsic_defs.IntrinsicDef(\n 'DUMMY_INTRINSIC', 'dummy_intrinsic',\n computation_types.AbstractType('T'))\n type_signature = computation_types.TensorType(tf.int32)\n comp = pb.Computation(\n intrinsic=pb.Intrinsic(uri='dummy_intrinsic'),\n type=type_serialization.serialize_type(type_signature))\n\n comp = self.run_sync(executor.create_value(comp))\n with self.assertRaises(NotImplementedError):\n self.run_sync(executor.create_call(comp))\n\n\nclass FederatingExecutorCreateStructTest(executor_test_utils.AsyncTestCase,\n parameterized.TestCase):\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('federated_type_at_clients',\n *executor_test_utils.create_dummy_value_at_clients()),\n ('federated_type_at_clients_all_equal',\n *executor_test_utils.create_dummy_value_at_clients_all_equal()),\n ('federated_type_at_server',\n *executor_test_utils.create_dummy_value_at_server()),\n ('unplaced_type',\n *executor_test_utils.create_dummy_value_unplaced()),\n ])\n # pyformat: enable\n def test_returns_value_with_elements_value(self, value, type_signature):\n executor = create_test_executor()\n\n element = self.run_sync(executor.create_value(value, type_signature))\n elements = [element] * 3\n type_signature = computation_types.StructType([type_signature] * 3)\n result = self.run_sync(executor.create_struct(elements))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = [self.run_sync(element.compute())] * 3\n self.assertCountEqual(actual_result, expected_result)\n\n def test_returns_value_with_elements_value_placement_literal(self):\n executor = create_test_executor()\n value, type_signature = executor_test_utils.create_dummy_placement_literal()\n\n element = self.run_sync(executor.create_value(value, type_signature))\n elements = [element] * 3\n type_signature = computation_types.StructType([type_signature] * 3)\n result = self.run_sync(executor.create_struct(elements))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.compact_representation())\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('intrinsic_def_federated_eval_at_server',\n *executor_test_utils.create_dummy_intrinsic_def_federated_eval_at_server(),\n *executor_test_utils.create_dummy_computation_tensorflow_constant()),\n ('computation_intrinsic',\n *executor_test_utils.create_dummy_computation_intrinsic(),\n *executor_test_utils.create_dummy_computation_tensorflow_constant()),\n ])\n # pyformat: enable\n def test_returns_value_with_elements_fn_and_arg(self, fn, fn_type, arg,\n arg_type):\n executor = create_test_executor()\n\n fn = self.run_sync(executor.create_value(fn, fn_type))\n arg = self.run_sync(executor.create_value(arg, arg_type))\n element = self.run_sync(executor.create_call(fn, arg))\n elements = [element] * 3\n type_signature = computation_types.StructType([fn_type.result] * 3)\n result = self.run_sync(executor.create_struct(elements))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = [self.run_sync(element.compute())] * 3\n self.assertCountEqual(actual_result, expected_result)\n\n # pyformat: disable\n @parameterized.named_parameters([\n ('computation_tensorflow',\n *executor_test_utils.create_dummy_computation_tensorflow_empty()),\n ])\n # pyformat: enable\n def test_returns_value_with_elements_fn_only(self, fn, fn_type):\n executor = create_test_executor()\n\n fn = self.run_sync(executor.create_value(fn, fn_type))\n element = self.run_sync(executor.create_call(fn))\n elements = [element] * 3\n type_signature = computation_types.StructType([fn_type.result] * 3)\n result = self.run_sync(executor.create_struct(elements))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = [self.run_sync(element.compute())] * 3\n self.assertCountEqual(actual_result, expected_result)\n\n def test_raises_type_error_with_unembedded_elements(self):\n executor = create_test_executor()\n element, _ = executor_test_utils.create_dummy_value_unplaced()\n\n elements = [element] * 3\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_struct(elements))\n\n\nclass FederatingExecutorCreateSelectionTest(executor_test_utils.AsyncTestCase):\n\n def test_returns_value_with_source_and_index_computation_tensorflow(self):\n executor = create_test_executor()\n source, type_signature = executor_test_utils.create_dummy_computation_tensorflow_tuple(\n )\n\n source = self.run_sync(executor.create_value(source, type_signature))\n source = self.run_sync(executor.create_call(source))\n result = self.run_sync(executor.create_selection(source, index=0))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.result[0].compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = self.run_sync(source.compute())[0]\n self.assertEqual(actual_result, expected_result)\n\n def test_returns_value_with_source_and_index_structure(self):\n executor = create_test_executor()\n element, element_type = executor_test_utils.create_dummy_value_unplaced()\n\n element = self.run_sync(executor.create_value(element, element_type))\n elements = [element] * 3\n type_signature = computation_types.StructType([element_type] * 3)\n source = self.run_sync(executor.create_struct(elements))\n result = self.run_sync(executor.create_selection(source, index=0))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature[0].compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = self.run_sync(source.compute())[0]\n self.assertEqual(actual_result, expected_result)\n\n def test_returns_value_with_source_and_name_computation_tensorflow(self):\n executor = create_test_executor()\n source, type_signature = executor_test_utils.create_dummy_computation_tensorflow_tuple(\n )\n\n source = self.run_sync(executor.create_value(source, type_signature))\n source = self.run_sync(executor.create_call(source))\n result = self.run_sync(executor.create_selection(source, name='a'))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature.result['a'].compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = self.run_sync(source.compute())['a']\n self.assertEqual(actual_result, expected_result)\n\n def test_returns_value_with_source_and_name_structure(self):\n executor = create_test_executor()\n element, element_type = executor_test_utils.create_dummy_value_unplaced()\n\n names = ['a', 'b', 'c']\n element = self.run_sync(executor.create_value(element, element_type))\n elements = structure.Struct((n, element) for n in names)\n type_signature = computation_types.StructType(\n (n, element_type) for n in names)\n source = self.run_sync(executor.create_struct(elements))\n result = self.run_sync(executor.create_selection(source, name='a'))\n\n self.assertIsInstance(result, executor_value_base.ExecutorValue)\n self.assertEqual(result.type_signature.compact_representation(),\n type_signature['a'].compact_representation())\n actual_result = self.run_sync(result.compute())\n expected_result = self.run_sync(source.compute())['a']\n self.assertEqual(actual_result, expected_result)\n\n def test_raises_type_error_with_unembedded_source(self):\n executor = create_test_executor()\n element, element_type = executor_test_utils.create_dummy_value_unplaced()\n\n element = self.run_sync(executor.create_value(element, element_type))\n source = [element] * 3\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_selection(source, index=0))\n\n def test_raises_type_error_with_not_tuple_type(self):\n executor = create_test_executor()\n element, element_type = executor_test_utils.create_dummy_value_unplaced()\n\n source = self.run_sync(executor.create_value(element, element_type))\n with self.assertRaises(TypeError):\n self.run_sync(executor.create_selection(source, index=0))\n\n def test_raises_value_error_with_no_index_or_name(self):\n executor = create_test_executor()\n element, element_type = executor_test_utils.create_dummy_value_unplaced()\n\n element = self.run_sync(executor.create_value(element, element_type))\n elements = [element] * 3\n source = self.run_sync(executor.create_struct(elements))\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_selection(source))\n\n def test_raises_value_error_with_unrecognized_generic_zero(self):\n executor = create_test_executor()\n\n value = intrinsic_defs.GENERIC_ZERO\n type_signature = computation_types.StructType(\n [computation_types.TensorType(tf.int32)] * 3)\n\n source = self.run_sync(executor.create_value(value, type_signature))\n with self.assertRaises(ValueError):\n self.run_sync(executor.create_selection(source, index=0))\n\n\nif __name__ == '__main__':\n absltest.main()\n"
] |
[
[
"tensorflow.device",
"tensorflow.Graph",
"tensorflow.constant",
"tensorflow.config.list_logical_devices",
"tensorflow.test.main",
"numpy.int64",
"tensorflow.data.Dataset.range"
],
[
"numpy.ndarray"
],
[
"tensorflow.data.Dataset.from_tensor_slices"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
GeNikolja/pandas
|
[
"7bb498083ce163f92822487dd4b15e9659dd45d7"
] |
[
"pandas/tests/indexing/test_indexing.py"
] |
[
"# -*- coding: utf-8 -*-\n# pylint: disable-msg=W0612,E1101\nimport sys\nimport nose\nimport itertools\nimport warnings\nfrom warnings import catch_warnings\nfrom datetime import datetime\n\nfrom pandas.types.common import (is_integer_dtype,\n is_float_dtype,\n is_scalar)\nfrom pandas.compat import range, lrange, lzip, StringIO, lmap, map\nfrom pandas.tslib import NaT\nfrom numpy import nan\nfrom numpy.random import randn\nimport numpy as np\n\nimport pandas as pd\nimport pandas.core.common as com\nfrom pandas import option_context\nfrom pandas.core.indexing import _non_reducing_slice, _maybe_numeric_slice\nfrom pandas.core.api import (DataFrame, Index, Series, Panel, isnull,\n MultiIndex, Timestamp, Timedelta, UInt64Index)\nfrom pandas.formats.printing import pprint_thing\nfrom pandas import concat\nfrom pandas.core.common import PerformanceWarning, UnsortedIndexError\n\nimport pandas.util.testing as tm\nfrom pandas import date_range\n\n\n_verbose = False\n\n# ------------------------------------------------------------------------\n# Indexing test cases\n\n\ndef _generate_indices(f, values=False):\n \"\"\" generate the indicies\n if values is True , use the axis values\n is False, use the range\n \"\"\"\n\n axes = f.axes\n if values:\n axes = [lrange(len(a)) for a in axes]\n\n return itertools.product(*axes)\n\n\ndef _get_value(f, i, values=False):\n \"\"\" return the value for the location i \"\"\"\n\n # check agains values\n if values:\n return f.values[i]\n\n # this is equiv of f[col][row].....\n # v = f\n # for a in reversed(i):\n # v = v.__getitem__(a)\n # return v\n with catch_warnings(record=True):\n return f.ix[i]\n\n\ndef _get_result(obj, method, key, axis):\n \"\"\" return the result for this obj with this key and this axis \"\"\"\n\n if isinstance(key, dict):\n key = key[axis]\n\n # use an artifical conversion to map the key as integers to the labels\n # so ix can work for comparisions\n if method == 'indexer':\n method = 'ix'\n key = obj._get_axis(axis)[key]\n\n # in case we actually want 0 index slicing\n try:\n xp = getattr(obj, method).__getitem__(_axify(obj, key, axis))\n except:\n xp = getattr(obj, method).__getitem__(key)\n\n return xp\n\n\ndef _axify(obj, key, axis):\n # create a tuple accessor\n axes = [slice(None)] * obj.ndim\n axes[axis] = key\n return tuple(axes)\n\n\ndef _mklbl(prefix, n):\n return [\"%s%s\" % (prefix, i) for i in range(n)]\n\n\nclass TestIndexing(tm.TestCase):\n\n _multiprocess_can_split_ = True\n\n _objs = set(['series', 'frame', 'panel'])\n _typs = set(['ints', 'uints', 'labels', 'mixed',\n 'ts', 'floats', 'empty', 'ts_rev'])\n\n def setUp(self):\n\n self.series_ints = Series(np.random.rand(4), index=lrange(0, 8, 2))\n self.frame_ints = DataFrame(np.random.randn(4, 4),\n index=lrange(0, 8, 2),\n columns=lrange(0, 12, 3))\n self.panel_ints = Panel(np.random.rand(4, 4, 4),\n items=lrange(0, 8, 2),\n major_axis=lrange(0, 12, 3),\n minor_axis=lrange(0, 16, 4))\n\n self.series_uints = Series(np.random.rand(4),\n index=UInt64Index(lrange(0, 8, 2)))\n self.frame_uints = DataFrame(np.random.randn(4, 4),\n index=UInt64Index(lrange(0, 8, 2)),\n columns=UInt64Index(lrange(0, 12, 3)))\n self.panel_uints = Panel(np.random.rand(4, 4, 4),\n items=UInt64Index(lrange(0, 8, 2)),\n major_axis=UInt64Index(lrange(0, 12, 3)),\n minor_axis=UInt64Index(lrange(0, 16, 4)))\n\n self.series_labels = Series(np.random.randn(4), index=list('abcd'))\n self.frame_labels = DataFrame(np.random.randn(4, 4),\n index=list('abcd'), columns=list('ABCD'))\n self.panel_labels = Panel(np.random.randn(4, 4, 4),\n items=list('abcd'),\n major_axis=list('ABCD'),\n minor_axis=list('ZYXW'))\n\n self.series_mixed = Series(np.random.randn(4), index=[2, 4, 'null', 8])\n self.frame_mixed = DataFrame(np.random.randn(4, 4),\n index=[2, 4, 'null', 8])\n self.panel_mixed = Panel(np.random.randn(4, 4, 4),\n items=[2, 4, 'null', 8])\n\n self.series_ts = Series(np.random.randn(4),\n index=date_range('20130101', periods=4))\n self.frame_ts = DataFrame(np.random.randn(4, 4),\n index=date_range('20130101', periods=4))\n self.panel_ts = Panel(np.random.randn(4, 4, 4),\n items=date_range('20130101', periods=4))\n\n dates_rev = (date_range('20130101', periods=4)\n .sort_values(ascending=False))\n self.series_ts_rev = Series(np.random.randn(4),\n index=dates_rev)\n self.frame_ts_rev = DataFrame(np.random.randn(4, 4),\n index=dates_rev)\n self.panel_ts_rev = Panel(np.random.randn(4, 4, 4),\n items=dates_rev)\n\n self.frame_empty = DataFrame({})\n self.series_empty = Series({})\n self.panel_empty = Panel({})\n\n # form agglomerates\n for o in self._objs:\n\n d = dict()\n for t in self._typs:\n d[t] = getattr(self, '%s_%s' % (o, t), None)\n\n setattr(self, o, d)\n\n def check_values(self, f, func, values=False):\n\n if f is None:\n return\n axes = f.axes\n indicies = itertools.product(*axes)\n\n for i in indicies:\n result = getattr(f, func)[i]\n\n # check agains values\n if values:\n expected = f.values[i]\n else:\n expected = f\n for a in reversed(i):\n expected = expected.__getitem__(a)\n\n tm.assert_almost_equal(result, expected)\n\n def check_result(self, name, method1, key1, method2, key2, typs=None,\n objs=None, axes=None, fails=None):\n def _eq(t, o, a, obj, k1, k2):\n \"\"\" compare equal for these 2 keys \"\"\"\n\n if a is not None and a > obj.ndim - 1:\n return\n\n def _print(result, error=None):\n if error is not None:\n error = str(error)\n v = (\"%-16.16s [%-16.16s]: [typ->%-8.8s,obj->%-8.8s,\"\n \"key1->(%-4.4s),key2->(%-4.4s),axis->%s] %s\" %\n (name, result, t, o, method1, method2, a, error or ''))\n if _verbose:\n pprint_thing(v)\n\n try:\n rs = getattr(obj, method1).__getitem__(_axify(obj, k1, a))\n\n try:\n xp = _get_result(obj, method2, k2, a)\n except:\n result = 'no comp'\n _print(result)\n return\n\n detail = None\n\n try:\n if is_scalar(rs) and is_scalar(xp):\n self.assertEqual(rs, xp)\n elif xp.ndim == 1:\n tm.assert_series_equal(rs, xp)\n elif xp.ndim == 2:\n tm.assert_frame_equal(rs, xp)\n elif xp.ndim == 3:\n tm.assert_panel_equal(rs, xp)\n result = 'ok'\n except AssertionError as e:\n detail = str(e)\n result = 'fail'\n\n # reverse the checks\n if fails is True:\n if result == 'fail':\n result = 'ok (fail)'\n\n _print(result)\n if not result.startswith('ok'):\n raise AssertionError(detail)\n\n except AssertionError:\n raise\n except Exception as detail:\n\n # if we are in fails, the ok, otherwise raise it\n if fails is not None:\n if isinstance(detail, fails):\n result = 'ok (%s)' % type(detail).__name__\n _print(result)\n return\n\n result = type(detail).__name__\n raise AssertionError(_print(result, error=detail))\n\n if typs is None:\n typs = self._typs\n\n if objs is None:\n objs = self._objs\n\n if axes is not None:\n if not isinstance(axes, (tuple, list)):\n axes = [axes]\n else:\n axes = list(axes)\n else:\n axes = [0, 1, 2]\n\n # check\n for o in objs:\n if o not in self._objs:\n continue\n\n d = getattr(self, o)\n for a in axes:\n for t in typs:\n if t not in self._typs:\n continue\n\n obj = d[t]\n if obj is not None:\n obj = obj.copy()\n\n k2 = key2\n _eq(t, o, a, obj, key1, k2)\n\n def test_ix_deprecation(self):\n # GH 15114\n\n df = DataFrame({'A': [1, 2, 3]})\n with tm.assert_produces_warning(DeprecationWarning,\n check_stacklevel=False):\n df.ix[1, 'A']\n\n def test_indexer_caching(self):\n # GH5727\n # make sure that indexers are in the _internal_names_set\n n = 1000001\n arrays = [lrange(n), lrange(n)]\n index = MultiIndex.from_tuples(lzip(*arrays))\n s = Series(np.zeros(n), index=index)\n str(s)\n\n # setitem\n expected = Series(np.ones(n), index=index)\n s = Series(np.zeros(n), index=index)\n s[s == 0] = 1\n tm.assert_series_equal(s, expected)\n\n def test_at_and_iat_get(self):\n def _check(f, func, values=False):\n\n if f is not None:\n indicies = _generate_indices(f, values)\n for i in indicies:\n result = getattr(f, func)[i]\n expected = _get_value(f, i, values)\n tm.assert_almost_equal(result, expected)\n\n for o in self._objs:\n\n d = getattr(self, o)\n\n # iat\n for f in [d['ints'], d['uints']]:\n _check(f, 'iat', values=True)\n\n for f in [d['labels'], d['ts'], d['floats']]:\n if f is not None:\n self.assertRaises(ValueError, self.check_values, f, 'iat')\n\n # at\n for f in [d['ints'], d['uints'], d['labels'],\n d['ts'], d['floats']]:\n _check(f, 'at')\n\n def test_at_and_iat_set(self):\n def _check(f, func, values=False):\n\n if f is not None:\n indicies = _generate_indices(f, values)\n for i in indicies:\n getattr(f, func)[i] = 1\n expected = _get_value(f, i, values)\n tm.assert_almost_equal(expected, 1)\n\n for t in self._objs:\n\n d = getattr(self, t)\n\n # iat\n for f in [d['ints'], d['uints']]:\n _check(f, 'iat', values=True)\n\n for f in [d['labels'], d['ts'], d['floats']]:\n if f is not None:\n self.assertRaises(ValueError, _check, f, 'iat')\n\n # at\n for f in [d['ints'], d['uints'], d['labels'],\n d['ts'], d['floats']]:\n _check(f, 'at')\n\n def test_at_iat_coercion(self):\n\n # as timestamp is not a tuple!\n dates = date_range('1/1/2000', periods=8)\n df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])\n s = df['A']\n\n result = s.at[dates[5]]\n xp = s.values[5]\n self.assertEqual(result, xp)\n\n # GH 7729\n # make sure we are boxing the returns\n s = Series(['2014-01-01', '2014-02-02'], dtype='datetime64[ns]')\n expected = Timestamp('2014-02-02')\n\n for r in [lambda: s.iat[1], lambda: s.iloc[1]]:\n result = r()\n self.assertEqual(result, expected)\n\n s = Series(['1 days', '2 days'], dtype='timedelta64[ns]')\n expected = Timedelta('2 days')\n\n for r in [lambda: s.iat[1], lambda: s.iloc[1]]:\n result = r()\n self.assertEqual(result, expected)\n\n def test_iat_invalid_args(self):\n pass\n\n def test_imethods_with_dups(self):\n\n # GH6493\n # iat/iloc with dups\n\n s = Series(range(5), index=[1, 1, 2, 2, 3], dtype='int64')\n result = s.iloc[2]\n self.assertEqual(result, 2)\n result = s.iat[2]\n self.assertEqual(result, 2)\n\n self.assertRaises(IndexError, lambda: s.iat[10])\n self.assertRaises(IndexError, lambda: s.iat[-10])\n\n result = s.iloc[[2, 3]]\n expected = Series([2, 3], [2, 2], dtype='int64')\n tm.assert_series_equal(result, expected)\n\n df = s.to_frame()\n result = df.iloc[2]\n expected = Series(2, index=[0], name=2)\n tm.assert_series_equal(result, expected)\n\n result = df.iat[2, 0]\n expected = 2\n self.assertEqual(result, 2)\n\n def test_repeated_getitem_dups(self):\n # GH 5678\n # repeated gettitems on a dup index returing a ndarray\n df = DataFrame(\n np.random.random_sample((20, 5)),\n index=['ABCDE' [x % 5] for x in range(20)])\n expected = df.loc['A', 0]\n result = df.loc[:, 0].loc['A']\n tm.assert_series_equal(result, expected)\n\n def test_iloc_exceeds_bounds(self):\n\n # GH6296\n # iloc should allow indexers that exceed the bounds\n df = DataFrame(np.random.random_sample((20, 5)), columns=list('ABCDE'))\n expected = df\n\n # lists of positions should raise IndexErrror!\n with tm.assertRaisesRegexp(IndexError,\n 'positional indexers are out-of-bounds'):\n df.iloc[:, [0, 1, 2, 3, 4, 5]]\n self.assertRaises(IndexError, lambda: df.iloc[[1, 30]])\n self.assertRaises(IndexError, lambda: df.iloc[[1, -30]])\n self.assertRaises(IndexError, lambda: df.iloc[[100]])\n\n s = df['A']\n self.assertRaises(IndexError, lambda: s.iloc[[100]])\n self.assertRaises(IndexError, lambda: s.iloc[[-100]])\n\n # still raise on a single indexer\n msg = 'single positional indexer is out-of-bounds'\n with tm.assertRaisesRegexp(IndexError, msg):\n df.iloc[30]\n self.assertRaises(IndexError, lambda: df.iloc[-30])\n\n # GH10779\n # single positive/negative indexer exceeding Series bounds should raise\n # an IndexError\n with tm.assertRaisesRegexp(IndexError, msg):\n s.iloc[30]\n self.assertRaises(IndexError, lambda: s.iloc[-30])\n\n # slices are ok\n result = df.iloc[:, 4:10] # 0 < start < len < stop\n expected = df.iloc[:, 4:]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, -4:-10] # stop < 0 < start < len\n expected = df.iloc[:, :0]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, 10:4:-1] # 0 < stop < len < start (down)\n expected = df.iloc[:, :4:-1]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, 4:-10:-1] # stop < 0 < start < len (down)\n expected = df.iloc[:, 4::-1]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, -10:4] # start < 0 < stop < len\n expected = df.iloc[:, :4]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, 10:4] # 0 < stop < len < start\n expected = df.iloc[:, :0]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, -10:-11:-1] # stop < start < 0 < len (down)\n expected = df.iloc[:, :0]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, 10:11] # 0 < len < start < stop\n expected = df.iloc[:, :0]\n tm.assert_frame_equal(result, expected)\n\n # slice bounds exceeding is ok\n result = s.iloc[18:30]\n expected = s.iloc[18:]\n tm.assert_series_equal(result, expected)\n\n result = s.iloc[30:]\n expected = s.iloc[:0]\n tm.assert_series_equal(result, expected)\n\n result = s.iloc[30::-1]\n expected = s.iloc[::-1]\n tm.assert_series_equal(result, expected)\n\n # doc example\n def check(result, expected):\n str(result)\n result.dtypes\n tm.assert_frame_equal(result, expected)\n\n dfl = DataFrame(np.random.randn(5, 2), columns=list('AB'))\n check(dfl.iloc[:, 2:3], DataFrame(index=dfl.index))\n check(dfl.iloc[:, 1:3], dfl.iloc[:, [1]])\n check(dfl.iloc[4:6], dfl.iloc[[4]])\n\n self.assertRaises(IndexError, lambda: dfl.iloc[[4, 5, 6]])\n self.assertRaises(IndexError, lambda: dfl.iloc[:, 4])\n\n def test_iloc_getitem_int(self):\n\n # integer\n self.check_result('integer', 'iloc', 2, 'ix',\n {0: 4, 1: 6, 2: 8}, typs=['ints', 'uints'])\n self.check_result('integer', 'iloc', 2, 'indexer', 2,\n typs=['labels', 'mixed', 'ts', 'floats', 'empty'],\n fails=IndexError)\n\n def test_iloc_getitem_neg_int(self):\n\n # neg integer\n self.check_result('neg int', 'iloc', -1, 'ix',\n {0: 6, 1: 9, 2: 12}, typs=['ints', 'uints'])\n self.check_result('neg int', 'iloc', -1, 'indexer', -1,\n typs=['labels', 'mixed', 'ts', 'floats', 'empty'],\n fails=IndexError)\n\n def test_iloc_getitem_list_int(self):\n\n # list of ints\n self.check_result('list int', 'iloc', [0, 1, 2], 'ix',\n {0: [0, 2, 4], 1: [0, 3, 6], 2: [0, 4, 8]},\n typs=['ints', 'uints'])\n self.check_result('list int', 'iloc', [2], 'ix',\n {0: [4], 1: [6], 2: [8]}, typs=['ints', 'uints'])\n self.check_result('list int', 'iloc', [0, 1, 2], 'indexer', [0, 1, 2],\n typs=['labels', 'mixed', 'ts', 'floats', 'empty'],\n fails=IndexError)\n\n # array of ints (GH5006), make sure that a single indexer is returning\n # the correct type\n self.check_result('array int', 'iloc', np.array([0, 1, 2]), 'ix',\n {0: [0, 2, 4],\n 1: [0, 3, 6],\n 2: [0, 4, 8]}, typs=['ints', 'uints'])\n self.check_result('array int', 'iloc', np.array([2]), 'ix',\n {0: [4], 1: [6], 2: [8]}, typs=['ints', 'uints'])\n self.check_result('array int', 'iloc', np.array([0, 1, 2]), 'indexer',\n [0, 1, 2],\n typs=['labels', 'mixed', 'ts', 'floats', 'empty'],\n fails=IndexError)\n\n def test_iloc_getitem_neg_int_can_reach_first_index(self):\n # GH10547 and GH10779\n # negative integers should be able to reach index 0\n df = DataFrame({'A': [2, 3, 5], 'B': [7, 11, 13]})\n s = df['A']\n\n expected = df.iloc[0]\n result = df.iloc[-3]\n tm.assert_series_equal(result, expected)\n\n expected = df.iloc[[0]]\n result = df.iloc[[-3]]\n tm.assert_frame_equal(result, expected)\n\n expected = s.iloc[0]\n result = s.iloc[-3]\n self.assertEqual(result, expected)\n\n expected = s.iloc[[0]]\n result = s.iloc[[-3]]\n tm.assert_series_equal(result, expected)\n\n # check the length 1 Series case highlighted in GH10547\n expected = pd.Series(['a'], index=['A'])\n result = expected.iloc[[-1]]\n tm.assert_series_equal(result, expected)\n\n def test_iloc_getitem_dups(self):\n\n # no dups in panel (bug?)\n self.check_result('list int (dups)', 'iloc', [0, 1, 1, 3], 'ix',\n {0: [0, 2, 2, 6], 1: [0, 3, 3, 9]},\n objs=['series', 'frame'], typs=['ints', 'uints'])\n\n # GH 6766\n df1 = DataFrame([{'A': None, 'B': 1}, {'A': 2, 'B': 2}])\n df2 = DataFrame([{'A': 3, 'B': 3}, {'A': 4, 'B': 4}])\n df = concat([df1, df2], axis=1)\n\n # cross-sectional indexing\n result = df.iloc[0, 0]\n self.assertTrue(isnull(result))\n\n result = df.iloc[0, :]\n expected = Series([np.nan, 1, 3, 3], index=['A', 'B', 'A', 'B'],\n name=0)\n tm.assert_series_equal(result, expected)\n\n def test_iloc_getitem_array(self):\n\n # array like\n s = Series(index=lrange(1, 4))\n self.check_result('array like', 'iloc', s.index, 'ix',\n {0: [2, 4, 6], 1: [3, 6, 9], 2: [4, 8, 12]},\n typs=['ints', 'uints'])\n\n def test_iloc_getitem_bool(self):\n\n # boolean indexers\n b = [True, False, True, False, ]\n self.check_result('bool', 'iloc', b, 'ix', b, typs=['ints', 'uints'])\n self.check_result('bool', 'iloc', b, 'ix', b,\n typs=['labels', 'mixed', 'ts', 'floats', 'empty'],\n fails=IndexError)\n\n def test_iloc_getitem_slice(self):\n\n # slices\n self.check_result('slice', 'iloc', slice(1, 3), 'ix',\n {0: [2, 4], 1: [3, 6], 2: [4, 8]},\n typs=['ints', 'uints'])\n self.check_result('slice', 'iloc', slice(1, 3), 'indexer',\n slice(1, 3),\n typs=['labels', 'mixed', 'ts', 'floats', 'empty'],\n fails=IndexError)\n\n def test_iloc_getitem_slice_dups(self):\n\n df1 = DataFrame(np.random.randn(10, 4), columns=['A', 'A', 'B', 'B'])\n df2 = DataFrame(np.random.randint(0, 10, size=20).reshape(10, 2),\n columns=['A', 'C'])\n\n # axis=1\n df = concat([df1, df2], axis=1)\n tm.assert_frame_equal(df.iloc[:, :4], df1)\n tm.assert_frame_equal(df.iloc[:, 4:], df2)\n\n df = concat([df2, df1], axis=1)\n tm.assert_frame_equal(df.iloc[:, :2], df2)\n tm.assert_frame_equal(df.iloc[:, 2:], df1)\n\n exp = concat([df2, df1.iloc[:, [0]]], axis=1)\n tm.assert_frame_equal(df.iloc[:, 0:3], exp)\n\n # axis=0\n df = concat([df, df], axis=0)\n tm.assert_frame_equal(df.iloc[0:10, :2], df2)\n tm.assert_frame_equal(df.iloc[0:10, 2:], df1)\n tm.assert_frame_equal(df.iloc[10:, :2], df2)\n tm.assert_frame_equal(df.iloc[10:, 2:], df1)\n\n def test_iloc_getitem_multiindex2(self):\n # TODO(wesm): fix this\n raise nose.SkipTest('this test was being suppressed, '\n 'needs to be fixed')\n\n arr = np.random.randn(3, 3)\n df = DataFrame(arr, columns=[[2, 2, 4], [6, 8, 10]],\n index=[[4, 4, 8], [8, 10, 12]])\n\n rs = df.iloc[2]\n xp = Series(arr[2], index=df.columns)\n tm.assert_series_equal(rs, xp)\n\n rs = df.iloc[:, 2]\n xp = Series(arr[:, 2], index=df.index)\n tm.assert_series_equal(rs, xp)\n\n rs = df.iloc[2, 2]\n xp = df.values[2, 2]\n self.assertEqual(rs, xp)\n\n # for multiple items\n # GH 5528\n rs = df.iloc[[0, 1]]\n xp = df.xs(4, drop_level=False)\n tm.assert_frame_equal(rs, xp)\n\n tup = zip(*[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']])\n index = MultiIndex.from_tuples(tup)\n df = DataFrame(np.random.randn(4, 4), index=index)\n rs = df.iloc[[2, 3]]\n xp = df.xs('b', drop_level=False)\n tm.assert_frame_equal(rs, xp)\n\n def test_iloc_setitem(self):\n df = self.frame_ints\n\n df.iloc[1, 1] = 1\n result = df.iloc[1, 1]\n self.assertEqual(result, 1)\n\n df.iloc[:, 2:3] = 0\n expected = df.iloc[:, 2:3]\n result = df.iloc[:, 2:3]\n tm.assert_frame_equal(result, expected)\n\n # GH5771\n s = Series(0, index=[4, 5, 6])\n s.iloc[1:2] += 1\n expected = Series([0, 1, 0], index=[4, 5, 6])\n tm.assert_series_equal(s, expected)\n\n def test_loc_setitem_slice(self):\n # GH10503\n\n # assigning the same type should not change the type\n df1 = DataFrame({'a': [0, 1, 1],\n 'b': Series([100, 200, 300], dtype='uint32')})\n ix = df1['a'] == 1\n newb1 = df1.loc[ix, 'b'] + 1\n df1.loc[ix, 'b'] = newb1\n expected = DataFrame({'a': [0, 1, 1],\n 'b': Series([100, 201, 301], dtype='uint32')})\n tm.assert_frame_equal(df1, expected)\n\n # assigning a new type should get the inferred type\n df2 = DataFrame({'a': [0, 1, 1], 'b': [100, 200, 300]},\n dtype='uint64')\n ix = df1['a'] == 1\n newb2 = df2.loc[ix, 'b']\n df1.loc[ix, 'b'] = newb2\n expected = DataFrame({'a': [0, 1, 1], 'b': [100, 200, 300]},\n dtype='uint64')\n tm.assert_frame_equal(df2, expected)\n\n def test_ix_loc_setitem_consistency(self):\n\n # GH 5771\n # loc with slice and series\n s = Series(0, index=[4, 5, 6])\n s.loc[4:5] += 1\n expected = Series([1, 1, 0], index=[4, 5, 6])\n tm.assert_series_equal(s, expected)\n\n # GH 5928\n # chained indexing assignment\n df = DataFrame({'a': [0, 1, 2]})\n expected = df.copy()\n with catch_warnings(record=True):\n expected.ix[[0, 1, 2], 'a'] = -expected.ix[[0, 1, 2], 'a']\n\n with catch_warnings(record=True):\n df['a'].ix[[0, 1, 2]] = -df['a'].ix[[0, 1, 2]]\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({'a': [0, 1, 2], 'b': [0, 1, 2]})\n with catch_warnings(record=True):\n df['a'].ix[[0, 1, 2]] = -df['a'].ix[[0, 1, 2]].astype(\n 'float64') + 0.5\n expected = DataFrame({'a': [0.5, -0.5, -1.5], 'b': [0, 1, 2]})\n tm.assert_frame_equal(df, expected)\n\n # GH 8607\n # ix setitem consistency\n df = DataFrame({'timestamp': [1413840976, 1413842580, 1413760580],\n 'delta': [1174, 904, 161],\n 'elapsed': [7673, 9277, 1470]})\n expected = DataFrame({'timestamp': pd.to_datetime(\n [1413840976, 1413842580, 1413760580], unit='s'),\n 'delta': [1174, 904, 161],\n 'elapsed': [7673, 9277, 1470]})\n\n df2 = df.copy()\n df2['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')\n tm.assert_frame_equal(df2, expected)\n\n df2 = df.copy()\n df2.loc[:, 'timestamp'] = pd.to_datetime(df['timestamp'], unit='s')\n tm.assert_frame_equal(df2, expected)\n\n df2 = df.copy()\n with catch_warnings(record=True):\n df2.ix[:, 2] = pd.to_datetime(df['timestamp'], unit='s')\n tm.assert_frame_equal(df2, expected)\n\n def test_ix_loc_consistency(self):\n\n # GH 8613\n # some edge cases where ix/loc should return the same\n # this is not an exhaustive case\n\n def compare(result, expected):\n if is_scalar(expected):\n self.assertEqual(result, expected)\n else:\n self.assertTrue(expected.equals(result))\n\n # failure cases for .loc, but these work for .ix\n df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'))\n for key in [slice(1, 3), tuple([slice(0, 2), slice(0, 2)]),\n tuple([slice(0, 2), df.columns[0:2]])]:\n\n for index in [tm.makeStringIndex, tm.makeUnicodeIndex,\n tm.makeDateIndex, tm.makePeriodIndex,\n tm.makeTimedeltaIndex]:\n df.index = index(len(df.index))\n with catch_warnings(record=True):\n df.ix[key]\n\n self.assertRaises(TypeError, lambda: df.loc[key])\n\n df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'),\n index=pd.date_range('2012-01-01', periods=5))\n\n for key in ['2012-01-03',\n '2012-01-31',\n slice('2012-01-03', '2012-01-03'),\n slice('2012-01-03', '2012-01-04'),\n slice('2012-01-03', '2012-01-06', 2),\n slice('2012-01-03', '2012-01-31'),\n tuple([[True, True, True, False, True]]), ]:\n\n # getitem\n\n # if the expected raises, then compare the exceptions\n try:\n with catch_warnings(record=True):\n expected = df.ix[key]\n except KeyError:\n self.assertRaises(KeyError, lambda: df.loc[key])\n continue\n\n result = df.loc[key]\n compare(result, expected)\n\n # setitem\n df1 = df.copy()\n df2 = df.copy()\n\n with catch_warnings(record=True):\n df1.ix[key] = 10\n df2.loc[key] = 10\n compare(df2, df1)\n\n # edge cases\n s = Series([1, 2, 3, 4], index=list('abde'))\n\n result1 = s['a':'c']\n with catch_warnings(record=True):\n result2 = s.ix['a':'c']\n result3 = s.loc['a':'c']\n tm.assert_series_equal(result1, result2)\n tm.assert_series_equal(result1, result3)\n\n # now work rather than raising KeyError\n s = Series(range(5), [-2, -1, 1, 2, 3])\n\n with catch_warnings(record=True):\n result1 = s.ix[-10:3]\n result2 = s.loc[-10:3]\n tm.assert_series_equal(result1, result2)\n\n with catch_warnings(record=True):\n result1 = s.ix[0:3]\n result2 = s.loc[0:3]\n tm.assert_series_equal(result1, result2)\n\n def test_setitem_multiindex(self):\n for index_fn in ('ix', 'loc'):\n\n def check(target, indexers, value, compare_fn, expected=None):\n fn = getattr(target, index_fn)\n fn.__setitem__(indexers, value)\n result = fn.__getitem__(indexers)\n if expected is None:\n expected = value\n compare_fn(result, expected)\n # GH7190\n index = pd.MultiIndex.from_product([np.arange(0, 100),\n np.arange(0, 80)],\n names=['time', 'firm'])\n t, n = 0, 2\n df = DataFrame(np.nan, columns=['A', 'w', 'l', 'a', 'x',\n 'X', 'd', 'profit'],\n index=index)\n check(target=df, indexers=((t, n), 'X'), value=0,\n compare_fn=self.assertEqual)\n\n df = DataFrame(-999, columns=['A', 'w', 'l', 'a', 'x',\n 'X', 'd', 'profit'],\n index=index)\n check(target=df, indexers=((t, n), 'X'), value=1,\n compare_fn=self.assertEqual)\n\n df = DataFrame(columns=['A', 'w', 'l', 'a', 'x',\n 'X', 'd', 'profit'],\n index=index)\n check(target=df, indexers=((t, n), 'X'), value=2,\n compare_fn=self.assertEqual)\n\n # GH 7218, assinging with 0-dim arrays\n df = DataFrame(-999, columns=['A', 'w', 'l', 'a', 'x',\n 'X', 'd', 'profit'],\n index=index)\n check(target=df,\n indexers=((t, n), 'X'),\n value=np.array(3),\n compare_fn=self.assertEqual,\n expected=3, )\n\n # GH5206\n df = pd.DataFrame(np.arange(25).reshape(5, 5),\n columns='A,B,C,D,E'.split(','), dtype=float)\n df['F'] = 99\n row_selection = df['A'] % 2 == 0\n col_selection = ['B', 'C']\n with catch_warnings(record=True):\n df.ix[row_selection, col_selection] = df['F']\n output = pd.DataFrame(99., index=[0, 2, 4], columns=['B', 'C'])\n with catch_warnings(record=True):\n tm.assert_frame_equal(df.ix[row_selection, col_selection],\n output)\n check(target=df,\n indexers=(row_selection, col_selection),\n value=df['F'],\n compare_fn=tm.assert_frame_equal,\n expected=output, )\n\n # GH11372\n idx = pd.MultiIndex.from_product([\n ['A', 'B', 'C'],\n pd.date_range('2015-01-01', '2015-04-01', freq='MS')])\n cols = pd.MultiIndex.from_product([\n ['foo', 'bar'],\n pd.date_range('2016-01-01', '2016-02-01', freq='MS')])\n\n df = pd.DataFrame(np.random.random((12, 4)),\n index=idx, columns=cols)\n\n subidx = pd.MultiIndex.from_tuples(\n [('A', pd.Timestamp('2015-01-01')),\n ('A', pd.Timestamp('2015-02-01'))])\n subcols = pd.MultiIndex.from_tuples(\n [('foo', pd.Timestamp('2016-01-01')),\n ('foo', pd.Timestamp('2016-02-01'))])\n\n vals = pd.DataFrame(np.random.random((2, 2)),\n index=subidx, columns=subcols)\n check(target=df,\n indexers=(subidx, subcols),\n value=vals,\n compare_fn=tm.assert_frame_equal, )\n # set all columns\n vals = pd.DataFrame(\n np.random.random((2, 4)), index=subidx, columns=cols)\n check(target=df,\n indexers=(subidx, slice(None, None, None)),\n value=vals,\n compare_fn=tm.assert_frame_equal, )\n # identity\n copy = df.copy()\n check(target=df, indexers=(df.index, df.columns), value=df,\n compare_fn=tm.assert_frame_equal, expected=copy)\n\n def test_indexing_with_datetime_tz(self):\n\n # 8260\n # support datetime64 with tz\n\n idx = Index(date_range('20130101', periods=3, tz='US/Eastern'),\n name='foo')\n dr = date_range('20130110', periods=3)\n df = DataFrame({'A': idx, 'B': dr})\n df['C'] = idx\n df.iloc[1, 1] = pd.NaT\n df.iloc[1, 2] = pd.NaT\n\n # indexing\n result = df.iloc[1]\n expected = Series([Timestamp('2013-01-02 00:00:00-0500',\n tz='US/Eastern'), np.nan, np.nan],\n index=list('ABC'), dtype='object', name=1)\n tm.assert_series_equal(result, expected)\n result = df.loc[1]\n expected = Series([Timestamp('2013-01-02 00:00:00-0500',\n tz='US/Eastern'), np.nan, np.nan],\n index=list('ABC'), dtype='object', name=1)\n tm.assert_series_equal(result, expected)\n\n # indexing - fast_xs\n df = DataFrame({'a': date_range('2014-01-01', periods=10, tz='UTC')})\n result = df.iloc[5]\n expected = Timestamp('2014-01-06 00:00:00+0000', tz='UTC', freq='D')\n self.assertEqual(result, expected)\n\n result = df.loc[5]\n self.assertEqual(result, expected)\n\n # indexing - boolean\n result = df[df.a > df.a[3]]\n expected = df.iloc[4:]\n tm.assert_frame_equal(result, expected)\n\n # indexing - setting an element\n df = DataFrame(data=pd.to_datetime(\n ['2015-03-30 20:12:32', '2015-03-12 00:11:11']), columns=['time'])\n df['new_col'] = ['new', 'old']\n df.time = df.set_index('time').index.tz_localize('UTC')\n v = df[df.new_col == 'new'].set_index('time').index.tz_convert(\n 'US/Pacific')\n\n # trying to set a single element on a part of a different timezone\n def f():\n df.loc[df.new_col == 'new', 'time'] = v\n\n self.assertRaises(ValueError, f)\n\n v = df.loc[df.new_col == 'new', 'time'] + pd.Timedelta('1s')\n df.loc[df.new_col == 'new', 'time'] = v\n tm.assert_series_equal(df.loc[df.new_col == 'new', 'time'], v)\n\n def test_indexing_with_datetimeindex_tz(self):\n\n # GH 12050\n # indexing on a series with a datetimeindex with tz\n index = pd.date_range('2015-01-01', periods=2, tz='utc')\n\n ser = pd.Series(range(2), index=index,\n dtype='int64')\n\n # list-like indexing\n\n for sel in (index, list(index)):\n # getitem\n tm.assert_series_equal(ser[sel], ser)\n\n # setitem\n result = ser.copy()\n result[sel] = 1\n expected = pd.Series(1, index=index)\n tm.assert_series_equal(result, expected)\n\n # .loc getitem\n tm.assert_series_equal(ser.loc[sel], ser)\n\n # .loc setitem\n result = ser.copy()\n result.loc[sel] = 1\n expected = pd.Series(1, index=index)\n tm.assert_series_equal(result, expected)\n\n # single element indexing\n\n # getitem\n self.assertEqual(ser[index[1]], 1)\n\n # setitem\n result = ser.copy()\n result[index[1]] = 5\n expected = pd.Series([0, 5], index=index)\n tm.assert_series_equal(result, expected)\n\n # .loc getitem\n self.assertEqual(ser.loc[index[1]], 1)\n\n # .loc setitem\n result = ser.copy()\n result.loc[index[1]] = 5\n expected = pd.Series([0, 5], index=index)\n tm.assert_series_equal(result, expected)\n\n def test_loc_setitem_dups(self):\n\n # GH 6541\n df_orig = DataFrame(\n {'me': list('rttti'),\n 'foo': list('aaade'),\n 'bar': np.arange(5, dtype='float64') * 1.34 + 2,\n 'bar2': np.arange(5, dtype='float64') * -.34 + 2}).set_index('me')\n\n indexer = tuple(['r', ['bar', 'bar2']])\n df = df_orig.copy()\n df.loc[indexer] *= 2.0\n tm.assert_series_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer])\n\n indexer = tuple(['r', 'bar'])\n df = df_orig.copy()\n df.loc[indexer] *= 2.0\n self.assertEqual(df.loc[indexer], 2.0 * df_orig.loc[indexer])\n\n indexer = tuple(['t', ['bar', 'bar2']])\n df = df_orig.copy()\n df.loc[indexer] *= 2.0\n tm.assert_frame_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer])\n\n def test_iloc_setitem_dups(self):\n\n # GH 6766\n # iloc with a mask aligning from another iloc\n df1 = DataFrame([{'A': None, 'B': 1}, {'A': 2, 'B': 2}])\n df2 = DataFrame([{'A': 3, 'B': 3}, {'A': 4, 'B': 4}])\n df = concat([df1, df2], axis=1)\n\n expected = df.fillna(3)\n expected['A'] = expected['A'].astype('float64')\n inds = np.isnan(df.iloc[:, 0])\n mask = inds[inds].index\n df.iloc[mask, 0] = df.iloc[mask, 2]\n tm.assert_frame_equal(df, expected)\n\n # del a dup column across blocks\n expected = DataFrame({0: [1, 2], 1: [3, 4]})\n expected.columns = ['B', 'B']\n del df['A']\n tm.assert_frame_equal(df, expected)\n\n # assign back to self\n df.iloc[[0, 1], [0, 1]] = df.iloc[[0, 1], [0, 1]]\n tm.assert_frame_equal(df, expected)\n\n # reversed x 2\n df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(\n drop=True)\n df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(\n drop=True)\n tm.assert_frame_equal(df, expected)\n\n def test_chained_getitem_with_lists(self):\n\n # GH6394\n # Regression in chained getitem indexing with embedded list-like from\n # 0.12\n def check(result, expected):\n tm.assert_numpy_array_equal(result, expected)\n tm.assertIsInstance(result, np.ndarray)\n\n df = DataFrame({'A': 5 * [np.zeros(3)], 'B': 5 * [np.ones(3)]})\n expected = df['A'].iloc[2]\n result = df.loc[2, 'A']\n check(result, expected)\n result2 = df.iloc[2]['A']\n check(result2, expected)\n result3 = df['A'].loc[2]\n check(result3, expected)\n result4 = df['A'].iloc[2]\n check(result4, expected)\n\n def test_loc_getitem_int(self):\n\n # int label\n self.check_result('int label', 'loc', 2, 'ix', 2,\n typs=['ints', 'uints'], axes=0)\n self.check_result('int label', 'loc', 3, 'ix', 3,\n typs=['ints', 'uints'], axes=1)\n self.check_result('int label', 'loc', 4, 'ix', 4,\n typs=['ints', 'uints'], axes=2)\n self.check_result('int label', 'loc', 2, 'ix', 2,\n typs=['label'], fails=KeyError)\n\n def test_loc_getitem_label(self):\n\n # label\n self.check_result('label', 'loc', 'c', 'ix', 'c', typs=['labels'],\n axes=0)\n self.check_result('label', 'loc', 'null', 'ix', 'null', typs=['mixed'],\n axes=0)\n self.check_result('label', 'loc', 8, 'ix', 8, typs=['mixed'], axes=0)\n self.check_result('label', 'loc', Timestamp('20130102'), 'ix', 1,\n typs=['ts'], axes=0)\n self.check_result('label', 'loc', 'c', 'ix', 'c', typs=['empty'],\n fails=KeyError)\n\n def test_loc_getitem_label_out_of_range(self):\n\n # out of range label\n self.check_result('label range', 'loc', 'f', 'ix', 'f',\n typs=['ints', 'uints', 'labels', 'mixed', 'ts'],\n fails=KeyError)\n self.check_result('label range', 'loc', 'f', 'ix', 'f',\n typs=['floats'], fails=TypeError)\n self.check_result('label range', 'loc', 20, 'ix', 20,\n typs=['ints', 'uints', 'mixed'], fails=KeyError)\n self.check_result('label range', 'loc', 20, 'ix', 20,\n typs=['labels'], fails=TypeError)\n self.check_result('label range', 'loc', 20, 'ix', 20, typs=['ts'],\n axes=0, fails=TypeError)\n self.check_result('label range', 'loc', 20, 'ix', 20, typs=['floats'],\n axes=0, fails=TypeError)\n\n def test_loc_getitem_label_list(self):\n\n # list of labels\n self.check_result('list lbl', 'loc', [0, 2, 4], 'ix', [0, 2, 4],\n typs=['ints', 'uints'], axes=0)\n self.check_result('list lbl', 'loc', [3, 6, 9], 'ix', [3, 6, 9],\n typs=['ints', 'uints'], axes=1)\n self.check_result('list lbl', 'loc', [4, 8, 12], 'ix', [4, 8, 12],\n typs=['ints', 'uints'], axes=2)\n self.check_result('list lbl', 'loc', ['a', 'b', 'd'], 'ix',\n ['a', 'b', 'd'], typs=['labels'], axes=0)\n self.check_result('list lbl', 'loc', ['A', 'B', 'C'], 'ix',\n ['A', 'B', 'C'], typs=['labels'], axes=1)\n self.check_result('list lbl', 'loc', ['Z', 'Y', 'W'], 'ix',\n ['Z', 'Y', 'W'], typs=['labels'], axes=2)\n self.check_result('list lbl', 'loc', [2, 8, 'null'], 'ix',\n [2, 8, 'null'], typs=['mixed'], axes=0)\n self.check_result('list lbl', 'loc',\n [Timestamp('20130102'), Timestamp('20130103')], 'ix',\n [Timestamp('20130102'), Timestamp('20130103')],\n typs=['ts'], axes=0)\n\n self.check_result('list lbl', 'loc', [0, 1, 2], 'indexer', [0, 1, 2],\n typs=['empty'], fails=KeyError)\n self.check_result('list lbl', 'loc', [0, 2, 3], 'ix', [0, 2, 3],\n typs=['ints', 'uints'], axes=0, fails=KeyError)\n self.check_result('list lbl', 'loc', [3, 6, 7], 'ix', [3, 6, 7],\n typs=['ints', 'uints'], axes=1, fails=KeyError)\n self.check_result('list lbl', 'loc', [4, 8, 10], 'ix', [4, 8, 10],\n typs=['ints', 'uints'], axes=2, fails=KeyError)\n\n def test_loc_getitem_label_list_fails(self):\n # fails\n self.check_result('list lbl', 'loc', [20, 30, 40], 'ix', [20, 30, 40],\n typs=['ints', 'uints'], axes=1, fails=KeyError)\n self.check_result('list lbl', 'loc', [20, 30, 40], 'ix', [20, 30, 40],\n typs=['ints', 'uints'], axes=2, fails=KeyError)\n\n def test_loc_getitem_label_array_like(self):\n # array like\n self.check_result('array like', 'loc', Series(index=[0, 2, 4]).index,\n 'ix', [0, 2, 4], typs=['ints', 'uints'], axes=0)\n self.check_result('array like', 'loc', Series(index=[3, 6, 9]).index,\n 'ix', [3, 6, 9], typs=['ints', 'uints'], axes=1)\n self.check_result('array like', 'loc', Series(index=[4, 8, 12]).index,\n 'ix', [4, 8, 12], typs=['ints', 'uints'], axes=2)\n\n def test_loc_getitem_series(self):\n # GH14730\n # passing a series as a key with a MultiIndex\n index = MultiIndex.from_product([[1, 2, 3], ['A', 'B', 'C']])\n x = Series(index=index, data=range(9), dtype=np.float64)\n y = Series([1, 3])\n expected = Series(\n data=[0, 1, 2, 6, 7, 8],\n index=MultiIndex.from_product([[1, 3], ['A', 'B', 'C']]),\n dtype=np.float64)\n result = x.loc[y]\n tm.assert_series_equal(result, expected)\n\n result = x.loc[[1, 3]]\n tm.assert_series_equal(result, expected)\n\n empty = Series(data=[], dtype=np.float64)\n expected = Series([], index=MultiIndex(\n levels=index.levels, labels=[[], []], dtype=np.float64))\n result = x.loc[empty]\n tm.assert_series_equal(result, expected)\n\n def test_loc_getitem_bool(self):\n # boolean indexers\n b = [True, False, True, False]\n self.check_result('bool', 'loc', b, 'ix', b,\n typs=['ints', 'uints', 'labels',\n 'mixed', 'ts', 'floats'])\n self.check_result('bool', 'loc', b, 'ix', b, typs=['empty'],\n fails=KeyError)\n\n def test_loc_getitem_int_slice(self):\n\n # ok\n self.check_result('int slice2', 'loc', slice(2, 4), 'ix', [2, 4],\n typs=['ints', 'uints'], axes=0)\n self.check_result('int slice2', 'loc', slice(3, 6), 'ix', [3, 6],\n typs=['ints', 'uints'], axes=1)\n self.check_result('int slice2', 'loc', slice(4, 8), 'ix', [4, 8],\n typs=['ints', 'uints'], axes=2)\n\n # GH 3053\n # loc should treat integer slices like label slices\n from itertools import product\n\n index = MultiIndex.from_tuples([t for t in product(\n [6, 7, 8], ['a', 'b'])])\n df = DataFrame(np.random.randn(6, 6), index, index)\n result = df.loc[6:8, :]\n with catch_warnings(record=True):\n expected = df.ix[6:8, :]\n tm.assert_frame_equal(result, expected)\n\n index = MultiIndex.from_tuples([t\n for t in product(\n [10, 20, 30], ['a', 'b'])])\n df = DataFrame(np.random.randn(6, 6), index, index)\n result = df.loc[20:30, :]\n with catch_warnings(record=True):\n expected = df.ix[20:30, :]\n tm.assert_frame_equal(result, expected)\n\n # doc examples\n result = df.loc[10, :]\n with catch_warnings(record=True):\n expected = df.ix[10, :]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[:, 10]\n # expected = df.ix[:,10] (this fails)\n expected = df[10]\n tm.assert_frame_equal(result, expected)\n\n def test_loc_to_fail(self):\n\n # GH3449\n df = DataFrame(np.random.random((3, 3)),\n index=['a', 'b', 'c'],\n columns=['e', 'f', 'g'])\n\n # raise a KeyError?\n self.assertRaises(KeyError, df.loc.__getitem__,\n tuple([[1, 2], [1, 2]]))\n\n # GH 7496\n # loc should not fallback\n\n s = Series()\n s.loc[1] = 1\n s.loc['a'] = 2\n\n self.assertRaises(KeyError, lambda: s.loc[-1])\n self.assertRaises(KeyError, lambda: s.loc[[-1, -2]])\n\n self.assertRaises(KeyError, lambda: s.loc[['4']])\n\n s.loc[-1] = 3\n result = s.loc[[-1, -2]]\n expected = Series([3, np.nan], index=[-1, -2])\n tm.assert_series_equal(result, expected)\n\n s['a'] = 2\n self.assertRaises(KeyError, lambda: s.loc[[-2]])\n\n del s['a']\n\n def f():\n s.loc[[-2]] = 0\n\n self.assertRaises(KeyError, f)\n\n # inconsistency between .loc[values] and .loc[values,:]\n # GH 7999\n df = DataFrame([['a'], ['b']], index=[1, 2], columns=['value'])\n\n def f():\n df.loc[[3], :]\n\n self.assertRaises(KeyError, f)\n\n def f():\n df.loc[[3]]\n\n self.assertRaises(KeyError, f)\n\n def test_at_to_fail(self):\n # at should not fallback\n # GH 7814\n s = Series([1, 2, 3], index=list('abc'))\n result = s.at['a']\n self.assertEqual(result, 1)\n self.assertRaises(ValueError, lambda: s.at[0])\n\n df = DataFrame({'A': [1, 2, 3]}, index=list('abc'))\n result = df.at['a', 'A']\n self.assertEqual(result, 1)\n self.assertRaises(ValueError, lambda: df.at['a', 0])\n\n s = Series([1, 2, 3], index=[3, 2, 1])\n result = s.at[1]\n self.assertEqual(result, 3)\n self.assertRaises(ValueError, lambda: s.at['a'])\n\n df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1])\n result = df.at[1, 0]\n self.assertEqual(result, 3)\n self.assertRaises(ValueError, lambda: df.at['a', 0])\n\n # GH 13822, incorrect error string with non-unique columns when missing\n # column is accessed\n df = DataFrame({'x': [1.], 'y': [2.], 'z': [3.]})\n df.columns = ['x', 'x', 'z']\n\n # Check that we get the correct value in the KeyError\n self.assertRaisesRegexp(KeyError, r\"\\['y'\\] not in index\",\n lambda: df[['x', 'y', 'z']])\n\n def test_loc_getitem_label_slice(self):\n\n # label slices (with ints)\n self.check_result('lab slice', 'loc', slice(1, 3),\n 'ix', slice(1, 3),\n typs=['labels', 'mixed', 'empty', 'ts', 'floats'],\n fails=TypeError)\n\n # real label slices\n self.check_result('lab slice', 'loc', slice('a', 'c'),\n 'ix', slice('a', 'c'), typs=['labels'], axes=0)\n self.check_result('lab slice', 'loc', slice('A', 'C'),\n 'ix', slice('A', 'C'), typs=['labels'], axes=1)\n self.check_result('lab slice', 'loc', slice('W', 'Z'),\n 'ix', slice('W', 'Z'), typs=['labels'], axes=2)\n\n self.check_result('ts slice', 'loc', slice('20130102', '20130104'),\n 'ix', slice('20130102', '20130104'),\n typs=['ts'], axes=0)\n self.check_result('ts slice', 'loc', slice('20130102', '20130104'),\n 'ix', slice('20130102', '20130104'),\n typs=['ts'], axes=1, fails=TypeError)\n self.check_result('ts slice', 'loc', slice('20130102', '20130104'),\n 'ix', slice('20130102', '20130104'),\n typs=['ts'], axes=2, fails=TypeError)\n\n # GH 14316\n self.check_result('ts slice rev', 'loc', slice('20130104', '20130102'),\n 'indexer', [0, 1, 2], typs=['ts_rev'], axes=0)\n\n self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8),\n typs=['mixed'], axes=0, fails=TypeError)\n self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8),\n typs=['mixed'], axes=1, fails=KeyError)\n self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8),\n typs=['mixed'], axes=2, fails=KeyError)\n\n self.check_result('mixed slice', 'loc', slice(2, 4, 2), 'ix', slice(\n 2, 4, 2), typs=['mixed'], axes=0, fails=TypeError)\n\n def test_loc_general(self):\n\n df = DataFrame(\n np.random.rand(4, 4), columns=['A', 'B', 'C', 'D'],\n index=['A', 'B', 'C', 'D'])\n\n # want this to work\n result = df.loc[:, \"A\":\"B\"].iloc[0:2, :]\n self.assertTrue((result.columns == ['A', 'B']).all())\n self.assertTrue((result.index == ['A', 'B']).all())\n\n # mixed type\n result = DataFrame({'a': [Timestamp('20130101')], 'b': [1]}).iloc[0]\n expected = Series([Timestamp('20130101'), 1], index=['a', 'b'], name=0)\n tm.assert_series_equal(result, expected)\n self.assertEqual(result.dtype, object)\n\n def test_loc_setitem_consistency(self):\n # GH 6149\n # coerce similary for setitem and loc when rows have a null-slice\n expected = DataFrame({'date': Series(0, index=range(5),\n dtype=np.int64),\n 'val': Series(range(5), dtype=np.int64)})\n\n df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'),\n 'val': Series(\n range(5), dtype=np.int64)})\n df.loc[:, 'date'] = 0\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'),\n 'val': Series(range(5), dtype=np.int64)})\n df.loc[:, 'date'] = np.array(0, dtype=np.int64)\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'),\n 'val': Series(range(5), dtype=np.int64)})\n df.loc[:, 'date'] = np.array([0, 0, 0, 0, 0], dtype=np.int64)\n tm.assert_frame_equal(df, expected)\n\n expected = DataFrame({'date': Series('foo', index=range(5)),\n 'val': Series(range(5), dtype=np.int64)})\n df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'),\n 'val': Series(range(5), dtype=np.int64)})\n df.loc[:, 'date'] = 'foo'\n tm.assert_frame_equal(df, expected)\n\n expected = DataFrame({'date': Series(1.0, index=range(5)),\n 'val': Series(range(5), dtype=np.int64)})\n df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'),\n 'val': Series(range(5), dtype=np.int64)})\n df.loc[:, 'date'] = 1.0\n tm.assert_frame_equal(df, expected)\n\n def test_loc_setitem_consistency_empty(self):\n # empty (essentially noops)\n expected = DataFrame(columns=['x', 'y'])\n expected['x'] = expected['x'].astype(np.int64)\n df = DataFrame(columns=['x', 'y'])\n df.loc[:, 'x'] = 1\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame(columns=['x', 'y'])\n df['x'] = 1\n tm.assert_frame_equal(df, expected)\n\n def test_loc_setitem_consistency_slice_column_len(self):\n # .loc[:,column] setting with slice == len of the column\n # GH10408\n data = \"\"\"Level_0,,,Respondent,Respondent,Respondent,OtherCat,OtherCat\nLevel_1,,,Something,StartDate,EndDate,Yes/No,SomethingElse\nRegion,Site,RespondentID,,,,,\nRegion_1,Site_1,3987227376,A,5/25/2015 10:59,5/25/2015 11:22,Yes,\nRegion_1,Site_1,3980680971,A,5/21/2015 9:40,5/21/2015 9:52,Yes,Yes\nRegion_1,Site_2,3977723249,A,5/20/2015 8:27,5/20/2015 8:41,Yes,\nRegion_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No\"\"\"\n\n df = pd.read_csv(StringIO(data), header=[0, 1], index_col=[0, 1, 2])\n df.loc[:, ('Respondent', 'StartDate')] = pd.to_datetime(df.loc[:, (\n 'Respondent', 'StartDate')])\n df.loc[:, ('Respondent', 'EndDate')] = pd.to_datetime(df.loc[:, (\n 'Respondent', 'EndDate')])\n df.loc[:, ('Respondent', 'Duration')] = df.loc[:, (\n 'Respondent', 'EndDate')] - df.loc[:, ('Respondent', 'StartDate')]\n\n df.loc[:, ('Respondent', 'Duration')] = df.loc[:, (\n 'Respondent', 'Duration')].astype('timedelta64[s]')\n expected = Series([1380, 720, 840, 2160.], index=df.index,\n name=('Respondent', 'Duration'))\n tm.assert_series_equal(df[('Respondent', 'Duration')], expected)\n\n def test_loc_setitem_frame(self):\n df = self.frame_labels\n\n result = df.iloc[0, 0]\n\n df.loc['a', 'A'] = 1\n result = df.loc['a', 'A']\n self.assertEqual(result, 1)\n\n result = df.iloc[0, 0]\n self.assertEqual(result, 1)\n\n df.loc[:, 'B':'D'] = 0\n expected = df.loc[:, 'B':'D']\n with catch_warnings(record=True):\n result = df.ix[:, 1:]\n tm.assert_frame_equal(result, expected)\n\n # GH 6254\n # setting issue\n df = DataFrame(index=[3, 5, 4], columns=['A'])\n df.loc[[4, 3, 5], 'A'] = np.array([1, 2, 3], dtype='int64')\n expected = DataFrame(dict(A=Series(\n [1, 2, 3], index=[4, 3, 5]))).reindex(index=[3, 5, 4])\n tm.assert_frame_equal(df, expected)\n\n # GH 6252\n # setting with an empty frame\n keys1 = ['@' + str(i) for i in range(5)]\n val1 = np.arange(5, dtype='int64')\n\n keys2 = ['@' + str(i) for i in range(4)]\n val2 = np.arange(4, dtype='int64')\n\n index = list(set(keys1).union(keys2))\n df = DataFrame(index=index)\n df['A'] = nan\n df.loc[keys1, 'A'] = val1\n\n df['B'] = nan\n df.loc[keys2, 'B'] = val2\n\n expected = DataFrame(dict(A=Series(val1, index=keys1), B=Series(\n val2, index=keys2))).reindex(index=index)\n tm.assert_frame_equal(df, expected)\n\n # GH 8669\n # invalid coercion of nan -> int\n df = DataFrame({'A': [1, 2, 3], 'B': np.nan})\n df.loc[df.B > df.A, 'B'] = df.A\n expected = DataFrame({'A': [1, 2, 3], 'B': np.nan})\n tm.assert_frame_equal(df, expected)\n\n # GH 6546\n # setting with mixed labels\n df = DataFrame({1: [1, 2], 2: [3, 4], 'a': ['a', 'b']})\n\n result = df.loc[0, [1, 2]]\n expected = Series([1, 3], index=[1, 2], dtype=object, name=0)\n tm.assert_series_equal(result, expected)\n\n expected = DataFrame({1: [5, 2], 2: [6, 4], 'a': ['a', 'b']})\n df.loc[0, [1, 2]] = [5, 6]\n tm.assert_frame_equal(df, expected)\n\n def test_loc_setitem_frame_multiples(self):\n # multiple setting\n df = DataFrame({'A': ['foo', 'bar', 'baz'],\n 'B': Series(\n range(3), dtype=np.int64)})\n rhs = df.loc[1:2]\n rhs.index = df.index[0:2]\n df.loc[0:1] = rhs\n expected = DataFrame({'A': ['bar', 'baz', 'baz'],\n 'B': Series(\n [1, 2, 2], dtype=np.int64)})\n tm.assert_frame_equal(df, expected)\n\n # multiple setting with frame on rhs (with M8)\n df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'),\n 'val': Series(\n range(5), dtype=np.int64)})\n expected = DataFrame({'date': [Timestamp('20000101'), Timestamp(\n '20000102'), Timestamp('20000101'), Timestamp('20000102'),\n Timestamp('20000103')],\n 'val': Series(\n [0, 1, 0, 1, 2], dtype=np.int64)})\n rhs = df.loc[0:2]\n rhs.index = df.index[2:5]\n df.loc[2:4] = rhs\n tm.assert_frame_equal(df, expected)\n\n def test_iloc_getitem_frame(self):\n df = DataFrame(np.random.randn(10, 4), index=lrange(0, 20, 2),\n columns=lrange(0, 8, 2))\n\n result = df.iloc[2]\n with catch_warnings(record=True):\n exp = df.ix[4]\n tm.assert_series_equal(result, exp)\n\n result = df.iloc[2, 2]\n with catch_warnings(record=True):\n exp = df.ix[4, 4]\n self.assertEqual(result, exp)\n\n # slice\n result = df.iloc[4:8]\n with catch_warnings(record=True):\n expected = df.ix[8:14]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[:, 2:3]\n with catch_warnings(record=True):\n expected = df.ix[:, 4:5]\n tm.assert_frame_equal(result, expected)\n\n # list of integers\n result = df.iloc[[0, 1, 3]]\n with catch_warnings(record=True):\n expected = df.ix[[0, 2, 6]]\n tm.assert_frame_equal(result, expected)\n\n result = df.iloc[[0, 1, 3], [0, 1]]\n with catch_warnings(record=True):\n expected = df.ix[[0, 2, 6], [0, 2]]\n tm.assert_frame_equal(result, expected)\n\n # neg indicies\n result = df.iloc[[-1, 1, 3], [-1, 1]]\n with catch_warnings(record=True):\n expected = df.ix[[18, 2, 6], [6, 2]]\n tm.assert_frame_equal(result, expected)\n\n # dups indicies\n result = df.iloc[[-1, -1, 1, 3], [-1, 1]]\n with catch_warnings(record=True):\n expected = df.ix[[18, 18, 2, 6], [6, 2]]\n tm.assert_frame_equal(result, expected)\n\n # with index-like\n s = Series(index=lrange(1, 5))\n result = df.iloc[s.index]\n with catch_warnings(record=True):\n expected = df.ix[[2, 4, 6, 8]]\n tm.assert_frame_equal(result, expected)\n\n def test_iloc_getitem_labelled_frame(self):\n # try with labelled frame\n df = DataFrame(np.random.randn(10, 4),\n index=list('abcdefghij'), columns=list('ABCD'))\n\n result = df.iloc[1, 1]\n exp = df.loc['b', 'B']\n self.assertEqual(result, exp)\n\n result = df.iloc[:, 2:3]\n expected = df.loc[:, ['C']]\n tm.assert_frame_equal(result, expected)\n\n # negative indexing\n result = df.iloc[-1, -1]\n exp = df.loc['j', 'D']\n self.assertEqual(result, exp)\n\n # out-of-bounds exception\n self.assertRaises(IndexError, df.iloc.__getitem__, tuple([10, 5]))\n\n # trying to use a label\n self.assertRaises(ValueError, df.iloc.__getitem__, tuple(['j', 'D']))\n\n def test_iloc_getitem_panel(self):\n\n # GH 7189\n p = Panel(np.arange(4 * 3 * 2).reshape(4, 3, 2),\n items=['A', 'B', 'C', 'D'],\n major_axis=['a', 'b', 'c'],\n minor_axis=['one', 'two'])\n\n result = p.iloc[1]\n expected = p.loc['B']\n tm.assert_frame_equal(result, expected)\n\n result = p.iloc[1, 1]\n expected = p.loc['B', 'b']\n tm.assert_series_equal(result, expected)\n\n result = p.iloc[1, 1, 1]\n expected = p.loc['B', 'b', 'two']\n self.assertEqual(result, expected)\n\n # slice\n result = p.iloc[1:3]\n expected = p.loc[['B', 'C']]\n tm.assert_panel_equal(result, expected)\n\n result = p.iloc[:, 0:2]\n expected = p.loc[:, ['a', 'b']]\n tm.assert_panel_equal(result, expected)\n\n # list of integers\n result = p.iloc[[0, 2]]\n expected = p.loc[['A', 'C']]\n tm.assert_panel_equal(result, expected)\n\n # neg indicies\n result = p.iloc[[-1, 1], [-1, 1]]\n expected = p.loc[['D', 'B'], ['c', 'b']]\n tm.assert_panel_equal(result, expected)\n\n # dups indicies\n result = p.iloc[[-1, -1, 1], [-1, 1]]\n expected = p.loc[['D', 'D', 'B'], ['c', 'b']]\n tm.assert_panel_equal(result, expected)\n\n # combined\n result = p.iloc[0, [True, True], [0, 1]]\n expected = p.loc['A', ['a', 'b'], ['one', 'two']]\n tm.assert_frame_equal(result, expected)\n\n # out-of-bounds exception\n self.assertRaises(IndexError, p.iloc.__getitem__, tuple([10, 5]))\n\n def f():\n p.iloc[0, [True, True], [0, 1, 2]]\n\n self.assertRaises(IndexError, f)\n\n # trying to use a label\n self.assertRaises(ValueError, p.iloc.__getitem__, tuple(['j', 'D']))\n\n # GH\n p = Panel(\n np.random.rand(4, 3, 2), items=['A', 'B', 'C', 'D'],\n major_axis=['U', 'V', 'W'], minor_axis=['X', 'Y'])\n expected = p['A']\n\n result = p.iloc[0, :, :]\n tm.assert_frame_equal(result, expected)\n\n result = p.iloc[0, [True, True, True], :]\n tm.assert_frame_equal(result, expected)\n\n result = p.iloc[0, [True, True, True], [0, 1]]\n tm.assert_frame_equal(result, expected)\n\n def f():\n p.iloc[0, [True, True, True], [0, 1, 2]]\n\n self.assertRaises(IndexError, f)\n\n def f():\n p.iloc[0, [True, True, True], [2]]\n\n self.assertRaises(IndexError, f)\n\n def test_iloc_getitem_panel_multiindex(self):\n # GH 7199\n # Panel with multi-index\n multi_index = pd.MultiIndex.from_tuples([('ONE', 'one'),\n ('TWO', 'two'),\n ('THREE', 'three')],\n names=['UPPER', 'lower'])\n\n simple_index = [x[0] for x in multi_index]\n wd1 = Panel(items=['First', 'Second'], major_axis=['a', 'b', 'c', 'd'],\n minor_axis=multi_index)\n\n wd2 = Panel(items=['First', 'Second'], major_axis=['a', 'b', 'c', 'd'],\n minor_axis=simple_index)\n\n expected1 = wd1['First'].iloc[[True, True, True, False], [0, 2]]\n result1 = wd1.iloc[0, [True, True, True, False], [0, 2]] # WRONG\n tm.assert_frame_equal(result1, expected1)\n\n expected2 = wd2['First'].iloc[[True, True, True, False], [0, 2]]\n result2 = wd2.iloc[0, [True, True, True, False], [0, 2]]\n tm.assert_frame_equal(result2, expected2)\n\n expected1 = DataFrame(index=['a'], columns=multi_index,\n dtype='float64')\n result1 = wd1.iloc[0, [0], [0, 1, 2]]\n tm.assert_frame_equal(result1, expected1)\n\n expected2 = DataFrame(index=['a'], columns=simple_index,\n dtype='float64')\n result2 = wd2.iloc[0, [0], [0, 1, 2]]\n tm.assert_frame_equal(result2, expected2)\n\n # GH 7516\n mi = MultiIndex.from_tuples([(0, 'x'), (1, 'y'), (2, 'z')])\n p = Panel(np.arange(3 * 3 * 3, dtype='int64').reshape(3, 3, 3),\n items=['a', 'b', 'c'], major_axis=mi,\n minor_axis=['u', 'v', 'w'])\n result = p.iloc[:, 1, 0]\n expected = Series([3, 12, 21], index=['a', 'b', 'c'], name='u')\n tm.assert_series_equal(result, expected)\n\n result = p.loc[:, (1, 'y'), 'u']\n tm.assert_series_equal(result, expected)\n\n def test_iloc_getitem_doc_issue(self):\n\n # multi axis slicing issue with single block\n # surfaced in GH 6059\n\n arr = np.random.randn(6, 4)\n index = date_range('20130101', periods=6)\n columns = list('ABCD')\n df = DataFrame(arr, index=index, columns=columns)\n\n # defines ref_locs\n df.describe()\n\n result = df.iloc[3:5, 0:2]\n str(result)\n result.dtypes\n\n expected = DataFrame(arr[3:5, 0:2], index=index[3:5],\n columns=columns[0:2])\n tm.assert_frame_equal(result, expected)\n\n # for dups\n df.columns = list('aaaa')\n result = df.iloc[3:5, 0:2]\n str(result)\n result.dtypes\n\n expected = DataFrame(arr[3:5, 0:2], index=index[3:5],\n columns=list('aa'))\n tm.assert_frame_equal(result, expected)\n\n # related\n arr = np.random.randn(6, 4)\n index = list(range(0, 12, 2))\n columns = list(range(0, 8, 2))\n df = DataFrame(arr, index=index, columns=columns)\n\n df._data.blocks[0].mgr_locs\n result = df.iloc[1:5, 2:4]\n str(result)\n result.dtypes\n expected = DataFrame(arr[1:5, 2:4], index=index[1:5],\n columns=columns[2:4])\n tm.assert_frame_equal(result, expected)\n\n def test_setitem_ndarray_1d(self):\n # GH5508\n\n # len of indexer vs length of the 1d ndarray\n df = DataFrame(index=Index(lrange(1, 11)))\n df['foo'] = np.zeros(10, dtype=np.float64)\n df['bar'] = np.zeros(10, dtype=np.complex)\n\n # invalid\n def f():\n with catch_warnings(record=True):\n df.ix[2:5, 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2])\n\n self.assertRaises(ValueError, f)\n\n def f():\n df.loc[df.index[2:5], 'bar'] = np.array([2.33j, 1.23 + 0.1j,\n 2.2, 1.0])\n\n self.assertRaises(ValueError, f)\n\n # valid\n df.loc[df.index[2:6], 'bar'] = np.array([2.33j, 1.23 + 0.1j,\n 2.2, 1.0])\n\n result = df.loc[df.index[2:6], 'bar']\n expected = Series([2.33j, 1.23 + 0.1j, 2.2, 1.0], index=[3, 4, 5, 6],\n name='bar')\n tm.assert_series_equal(result, expected)\n\n # dtype getting changed?\n df = DataFrame(index=Index(lrange(1, 11)))\n df['foo'] = np.zeros(10, dtype=np.float64)\n df['bar'] = np.zeros(10, dtype=np.complex)\n\n def f():\n df[2:5] = np.arange(1, 4) * 1j\n\n self.assertRaises(ValueError, f)\n\n def test_iloc_setitem_series(self):\n df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'),\n columns=list('ABCD'))\n\n df.iloc[1, 1] = 1\n result = df.iloc[1, 1]\n self.assertEqual(result, 1)\n\n df.iloc[:, 2:3] = 0\n expected = df.iloc[:, 2:3]\n result = df.iloc[:, 2:3]\n tm.assert_frame_equal(result, expected)\n\n s = Series(np.random.randn(10), index=lrange(0, 20, 2))\n\n s.iloc[1] = 1\n result = s.iloc[1]\n self.assertEqual(result, 1)\n\n s.iloc[:4] = 0\n expected = s.iloc[:4]\n result = s.iloc[:4]\n tm.assert_series_equal(result, expected)\n\n s = Series([-1] * 6)\n s.iloc[0::2] = [0, 2, 4]\n s.iloc[1::2] = [1, 3, 5]\n result = s\n expected = Series([0, 1, 2, 3, 4, 5])\n tm.assert_series_equal(result, expected)\n\n def test_iloc_setitem_list_of_lists(self):\n\n # GH 7551\n # list-of-list is set incorrectly in mixed vs. single dtyped frames\n df = DataFrame(dict(A=np.arange(5, dtype='int64'),\n B=np.arange(5, 10, dtype='int64')))\n df.iloc[2:4] = [[10, 11], [12, 13]]\n expected = DataFrame(dict(A=[0, 1, 10, 12, 4], B=[5, 6, 11, 13, 9]))\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame(\n dict(A=list('abcde'), B=np.arange(5, 10, dtype='int64')))\n df.iloc[2:4] = [['x', 11], ['y', 13]]\n expected = DataFrame(dict(A=['a', 'b', 'x', 'y', 'e'],\n B=[5, 6, 11, 13, 9]))\n tm.assert_frame_equal(df, expected)\n\n def test_iloc_getitem_multiindex(self):\n mi_labels = DataFrame(np.random.randn(4, 3),\n columns=[['i', 'i', 'j'], ['A', 'A', 'B']],\n index=[['i', 'i', 'j', 'k'],\n ['X', 'X', 'Y', 'Y']])\n\n mi_int = DataFrame(np.random.randn(3, 3),\n columns=[[2, 2, 4], [6, 8, 10]],\n index=[[4, 4, 8], [8, 10, 12]])\n\n # the first row\n rs = mi_int.iloc[0]\n with catch_warnings(record=True):\n xp = mi_int.ix[4].ix[8]\n tm.assert_series_equal(rs, xp, check_names=False)\n self.assertEqual(rs.name, (4, 8))\n self.assertEqual(xp.name, 8)\n\n # 2nd (last) columns\n rs = mi_int.iloc[:, 2]\n with catch_warnings(record=True):\n xp = mi_int.ix[:, 2]\n tm.assert_series_equal(rs, xp)\n\n # corner column\n rs = mi_int.iloc[2, 2]\n with catch_warnings(record=True):\n xp = mi_int.ix[:, 2].ix[2]\n self.assertEqual(rs, xp)\n\n # this is basically regular indexing\n rs = mi_labels.iloc[2, 2]\n with catch_warnings(record=True):\n xp = mi_labels.ix['j'].ix[:, 'j'].ix[0, 0]\n self.assertEqual(rs, xp)\n\n def test_loc_multiindex(self):\n\n mi_labels = DataFrame(np.random.randn(3, 3),\n columns=[['i', 'i', 'j'], ['A', 'A', 'B']],\n index=[['i', 'i', 'j'], ['X', 'X', 'Y']])\n\n mi_int = DataFrame(np.random.randn(3, 3),\n columns=[[2, 2, 4], [6, 8, 10]],\n index=[[4, 4, 8], [8, 10, 12]])\n\n # the first row\n rs = mi_labels.loc['i']\n with catch_warnings(record=True):\n xp = mi_labels.ix['i']\n tm.assert_frame_equal(rs, xp)\n\n # 2nd (last) columns\n rs = mi_labels.loc[:, 'j']\n with catch_warnings(record=True):\n xp = mi_labels.ix[:, 'j']\n tm.assert_frame_equal(rs, xp)\n\n # corner column\n rs = mi_labels.loc['j'].loc[:, 'j']\n with catch_warnings(record=True):\n xp = mi_labels.ix['j'].ix[:, 'j']\n tm.assert_frame_equal(rs, xp)\n\n # with a tuple\n rs = mi_labels.loc[('i', 'X')]\n with catch_warnings(record=True):\n xp = mi_labels.ix[('i', 'X')]\n tm.assert_frame_equal(rs, xp)\n\n rs = mi_int.loc[4]\n with catch_warnings(record=True):\n xp = mi_int.ix[4]\n tm.assert_frame_equal(rs, xp)\n\n def test_loc_multiindex_indexer_none(self):\n\n # GH6788\n # multi-index indexer is None (meaning take all)\n attributes = ['Attribute' + str(i) for i in range(1)]\n attribute_values = ['Value' + str(i) for i in range(5)]\n\n index = MultiIndex.from_product([attributes, attribute_values])\n df = 0.1 * np.random.randn(10, 1 * 5) + 0.5\n df = DataFrame(df, columns=index)\n result = df[attributes]\n tm.assert_frame_equal(result, df)\n\n # GH 7349\n # loc with a multi-index seems to be doing fallback\n df = DataFrame(np.arange(12).reshape(-1, 1),\n index=pd.MultiIndex.from_product([[1, 2, 3, 4],\n [1, 2, 3]]))\n\n expected = df.loc[([1, 2], ), :]\n result = df.loc[[1, 2]]\n tm.assert_frame_equal(result, expected)\n\n def test_loc_multiindex_incomplete(self):\n\n # GH 7399\n # incomplete indexers\n s = pd.Series(np.arange(15, dtype='int64'),\n MultiIndex.from_product([range(5), ['a', 'b', 'c']]))\n expected = s.loc[:, 'a':'c']\n\n result = s.loc[0:4, 'a':'c']\n tm.assert_series_equal(result, expected)\n tm.assert_series_equal(result, expected)\n\n result = s.loc[:4, 'a':'c']\n tm.assert_series_equal(result, expected)\n tm.assert_series_equal(result, expected)\n\n result = s.loc[0:, 'a':'c']\n tm.assert_series_equal(result, expected)\n tm.assert_series_equal(result, expected)\n\n # GH 7400\n # multiindexer gettitem with list of indexers skips wrong element\n s = pd.Series(np.arange(15, dtype='int64'),\n MultiIndex.from_product([range(5), ['a', 'b', 'c']]))\n expected = s.iloc[[6, 7, 8, 12, 13, 14]]\n result = s.loc[2:4:2, 'a':'c']\n tm.assert_series_equal(result, expected)\n\n def test_multiindex_perf_warn(self):\n\n if sys.version_info < (2, 7):\n raise nose.SkipTest('python version < 2.7')\n\n df = DataFrame({'jim': [0, 0, 1, 1],\n 'joe': ['x', 'x', 'z', 'y'],\n 'jolie': np.random.rand(4)}).set_index(['jim', 'joe'])\n\n with tm.assert_produces_warning(PerformanceWarning,\n clear=[pd.core.index]):\n df.loc[(1, 'z')]\n\n df = df.iloc[[2, 1, 3, 0]]\n with tm.assert_produces_warning(PerformanceWarning):\n df.loc[(0, )]\n\n def test_series_getitem_multiindex(self):\n\n # GH 6018\n # series regression getitem with a multi-index\n\n s = Series([1, 2, 3])\n s.index = MultiIndex.from_tuples([(0, 0), (1, 1), (2, 1)])\n\n result = s[:, 0]\n expected = Series([1], index=[0])\n tm.assert_series_equal(result, expected)\n\n result = s.loc[:, 1]\n expected = Series([2, 3], index=[1, 2])\n tm.assert_series_equal(result, expected)\n\n # xs\n result = s.xs(0, level=0)\n expected = Series([1], index=[0])\n tm.assert_series_equal(result, expected)\n\n result = s.xs(1, level=1)\n expected = Series([2, 3], index=[1, 2])\n tm.assert_series_equal(result, expected)\n\n # GH6258\n dt = list(date_range('20130903', periods=3))\n idx = MultiIndex.from_product([list('AB'), dt])\n s = Series([1, 3, 4, 1, 3, 4], index=idx)\n\n result = s.xs('20130903', level=1)\n expected = Series([1, 1], index=list('AB'))\n tm.assert_series_equal(result, expected)\n\n # GH5684\n idx = MultiIndex.from_tuples([('a', 'one'), ('a', 'two'), ('b', 'one'),\n ('b', 'two')])\n s = Series([1, 2, 3, 4], index=idx)\n s.index.set_names(['L1', 'L2'], inplace=True)\n result = s.xs('one', level='L2')\n expected = Series([1, 3], index=['a', 'b'])\n expected.index.set_names(['L1'], inplace=True)\n tm.assert_series_equal(result, expected)\n\n def test_ix_general(self):\n\n # ix general issues\n\n # GH 2817\n data = {'amount': {0: 700, 1: 600, 2: 222, 3: 333, 4: 444},\n 'col': {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0},\n 'year': {0: 2012, 1: 2011, 2: 2012, 3: 2012, 4: 2012}}\n df = DataFrame(data).set_index(keys=['col', 'year'])\n key = 4.0, 2012\n\n # emits a PerformanceWarning, ok\n with self.assert_produces_warning(PerformanceWarning):\n tm.assert_frame_equal(df.loc[key], df.iloc[2:])\n\n # this is ok\n df.sort_index(inplace=True)\n res = df.loc[key]\n\n # col has float dtype, result should be Float64Index\n index = MultiIndex.from_arrays([[4.] * 3, [2012] * 3],\n names=['col', 'year'])\n expected = DataFrame({'amount': [222, 333, 444]}, index=index)\n tm.assert_frame_equal(res, expected)\n\n def test_ix_weird_slicing(self):\n # http://stackoverflow.com/q/17056560/1240268\n df = DataFrame({'one': [1, 2, 3, np.nan, np.nan],\n 'two': [1, 2, 3, 4, 5]})\n df.loc[df['one'] > 1, 'two'] = -df['two']\n\n expected = DataFrame({'one': {0: 1.0,\n 1: 2.0,\n 2: 3.0,\n 3: nan,\n 4: nan},\n 'two': {0: 1,\n 1: -2,\n 2: -3,\n 3: 4,\n 4: 5}})\n tm.assert_frame_equal(df, expected)\n\n def test_xs_multiindex(self):\n\n # GH2903\n columns = MultiIndex.from_tuples(\n [('a', 'foo'), ('a', 'bar'), ('b', 'hello'),\n ('b', 'world')], names=['lvl0', 'lvl1'])\n df = DataFrame(np.random.randn(4, 4), columns=columns)\n df.sort_index(axis=1, inplace=True)\n result = df.xs('a', level='lvl0', axis=1)\n expected = df.iloc[:, 0:2].loc[:, 'a']\n tm.assert_frame_equal(result, expected)\n\n result = df.xs('foo', level='lvl1', axis=1)\n expected = df.iloc[:, 1:2].copy()\n expected.columns = expected.columns.droplevel('lvl1')\n tm.assert_frame_equal(result, expected)\n\n def test_per_axis_per_level_getitem(self):\n\n # GH6134\n # example test case\n ix = MultiIndex.from_product([_mklbl('A', 5), _mklbl('B', 7), _mklbl(\n 'C', 4), _mklbl('D', 2)])\n df = DataFrame(np.arange(len(ix.get_values())), index=ix)\n\n result = df.loc[(slice('A1', 'A3'), slice(None), ['C1', 'C3']), :]\n expected = df.loc[[tuple([a, b, c, d])\n for a, b, c, d in df.index.values\n if (a == 'A1' or a == 'A2' or a == 'A3') and (\n c == 'C1' or c == 'C3')]]\n tm.assert_frame_equal(result, expected)\n\n expected = df.loc[[tuple([a, b, c, d])\n for a, b, c, d in df.index.values\n if (a == 'A1' or a == 'A2' or a == 'A3') and (\n c == 'C1' or c == 'C2' or c == 'C3')]]\n result = df.loc[(slice('A1', 'A3'), slice(None), slice('C1', 'C3')), :]\n tm.assert_frame_equal(result, expected)\n\n # test multi-index slicing with per axis and per index controls\n index = MultiIndex.from_tuples([('A', 1), ('A', 2),\n ('A', 3), ('B', 1)],\n names=['one', 'two'])\n columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'),\n ('b', 'foo'), ('b', 'bah')],\n names=['lvl0', 'lvl1'])\n\n df = DataFrame(\n np.arange(16, dtype='int64').reshape(\n 4, 4), index=index, columns=columns)\n df = df.sort_index(axis=0).sort_index(axis=1)\n\n # identity\n result = df.loc[(slice(None), slice(None)), :]\n tm.assert_frame_equal(result, df)\n result = df.loc[(slice(None), slice(None)), (slice(None), slice(None))]\n tm.assert_frame_equal(result, df)\n result = df.loc[:, (slice(None), slice(None))]\n tm.assert_frame_equal(result, df)\n\n # index\n result = df.loc[(slice(None), [1]), :]\n expected = df.iloc[[0, 3]]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[(slice(None), 1), :]\n expected = df.iloc[[0, 3]]\n tm.assert_frame_equal(result, expected)\n\n # columns\n result = df.loc[:, (slice(None), ['foo'])]\n expected = df.iloc[:, [1, 3]]\n tm.assert_frame_equal(result, expected)\n\n # both\n result = df.loc[(slice(None), 1), (slice(None), ['foo'])]\n expected = df.iloc[[0, 3], [1, 3]]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc['A', 'a']\n expected = DataFrame(dict(bar=[1, 5, 9], foo=[0, 4, 8]),\n index=Index([1, 2, 3], name='two'),\n columns=Index(['bar', 'foo'], name='lvl1'))\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[(slice(None), [1, 2]), :]\n expected = df.iloc[[0, 1, 3]]\n tm.assert_frame_equal(result, expected)\n\n # multi-level series\n s = Series(np.arange(len(ix.get_values())), index=ix)\n result = s.loc['A1':'A3', :, ['C1', 'C3']]\n expected = s.loc[[tuple([a, b, c, d])\n for a, b, c, d in s.index.values\n if (a == 'A1' or a == 'A2' or a == 'A3') and (\n c == 'C1' or c == 'C3')]]\n tm.assert_series_equal(result, expected)\n\n # boolean indexers\n result = df.loc[(slice(None), df.loc[:, ('a', 'bar')] > 5), :]\n expected = df.iloc[[2, 3]]\n tm.assert_frame_equal(result, expected)\n\n def f():\n df.loc[(slice(None), np.array([True, False])), :]\n\n self.assertRaises(ValueError, f)\n\n # ambiguous cases\n # these can be multiply interpreted (e.g. in this case\n # as df.loc[slice(None),[1]] as well\n self.assertRaises(KeyError, lambda: df.loc[slice(None), [1]])\n\n result = df.loc[(slice(None), [1]), :]\n expected = df.iloc[[0, 3]]\n tm.assert_frame_equal(result, expected)\n\n # not lexsorted\n self.assertEqual(df.index.lexsort_depth, 2)\n df = df.sort_index(level=1, axis=0)\n self.assertEqual(df.index.lexsort_depth, 0)\n with tm.assertRaisesRegexp(\n UnsortedIndexError,\n 'MultiIndex Slicing requires the index to be fully '\n r'lexsorted tuple len \\(2\\), lexsort depth \\(0\\)'):\n df.loc[(slice(None), df.loc[:, ('a', 'bar')] > 5), :]\n\n def test_multiindex_slicers_non_unique(self):\n\n # GH 7106\n # non-unique mi index support\n df = (DataFrame(dict(A=['foo', 'foo', 'foo', 'foo'],\n B=['a', 'a', 'a', 'a'],\n C=[1, 2, 1, 3],\n D=[1, 2, 3, 4]))\n .set_index(['A', 'B', 'C']).sort_index())\n self.assertFalse(df.index.is_unique)\n expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'],\n C=[1, 1], D=[1, 3]))\n .set_index(['A', 'B', 'C']).sort_index())\n result = df.loc[(slice(None), slice(None), 1), :]\n tm.assert_frame_equal(result, expected)\n\n # this is equivalent of an xs expression\n result = df.xs(1, level=2, drop_level=False)\n tm.assert_frame_equal(result, expected)\n\n df = (DataFrame(dict(A=['foo', 'foo', 'foo', 'foo'],\n B=['a', 'a', 'a', 'a'],\n C=[1, 2, 1, 2],\n D=[1, 2, 3, 4]))\n .set_index(['A', 'B', 'C']).sort_index())\n self.assertFalse(df.index.is_unique)\n expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'],\n C=[1, 1], D=[1, 3]))\n .set_index(['A', 'B', 'C']).sort_index())\n result = df.loc[(slice(None), slice(None), 1), :]\n self.assertFalse(result.index.is_unique)\n tm.assert_frame_equal(result, expected)\n\n # GH12896\n # numpy-implementation dependent bug\n ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 13, 14, 14, 16,\n 17, 18, 19, 200000, 200000]\n n = len(ints)\n idx = MultiIndex.from_arrays([['a'] * n, ints])\n result = Series([1] * n, index=idx)\n result = result.sort_index()\n result = result.loc[(slice(None), slice(100000))]\n expected = Series([1] * (n - 2), index=idx[:-2]).sort_index()\n tm.assert_series_equal(result, expected)\n\n def test_multiindex_slicers_datetimelike(self):\n\n # GH 7429\n # buggy/inconsistent behavior when slicing with datetime-like\n import datetime\n dates = [datetime.datetime(2012, 1, 1, 12, 12, 12) +\n datetime.timedelta(days=i) for i in range(6)]\n freq = [1, 2]\n index = MultiIndex.from_product(\n [dates, freq], names=['date', 'frequency'])\n\n df = DataFrame(\n np.arange(6 * 2 * 4, dtype='int64').reshape(\n -1, 4), index=index, columns=list('ABCD'))\n\n # multi-axis slicing\n idx = pd.IndexSlice\n expected = df.iloc[[0, 2, 4], [0, 1]]\n result = df.loc[(slice(Timestamp('2012-01-01 12:12:12'),\n Timestamp('2012-01-03 12:12:12')),\n slice(1, 1)), slice('A', 'B')]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[(idx[Timestamp('2012-01-01 12:12:12'):Timestamp(\n '2012-01-03 12:12:12')], idx[1:1]), slice('A', 'B')]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[(slice(Timestamp('2012-01-01 12:12:12'),\n Timestamp('2012-01-03 12:12:12')), 1),\n slice('A', 'B')]\n tm.assert_frame_equal(result, expected)\n\n # with strings\n result = df.loc[(slice('2012-01-01 12:12:12', '2012-01-03 12:12:12'),\n slice(1, 1)), slice('A', 'B')]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[(idx['2012-01-01 12:12:12':'2012-01-03 12:12:12'], 1),\n idx['A', 'B']]\n tm.assert_frame_equal(result, expected)\n\n def test_multiindex_slicers_edges(self):\n # GH 8132\n # various edge cases\n df = DataFrame(\n {'A': ['A0'] * 5 + ['A1'] * 5 + ['A2'] * 5,\n 'B': ['B0', 'B0', 'B1', 'B1', 'B2'] * 3,\n 'DATE': [\"2013-06-11\", \"2013-07-02\", \"2013-07-09\", \"2013-07-30\",\n \"2013-08-06\", \"2013-06-11\", \"2013-07-02\", \"2013-07-09\",\n \"2013-07-30\", \"2013-08-06\", \"2013-09-03\", \"2013-10-01\",\n \"2013-07-09\", \"2013-08-06\", \"2013-09-03\"],\n 'VALUES': [22, 35, 14, 9, 4, 40, 18, 4, 2, 5, 1, 2, 3, 4, 2]})\n\n df['DATE'] = pd.to_datetime(df['DATE'])\n df1 = df.set_index(['A', 'B', 'DATE'])\n df1 = df1.sort_index()\n\n # A1 - Get all values under \"A0\" and \"A1\"\n result = df1.loc[(slice('A1')), :]\n expected = df1.iloc[0:10]\n tm.assert_frame_equal(result, expected)\n\n # A2 - Get all values from the start to \"A2\"\n result = df1.loc[(slice('A2')), :]\n expected = df1\n tm.assert_frame_equal(result, expected)\n\n # A3 - Get all values under \"B1\" or \"B2\"\n result = df1.loc[(slice(None), slice('B1', 'B2')), :]\n expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13, 14]]\n tm.assert_frame_equal(result, expected)\n\n # A4 - Get all values between 2013-07-02 and 2013-07-09\n result = df1.loc[(slice(None), slice(None),\n slice('20130702', '20130709')), :]\n expected = df1.iloc[[1, 2, 6, 7, 12]]\n tm.assert_frame_equal(result, expected)\n\n # B1 - Get all values in B0 that are also under A0, A1 and A2\n result = df1.loc[(slice('A2'), slice('B0')), :]\n expected = df1.iloc[[0, 1, 5, 6, 10, 11]]\n tm.assert_frame_equal(result, expected)\n\n # B2 - Get all values in B0, B1 and B2 (similar to what #2 is doing for\n # the As)\n result = df1.loc[(slice(None), slice('B2')), :]\n expected = df1\n tm.assert_frame_equal(result, expected)\n\n # B3 - Get all values from B1 to B2 and up to 2013-08-06\n result = df1.loc[(slice(None), slice('B1', 'B2'),\n slice('2013-08-06')), :]\n expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13]]\n tm.assert_frame_equal(result, expected)\n\n # B4 - Same as A4 but the start of the date slice is not a key.\n # shows indexing on a partial selection slice\n result = df1.loc[(slice(None), slice(None),\n slice('20130701', '20130709')), :]\n expected = df1.iloc[[1, 2, 6, 7, 12]]\n tm.assert_frame_equal(result, expected)\n\n def test_per_axis_per_level_doc_examples(self):\n\n # test index maker\n idx = pd.IndexSlice\n\n # from indexing.rst / advanced\n index = MultiIndex.from_product([_mklbl('A', 4), _mklbl('B', 2),\n _mklbl('C', 4), _mklbl('D', 2)])\n columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'),\n ('b', 'foo'), ('b', 'bah')],\n names=['lvl0', 'lvl1'])\n df = DataFrame(np.arange(len(index) * len(columns), dtype='int64')\n .reshape((len(index), len(columns))),\n index=index, columns=columns)\n result = df.loc[(slice('A1', 'A3'), slice(None), ['C1', 'C3']), :]\n expected = df.loc[[tuple([a, b, c, d])\n for a, b, c, d in df.index.values\n if (a == 'A1' or a == 'A2' or a == 'A3') and (\n c == 'C1' or c == 'C3')]]\n tm.assert_frame_equal(result, expected)\n result = df.loc[idx['A1':'A3', :, ['C1', 'C3']], :]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[(slice(None), slice(None), ['C1', 'C3']), :]\n expected = df.loc[[tuple([a, b, c, d])\n for a, b, c, d in df.index.values\n if (c == 'C1' or c == 'C3')]]\n tm.assert_frame_equal(result, expected)\n result = df.loc[idx[:, :, ['C1', 'C3']], :]\n tm.assert_frame_equal(result, expected)\n\n # not sorted\n def f():\n df.loc['A1', (slice(None), 'foo')]\n\n self.assertRaises(UnsortedIndexError, f)\n df = df.sort_index(axis=1)\n\n # slicing\n df.loc['A1', (slice(None), 'foo')]\n df.loc[(slice(None), slice(None), ['C1', 'C3']), (slice(None), 'foo')]\n\n # setitem\n df.loc(axis=0)[:, :, ['C1', 'C3']] = -10\n\n def test_loc_axis_arguments(self):\n\n index = MultiIndex.from_product([_mklbl('A', 4), _mklbl('B', 2),\n _mklbl('C', 4), _mklbl('D', 2)])\n columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'),\n ('b', 'foo'), ('b', 'bah')],\n names=['lvl0', 'lvl1'])\n df = DataFrame(np.arange(len(index) * len(columns), dtype='int64')\n .reshape((len(index), len(columns))),\n index=index,\n columns=columns).sort_index().sort_index(axis=1)\n\n # axis 0\n result = df.loc(axis=0)['A1':'A3', :, ['C1', 'C3']]\n expected = df.loc[[tuple([a, b, c, d])\n for a, b, c, d in df.index.values\n if (a == 'A1' or a == 'A2' or a == 'A3') and (\n c == 'C1' or c == 'C3')]]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc(axis='index')[:, :, ['C1', 'C3']]\n expected = df.loc[[tuple([a, b, c, d])\n for a, b, c, d in df.index.values\n if (c == 'C1' or c == 'C3')]]\n tm.assert_frame_equal(result, expected)\n\n # axis 1\n result = df.loc(axis=1)[:, 'foo']\n expected = df.loc[:, (slice(None), 'foo')]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc(axis='columns')[:, 'foo']\n expected = df.loc[:, (slice(None), 'foo')]\n tm.assert_frame_equal(result, expected)\n\n # invalid axis\n def f():\n df.loc(axis=-1)[:, :, ['C1', 'C3']]\n\n self.assertRaises(ValueError, f)\n\n def f():\n df.loc(axis=2)[:, :, ['C1', 'C3']]\n\n self.assertRaises(ValueError, f)\n\n def f():\n df.loc(axis='foo')[:, :, ['C1', 'C3']]\n\n self.assertRaises(ValueError, f)\n\n def test_loc_coerceion(self):\n\n # 12411\n df = DataFrame({'date': [pd.Timestamp('20130101').tz_localize('UTC'),\n pd.NaT]})\n expected = df.dtypes\n\n result = df.iloc[[0]]\n tm.assert_series_equal(result.dtypes, expected)\n\n result = df.iloc[[1]]\n tm.assert_series_equal(result.dtypes, expected)\n\n # 12045\n import datetime\n df = DataFrame({'date': [datetime.datetime(2012, 1, 1),\n datetime.datetime(1012, 1, 2)]})\n expected = df.dtypes\n\n result = df.iloc[[0]]\n tm.assert_series_equal(result.dtypes, expected)\n\n result = df.iloc[[1]]\n tm.assert_series_equal(result.dtypes, expected)\n\n # 11594\n df = DataFrame({'text': ['some words'] + [None] * 9})\n expected = df.dtypes\n\n result = df.iloc[0:2]\n tm.assert_series_equal(result.dtypes, expected)\n\n result = df.iloc[3:]\n tm.assert_series_equal(result.dtypes, expected)\n\n def test_per_axis_per_level_setitem(self):\n\n # test index maker\n idx = pd.IndexSlice\n\n # test multi-index slicing with per axis and per index controls\n index = MultiIndex.from_tuples([('A', 1), ('A', 2),\n ('A', 3), ('B', 1)],\n names=['one', 'two'])\n columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'),\n ('b', 'foo'), ('b', 'bah')],\n names=['lvl0', 'lvl1'])\n\n df_orig = DataFrame(\n np.arange(16, dtype='int64').reshape(\n 4, 4), index=index, columns=columns)\n df_orig = df_orig.sort_index(axis=0).sort_index(axis=1)\n\n # identity\n df = df_orig.copy()\n df.loc[(slice(None), slice(None)), :] = 100\n expected = df_orig.copy()\n expected.iloc[:, :] = 100\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc(axis=0)[:, :] = 100\n expected = df_orig.copy()\n expected.iloc[:, :] = 100\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc[(slice(None), slice(None)), (slice(None), slice(None))] = 100\n expected = df_orig.copy()\n expected.iloc[:, :] = 100\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc[:, (slice(None), slice(None))] = 100\n expected = df_orig.copy()\n expected.iloc[:, :] = 100\n tm.assert_frame_equal(df, expected)\n\n # index\n df = df_orig.copy()\n df.loc[(slice(None), [1]), :] = 100\n expected = df_orig.copy()\n expected.iloc[[0, 3]] = 100\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc[(slice(None), 1), :] = 100\n expected = df_orig.copy()\n expected.iloc[[0, 3]] = 100\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc(axis=0)[:, 1] = 100\n expected = df_orig.copy()\n expected.iloc[[0, 3]] = 100\n tm.assert_frame_equal(df, expected)\n\n # columns\n df = df_orig.copy()\n df.loc[:, (slice(None), ['foo'])] = 100\n expected = df_orig.copy()\n expected.iloc[:, [1, 3]] = 100\n tm.assert_frame_equal(df, expected)\n\n # both\n df = df_orig.copy()\n df.loc[(slice(None), 1), (slice(None), ['foo'])] = 100\n expected = df_orig.copy()\n expected.iloc[[0, 3], [1, 3]] = 100\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc[idx[:, 1], idx[:, ['foo']]] = 100\n expected = df_orig.copy()\n expected.iloc[[0, 3], [1, 3]] = 100\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc['A', 'a'] = 100\n expected = df_orig.copy()\n expected.iloc[0:3, 0:2] = 100\n tm.assert_frame_equal(df, expected)\n\n # setting with a list-like\n df = df_orig.copy()\n df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array(\n [[100, 100], [100, 100]], dtype='int64')\n expected = df_orig.copy()\n expected.iloc[[0, 3], [1, 3]] = 100\n tm.assert_frame_equal(df, expected)\n\n # not enough values\n df = df_orig.copy()\n\n def f():\n df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array(\n [[100], [100, 100]], dtype='int64')\n\n self.assertRaises(ValueError, f)\n\n def f():\n df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array(\n [100, 100, 100, 100], dtype='int64')\n\n self.assertRaises(ValueError, f)\n\n # with an alignable rhs\n df = df_orig.copy()\n df.loc[(slice(None), 1), (slice(None), ['foo'])] = df.loc[(slice(\n None), 1), (slice(None), ['foo'])] * 5\n expected = df_orig.copy()\n expected.iloc[[0, 3], [1, 3]] = expected.iloc[[0, 3], [1, 3]] * 5\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc[(slice(None), 1), (slice(None), ['foo'])] *= df.loc[(slice(\n None), 1), (slice(None), ['foo'])]\n expected = df_orig.copy()\n expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]]\n tm.assert_frame_equal(df, expected)\n\n rhs = df_orig.loc[(slice(None), 1), (slice(None), ['foo'])].copy()\n rhs.loc[:, ('c', 'bah')] = 10\n df = df_orig.copy()\n df.loc[(slice(None), 1), (slice(None), ['foo'])] *= rhs\n expected = df_orig.copy()\n expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]]\n tm.assert_frame_equal(df, expected)\n\n def test_multiindex_setitem(self):\n\n # GH 3738\n # setting with a multi-index right hand side\n arrays = [np.array(['bar', 'bar', 'baz', 'qux', 'qux', 'bar']),\n np.array(['one', 'two', 'one', 'one', 'two', 'one']),\n np.arange(0, 6, 1)]\n\n df_orig = pd.DataFrame(np.random.randn(6, 3),\n index=arrays,\n columns=['A', 'B', 'C']).sort_index()\n\n expected = df_orig.loc[['bar']] * 2\n df = df_orig.copy()\n df.loc[['bar']] *= 2\n tm.assert_frame_equal(df.loc[['bar']], expected)\n\n # raise because these have differing levels\n def f():\n df.loc['bar'] *= 2\n\n self.assertRaises(TypeError, f)\n\n # from SO\n # http://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation\n df_orig = DataFrame.from_dict({'price': {\n ('DE', 'Coal', 'Stock'): 2,\n ('DE', 'Gas', 'Stock'): 4,\n ('DE', 'Elec', 'Demand'): 1,\n ('FR', 'Gas', 'Stock'): 5,\n ('FR', 'Solar', 'SupIm'): 0,\n ('FR', 'Wind', 'SupIm'): 0\n }})\n df_orig.index = MultiIndex.from_tuples(df_orig.index,\n names=['Sit', 'Com', 'Type'])\n\n expected = df_orig.copy()\n expected.iloc[[0, 2, 3]] *= 2\n\n idx = pd.IndexSlice\n df = df_orig.copy()\n df.loc[idx[:, :, 'Stock'], :] *= 2\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc[idx[:, :, 'Stock'], 'price'] *= 2\n tm.assert_frame_equal(df, expected)\n\n def test_getitem_multiindex(self):\n # GH 5725 the 'A' happens to be a valid Timestamp so the doesn't raise\n # the appropriate error, only in PY3 of course!\n index = MultiIndex(levels=[['D', 'B', 'C'],\n [0, 26, 27, 37, 57, 67, 75, 82]],\n labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2],\n [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],\n names=['tag', 'day'])\n arr = np.random.randn(len(index), 1)\n df = DataFrame(arr, index=index, columns=['val'])\n result = df.val['D']\n expected = Series(arr.ravel()[0:3], name='val', index=Index(\n [26, 37, 57], name='day'))\n tm.assert_series_equal(result, expected)\n\n def f():\n df.val['A']\n\n self.assertRaises(KeyError, f)\n\n def f():\n df.val['X']\n\n self.assertRaises(KeyError, f)\n\n # A is treated as a special Timestamp\n index = MultiIndex(levels=[['A', 'B', 'C'],\n [0, 26, 27, 37, 57, 67, 75, 82]],\n labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2],\n [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],\n names=['tag', 'day'])\n df = DataFrame(arr, index=index, columns=['val'])\n result = df.val['A']\n expected = Series(arr.ravel()[0:3], name='val', index=Index(\n [26, 37, 57], name='day'))\n tm.assert_series_equal(result, expected)\n\n def f():\n df.val['X']\n\n self.assertRaises(KeyError, f)\n\n # GH 7866\n # multi-index slicing with missing indexers\n idx = pd.MultiIndex.from_product([['A', 'B', 'C'],\n ['foo', 'bar', 'baz']],\n names=['one', 'two'])\n s = pd.Series(np.arange(9, dtype='int64'), index=idx).sort_index()\n\n exp_idx = pd.MultiIndex.from_product([['A'], ['foo', 'bar', 'baz']],\n names=['one', 'two'])\n expected = pd.Series(np.arange(3, dtype='int64'),\n index=exp_idx).sort_index()\n\n result = s.loc[['A']]\n tm.assert_series_equal(result, expected)\n result = s.loc[['A', 'D']]\n tm.assert_series_equal(result, expected)\n\n # not any values found\n self.assertRaises(KeyError, lambda: s.loc[['D']])\n\n # empty ok\n result = s.loc[[]]\n expected = s.iloc[[]]\n tm.assert_series_equal(result, expected)\n\n idx = pd.IndexSlice\n expected = pd.Series([0, 3, 6], index=pd.MultiIndex.from_product(\n [['A', 'B', 'C'], ['foo']], names=['one', 'two'])).sort_index()\n\n result = s.loc[idx[:, ['foo']]]\n tm.assert_series_equal(result, expected)\n result = s.loc[idx[:, ['foo', 'bah']]]\n tm.assert_series_equal(result, expected)\n\n # GH 8737\n # empty indexer\n multi_index = pd.MultiIndex.from_product((['foo', 'bar', 'baz'],\n ['alpha', 'beta']))\n df = DataFrame(\n np.random.randn(5, 6), index=range(5), columns=multi_index)\n df = df.sort_index(level=0, axis=1)\n\n expected = DataFrame(index=range(5),\n columns=multi_index.reindex([])[0])\n result1 = df.loc[:, ([], slice(None))]\n result2 = df.loc[:, (['foo'], [])]\n tm.assert_frame_equal(result1, expected)\n tm.assert_frame_equal(result2, expected)\n\n # regression from < 0.14.0\n # GH 7914\n df = DataFrame([[np.mean, np.median], ['mean', 'median']],\n columns=MultiIndex.from_tuples([('functs', 'mean'),\n ('functs', 'median')]),\n index=['function', 'name'])\n result = df.loc['function', ('functs', 'mean')]\n self.assertEqual(result, np.mean)\n\n def test_setitem_dtype_upcast(self):\n\n # GH3216\n df = DataFrame([{\"a\": 1}, {\"a\": 3, \"b\": 2}])\n df['c'] = np.nan\n self.assertEqual(df['c'].dtype, np.float64)\n\n df.loc[0, 'c'] = 'foo'\n expected = DataFrame([{\"a\": 1, \"c\": 'foo'},\n {\"a\": 3, \"b\": 2, \"c\": np.nan}])\n tm.assert_frame_equal(df, expected)\n\n # GH10280\n df = DataFrame(np.arange(6, dtype='int64').reshape(2, 3),\n index=list('ab'),\n columns=['foo', 'bar', 'baz'])\n\n for val in [3.14, 'wxyz']:\n left = df.copy()\n left.loc['a', 'bar'] = val\n right = DataFrame([[0, val, 2], [3, 4, 5]], index=list('ab'),\n columns=['foo', 'bar', 'baz'])\n\n tm.assert_frame_equal(left, right)\n self.assertTrue(is_integer_dtype(left['foo']))\n self.assertTrue(is_integer_dtype(left['baz']))\n\n left = DataFrame(np.arange(6, dtype='int64').reshape(2, 3) / 10.0,\n index=list('ab'),\n columns=['foo', 'bar', 'baz'])\n left.loc['a', 'bar'] = 'wxyz'\n\n right = DataFrame([[0, 'wxyz', .2], [.3, .4, .5]], index=list('ab'),\n columns=['foo', 'bar', 'baz'])\n\n tm.assert_frame_equal(left, right)\n self.assertTrue(is_float_dtype(left['foo']))\n self.assertTrue(is_float_dtype(left['baz']))\n\n def test_setitem_iloc(self):\n\n # setitem with an iloc list\n df = DataFrame(np.arange(9).reshape((3, 3)), index=[\"A\", \"B\", \"C\"],\n columns=[\"A\", \"B\", \"C\"])\n df.iloc[[0, 1], [1, 2]]\n df.iloc[[0, 1], [1, 2]] += 100\n\n expected = DataFrame(\n np.array([0, 101, 102, 3, 104, 105, 6, 7, 8]).reshape((3, 3)),\n index=[\"A\", \"B\", \"C\"], columns=[\"A\", \"B\", \"C\"])\n tm.assert_frame_equal(df, expected)\n\n def test_dups_fancy_indexing(self):\n\n # GH 3455\n from pandas.util.testing import makeCustomDataframe as mkdf\n df = mkdf(10, 3)\n df.columns = ['a', 'a', 'b']\n result = df[['b', 'a']].columns\n expected = Index(['b', 'a', 'a'])\n self.assert_index_equal(result, expected)\n\n # across dtypes\n df = DataFrame([[1, 2, 1., 2., 3., 'foo', 'bar']],\n columns=list('aaaaaaa'))\n df.head()\n str(df)\n result = DataFrame([[1, 2, 1., 2., 3., 'foo', 'bar']])\n result.columns = list('aaaaaaa')\n\n # TODO(wesm): unused?\n df_v = df.iloc[:, 4] # noqa\n res_v = result.iloc[:, 4] # noqa\n\n tm.assert_frame_equal(df, result)\n\n # GH 3561, dups not in selected order\n df = DataFrame(\n {'test': [5, 7, 9, 11],\n 'test1': [4., 5, 6, 7],\n 'other': list('abcd')}, index=['A', 'A', 'B', 'C'])\n rows = ['C', 'B']\n expected = DataFrame(\n {'test': [11, 9],\n 'test1': [7., 6],\n 'other': ['d', 'c']}, index=rows)\n result = df.loc[rows]\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[Index(rows)]\n tm.assert_frame_equal(result, expected)\n\n rows = ['C', 'B', 'E']\n expected = DataFrame(\n {'test': [11, 9, np.nan],\n 'test1': [7., 6, np.nan],\n 'other': ['d', 'c', np.nan]}, index=rows)\n\n result = df.loc[rows]\n tm.assert_frame_equal(result, expected)\n\n # see GH5553, make sure we use the right indexer\n rows = ['F', 'G', 'H', 'C', 'B', 'E']\n expected = DataFrame({'test': [np.nan, np.nan, np.nan, 11, 9, np.nan],\n 'test1': [np.nan, np.nan, np.nan, 7., 6, np.nan],\n 'other': [np.nan, np.nan, np.nan,\n 'd', 'c', np.nan]},\n index=rows)\n result = df.loc[rows]\n tm.assert_frame_equal(result, expected)\n\n # inconsistent returns for unique/duplicate indices when values are\n # missing\n df = DataFrame(randn(4, 3), index=list('ABCD'))\n expected = df.ix[['E']]\n\n dfnu = DataFrame(randn(5, 3), index=list('AABCD'))\n result = dfnu.ix[['E']]\n tm.assert_frame_equal(result, expected)\n\n # ToDo: check_index_type can be True after GH 11497\n\n # GH 4619; duplicate indexer with missing label\n df = DataFrame({\"A\": [0, 1, 2]})\n result = df.ix[[0, 8, 0]]\n expected = DataFrame({\"A\": [0, np.nan, 0]}, index=[0, 8, 0])\n tm.assert_frame_equal(result, expected, check_index_type=False)\n\n df = DataFrame({\"A\": list('abc')})\n result = df.ix[[0, 8, 0]]\n expected = DataFrame({\"A\": ['a', np.nan, 'a']}, index=[0, 8, 0])\n tm.assert_frame_equal(result, expected, check_index_type=False)\n\n # non unique with non unique selector\n df = DataFrame({'test': [5, 7, 9, 11]}, index=['A', 'A', 'B', 'C'])\n expected = DataFrame(\n {'test': [5, 7, 5, 7, np.nan]}, index=['A', 'A', 'A', 'A', 'E'])\n result = df.ix[['A', 'A', 'E']]\n tm.assert_frame_equal(result, expected)\n\n # GH 5835\n # dups on index and missing values\n df = DataFrame(\n np.random.randn(5, 5), columns=['A', 'B', 'B', 'B', 'A'])\n\n expected = pd.concat(\n [df.ix[:, ['A', 'B']], DataFrame(np.nan, columns=['C'],\n index=df.index)], axis=1)\n result = df.ix[:, ['A', 'B', 'C']]\n tm.assert_frame_equal(result, expected)\n\n # GH 6504, multi-axis indexing\n df = DataFrame(np.random.randn(9, 2),\n index=[1, 1, 1, 2, 2, 2, 3, 3, 3], columns=['a', 'b'])\n\n expected = df.iloc[0:6]\n result = df.loc[[1, 2]]\n tm.assert_frame_equal(result, expected)\n\n expected = df\n result = df.loc[:, ['a', 'b']]\n tm.assert_frame_equal(result, expected)\n\n expected = df.iloc[0:6, :]\n result = df.loc[[1, 2], ['a', 'b']]\n tm.assert_frame_equal(result, expected)\n\n def test_indexing_mixed_frame_bug(self):\n\n # GH3492\n df = DataFrame({'a': {1: 'aaa', 2: 'bbb', 3: 'ccc'},\n 'b': {1: 111, 2: 222, 3: 333}})\n\n # this works, new column is created correctly\n df['test'] = df['a'].apply(lambda x: '_' if x == 'aaa' else x)\n\n # this does not work, ie column test is not changed\n idx = df['test'] == '_'\n temp = df.ix[idx, 'a'].apply(lambda x: '-----' if x == 'aaa' else x)\n df.ix[idx, 'test'] = temp\n self.assertEqual(df.iloc[0, 2], '-----')\n\n # if I look at df, then element [0,2] equals '_'. If instead I type\n # df.ix[idx,'test'], I get '-----', finally by typing df.iloc[0,2] I\n # get '_'.\n\n def test_multitype_list_index_access(self):\n # GH 10610\n df = pd.DataFrame(np.random.random((10, 5)),\n columns=[\"a\"] + [20, 21, 22, 23])\n\n with self.assertRaises(KeyError):\n df[[22, 26, -8]]\n self.assertEqual(df[21].shape[0], df.shape[0])\n\n def test_set_index_nan(self):\n\n # GH 3586\n df = DataFrame({'PRuid': {17: 'nonQC',\n 18: 'nonQC',\n 19: 'nonQC',\n 20: '10',\n 21: '11',\n 22: '12',\n 23: '13',\n 24: '24',\n 25: '35',\n 26: '46',\n 27: '47',\n 28: '48',\n 29: '59',\n 30: '10'},\n 'QC': {17: 0.0,\n 18: 0.0,\n 19: 0.0,\n 20: nan,\n 21: nan,\n 22: nan,\n 23: nan,\n 24: 1.0,\n 25: nan,\n 26: nan,\n 27: nan,\n 28: nan,\n 29: nan,\n 30: nan},\n 'data': {17: 7.9544899999999998,\n 18: 8.0142609999999994,\n 19: 7.8591520000000008,\n 20: 0.86140349999999999,\n 21: 0.87853110000000001,\n 22: 0.8427041999999999,\n 23: 0.78587700000000005,\n 24: 0.73062459999999996,\n 25: 0.81668560000000001,\n 26: 0.81927080000000008,\n 27: 0.80705009999999999,\n 28: 0.81440240000000008,\n 29: 0.80140849999999997,\n 30: 0.81307740000000006},\n 'year': {17: 2006,\n 18: 2007,\n 19: 2008,\n 20: 1985,\n 21: 1985,\n 22: 1985,\n 23: 1985,\n 24: 1985,\n 25: 1985,\n 26: 1985,\n 27: 1985,\n 28: 1985,\n 29: 1985,\n 30: 1986}}).reset_index()\n\n result = df.set_index(['year', 'PRuid', 'QC']).reset_index().reindex(\n columns=df.columns)\n tm.assert_frame_equal(result, df)\n\n def test_multi_nan_indexing(self):\n\n # GH 3588\n df = DataFrame({\"a\": ['R1', 'R2', np.nan, 'R4'],\n 'b': [\"C1\", \"C2\", \"C3\", \"C4\"],\n \"c\": [10, 15, np.nan, 20]})\n result = df.set_index(['a', 'b'], drop=False)\n expected = DataFrame({\"a\": ['R1', 'R2', np.nan, 'R4'],\n 'b': [\"C1\", \"C2\", \"C3\", \"C4\"],\n \"c\": [10, 15, np.nan, 20]},\n index=[Index(['R1', 'R2', np.nan, 'R4'],\n name='a'),\n Index(['C1', 'C2', 'C3', 'C4'], name='b')])\n tm.assert_frame_equal(result, expected)\n\n def test_iloc_panel_issue(self):\n\n # GH 3617\n p = Panel(randn(4, 4, 4))\n\n self.assertEqual(p.iloc[:3, :3, :3].shape, (3, 3, 3))\n self.assertEqual(p.iloc[1, :3, :3].shape, (3, 3))\n self.assertEqual(p.iloc[:3, 1, :3].shape, (3, 3))\n self.assertEqual(p.iloc[:3, :3, 1].shape, (3, 3))\n self.assertEqual(p.iloc[1, 1, :3].shape, (3, ))\n self.assertEqual(p.iloc[1, :3, 1].shape, (3, ))\n self.assertEqual(p.iloc[:3, 1, 1].shape, (3, ))\n\n def test_panel_getitem(self):\n # GH4016, date selection returns a frame when a partial string\n # selection\n ind = date_range(start=\"2000\", freq=\"D\", periods=1000)\n df = DataFrame(\n np.random.randn(\n len(ind), 5), index=ind, columns=list('ABCDE'))\n panel = Panel(dict([('frame_' + c, df) for c in list('ABC')]))\n\n test2 = panel.ix[:, \"2002\":\"2002-12-31\"]\n test1 = panel.ix[:, \"2002\"]\n tm.assert_panel_equal(test1, test2)\n\n # GH8710\n # multi-element getting with a list\n panel = tm.makePanel()\n\n expected = panel.iloc[[0, 1]]\n\n result = panel.loc[['ItemA', 'ItemB']]\n tm.assert_panel_equal(result, expected)\n\n result = panel.loc[['ItemA', 'ItemB'], :, :]\n tm.assert_panel_equal(result, expected)\n\n result = panel[['ItemA', 'ItemB']]\n tm.assert_panel_equal(result, expected)\n\n result = panel.loc['ItemA':'ItemB']\n tm.assert_panel_equal(result, expected)\n\n result = panel.ix['ItemA':'ItemB']\n tm.assert_panel_equal(result, expected)\n\n result = panel.ix[['ItemA', 'ItemB']]\n tm.assert_panel_equal(result, expected)\n\n # with an object-like\n # GH 9140\n class TestObject:\n\n def __str__(self):\n return \"TestObject\"\n\n obj = TestObject()\n\n p = Panel(np.random.randn(1, 5, 4), items=[obj],\n major_axis=date_range('1/1/2000', periods=5),\n minor_axis=['A', 'B', 'C', 'D'])\n\n expected = p.iloc[0]\n result = p[obj]\n tm.assert_frame_equal(result, expected)\n\n def test_panel_setitem(self):\n\n # GH 7763\n # loc and setitem have setting differences\n np.random.seed(0)\n index = range(3)\n columns = list('abc')\n\n panel = Panel({'A': DataFrame(np.random.randn(3, 3),\n index=index, columns=columns),\n 'B': DataFrame(np.random.randn(3, 3),\n index=index, columns=columns),\n 'C': DataFrame(np.random.randn(3, 3),\n index=index, columns=columns)})\n\n replace = DataFrame(np.eye(3, 3), index=range(3), columns=columns)\n expected = Panel({'A': replace, 'B': replace, 'C': replace})\n\n p = panel.copy()\n for idx in list('ABC'):\n p[idx] = replace\n tm.assert_panel_equal(p, expected)\n\n p = panel.copy()\n for idx in list('ABC'):\n p.loc[idx, :, :] = replace\n tm.assert_panel_equal(p, expected)\n\n def test_panel_setitem_with_multiindex(self):\n\n # 10360\n # failing with a multi-index\n arr = np.array([[[1, 2, 3], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]],\n dtype=np.float64)\n\n # reg index\n axes = dict(items=['A', 'B'], major_axis=[0, 1],\n minor_axis=['X', 'Y', 'Z'])\n p1 = Panel(0., **axes)\n p1.iloc[0, 0, :] = [1, 2, 3]\n expected = Panel(arr, **axes)\n tm.assert_panel_equal(p1, expected)\n\n # multi-indexes\n axes['items'] = pd.MultiIndex.from_tuples([('A', 'a'), ('B', 'b')])\n p2 = Panel(0., **axes)\n p2.iloc[0, 0, :] = [1, 2, 3]\n expected = Panel(arr, **axes)\n tm.assert_panel_equal(p2, expected)\n\n axes['major_axis'] = pd.MultiIndex.from_tuples([('A', 1), ('A', 2)])\n p3 = Panel(0., **axes)\n p3.iloc[0, 0, :] = [1, 2, 3]\n expected = Panel(arr, **axes)\n tm.assert_panel_equal(p3, expected)\n\n axes['minor_axis'] = pd.MultiIndex.from_product([['X'], range(3)])\n p4 = Panel(0., **axes)\n p4.iloc[0, 0, :] = [1, 2, 3]\n expected = Panel(arr, **axes)\n tm.assert_panel_equal(p4, expected)\n\n arr = np.array(\n [[[1, 0, 0], [2, 0, 0]], [[0, 0, 0], [0, 0, 0]]], dtype=np.float64)\n p5 = Panel(0., **axes)\n p5.iloc[0, :, 0] = [1, 2]\n expected = Panel(arr, **axes)\n tm.assert_panel_equal(p5, expected)\n\n def test_panel_assignment(self):\n # GH3777\n wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],\n major_axis=date_range('1/1/2000', periods=5),\n minor_axis=['A', 'B', 'C', 'D'])\n wp2 = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],\n major_axis=date_range('1/1/2000', periods=5),\n minor_axis=['A', 'B', 'C', 'D'])\n\n # TODO: unused?\n # expected = wp.loc[['Item1', 'Item2'], :, ['A', 'B']]\n\n def f():\n wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = wp2.loc[\n ['Item1', 'Item2'], :, ['A', 'B']]\n\n self.assertRaises(NotImplementedError, f)\n\n # to_assign = wp2.loc[['Item1', 'Item2'], :, ['A', 'B']]\n # wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = to_assign\n # result = wp.loc[['Item1', 'Item2'], :, ['A', 'B']]\n # tm.assert_panel_equal(result,expected)\n\n def test_multiindex_assignment(self):\n\n # GH3777 part 2\n\n # mixed dtype\n df = DataFrame(np.random.randint(5, 10, size=9).reshape(3, 3),\n columns=list('abc'),\n index=[[4, 4, 8], [8, 10, 12]])\n df['d'] = np.nan\n arr = np.array([0., 1.])\n\n df.ix[4, 'd'] = arr\n tm.assert_series_equal(df.ix[4, 'd'],\n Series(arr, index=[8, 10], name='d'))\n\n # single dtype\n df = DataFrame(np.random.randint(5, 10, size=9).reshape(3, 3),\n columns=list('abc'),\n index=[[4, 4, 8], [8, 10, 12]])\n\n df.ix[4, 'c'] = arr\n exp = Series(arr, index=[8, 10], name='c', dtype='float64')\n tm.assert_series_equal(df.ix[4, 'c'], exp)\n\n # scalar ok\n df.ix[4, 'c'] = 10\n exp = Series(10, index=[8, 10], name='c', dtype='float64')\n tm.assert_series_equal(df.ix[4, 'c'], exp)\n\n # invalid assignments\n def f():\n df.ix[4, 'c'] = [0, 1, 2, 3]\n\n self.assertRaises(ValueError, f)\n\n def f():\n df.ix[4, 'c'] = [0]\n\n self.assertRaises(ValueError, f)\n\n # groupby example\n NUM_ROWS = 100\n NUM_COLS = 10\n col_names = ['A' + num for num in\n map(str, np.arange(NUM_COLS).tolist())]\n index_cols = col_names[:5]\n\n df = DataFrame(np.random.randint(5, size=(NUM_ROWS, NUM_COLS)),\n dtype=np.int64, columns=col_names)\n df = df.set_index(index_cols).sort_index()\n grp = df.groupby(level=index_cols[:4])\n df['new_col'] = np.nan\n\n f_index = np.arange(5)\n\n def f(name, df2):\n return Series(np.arange(df2.shape[0]),\n name=df2.index.values[0]).reindex(f_index)\n\n # TODO(wesm): unused?\n # new_df = pd.concat([f(name, df2) for name, df2 in grp], axis=1).T\n\n # we are actually operating on a copy here\n # but in this case, that's ok\n for name, df2 in grp:\n new_vals = np.arange(df2.shape[0])\n df.ix[name, 'new_col'] = new_vals\n\n def test_multi_assign(self):\n\n # GH 3626, an assignement of a sub-df to a df\n df = DataFrame({'FC': ['a', 'b', 'a', 'b', 'a', 'b'],\n 'PF': [0, 0, 0, 0, 1, 1],\n 'col1': lrange(6),\n 'col2': lrange(6, 12)})\n df.ix[1, 0] = np.nan\n df2 = df.copy()\n\n mask = ~df2.FC.isnull()\n cols = ['col1', 'col2']\n\n dft = df2 * 2\n dft.ix[3, 3] = np.nan\n\n expected = DataFrame({'FC': ['a', np.nan, 'a', 'b', 'a', 'b'],\n 'PF': [0, 0, 0, 0, 1, 1],\n 'col1': Series([0, 1, 4, 6, 8, 10]),\n 'col2': [12, 7, 16, np.nan, 20, 22]})\n\n # frame on rhs\n df2.ix[mask, cols] = dft.ix[mask, cols]\n tm.assert_frame_equal(df2, expected)\n\n df2.ix[mask, cols] = dft.ix[mask, cols]\n tm.assert_frame_equal(df2, expected)\n\n # with an ndarray on rhs\n df2 = df.copy()\n df2.ix[mask, cols] = dft.ix[mask, cols].values\n tm.assert_frame_equal(df2, expected)\n df2.ix[mask, cols] = dft.ix[mask, cols].values\n tm.assert_frame_equal(df2, expected)\n\n # broadcasting on the rhs is required\n df = DataFrame(dict(A=[1, 2, 0, 0, 0], B=[0, 0, 0, 10, 11], C=[\n 0, 0, 0, 10, 11], D=[3, 4, 5, 6, 7]))\n\n expected = df.copy()\n mask = expected['A'] == 0\n for col in ['A', 'B']:\n expected.loc[mask, col] = df['D']\n\n df.loc[df['A'] == 0, ['A', 'B']] = df['D']\n tm.assert_frame_equal(df, expected)\n\n def test_ix_assign_column_mixed(self):\n # GH #1142\n df = DataFrame(tm.getSeriesData())\n df['foo'] = 'bar'\n\n orig = df.ix[:, 'B'].copy()\n df.ix[:, 'B'] = df.ix[:, 'B'] + 1\n tm.assert_series_equal(df.B, orig + 1)\n\n # GH 3668, mixed frame with series value\n df = DataFrame({'x': lrange(10), 'y': lrange(10, 20), 'z': 'bar'})\n expected = df.copy()\n\n for i in range(5):\n indexer = i * 2\n v = 1000 + i * 200\n expected.ix[indexer, 'y'] = v\n self.assertEqual(expected.ix[indexer, 'y'], v)\n\n df.ix[df.x % 2 == 0, 'y'] = df.ix[df.x % 2 == 0, 'y'] * 100\n tm.assert_frame_equal(df, expected)\n\n # GH 4508, making sure consistency of assignments\n df = DataFrame({'a': [1, 2, 3], 'b': [0, 1, 2]})\n df.ix[[0, 2, ], 'b'] = [100, -100]\n expected = DataFrame({'a': [1, 2, 3], 'b': [100, 1, -100]})\n tm.assert_frame_equal(df, expected)\n\n df = pd.DataFrame({'a': lrange(4)})\n df['b'] = np.nan\n df.ix[[1, 3], 'b'] = [100, -100]\n expected = DataFrame({'a': [0, 1, 2, 3],\n 'b': [np.nan, 100, np.nan, -100]})\n tm.assert_frame_equal(df, expected)\n\n # ok, but chained assignments are dangerous\n # if we turn off chained assignement it will work\n with option_context('chained_assignment', None):\n df = pd.DataFrame({'a': lrange(4)})\n df['b'] = np.nan\n df['b'].ix[[1, 3]] = [100, -100]\n tm.assert_frame_equal(df, expected)\n\n def test_ix_get_set_consistency(self):\n\n # GH 4544\n # ix/loc get/set not consistent when\n # a mixed int/string index\n df = DataFrame(np.arange(16).reshape((4, 4)),\n columns=['a', 'b', 8, 'c'],\n index=['e', 7, 'f', 'g'])\n\n self.assertEqual(df.ix['e', 8], 2)\n self.assertEqual(df.loc['e', 8], 2)\n\n df.ix['e', 8] = 42\n self.assertEqual(df.ix['e', 8], 42)\n self.assertEqual(df.loc['e', 8], 42)\n\n df.loc['e', 8] = 45\n self.assertEqual(df.ix['e', 8], 45)\n self.assertEqual(df.loc['e', 8], 45)\n\n def test_setitem_list(self):\n\n # GH 6043\n # ix with a list\n df = DataFrame(index=[0, 1], columns=[0])\n df.ix[1, 0] = [1, 2, 3]\n df.ix[1, 0] = [1, 2]\n\n result = DataFrame(index=[0, 1], columns=[0])\n result.ix[1, 0] = [1, 2]\n\n tm.assert_frame_equal(result, df)\n\n # ix with an object\n class TO(object):\n\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return \"[{0}]\".format(self.value)\n\n __repr__ = __str__\n\n def __eq__(self, other):\n return self.value == other.value\n\n def view(self):\n return self\n\n df = DataFrame(index=[0, 1], columns=[0])\n df.ix[1, 0] = TO(1)\n df.ix[1, 0] = TO(2)\n\n result = DataFrame(index=[0, 1], columns=[0])\n result.ix[1, 0] = TO(2)\n\n tm.assert_frame_equal(result, df)\n\n # remains object dtype even after setting it back\n df = DataFrame(index=[0, 1], columns=[0])\n df.ix[1, 0] = TO(1)\n df.ix[1, 0] = np.nan\n result = DataFrame(index=[0, 1], columns=[0])\n\n tm.assert_frame_equal(result, df)\n\n def test_iloc_mask(self):\n\n # GH 3631, iloc with a mask (of a series) should raise\n df = DataFrame(lrange(5), list('ABCDE'), columns=['a'])\n mask = (df.a % 2 == 0)\n self.assertRaises(ValueError, df.iloc.__getitem__, tuple([mask]))\n mask.index = lrange(len(mask))\n self.assertRaises(NotImplementedError, df.iloc.__getitem__,\n tuple([mask]))\n\n # ndarray ok\n result = df.iloc[np.array([True] * len(mask), dtype=bool)]\n tm.assert_frame_equal(result, df)\n\n # the possibilities\n locs = np.arange(4)\n nums = 2 ** locs\n reps = lmap(bin, nums)\n df = DataFrame({'locs': locs, 'nums': nums}, reps)\n\n expected = {\n (None, ''): '0b1100',\n (None, '.loc'): '0b1100',\n (None, '.iloc'): '0b1100',\n ('index', ''): '0b11',\n ('index', '.loc'): '0b11',\n ('index', '.iloc'): ('iLocation based boolean indexing '\n 'cannot use an indexable as a mask'),\n ('locs', ''): 'Unalignable boolean Series provided as indexer '\n '(index of the boolean Series and of the indexed '\n 'object do not match',\n ('locs', '.loc'): 'Unalignable boolean Series provided as indexer '\n '(index of the boolean Series and of the '\n 'indexed object do not match',\n ('locs', '.iloc'): ('iLocation based boolean indexing on an '\n 'integer type is not available'),\n }\n\n # UserWarnings from reindex of a boolean mask\n with warnings.catch_warnings(record=True):\n result = dict()\n for idx in [None, 'index', 'locs']:\n mask = (df.nums > 2).values\n if idx:\n mask = Series(mask, list(reversed(getattr(df, idx))))\n for method in ['', '.loc', '.iloc']:\n try:\n if method:\n accessor = getattr(df, method[1:])\n else:\n accessor = df\n ans = str(bin(accessor[mask]['nums'].sum()))\n except Exception as e:\n ans = str(e)\n\n key = tuple([idx, method])\n r = expected.get(key)\n if r != ans:\n raise AssertionError(\n \"[%s] does not match [%s], received [%s]\"\n % (key, ans, r))\n\n def test_ix_slicing_strings(self):\n # GH3836\n data = {'Classification':\n ['SA EQUITY CFD', 'bbb', 'SA EQUITY', 'SA SSF', 'aaa'],\n 'Random': [1, 2, 3, 4, 5],\n 'X': ['correct', 'wrong', 'correct', 'correct', 'wrong']}\n df = DataFrame(data)\n x = df[~df.Classification.isin(['SA EQUITY CFD', 'SA EQUITY', 'SA SSF'\n ])]\n df.ix[x.index, 'X'] = df['Classification']\n\n expected = DataFrame({'Classification': {0: 'SA EQUITY CFD',\n 1: 'bbb',\n 2: 'SA EQUITY',\n 3: 'SA SSF',\n 4: 'aaa'},\n 'Random': {0: 1,\n 1: 2,\n 2: 3,\n 3: 4,\n 4: 5},\n 'X': {0: 'correct',\n 1: 'bbb',\n 2: 'correct',\n 3: 'correct',\n 4: 'aaa'}}) # bug was 4: 'bbb'\n\n tm.assert_frame_equal(df, expected)\n\n def test_non_unique_loc(self):\n # GH3659\n # non-unique indexer with loc slice\n # https://groups.google.com/forum/?fromgroups#!topic/pydata/zTm2No0crYs\n\n # these are going to raise becuase the we are non monotonic\n df = DataFrame({'A': [1, 2, 3, 4, 5, 6],\n 'B': [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3])\n self.assertRaises(KeyError, df.loc.__getitem__,\n tuple([slice(1, None)]))\n self.assertRaises(KeyError, df.loc.__getitem__,\n tuple([slice(0, None)]))\n self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(1, 2)]))\n\n # monotonic are ok\n df = DataFrame({'A': [1, 2, 3, 4, 5, 6],\n 'B': [3, 4, 5, 6, 7, 8]},\n index=[0, 1, 0, 1, 2, 3]).sort_index(axis=0)\n result = df.loc[1:]\n expected = DataFrame({'A': [2, 4, 5, 6], 'B': [4, 6, 7, 8]},\n index=[1, 1, 2, 3])\n tm.assert_frame_equal(result, expected)\n\n result = df.loc[0:]\n tm.assert_frame_equal(result, df)\n\n result = df.loc[1:2]\n expected = DataFrame({'A': [2, 4, 5], 'B': [4, 6, 7]},\n index=[1, 1, 2])\n tm.assert_frame_equal(result, expected)\n\n def test_loc_name(self):\n # GH 3880\n df = DataFrame([[1, 1], [1, 1]])\n df.index.name = 'index_name'\n result = df.iloc[[0, 1]].index.name\n self.assertEqual(result, 'index_name')\n\n result = df.ix[[0, 1]].index.name\n self.assertEqual(result, 'index_name')\n\n result = df.loc[[0, 1]].index.name\n self.assertEqual(result, 'index_name')\n\n def test_iloc_non_unique_indexing(self):\n\n # GH 4017, non-unique indexing (on the axis)\n df = DataFrame({'A': [0.1] * 3000, 'B': [1] * 3000})\n idx = np.array(lrange(30)) * 99\n expected = df.iloc[idx]\n\n df3 = pd.concat([df, 2 * df, 3 * df])\n result = df3.iloc[idx]\n\n tm.assert_frame_equal(result, expected)\n\n df2 = DataFrame({'A': [0.1] * 1000, 'B': [1] * 1000})\n df2 = pd.concat([df2, 2 * df2, 3 * df2])\n\n sidx = df2.index.to_series()\n expected = df2.iloc[idx[idx <= sidx.max()]]\n\n new_list = []\n for r, s in expected.iterrows():\n new_list.append(s)\n new_list.append(s * 2)\n new_list.append(s * 3)\n\n expected = DataFrame(new_list)\n expected = pd.concat([expected, DataFrame(index=idx[idx > sidx.max()])\n ])\n result = df2.loc[idx]\n tm.assert_frame_equal(result, expected, check_index_type=False)\n\n def test_string_slice(self):\n # GH 14424\n # string indexing against datetimelike with object\n # dtype should properly raises KeyError\n df = pd.DataFrame([1], pd.Index([pd.Timestamp('2011-01-01')],\n dtype=object))\n self.assertTrue(df.index.is_all_dates)\n with tm.assertRaises(KeyError):\n df['2011']\n\n with tm.assertRaises(KeyError):\n df.loc['2011', 0]\n\n df = pd.DataFrame()\n self.assertFalse(df.index.is_all_dates)\n with tm.assertRaises(KeyError):\n df['2011']\n\n with tm.assertRaises(KeyError):\n df.loc['2011', 0]\n\n def test_mi_access(self):\n\n # GH 4145\n data = \"\"\"h1 main h3 sub h5\n0 a A 1 A1 1\n1 b B 2 B1 2\n2 c B 3 A1 3\n3 d A 4 B2 4\n4 e A 5 B2 5\n5 f B 6 A2 6\n\"\"\"\n\n df = pd.read_csv(StringIO(data), sep=r'\\s+', index_col=0)\n df2 = df.set_index(['main', 'sub']).T.sort_index(1)\n index = Index(['h1', 'h3', 'h5'])\n columns = MultiIndex.from_tuples([('A', 'A1')], names=['main', 'sub'])\n expected = DataFrame([['a', 1, 1]], index=columns, columns=index).T\n\n result = df2.loc[:, ('A', 'A1')]\n tm.assert_frame_equal(result, expected)\n\n result = df2[('A', 'A1')]\n tm.assert_frame_equal(result, expected)\n\n # GH 4146, not returning a block manager when selecting a unique index\n # from a duplicate index\n # as of 4879, this returns a Series (which is similar to what happens\n # with a non-unique)\n expected = Series(['a', 1, 1], index=['h1', 'h3', 'h5'], name='A1')\n result = df2['A']['A1']\n tm.assert_series_equal(result, expected)\n\n # selecting a non_unique from the 2nd level\n expected = DataFrame([['d', 4, 4], ['e', 5, 5]],\n index=Index(['B2', 'B2'], name='sub'),\n columns=['h1', 'h3', 'h5'], ).T\n result = df2['A']['B2']\n tm.assert_frame_equal(result, expected)\n\n def test_non_unique_loc_memory_error(self):\n\n # GH 4280\n # non_unique index with a large selection triggers a memory error\n\n columns = list('ABCDEFG')\n\n def gen_test(l, l2):\n return pd.concat([DataFrame(randn(l, len(columns)),\n index=lrange(l), columns=columns),\n DataFrame(np.ones((l2, len(columns))),\n index=[0] * l2, columns=columns)])\n\n def gen_expected(df, mask):\n l = len(mask)\n return pd.concat([df.take([0], convert=False),\n DataFrame(np.ones((l, len(columns))),\n index=[0] * l,\n columns=columns),\n df.take(mask[1:], convert=False)])\n\n df = gen_test(900, 100)\n self.assertFalse(df.index.is_unique)\n\n mask = np.arange(100)\n result = df.loc[mask]\n expected = gen_expected(df, mask)\n tm.assert_frame_equal(result, expected)\n\n df = gen_test(900000, 100000)\n self.assertFalse(df.index.is_unique)\n\n mask = np.arange(100000)\n result = df.loc[mask]\n expected = gen_expected(df, mask)\n tm.assert_frame_equal(result, expected)\n\n def test_astype_assignment(self):\n\n # GH4312 (iloc)\n df_orig = DataFrame([['1', '2', '3', '.4', 5, 6., 'foo']],\n columns=list('ABCDEFG'))\n\n df = df_orig.copy()\n df.iloc[:, 0:2] = df.iloc[:, 0:2].astype(np.int64)\n expected = DataFrame([[1, 2, '3', '.4', 5, 6., 'foo']],\n columns=list('ABCDEFG'))\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.iloc[:, 0:2] = df.iloc[:, 0:2]._convert(datetime=True, numeric=True)\n expected = DataFrame([[1, 2, '3', '.4', 5, 6., 'foo']],\n columns=list('ABCDEFG'))\n tm.assert_frame_equal(df, expected)\n\n # GH5702 (loc)\n df = df_orig.copy()\n df.loc[:, 'A'] = df.loc[:, 'A'].astype(np.int64)\n expected = DataFrame([[1, '2', '3', '.4', 5, 6., 'foo']],\n columns=list('ABCDEFG'))\n tm.assert_frame_equal(df, expected)\n\n df = df_orig.copy()\n df.loc[:, ['B', 'C']] = df.loc[:, ['B', 'C']].astype(np.int64)\n expected = DataFrame([['1', 2, 3, '.4', 5, 6., 'foo']],\n columns=list('ABCDEFG'))\n tm.assert_frame_equal(df, expected)\n\n # full replacements / no nans\n df = DataFrame({'A': [1., 2., 3., 4.]})\n df.iloc[:, 0] = df['A'].astype(np.int64)\n expected = DataFrame({'A': [1, 2, 3, 4]})\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame({'A': [1., 2., 3., 4.]})\n df.loc[:, 'A'] = df['A'].astype(np.int64)\n expected = DataFrame({'A': [1, 2, 3, 4]})\n tm.assert_frame_equal(df, expected)\n\n def test_astype_assignment_with_dups(self):\n\n # GH 4686\n # assignment with dups that has a dtype change\n cols = pd.MultiIndex.from_tuples([('A', '1'), ('B', '1'), ('A', '2')])\n df = DataFrame(np.arange(3).reshape((1, 3)),\n columns=cols, dtype=object)\n index = df.index.copy()\n\n df['A'] = df['A'].astype(np.float64)\n self.assert_index_equal(df.index, index)\n\n # TODO(wesm): unused variables\n # result = df.get_dtype_counts().sort_index()\n # expected = Series({'float64': 2, 'object': 1}).sort_index()\n\n def test_dups_loc(self):\n\n # GH4726\n # dup indexing with iloc/loc\n df = DataFrame([[1, 2, 'foo', 'bar', Timestamp('20130101')]],\n columns=['a', 'a', 'a', 'a', 'a'], index=[1])\n expected = Series([1, 2, 'foo', 'bar', Timestamp('20130101')],\n index=['a', 'a', 'a', 'a', 'a'], name=1)\n\n result = df.iloc[0]\n tm.assert_series_equal(result, expected)\n\n result = df.loc[1]\n tm.assert_series_equal(result, expected)\n\n def test_partial_setting(self):\n\n # GH2578, allow ix and friends to partially set\n\n # series\n s_orig = Series([1, 2, 3])\n\n s = s_orig.copy()\n s[5] = 5\n expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])\n tm.assert_series_equal(s, expected)\n\n s = s_orig.copy()\n s.loc[5] = 5\n expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])\n tm.assert_series_equal(s, expected)\n\n s = s_orig.copy()\n s[5] = 5.\n expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5])\n tm.assert_series_equal(s, expected)\n\n s = s_orig.copy()\n s.loc[5] = 5.\n expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5])\n tm.assert_series_equal(s, expected)\n\n # iloc/iat raise\n s = s_orig.copy()\n\n def f():\n s.iloc[3] = 5.\n\n self.assertRaises(IndexError, f)\n\n def f():\n s.iat[3] = 5.\n\n self.assertRaises(IndexError, f)\n\n # ## frame ##\n\n df_orig = DataFrame(\n np.arange(6).reshape(3, 2), columns=['A', 'B'], dtype='int64')\n\n # iloc/iat raise\n df = df_orig.copy()\n\n def f():\n df.iloc[4, 2] = 5.\n\n self.assertRaises(IndexError, f)\n\n def f():\n df.iat[4, 2] = 5.\n\n self.assertRaises(IndexError, f)\n\n # row setting where it exists\n expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]}))\n df = df_orig.copy()\n df.iloc[1] = df.iloc[2]\n tm.assert_frame_equal(df, expected)\n\n expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]}))\n df = df_orig.copy()\n df.loc[1] = df.loc[2]\n tm.assert_frame_equal(df, expected)\n\n # like 2578, partial setting with dtype preservation\n expected = DataFrame(dict({'A': [0, 2, 4, 4], 'B': [1, 3, 5, 5]}))\n df = df_orig.copy()\n df.loc[3] = df.loc[2]\n tm.assert_frame_equal(df, expected)\n\n # single dtype frame, overwrite\n expected = DataFrame(dict({'A': [0, 2, 4], 'B': [0, 2, 4]}))\n df = df_orig.copy()\n df.ix[:, 'B'] = df.ix[:, 'A']\n tm.assert_frame_equal(df, expected)\n\n # mixed dtype frame, overwrite\n expected = DataFrame(dict({'A': [0, 2, 4], 'B': Series([0, 2, 4])}))\n df = df_orig.copy()\n df['B'] = df['B'].astype(np.float64)\n df.ix[:, 'B'] = df.ix[:, 'A']\n tm.assert_frame_equal(df, expected)\n\n # single dtype frame, partial setting\n expected = df_orig.copy()\n expected['C'] = df['A']\n df = df_orig.copy()\n df.ix[:, 'C'] = df.ix[:, 'A']\n tm.assert_frame_equal(df, expected)\n\n # mixed frame, partial setting\n expected = df_orig.copy()\n expected['C'] = df['A']\n df = df_orig.copy()\n df.ix[:, 'C'] = df.ix[:, 'A']\n tm.assert_frame_equal(df, expected)\n\n # ## panel ##\n p_orig = Panel(np.arange(16).reshape(2, 4, 2),\n items=['Item1', 'Item2'],\n major_axis=pd.date_range('2001/1/12', periods=4),\n minor_axis=['A', 'B'], dtype='float64')\n\n # panel setting via item\n p_orig = Panel(np.arange(16).reshape(2, 4, 2),\n items=['Item1', 'Item2'],\n major_axis=pd.date_range('2001/1/12', periods=4),\n minor_axis=['A', 'B'], dtype='float64')\n expected = p_orig.copy()\n expected['Item3'] = expected['Item1']\n p = p_orig.copy()\n p.loc['Item3'] = p['Item1']\n tm.assert_panel_equal(p, expected)\n\n # panel with aligned series\n expected = p_orig.copy()\n expected = expected.transpose(2, 1, 0)\n expected['C'] = DataFrame({'Item1': [30, 30, 30, 30],\n 'Item2': [32, 32, 32, 32]},\n index=p_orig.major_axis)\n expected = expected.transpose(2, 1, 0)\n p = p_orig.copy()\n p.loc[:, :, 'C'] = Series([30, 32], index=p_orig.items)\n tm.assert_panel_equal(p, expected)\n\n # GH 8473\n dates = date_range('1/1/2000', periods=8)\n df_orig = DataFrame(np.random.randn(8, 4), index=dates,\n columns=['A', 'B', 'C', 'D'])\n\n expected = pd.concat([df_orig, DataFrame(\n {'A': 7}, index=[dates[-1] + 1])])\n df = df_orig.copy()\n df.loc[dates[-1] + 1, 'A'] = 7\n tm.assert_frame_equal(df, expected)\n df = df_orig.copy()\n df.at[dates[-1] + 1, 'A'] = 7\n tm.assert_frame_equal(df, expected)\n\n exp_other = DataFrame({0: 7}, index=[dates[-1] + 1])\n expected = pd.concat([df_orig, exp_other], axis=1)\n\n df = df_orig.copy()\n df.loc[dates[-1] + 1, 0] = 7\n tm.assert_frame_equal(df, expected)\n df = df_orig.copy()\n df.at[dates[-1] + 1, 0] = 7\n tm.assert_frame_equal(df, expected)\n\n def test_partial_setting_mixed_dtype(self):\n\n # in a mixed dtype environment, try to preserve dtypes\n # by appending\n df = DataFrame([[True, 1], [False, 2]], columns=[\"female\", \"fitness\"])\n\n s = df.loc[1].copy()\n s.name = 2\n expected = df.append(s)\n\n df.loc[2] = df.loc[1]\n tm.assert_frame_equal(df, expected)\n\n # columns will align\n df = DataFrame(columns=['A', 'B'])\n df.loc[0] = Series(1, index=range(4))\n tm.assert_frame_equal(df, DataFrame(columns=['A', 'B'], index=[0]))\n\n # columns will align\n df = DataFrame(columns=['A', 'B'])\n df.loc[0] = Series(1, index=['B'])\n\n exp = DataFrame([[np.nan, 1]], columns=['A', 'B'],\n index=[0], dtype='float64')\n tm.assert_frame_equal(df, exp)\n\n # list-like must conform\n df = DataFrame(columns=['A', 'B'])\n\n def f():\n df.loc[0] = [1, 2, 3]\n\n self.assertRaises(ValueError, f)\n\n # these are coerced to float unavoidably (as its a list-like to begin)\n df = DataFrame(columns=['A', 'B'])\n df.loc[3] = [6, 7]\n\n exp = DataFrame([[6, 7]], index=[3], columns=['A', 'B'],\n dtype='float64')\n tm.assert_frame_equal(df, exp)\n\n def test_partial_setting_with_datetimelike_dtype(self):\n\n # GH9478\n # a datetimeindex alignment issue with partial setting\n df = pd.DataFrame(np.arange(6.).reshape(3, 2), columns=list('AB'),\n index=pd.date_range('1/1/2000', periods=3,\n freq='1H'))\n expected = df.copy()\n expected['C'] = [expected.index[0]] + [pd.NaT, pd.NaT]\n\n mask = df.A < 1\n df.loc[mask, 'C'] = df.loc[mask].index\n tm.assert_frame_equal(df, expected)\n\n def test_loc_setitem_datetime(self):\n\n # GH 9516\n dt1 = Timestamp('20130101 09:00:00')\n dt2 = Timestamp('20130101 10:00:00')\n\n for conv in [lambda x: x, lambda x: x.to_datetime64(),\n lambda x: x.to_pydatetime(), lambda x: np.datetime64(x)]:\n\n df = pd.DataFrame()\n df.loc[conv(dt1), 'one'] = 100\n df.loc[conv(dt2), 'one'] = 200\n\n expected = DataFrame({'one': [100.0, 200.0]}, index=[dt1, dt2])\n tm.assert_frame_equal(df, expected)\n\n def test_series_partial_set(self):\n # partial set with new index\n # Regression from GH4825\n ser = Series([0.1, 0.2], index=[1, 2])\n\n # loc\n expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3])\n result = ser.loc[[3, 2, 3]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([np.nan, 0.2, np.nan, np.nan], index=[3, 2, 3, 'x'])\n result = ser.loc[[3, 2, 3, 'x']]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([0.2, 0.2, 0.1], index=[2, 2, 1])\n result = ser.loc[[2, 2, 1]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([0.2, 0.2, np.nan, 0.1], index=[2, 2, 'x', 1])\n result = ser.loc[[2, 2, 'x', 1]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n # raises as nothing in in the index\n self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]])\n\n expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3])\n result = ser.loc[[2, 2, 3]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4])\n result = Series([0.1, 0.2, 0.3], index=[1, 2, 3]).loc[[3, 4, 4]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3])\n result = Series([0.1, 0.2, 0.3, 0.4],\n index=[1, 2, 3, 4]).loc[[5, 3, 3]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4])\n result = Series([0.1, 0.2, 0.3, 0.4],\n index=[1, 2, 3, 4]).loc[[5, 4, 4]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2])\n result = Series([0.1, 0.2, 0.3, 0.4],\n index=[4, 5, 6, 7]).loc[[7, 2, 2]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5])\n result = Series([0.1, 0.2, 0.3, 0.4],\n index=[1, 2, 3, 4]).loc[[4, 5, 5]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n # iloc\n expected = Series([0.2, 0.2, 0.1, 0.1], index=[2, 2, 1, 1])\n result = ser.iloc[[1, 1, 0, 0]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n def test_series_partial_set_with_name(self):\n # GH 11497\n\n idx = Index([1, 2], dtype='int64', name='idx')\n ser = Series([0.1, 0.2], index=idx, name='s')\n\n # loc\n exp_idx = Index([3, 2, 3], dtype='int64', name='idx')\n expected = Series([np.nan, 0.2, np.nan], index=exp_idx, name='s')\n result = ser.loc[[3, 2, 3]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([3, 2, 3, 'x'], dtype='object', name='idx')\n expected = Series([np.nan, 0.2, np.nan, np.nan], index=exp_idx,\n name='s')\n result = ser.loc[[3, 2, 3, 'x']]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([2, 2, 1], dtype='int64', name='idx')\n expected = Series([0.2, 0.2, 0.1], index=exp_idx, name='s')\n result = ser.loc[[2, 2, 1]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([2, 2, 'x', 1], dtype='object', name='idx')\n expected = Series([0.2, 0.2, np.nan, 0.1], index=exp_idx, name='s')\n result = ser.loc[[2, 2, 'x', 1]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n # raises as nothing in in the index\n self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]])\n\n exp_idx = Index([2, 2, 3], dtype='int64', name='idx')\n expected = Series([0.2, 0.2, np.nan], index=exp_idx, name='s')\n result = ser.loc[[2, 2, 3]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([3, 4, 4], dtype='int64', name='idx')\n expected = Series([0.3, np.nan, np.nan], index=exp_idx, name='s')\n idx = Index([1, 2, 3], dtype='int64', name='idx')\n result = Series([0.1, 0.2, 0.3], index=idx, name='s').loc[[3, 4, 4]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([5, 3, 3], dtype='int64', name='idx')\n expected = Series([np.nan, 0.3, 0.3], index=exp_idx, name='s')\n idx = Index([1, 2, 3, 4], dtype='int64', name='idx')\n result = Series([0.1, 0.2, 0.3, 0.4], index=idx,\n name='s').loc[[5, 3, 3]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([5, 4, 4], dtype='int64', name='idx')\n expected = Series([np.nan, 0.4, 0.4], index=exp_idx, name='s')\n idx = Index([1, 2, 3, 4], dtype='int64', name='idx')\n result = Series([0.1, 0.2, 0.3, 0.4], index=idx,\n name='s').loc[[5, 4, 4]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([7, 2, 2], dtype='int64', name='idx')\n expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s')\n idx = Index([4, 5, 6, 7], dtype='int64', name='idx')\n result = Series([0.1, 0.2, 0.3, 0.4], index=idx,\n name='s').loc[[7, 2, 2]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n exp_idx = Index([4, 5, 5], dtype='int64', name='idx')\n expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s')\n idx = Index([1, 2, 3, 4], dtype='int64', name='idx')\n result = Series([0.1, 0.2, 0.3, 0.4], index=idx,\n name='s').loc[[4, 5, 5]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n # iloc\n exp_idx = Index([2, 2, 1, 1], dtype='int64', name='idx')\n expected = Series([0.2, 0.2, 0.1, 0.1], index=exp_idx, name='s')\n result = ser.iloc[[1, 1, 0, 0]]\n tm.assert_series_equal(result, expected, check_index_type=True)\n\n def test_series_partial_set_datetime(self):\n # GH 11497\n\n idx = date_range('2011-01-01', '2011-01-02', freq='D', name='idx')\n ser = Series([0.1, 0.2], index=idx, name='s')\n\n result = ser.loc[[Timestamp('2011-01-01'), Timestamp('2011-01-02')]]\n exp = Series([0.1, 0.2], index=idx, name='s')\n tm.assert_series_equal(result, exp, check_index_type=True)\n\n keys = [Timestamp('2011-01-02'), Timestamp('2011-01-02'),\n Timestamp('2011-01-01')]\n exp = Series([0.2, 0.2, 0.1], index=pd.DatetimeIndex(keys, name='idx'),\n name='s')\n tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True)\n\n keys = [Timestamp('2011-01-03'), Timestamp('2011-01-02'),\n Timestamp('2011-01-03')]\n exp = Series([np.nan, 0.2, np.nan],\n index=pd.DatetimeIndex(keys, name='idx'), name='s')\n tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True)\n\n def test_series_partial_set_period(self):\n # GH 11497\n\n idx = pd.period_range('2011-01-01', '2011-01-02', freq='D', name='idx')\n ser = Series([0.1, 0.2], index=idx, name='s')\n\n result = ser.loc[[pd.Period('2011-01-01', freq='D'),\n pd.Period('2011-01-02', freq='D')]]\n exp = Series([0.1, 0.2], index=idx, name='s')\n tm.assert_series_equal(result, exp, check_index_type=True)\n\n keys = [pd.Period('2011-01-02', freq='D'),\n pd.Period('2011-01-02', freq='D'),\n pd.Period('2011-01-01', freq='D')]\n exp = Series([0.2, 0.2, 0.1], index=pd.PeriodIndex(keys, name='idx'),\n name='s')\n tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True)\n\n keys = [pd.Period('2011-01-03', freq='D'),\n pd.Period('2011-01-02', freq='D'),\n pd.Period('2011-01-03', freq='D')]\n exp = Series([np.nan, 0.2, np.nan],\n index=pd.PeriodIndex(keys, name='idx'), name='s')\n result = ser.loc[keys]\n tm.assert_series_equal(result, exp)\n\n def test_partial_set_invalid(self):\n\n # GH 4940\n # allow only setting of 'valid' values\n\n orig = tm.makeTimeDataFrame()\n df = orig.copy()\n\n # don't allow not string inserts\n def f():\n df.loc[100.0, :] = df.ix[0]\n\n self.assertRaises(TypeError, f)\n\n def f():\n df.loc[100, :] = df.ix[0]\n\n self.assertRaises(TypeError, f)\n\n def f():\n df.ix[100.0, :] = df.ix[0]\n\n self.assertRaises(TypeError, f)\n\n def f():\n df.ix[100, :] = df.ix[0]\n\n self.assertRaises(ValueError, f)\n\n # allow object conversion here\n df = orig.copy()\n df.loc['a', :] = df.ix[0]\n exp = orig.append(pd.Series(df.ix[0], name='a'))\n tm.assert_frame_equal(df, exp)\n tm.assert_index_equal(df.index,\n pd.Index(orig.index.tolist() + ['a']))\n self.assertEqual(df.index.dtype, 'object')\n\n def test_partial_set_empty_series(self):\n\n # GH5226\n\n # partially set with an empty object series\n s = Series()\n s.loc[1] = 1\n tm.assert_series_equal(s, Series([1], index=[1]))\n s.loc[3] = 3\n tm.assert_series_equal(s, Series([1, 3], index=[1, 3]))\n\n s = Series()\n s.loc[1] = 1.\n tm.assert_series_equal(s, Series([1.], index=[1]))\n s.loc[3] = 3.\n tm.assert_series_equal(s, Series([1., 3.], index=[1, 3]))\n\n s = Series()\n s.loc['foo'] = 1\n tm.assert_series_equal(s, Series([1], index=['foo']))\n s.loc['bar'] = 3\n tm.assert_series_equal(s, Series([1, 3], index=['foo', 'bar']))\n s.loc[3] = 4\n tm.assert_series_equal(s, Series([1, 3, 4], index=['foo', 'bar', 3]))\n\n def test_partial_set_empty_frame(self):\n\n # partially set with an empty object\n # frame\n df = DataFrame()\n\n def f():\n df.loc[1] = 1\n\n self.assertRaises(ValueError, f)\n\n def f():\n df.loc[1] = Series([1], index=['foo'])\n\n self.assertRaises(ValueError, f)\n\n def f():\n df.loc[:, 1] = 1\n\n self.assertRaises(ValueError, f)\n\n # these work as they don't really change\n # anything but the index\n # GH5632\n expected = DataFrame(columns=['foo'], index=pd.Index(\n [], dtype='int64'))\n\n def f():\n df = DataFrame()\n df['foo'] = Series([], dtype='object')\n return df\n\n tm.assert_frame_equal(f(), expected)\n\n def f():\n df = DataFrame()\n df['foo'] = Series(df.index)\n return df\n\n tm.assert_frame_equal(f(), expected)\n\n def f():\n df = DataFrame()\n df['foo'] = df.index\n return df\n\n tm.assert_frame_equal(f(), expected)\n\n expected = DataFrame(columns=['foo'],\n index=pd.Index([], dtype='int64'))\n expected['foo'] = expected['foo'].astype('float64')\n\n def f():\n df = DataFrame()\n df['foo'] = []\n return df\n\n tm.assert_frame_equal(f(), expected)\n\n def f():\n df = DataFrame()\n df['foo'] = Series(range(len(df)))\n return df\n\n tm.assert_frame_equal(f(), expected)\n\n def f():\n df = DataFrame()\n tm.assert_index_equal(df.index, pd.Index([], dtype='object'))\n df['foo'] = range(len(df))\n return df\n\n expected = DataFrame(columns=['foo'],\n index=pd.Index([], dtype='int64'))\n expected['foo'] = expected['foo'].astype('float64')\n tm.assert_frame_equal(f(), expected)\n\n df = DataFrame()\n tm.assert_index_equal(df.columns, pd.Index([], dtype=object))\n df2 = DataFrame()\n df2[1] = Series([1], index=['foo'])\n df.loc[:, 1] = Series([1], index=['foo'])\n tm.assert_frame_equal(df, DataFrame([[1]], index=['foo'], columns=[1]))\n tm.assert_frame_equal(df, df2)\n\n # no index to start\n expected = DataFrame({0: Series(1, index=range(4))},\n columns=['A', 'B', 0])\n\n df = DataFrame(columns=['A', 'B'])\n df[0] = Series(1, index=range(4))\n df.dtypes\n str(df)\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame(columns=['A', 'B'])\n df.loc[:, 0] = Series(1, index=range(4))\n df.dtypes\n str(df)\n tm.assert_frame_equal(df, expected)\n\n def test_partial_set_empty_frame_row(self):\n # GH5720, GH5744\n # don't create rows when empty\n expected = DataFrame(columns=['A', 'B', 'New'],\n index=pd.Index([], dtype='int64'))\n expected['A'] = expected['A'].astype('int64')\n expected['B'] = expected['B'].astype('float64')\n expected['New'] = expected['New'].astype('float64')\n\n df = DataFrame({\"A\": [1, 2, 3], \"B\": [1.2, 4.2, 5.2]})\n y = df[df.A > 5]\n y['New'] = np.nan\n tm.assert_frame_equal(y, expected)\n # tm.assert_frame_equal(y,expected)\n\n expected = DataFrame(columns=['a', 'b', 'c c', 'd'])\n expected['d'] = expected['d'].astype('int64')\n df = DataFrame(columns=['a', 'b', 'c c'])\n df['d'] = 3\n tm.assert_frame_equal(df, expected)\n tm.assert_series_equal(df['c c'], Series(name='c c', dtype=object))\n\n # reindex columns is ok\n df = DataFrame({\"A\": [1, 2, 3], \"B\": [1.2, 4.2, 5.2]})\n y = df[df.A > 5]\n result = y.reindex(columns=['A', 'B', 'C'])\n expected = DataFrame(columns=['A', 'B', 'C'],\n index=pd.Index([], dtype='int64'))\n expected['A'] = expected['A'].astype('int64')\n expected['B'] = expected['B'].astype('float64')\n expected['C'] = expected['C'].astype('float64')\n tm.assert_frame_equal(result, expected)\n\n def test_partial_set_empty_frame_set_series(self):\n # GH 5756\n # setting with empty Series\n df = DataFrame(Series())\n tm.assert_frame_equal(df, DataFrame({0: Series()}))\n\n df = DataFrame(Series(name='foo'))\n tm.assert_frame_equal(df, DataFrame({'foo': Series()}))\n\n def test_partial_set_empty_frame_empty_copy_assignment(self):\n # GH 5932\n # copy on empty with assignment fails\n df = DataFrame(index=[0])\n df = df.copy()\n df['a'] = 0\n expected = DataFrame(0, index=[0], columns=['a'])\n tm.assert_frame_equal(df, expected)\n\n def test_partial_set_empty_frame_empty_consistencies(self):\n # GH 6171\n # consistency on empty frames\n df = DataFrame(columns=['x', 'y'])\n df['x'] = [1, 2]\n expected = DataFrame(dict(x=[1, 2], y=[np.nan, np.nan]))\n tm.assert_frame_equal(df, expected, check_dtype=False)\n\n df = DataFrame(columns=['x', 'y'])\n df['x'] = ['1', '2']\n expected = DataFrame(\n dict(x=['1', '2'], y=[np.nan, np.nan]), dtype=object)\n tm.assert_frame_equal(df, expected)\n\n df = DataFrame(columns=['x', 'y'])\n df.loc[0, 'x'] = 1\n expected = DataFrame(dict(x=[1], y=[np.nan]))\n tm.assert_frame_equal(df, expected, check_dtype=False)\n\n def test_cache_updating(self):\n # GH 4939, make sure to update the cache on setitem\n\n df = tm.makeDataFrame()\n df['A'] # cache series\n df.ix[\"Hello Friend\"] = df.ix[0]\n self.assertIn(\"Hello Friend\", df['A'].index)\n self.assertIn(\"Hello Friend\", df['B'].index)\n\n panel = tm.makePanel()\n panel.ix[0] # get first item into cache\n panel.ix[:, :, 'A+1'] = panel.ix[:, :, 'A'] + 1\n self.assertIn(\"A+1\", panel.ix[0].columns)\n self.assertIn(\"A+1\", panel.ix[1].columns)\n\n # 5216\n # make sure that we don't try to set a dead cache\n a = np.random.rand(10, 3)\n df = DataFrame(a, columns=['x', 'y', 'z'])\n tuples = [(i, j) for i in range(5) for j in range(2)]\n index = MultiIndex.from_tuples(tuples)\n df.index = index\n\n # setting via chained assignment\n # but actually works, since everything is a view\n df.loc[0]['z'].iloc[0] = 1.\n result = df.loc[(0, 0), 'z']\n self.assertEqual(result, 1)\n\n # correct setting\n df.loc[(0, 0), 'z'] = 2\n result = df.loc[(0, 0), 'z']\n self.assertEqual(result, 2)\n\n # 10264\n df = DataFrame(np.zeros((5, 5), dtype='int64'), columns=[\n 'a', 'b', 'c', 'd', 'e'], index=range(5))\n df['f'] = 0\n df.f.values[3] = 1\n\n # TODO(wesm): unused?\n # y = df.iloc[np.arange(2, len(df))]\n\n df.f.values[3] = 2\n expected = DataFrame(np.zeros((5, 6), dtype='int64'), columns=[\n 'a', 'b', 'c', 'd', 'e', 'f'], index=range(5))\n expected.at[3, 'f'] = 2\n tm.assert_frame_equal(df, expected)\n expected = Series([0, 0, 0, 2, 0], name='f')\n tm.assert_series_equal(df.f, expected)\n\n def test_slice_consolidate_invalidate_item_cache(self):\n\n # this is chained assignment, but will 'work'\n with option_context('chained_assignment', None):\n\n # #3970\n df = DataFrame({\"aa\": lrange(5), \"bb\": [2.2] * 5})\n\n # Creates a second float block\n df[\"cc\"] = 0.0\n\n # caches a reference to the 'bb' series\n df[\"bb\"]\n\n # repr machinery triggers consolidation\n repr(df)\n\n # Assignment to wrong series\n df['bb'].iloc[0] = 0.17\n df._clear_item_cache()\n self.assertAlmostEqual(df['bb'][0], 0.17)\n\n def test_setitem_cache_updating(self):\n # GH 5424\n cont = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']\n\n for do_ref in [False, False]:\n df = DataFrame({'a': cont,\n \"b\": cont[3:] + cont[:3],\n 'c': np.arange(7)})\n\n # ref the cache\n if do_ref:\n df.ix[0, \"c\"]\n\n # set it\n df.ix[7, 'c'] = 1\n\n self.assertEqual(df.ix[0, 'c'], 0.0)\n self.assertEqual(df.ix[7, 'c'], 1.0)\n\n # GH 7084\n # not updating cache on series setting with slices\n expected = DataFrame({'A': [600, 600, 600]},\n index=date_range('5/7/2014', '5/9/2014'))\n out = DataFrame({'A': [0, 0, 0]},\n index=date_range('5/7/2014', '5/9/2014'))\n df = DataFrame({'C': ['A', 'A', 'A'], 'D': [100, 200, 300]})\n\n # loop through df to update out\n six = Timestamp('5/7/2014')\n eix = Timestamp('5/9/2014')\n for ix, row in df.iterrows():\n out.loc[six:eix, row['C']] = out.loc[six:eix, row['C']] + row['D']\n\n tm.assert_frame_equal(out, expected)\n tm.assert_series_equal(out['A'], expected['A'])\n\n # try via a chain indexing\n # this actually works\n out = DataFrame({'A': [0, 0, 0]},\n index=date_range('5/7/2014', '5/9/2014'))\n for ix, row in df.iterrows():\n v = out[row['C']][six:eix] + row['D']\n out[row['C']][six:eix] = v\n\n tm.assert_frame_equal(out, expected)\n tm.assert_series_equal(out['A'], expected['A'])\n\n out = DataFrame({'A': [0, 0, 0]},\n index=date_range('5/7/2014', '5/9/2014'))\n for ix, row in df.iterrows():\n out.loc[six:eix, row['C']] += row['D']\n\n tm.assert_frame_equal(out, expected)\n tm.assert_series_equal(out['A'], expected['A'])\n\n def test_setitem_chained_setfault(self):\n\n # GH6026\n # setfaults under numpy 1.7.1 (ok on 1.8)\n data = ['right', 'left', 'left', 'left', 'right', 'left', 'timeout']\n mdata = ['right', 'left', 'left', 'left', 'right', 'left', 'none']\n\n df = DataFrame({'response': np.array(data)})\n mask = df.response == 'timeout'\n df.response[mask] = 'none'\n tm.assert_frame_equal(df, DataFrame({'response': mdata}))\n\n recarray = np.rec.fromarrays([data], names=['response'])\n df = DataFrame(recarray)\n mask = df.response == 'timeout'\n df.response[mask] = 'none'\n tm.assert_frame_equal(df, DataFrame({'response': mdata}))\n\n df = DataFrame({'response': data, 'response1': data})\n mask = df.response == 'timeout'\n df.response[mask] = 'none'\n tm.assert_frame_equal(df, DataFrame({'response': mdata,\n 'response1': data}))\n\n # GH 6056\n expected = DataFrame(dict(A=[np.nan, 'bar', 'bah', 'foo', 'bar']))\n df = DataFrame(dict(A=np.array(['foo', 'bar', 'bah', 'foo', 'bar'])))\n df['A'].iloc[0] = np.nan\n result = df.head()\n tm.assert_frame_equal(result, expected)\n\n df = DataFrame(dict(A=np.array(['foo', 'bar', 'bah', 'foo', 'bar'])))\n df.A.iloc[0] = np.nan\n result = df.head()\n tm.assert_frame_equal(result, expected)\n\n def test_detect_chained_assignment(self):\n\n pd.set_option('chained_assignment', 'raise')\n\n # work with the chain\n expected = DataFrame([[-5, 1], [-6, 3]], columns=list('AB'))\n df = DataFrame(np.arange(4).reshape(2, 2),\n columns=list('AB'), dtype='int64')\n self.assertIsNone(df.is_copy)\n df['A'][0] = -5\n df['A'][1] = -6\n tm.assert_frame_equal(df, expected)\n\n # test with the chaining\n df = DataFrame({'A': Series(range(2), dtype='int64'),\n 'B': np.array(np.arange(2, 4), dtype=np.float64)})\n self.assertIsNone(df.is_copy)\n\n def f():\n df['A'][0] = -5\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n def f():\n df['A'][1] = np.nan\n\n self.assertRaises(com.SettingWithCopyError, f)\n self.assertIsNone(df['A'].is_copy)\n\n # using a copy (the chain), fails\n df = DataFrame({'A': Series(range(2), dtype='int64'),\n 'B': np.array(np.arange(2, 4), dtype=np.float64)})\n\n def f():\n df.loc[0]['A'] = -5\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n # doc example\n df = DataFrame({'a': ['one', 'one', 'two', 'three',\n 'two', 'one', 'six'],\n 'c': Series(range(7), dtype='int64')})\n self.assertIsNone(df.is_copy)\n expected = DataFrame({'a': ['one', 'one', 'two', 'three',\n 'two', 'one', 'six'],\n 'c': [42, 42, 2, 3, 4, 42, 6]})\n\n def f():\n indexer = df.a.str.startswith('o')\n df[indexer]['c'] = 42\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n expected = DataFrame({'A': [111, 'bbb', 'ccc'], 'B': [1, 2, 3]})\n df = DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]})\n\n def f():\n df['A'][0] = 111\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n def f():\n df.loc[0]['A'] = 111\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n df.loc[0, 'A'] = 111\n tm.assert_frame_equal(df, expected)\n\n # make sure that is_copy is picked up reconstruction\n # GH5475\n df = DataFrame({\"A\": [1, 2]})\n self.assertIsNone(df.is_copy)\n with tm.ensure_clean('__tmp__pickle') as path:\n df.to_pickle(path)\n df2 = pd.read_pickle(path)\n df2[\"B\"] = df2[\"A\"]\n df2[\"B\"] = df2[\"A\"]\n\n # a suprious raise as we are setting the entire column here\n # GH5597\n from string import ascii_letters as letters\n\n def random_text(nobs=100):\n df = []\n for i in range(nobs):\n idx = np.random.randint(len(letters), size=2)\n idx.sort()\n df.append([letters[idx[0]:idx[1]]])\n\n return DataFrame(df, columns=['letters'])\n\n df = random_text(100000)\n\n # always a copy\n x = df.iloc[[0, 1, 2]]\n self.assertIsNotNone(x.is_copy)\n x = df.iloc[[0, 1, 2, 4]]\n self.assertIsNotNone(x.is_copy)\n\n # explicity copy\n indexer = df.letters.apply(lambda x: len(x) > 10)\n df = df.ix[indexer].copy()\n self.assertIsNone(df.is_copy)\n df['letters'] = df['letters'].apply(str.lower)\n\n # implicity take\n df = random_text(100000)\n indexer = df.letters.apply(lambda x: len(x) > 10)\n df = df.ix[indexer]\n self.assertIsNotNone(df.is_copy)\n df['letters'] = df['letters'].apply(str.lower)\n\n # implicity take 2\n df = random_text(100000)\n indexer = df.letters.apply(lambda x: len(x) > 10)\n df = df.ix[indexer]\n self.assertIsNotNone(df.is_copy)\n df.loc[:, 'letters'] = df['letters'].apply(str.lower)\n\n # should be ok even though it's a copy!\n self.assertIsNone(df.is_copy)\n df['letters'] = df['letters'].apply(str.lower)\n self.assertIsNone(df.is_copy)\n\n df = random_text(100000)\n indexer = df.letters.apply(lambda x: len(x) > 10)\n df.ix[indexer, 'letters'] = df.ix[indexer, 'letters'].apply(str.lower)\n\n # an identical take, so no copy\n df = DataFrame({'a': [1]}).dropna()\n self.assertIsNone(df.is_copy)\n df['a'] += 1\n\n # inplace ops\n # original from:\n # http://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug\n a = [12, 23]\n b = [123, None]\n c = [1234, 2345]\n d = [12345, 23456]\n tuples = [('eyes', 'left'), ('eyes', 'right'), ('ears', 'left'),\n ('ears', 'right')]\n events = {('eyes', 'left'): a,\n ('eyes', 'right'): b,\n ('ears', 'left'): c,\n ('ears', 'right'): d}\n multiind = MultiIndex.from_tuples(tuples, names=['part', 'side'])\n zed = DataFrame(events, index=['a', 'b'], columns=multiind)\n\n def f():\n zed['eyes']['right'].fillna(value=555, inplace=True)\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n df = DataFrame(np.random.randn(10, 4))\n s = df.iloc[:, 0].sort_values()\n tm.assert_series_equal(s, df.iloc[:, 0].sort_values())\n tm.assert_series_equal(s, df[0].sort_values())\n\n # false positives GH6025\n df = DataFrame({'column1': ['a', 'a', 'a'], 'column2': [4, 8, 9]})\n str(df)\n df['column1'] = df['column1'] + 'b'\n str(df)\n df = df[df['column2'] != 8]\n str(df)\n df['column1'] = df['column1'] + 'c'\n str(df)\n\n # from SO:\n # http://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc\n df = DataFrame(np.arange(0, 9), columns=['count'])\n df['group'] = 'b'\n\n def f():\n df.iloc[0:5]['group'] = 'a'\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n # mixed type setting\n # same dtype & changing dtype\n df = DataFrame(dict(A=date_range('20130101', periods=5),\n B=np.random.randn(5),\n C=np.arange(5, dtype='int64'),\n D=list('abcde')))\n\n def f():\n df.ix[2]['D'] = 'foo'\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n def f():\n df.ix[2]['C'] = 'foo'\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n def f():\n df['C'][2] = 'foo'\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n def test_setting_with_copy_bug(self):\n\n # operating on a copy\n df = pd.DataFrame({'a': list(range(4)),\n 'b': list('ab..'),\n 'c': ['a', 'b', np.nan, 'd']})\n mask = pd.isnull(df.c)\n\n def f():\n df[['c']][mask] = df[['b']][mask]\n\n self.assertRaises(com.SettingWithCopyError, f)\n\n # invalid warning as we are returning a new object\n # GH 8730\n df1 = DataFrame({'x': Series(['a', 'b', 'c']),\n 'y': Series(['d', 'e', 'f'])})\n df2 = df1[['x']]\n\n # this should not raise\n df2['y'] = ['g', 'h', 'i']\n\n def test_detect_chained_assignment_warnings(self):\n\n # warnings\n with option_context('chained_assignment', 'warn'):\n df = DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]})\n with tm.assert_produces_warning(\n expected_warning=com.SettingWithCopyWarning):\n df.loc[0]['A'] = 111\n\n def test_float64index_slicing_bug(self):\n # GH 5557, related to slicing a float index\n ser = {256: 2321.0,\n 1: 78.0,\n 2: 2716.0,\n 3: 0.0,\n 4: 369.0,\n 5: 0.0,\n 6: 269.0,\n 7: 0.0,\n 8: 0.0,\n 9: 0.0,\n 10: 3536.0,\n 11: 0.0,\n 12: 24.0,\n 13: 0.0,\n 14: 931.0,\n 15: 0.0,\n 16: 101.0,\n 17: 78.0,\n 18: 9643.0,\n 19: 0.0,\n 20: 0.0,\n 21: 0.0,\n 22: 63761.0,\n 23: 0.0,\n 24: 446.0,\n 25: 0.0,\n 26: 34773.0,\n 27: 0.0,\n 28: 729.0,\n 29: 78.0,\n 30: 0.0,\n 31: 0.0,\n 32: 3374.0,\n 33: 0.0,\n 34: 1391.0,\n 35: 0.0,\n 36: 361.0,\n 37: 0.0,\n 38: 61808.0,\n 39: 0.0,\n 40: 0.0,\n 41: 0.0,\n 42: 6677.0,\n 43: 0.0,\n 44: 802.0,\n 45: 0.0,\n 46: 2691.0,\n 47: 0.0,\n 48: 3582.0,\n 49: 0.0,\n 50: 734.0,\n 51: 0.0,\n 52: 627.0,\n 53: 70.0,\n 54: 2584.0,\n 55: 0.0,\n 56: 324.0,\n 57: 0.0,\n 58: 605.0,\n 59: 0.0,\n 60: 0.0,\n 61: 0.0,\n 62: 3989.0,\n 63: 10.0,\n 64: 42.0,\n 65: 0.0,\n 66: 904.0,\n 67: 0.0,\n 68: 88.0,\n 69: 70.0,\n 70: 8172.0,\n 71: 0.0,\n 72: 0.0,\n 73: 0.0,\n 74: 64902.0,\n 75: 0.0,\n 76: 347.0,\n 77: 0.0,\n 78: 36605.0,\n 79: 0.0,\n 80: 379.0,\n 81: 70.0,\n 82: 0.0,\n 83: 0.0,\n 84: 3001.0,\n 85: 0.0,\n 86: 1630.0,\n 87: 7.0,\n 88: 364.0,\n 89: 0.0,\n 90: 67404.0,\n 91: 9.0,\n 92: 0.0,\n 93: 0.0,\n 94: 7685.0,\n 95: 0.0,\n 96: 1017.0,\n 97: 0.0,\n 98: 2831.0,\n 99: 0.0,\n 100: 2963.0,\n 101: 0.0,\n 102: 854.0,\n 103: 0.0,\n 104: 0.0,\n 105: 0.0,\n 106: 0.0,\n 107: 0.0,\n 108: 0.0,\n 109: 0.0,\n 110: 0.0,\n 111: 0.0,\n 112: 0.0,\n 113: 0.0,\n 114: 0.0,\n 115: 0.0,\n 116: 0.0,\n 117: 0.0,\n 118: 0.0,\n 119: 0.0,\n 120: 0.0,\n 121: 0.0,\n 122: 0.0,\n 123: 0.0,\n 124: 0.0,\n 125: 0.0,\n 126: 67744.0,\n 127: 22.0,\n 128: 264.0,\n 129: 0.0,\n 260: 197.0,\n 268: 0.0,\n 265: 0.0,\n 269: 0.0,\n 261: 0.0,\n 266: 1198.0,\n 267: 0.0,\n 262: 2629.0,\n 258: 775.0,\n 257: 0.0,\n 263: 0.0,\n 259: 0.0,\n 264: 163.0,\n 250: 10326.0,\n 251: 0.0,\n 252: 1228.0,\n 253: 0.0,\n 254: 2769.0,\n 255: 0.0}\n\n # smoke test for the repr\n s = Series(ser)\n result = s.value_counts()\n str(result)\n\n def test_set_ix_out_of_bounds_axis_0(self):\n df = pd.DataFrame(\n randn(2, 5), index=[\"row%s\" % i for i in range(2)],\n columns=[\"col%s\" % i for i in range(5)])\n self.assertRaises(ValueError, df.ix.__setitem__, (2, 0), 100)\n\n def test_set_ix_out_of_bounds_axis_1(self):\n df = pd.DataFrame(\n randn(5, 2), index=[\"row%s\" % i for i in range(5)],\n columns=[\"col%s\" % i for i in range(2)])\n self.assertRaises(ValueError, df.ix.__setitem__, (0, 2), 100)\n\n def test_iloc_empty_list_indexer_is_ok(self):\n from pandas.util.testing import makeCustomDataframe as mkdf\n df = mkdf(5, 2)\n # vertical empty\n tm.assert_frame_equal(df.iloc[:, []], df.iloc[:, :0],\n check_index_type=True, check_column_type=True)\n # horizontal empty\n tm.assert_frame_equal(df.iloc[[], :], df.iloc[:0, :],\n check_index_type=True, check_column_type=True)\n # horizontal empty\n tm.assert_frame_equal(df.iloc[[]], df.iloc[:0, :],\n check_index_type=True,\n check_column_type=True)\n\n def test_loc_empty_list_indexer_is_ok(self):\n from pandas.util.testing import makeCustomDataframe as mkdf\n df = mkdf(5, 2)\n # vertical empty\n tm.assert_frame_equal(df.loc[:, []], df.iloc[:, :0],\n check_index_type=True, check_column_type=True)\n # horizontal empty\n tm.assert_frame_equal(df.loc[[], :], df.iloc[:0, :],\n check_index_type=True, check_column_type=True)\n # horizontal empty\n tm.assert_frame_equal(df.loc[[]], df.iloc[:0, :],\n check_index_type=True,\n check_column_type=True)\n\n def test_ix_empty_list_indexer_is_ok(self):\n from pandas.util.testing import makeCustomDataframe as mkdf\n df = mkdf(5, 2)\n # vertical empty\n tm.assert_frame_equal(df.ix[:, []], df.iloc[:, :0],\n check_index_type=True,\n check_column_type=True)\n # horizontal empty\n tm.assert_frame_equal(df.ix[[], :], df.iloc[:0, :],\n check_index_type=True,\n check_column_type=True)\n # horizontal empty\n tm.assert_frame_equal(df.ix[[]], df.iloc[:0, :],\n check_index_type=True,\n check_column_type=True)\n\n def test_index_type_coercion(self):\n\n # GH 11836\n # if we have an index type and set it with something that looks\n # to numpy like the same, but is actually, not\n # (e.g. setting with a float or string '0')\n # then we need to coerce to object\n\n # integer indexes\n for s in [Series(range(5)),\n Series(range(5), index=range(1, 6))]:\n\n self.assertTrue(s.index.is_integer())\n\n for indexer in [lambda x: x.ix,\n lambda x: x.loc,\n lambda x: x]:\n s2 = s.copy()\n indexer(s2)[0.1] = 0\n self.assertTrue(s2.index.is_floating())\n self.assertTrue(indexer(s2)[0.1] == 0)\n\n s2 = s.copy()\n indexer(s2)[0.0] = 0\n exp = s.index\n if 0 not in s:\n exp = Index(s.index.tolist() + [0])\n tm.assert_index_equal(s2.index, exp)\n\n s2 = s.copy()\n indexer(s2)['0'] = 0\n self.assertTrue(s2.index.is_object())\n\n for s in [Series(range(5), index=np.arange(5.))]:\n\n self.assertTrue(s.index.is_floating())\n\n for idxr in [lambda x: x.ix,\n lambda x: x.loc,\n lambda x: x]:\n\n s2 = s.copy()\n idxr(s2)[0.1] = 0\n self.assertTrue(s2.index.is_floating())\n self.assertTrue(idxr(s2)[0.1] == 0)\n\n s2 = s.copy()\n idxr(s2)[0.0] = 0\n tm.assert_index_equal(s2.index, s.index)\n\n s2 = s.copy()\n idxr(s2)['0'] = 0\n self.assertTrue(s2.index.is_object())\n\n def test_float_index_to_mixed(self):\n df = DataFrame({0.0: np.random.rand(10), 1.0: np.random.rand(10)})\n df['a'] = 10\n tm.assert_frame_equal(DataFrame({0.0: df[0.0],\n 1.0: df[1.0],\n 'a': [10] * 10}),\n df)\n\n def test_duplicate_ix_returns_series(self):\n df = DataFrame(np.random.randn(3, 3), index=[0.1, 0.2, 0.2],\n columns=list('abc'))\n r = df.ix[0.2, 'a']\n e = df.loc[0.2, 'a']\n tm.assert_series_equal(r, e)\n\n def test_float_index_non_scalar_assignment(self):\n df = DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]}, index=[1., 2., 3.])\n df.loc[df.index[:2]] = 1\n expected = DataFrame({'a': [1, 1, 3], 'b': [1, 1, 5]}, index=df.index)\n tm.assert_frame_equal(expected, df)\n\n df = DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]}, index=[1., 2., 3.])\n df2 = df.copy()\n df.loc[df.index] = df.loc[df.index]\n tm.assert_frame_equal(df, df2)\n\n def test_float_index_at_iat(self):\n s = pd.Series([1, 2, 3], index=[0.1, 0.2, 0.3])\n for el, item in s.iteritems():\n self.assertEqual(s.at[el], item)\n for i in range(len(s)):\n self.assertEqual(s.iat[i], i + 1)\n\n def test_rhs_alignment(self):\n # GH8258, tests that both rows & columns are aligned to what is\n # assigned to. covers both uniform data-type & multi-type cases\n def run_tests(df, rhs, right):\n # label, index, slice\n r, i, s = list('bcd'), [1, 2, 3], slice(1, 4)\n c, j, l = ['joe', 'jolie'], [1, 2], slice(1, 3)\n\n left = df.copy()\n left.loc[r, c] = rhs\n tm.assert_frame_equal(left, right)\n\n left = df.copy()\n left.iloc[i, j] = rhs\n tm.assert_frame_equal(left, right)\n\n left = df.copy()\n left.ix[s, l] = rhs\n tm.assert_frame_equal(left, right)\n\n left = df.copy()\n left.ix[i, j] = rhs\n tm.assert_frame_equal(left, right)\n\n left = df.copy()\n left.ix[r, c] = rhs\n tm.assert_frame_equal(left, right)\n\n xs = np.arange(20).reshape(5, 4)\n cols = ['jim', 'joe', 'jolie', 'joline']\n df = pd.DataFrame(xs, columns=cols, index=list('abcde'))\n\n # right hand side; permute the indices and multiplpy by -2\n rhs = -2 * df.iloc[3:0:-1, 2:0:-1]\n\n # expected `right` result; just multiply by -2\n right = df.copy()\n right.iloc[1:4, 1:3] *= -2\n\n # run tests with uniform dtypes\n run_tests(df, rhs, right)\n\n # make frames multi-type & re-run tests\n for frame in [df, rhs, right]:\n frame['joe'] = frame['joe'].astype('float64')\n frame['jolie'] = frame['jolie'].map('@{0}'.format)\n\n run_tests(df, rhs, right)\n\n def test_str_label_slicing_with_negative_step(self):\n SLC = pd.IndexSlice\n\n def assert_slices_equivalent(l_slc, i_slc):\n tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])\n\n if not idx.is_integer:\n # For integer indices, ix and plain getitem are position-based.\n tm.assert_series_equal(s[l_slc], s.iloc[i_slc])\n tm.assert_series_equal(s.ix[l_slc], s.iloc[i_slc])\n\n for idx in [_mklbl('A', 20), np.arange(20) + 100,\n np.linspace(100, 150, 20)]:\n idx = Index(idx)\n s = Series(np.arange(20), index=idx)\n assert_slices_equivalent(SLC[idx[9]::-1], SLC[9::-1])\n assert_slices_equivalent(SLC[:idx[9]:-1], SLC[:8:-1])\n assert_slices_equivalent(SLC[idx[13]:idx[9]:-1], SLC[13:8:-1])\n assert_slices_equivalent(SLC[idx[9]:idx[13]:-1], SLC[:0])\n\n def test_multiindex_label_slicing_with_negative_step(self):\n s = Series(np.arange(20),\n MultiIndex.from_product([list('abcde'), np.arange(4)]))\n SLC = pd.IndexSlice\n\n def assert_slices_equivalent(l_slc, i_slc):\n tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])\n tm.assert_series_equal(s[l_slc], s.iloc[i_slc])\n tm.assert_series_equal(s.ix[l_slc], s.iloc[i_slc])\n\n assert_slices_equivalent(SLC[::-1], SLC[::-1])\n\n assert_slices_equivalent(SLC['d'::-1], SLC[15::-1])\n assert_slices_equivalent(SLC[('d', )::-1], SLC[15::-1])\n\n assert_slices_equivalent(SLC[:'d':-1], SLC[:11:-1])\n assert_slices_equivalent(SLC[:('d', ):-1], SLC[:11:-1])\n\n assert_slices_equivalent(SLC['d':'b':-1], SLC[15:3:-1])\n assert_slices_equivalent(SLC[('d', ):'b':-1], SLC[15:3:-1])\n assert_slices_equivalent(SLC['d':('b', ):-1], SLC[15:3:-1])\n assert_slices_equivalent(SLC[('d', ):('b', ):-1], SLC[15:3:-1])\n assert_slices_equivalent(SLC['b':'d':-1], SLC[:0])\n\n assert_slices_equivalent(SLC[('c', 2)::-1], SLC[10::-1])\n assert_slices_equivalent(SLC[:('c', 2):-1], SLC[:9:-1])\n assert_slices_equivalent(SLC[('e', 0):('c', 2):-1], SLC[16:9:-1])\n\n def test_slice_with_zero_step_raises(self):\n s = Series(np.arange(20), index=_mklbl('A', 20))\n self.assertRaisesRegexp(ValueError, 'slice step cannot be zero',\n lambda: s[::0])\n self.assertRaisesRegexp(ValueError, 'slice step cannot be zero',\n lambda: s.loc[::0])\n self.assertRaisesRegexp(ValueError, 'slice step cannot be zero',\n lambda: s.ix[::0])\n\n def test_indexing_assignment_dict_already_exists(self):\n df = pd.DataFrame({'x': [1, 2, 6],\n 'y': [2, 2, 8],\n 'z': [-5, 0, 5]}).set_index('z')\n expected = df.copy()\n rhs = dict(x=9, y=99)\n df.loc[5] = rhs\n expected.loc[5] = [9, 99]\n tm.assert_frame_equal(df, expected)\n\n def test_indexing_dtypes_on_empty(self):\n # Check that .iloc and .ix return correct dtypes GH9983\n df = DataFrame({'a': [1, 2, 3], 'b': ['b', 'b2', 'b3']})\n df2 = df.ix[[], :]\n\n self.assertEqual(df2.loc[:, 'a'].dtype, np.int64)\n tm.assert_series_equal(df2.loc[:, 'a'], df2.iloc[:, 0])\n tm.assert_series_equal(df2.loc[:, 'a'], df2.ix[:, 0])\n\n def test_range_in_series_indexing(self):\n # range can cause an indexing error\n # GH 11652\n for x in [5, 999999, 1000000]:\n s = pd.Series(index=range(x))\n s.loc[range(1)] = 42\n tm.assert_series_equal(s.loc[range(1)], Series(42.0, index=[0]))\n\n s.loc[range(2)] = 43\n tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1]))\n\n def test_non_reducing_slice(self):\n df = pd.DataFrame([[0, 1], [2, 3]])\n\n slices = [\n # pd.IndexSlice[:, :],\n pd.IndexSlice[:, 1],\n pd.IndexSlice[1, :],\n pd.IndexSlice[[1], [1]],\n pd.IndexSlice[1, [1]],\n pd.IndexSlice[[1], 1],\n pd.IndexSlice[1],\n pd.IndexSlice[1, 1],\n slice(None, None, None),\n [0, 1],\n np.array([0, 1]),\n pd.Series([0, 1])\n ]\n for slice_ in slices:\n tslice_ = _non_reducing_slice(slice_)\n self.assertTrue(isinstance(df.loc[tslice_], DataFrame))\n\n def test_list_slice(self):\n # like dataframe getitem\n slices = [['A'], pd.Series(['A']), np.array(['A'])]\n df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['A', 'B'])\n expected = pd.IndexSlice[:, ['A']]\n for subset in slices:\n result = _non_reducing_slice(subset)\n tm.assert_frame_equal(df.loc[result], df.loc[expected])\n\n def test_maybe_numeric_slice(self):\n df = pd.DataFrame({'A': [1, 2], 'B': ['c', 'd'], 'C': [True, False]})\n result = _maybe_numeric_slice(df, slice_=None)\n expected = pd.IndexSlice[:, ['A']]\n self.assertEqual(result, expected)\n\n result = _maybe_numeric_slice(df, None, include_bool=True)\n expected = pd.IndexSlice[:, ['A', 'C']]\n result = _maybe_numeric_slice(df, [1])\n expected = [1]\n self.assertEqual(result, expected)\n\n def test_multiindex_slice_first_level(self):\n # GH 12697\n freq = ['a', 'b', 'c', 'd']\n idx = pd.MultiIndex.from_product([freq, np.arange(500)])\n df = pd.DataFrame(list(range(2000)), index=idx, columns=['Test'])\n df_slice = df.loc[pd.IndexSlice[:, 30:70], :]\n result = df_slice.loc['a']\n expected = pd.DataFrame(list(range(30, 71)),\n columns=['Test'],\n index=range(30, 71))\n tm.assert_frame_equal(result, expected)\n result = df_slice.loc['d']\n expected = pd.DataFrame(list(range(1530, 1571)),\n columns=['Test'],\n index=range(30, 71))\n tm.assert_frame_equal(result, expected)\n\n\nclass TestSeriesNoneCoercion(tm.TestCase):\n EXPECTED_RESULTS = [\n # For numeric series, we should coerce to NaN.\n ([1, 2, 3], [np.nan, 2, 3]),\n ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]),\n\n # For datetime series, we should coerce to NaT.\n ([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]),\n\n # For objects, we should preserve the None value.\n ([\"foo\", \"bar\", \"baz\"], [None, \"bar\", \"baz\"]),\n ]\n\n def test_coercion_with_setitem(self):\n for start_data, expected_result in self.EXPECTED_RESULTS:\n start_series = Series(start_data)\n start_series[0] = None\n\n expected_series = Series(expected_result)\n tm.assert_series_equal(start_series, expected_series)\n\n def test_coercion_with_loc_setitem(self):\n for start_data, expected_result in self.EXPECTED_RESULTS:\n start_series = Series(start_data)\n start_series.loc[0] = None\n\n expected_series = Series(expected_result)\n tm.assert_series_equal(start_series, expected_series)\n\n def test_coercion_with_setitem_and_series(self):\n for start_data, expected_result in self.EXPECTED_RESULTS:\n start_series = Series(start_data)\n start_series[start_series == start_series[0]] = None\n\n expected_series = Series(expected_result)\n tm.assert_series_equal(start_series, expected_series)\n\n def test_coercion_with_loc_and_series(self):\n for start_data, expected_result in self.EXPECTED_RESULTS:\n start_series = Series(start_data)\n start_series.loc[start_series == start_series[0]] = None\n\n expected_series = Series(expected_result)\n tm.assert_series_equal(start_series, expected_series)\n\n\nclass TestDataframeNoneCoercion(tm.TestCase):\n EXPECTED_SINGLE_ROW_RESULTS = [\n # For numeric series, we should coerce to NaN.\n ([1, 2, 3], [np.nan, 2, 3]),\n ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]),\n\n # For datetime series, we should coerce to NaT.\n ([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],\n [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]),\n\n # For objects, we should preserve the None value.\n ([\"foo\", \"bar\", \"baz\"], [None, \"bar\", \"baz\"]),\n ]\n\n def test_coercion_with_loc(self):\n for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS:\n start_dataframe = DataFrame({'foo': start_data})\n start_dataframe.loc[0, ['foo']] = None\n\n expected_dataframe = DataFrame({'foo': expected_result})\n tm.assert_frame_equal(start_dataframe, expected_dataframe)\n\n def test_coercion_with_setitem_and_dataframe(self):\n for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS:\n start_dataframe = DataFrame({'foo': start_data})\n start_dataframe[start_dataframe['foo'] == start_dataframe['foo'][\n 0]] = None\n\n expected_dataframe = DataFrame({'foo': expected_result})\n tm.assert_frame_equal(start_dataframe, expected_dataframe)\n\n def test_none_coercion_loc_and_dataframe(self):\n for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS:\n start_dataframe = DataFrame({'foo': start_data})\n start_dataframe.loc[start_dataframe['foo'] == start_dataframe[\n 'foo'][0]] = None\n\n expected_dataframe = DataFrame({'foo': expected_result})\n tm.assert_frame_equal(start_dataframe, expected_dataframe)\n\n def test_none_coercion_mixed_dtypes(self):\n start_dataframe = DataFrame({\n 'a': [1, 2, 3],\n 'b': [1.0, 2.0, 3.0],\n 'c': [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1,\n 3)],\n 'd': ['a', 'b', 'c']\n })\n start_dataframe.iloc[0] = None\n\n exp = DataFrame({'a': [np.nan, 2, 3],\n 'b': [np.nan, 2.0, 3.0],\n 'c': [NaT, datetime(2000, 1, 2),\n datetime(2000, 1, 3)],\n 'd': [None, 'b', 'c']})\n tm.assert_frame_equal(start_dataframe, exp)\n\n\nclass TestTimedeltaIndexing(tm.TestCase):\n\n def test_boolean_indexing(self):\n # GH 14946\n df = pd.DataFrame({'x': range(10)})\n df.index = pd.to_timedelta(range(10), unit='s')\n conditions = [df['x'] > 3, df['x'] == 3, df['x'] < 3]\n expected_data = [[0, 1, 2, 3, 10, 10, 10, 10, 10, 10],\n [0, 1, 2, 10, 4, 5, 6, 7, 8, 9],\n [10, 10, 10, 3, 4, 5, 6, 7, 8, 9]]\n for cond, data in zip(conditions, expected_data):\n result = df.copy()\n result.loc[cond, 'x'] = 10\n expected = pd.DataFrame(data,\n index=pd.to_timedelta(range(10), unit='s'),\n columns=['x'])\n tm.assert_frame_equal(expected, result)\n\n\nif __name__ == '__main__':\n nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],\n exit=False)\n"
] |
[
[
"pandas.core.api.Timedelta",
"pandas.to_datetime",
"pandas.Series",
"pandas.util.testing.assertIsInstance",
"pandas.util.testing.ensure_clean",
"numpy.linspace",
"pandas.PeriodIndex",
"pandas.types.common.is_float_dtype",
"pandas.util.testing.assert_produces_warning",
"pandas.MultiIndex.from_tuples",
"pandas.DataFrame",
"pandas.core.api.MultiIndex.from_arrays",
"pandas.util.testing.assert_frame_equal",
"numpy.random.random_sample",
"pandas.util.testing.makePanel",
"pandas.util.testing.assert_index_equal",
"numpy.random.randn",
"pandas.core.api.MultiIndex.from_product",
"pandas.compat.lzip",
"pandas.core.indexing._non_reducing_slice",
"pandas.util.testing.makeDataFrame",
"numpy.random.randint",
"pandas.util.testing.makeTimeDataFrame",
"pandas.core.api.MultiIndex.from_tuples",
"pandas.util.testing.assert_numpy_array_equal",
"pandas.Timestamp",
"numpy.arange",
"pandas.compat.StringIO",
"numpy.eye",
"pandas.core.api.Panel",
"pandas.util.testing.assert_series_equal",
"pandas.Index",
"pandas.types.common.is_integer_dtype",
"pandas.DatetimeIndex",
"pandas.core.api.Index",
"pandas.compat.lmap",
"pandas.util.testing.assert_panel_equal",
"pandas.core.api.MultiIndex",
"pandas.core.api.isnull",
"pandas.set_option",
"numpy.zeros",
"pandas.types.common.is_scalar",
"pandas.concat",
"numpy.isnan",
"pandas.util.testing.assert_almost_equal",
"pandas.Timedelta",
"pandas.option_context",
"pandas.util.testing.getSeriesData",
"pandas.core.indexing._maybe_numeric_slice",
"pandas.MultiIndex.from_product",
"numpy.random.rand",
"pandas.date_range",
"pandas.core.api.Series",
"pandas.core.api.DataFrame",
"pandas.core.api.Timestamp",
"numpy.array",
"pandas.core.api.DataFrame.from_dict",
"pandas.util.testing.makeCustomDataframe",
"numpy.random.random",
"numpy.random.seed",
"pandas.period_range",
"pandas.isnull",
"pandas.util.testing.assertRaisesRegexp",
"numpy.rec.fromarrays",
"pandas.formats.printing.pprint_thing",
"numpy.ones",
"pandas.util.testing.assertRaises",
"numpy.datetime64",
"pandas.Period",
"pandas.read_pickle",
"pandas.compat.lrange",
"pandas.compat.range"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
oliviaweng/imgclsmob
|
[
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"80fffbb46f986614b162c725b21f3d208597ac77",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"80fffbb46f986614b162c725b21f3d208597ac77",
"a1f1f52eecbb841fa878bff4d3c311b79864835d",
"80fffbb46f986614b162c725b21f3d208597ac77",
"a1f1f52eecbb841fa878bff4d3c311b79864835d"
] |
[
"keras_/kerascv/models/seresnext.py",
"other/eval_gl_mch.py",
"gluon/gluoncv2/models/darts.py",
"tensorflow2/tf2cv/models/drn.py",
"tensorflow2/tf2cv/models/ghostnet.py",
"pytorch/pytorchcv/models/sparsenet.py",
"tensorflow_/tensorflowcv/models/menet.py",
"tensorflow2/tf2cv/models/resnext_cifar.py",
"chainer_/datasets/voc_seg_dataset.py",
"gluon/datasets/coco_seg_dataset.py",
"tensorflow2/datasets/seg_dataset.py",
"pytorch/pytorchcv/models/resnet.py",
"tensorflow2/datasets/svhn_cls_dataset.py"
] |
[
"\"\"\"\n SE-ResNeXt for ImageNet-1K, implemented in Keras.\n Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\"\"\"\n\n__all__ = ['seresnext', 'seresnext50_32x4d', 'seresnext101_32x4d', 'seresnext101_64x4d']\n\nimport os\nfrom keras import layers as nn\nfrom keras.models import Model\nfrom .common import conv1x1_block, se_block, is_channels_first, flatten\nfrom .resnet import res_init_block\nfrom .resnext import resnext_bottleneck\n\n\ndef seresnext_unit(x,\n in_channels,\n out_channels,\n strides,\n cardinality,\n bottleneck_width,\n name=\"seresnext_unit\"):\n \"\"\"\n SE-ResNeXt unit.\n\n Parameters:\n ----------\n x : keras.backend tensor/variable/symbol\n Input tensor/variable/symbol.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n cardinality: int\n Number of groups.\n bottleneck_width: int\n Width of bottleneck block.\n name : str, default 'seresnext_unit'\n Unit name.\n\n Returns\n -------\n keras.backend tensor/variable/symbol\n Resulted tensor/variable/symbol.\n \"\"\"\n resize_identity = (in_channels != out_channels) or (strides != 1)\n if resize_identity:\n identity = conv1x1_block(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n activation=None,\n name=name + \"/identity_conv\")\n else:\n identity = x\n\n x = resnext_bottleneck(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n cardinality=cardinality,\n bottleneck_width=bottleneck_width,\n name=name + \"/body\")\n\n x = se_block(\n x=x,\n channels=out_channels,\n name=name + \"/se\")\n\n x = nn.add([x, identity], name=name + \"/add\")\n\n activ = nn.Activation(\"relu\", name=name + \"/activ\")\n x = activ(x)\n return x\n\n\ndef seresnext(channels,\n init_block_channels,\n cardinality,\n bottleneck_width,\n in_channels=3,\n in_size=(224, 224),\n classes=1000):\n \"\"\"\n SE-ResNeXt model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n cardinality: int\n Number of groups.\n bottleneck_width: int\n Width of bottleneck block.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n \"\"\"\n input_shape = (in_channels, in_size[0], in_size[1]) if is_channels_first() else\\\n (in_size[0], in_size[1], in_channels)\n input = nn.Input(shape=input_shape)\n\n x = res_init_block(\n x=input,\n in_channels=in_channels,\n out_channels=init_block_channels,\n name=\"features/init_block\")\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n for j, out_channels in enumerate(channels_per_stage):\n strides = 2 if (j == 0) and (i != 0) else 1\n x = seresnext_unit(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n cardinality=cardinality,\n bottleneck_width=bottleneck_width,\n name=\"features/stage{}/unit{}\".format(i + 1, j + 1))\n in_channels = out_channels\n x = nn.AvgPool2D(\n pool_size=7,\n strides=1,\n name=\"features/final_pool\")(x)\n\n # x = nn.Flatten()(x)\n x = flatten(x)\n x = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output\")(x)\n\n model = Model(inputs=input, outputs=x)\n model.in_size = in_size\n model.classes = classes\n return model\n\n\ndef get_seresnext(blocks,\n cardinality,\n bottleneck_width,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".keras\", \"models\"),\n **kwargs):\n \"\"\"\n Create SE-ResNeXt model with specific parameters.\n\n Parameters:\n ----------\n blocks : int\n Number of blocks.\n cardinality: int\n Number of groups.\n bottleneck_width: int\n Width of bottleneck block.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if blocks == 50:\n layers = [3, 4, 6, 3]\n elif blocks == 101:\n layers = [3, 4, 23, 3]\n else:\n raise ValueError(\"Unsupported SE-ResNeXt with number of blocks: {}\".format(blocks))\n\n init_block_channels = 64\n channels_per_layers = [256, 512, 1024, 2048]\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n net = seresnext(\n channels=channels,\n init_block_channels=init_block_channels,\n cardinality=cardinality,\n bottleneck_width=bottleneck_width,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef seresnext50_32x4d(**kwargs):\n \"\"\"\n SE-ResNeXt-50 (32x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnext(blocks=50, cardinality=32, bottleneck_width=4, model_name=\"seresnext50_32x4d\", **kwargs)\n\n\ndef seresnext101_32x4d(**kwargs):\n \"\"\"\n SE-ResNeXt-101 (32x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name=\"seresnext101_32x4d\", **kwargs)\n\n\ndef seresnext101_64x4d(**kwargs):\n \"\"\"\n SE-ResNeXt-101 (64x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_seresnext(blocks=101, cardinality=64, bottleneck_width=4, model_name=\"seresnext101_64x4d\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import keras\n\n pretrained = False\n\n models = [\n seresnext50_32x4d,\n seresnext101_32x4d,\n seresnext101_64x4d,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n # net.summary()\n weight_count = keras.utils.layer_utils.count_params(net.trainable_weights)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != seresnext50_32x4d or weight_count == 27559896)\n assert (model != seresnext101_32x4d or weight_count == 48955416)\n assert (model != seresnext101_64x4d or weight_count == 88232984)\n\n if is_channels_first():\n x = np.zeros((1, 3, 224, 224), np.float32)\n else:\n x = np.zeros((1, 224, 224, 3), np.float32)\n y = net.predict(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n Script for evaluating trained image matching model on MXNet/Gluon (under development).\n\"\"\"\n\nimport os\nimport time\nimport logging\nimport argparse\nimport numpy as np\nimport mxnet as mx\nfrom mxnet.gluon.utils import split_and_load\nfrom common.logger_utils import initialize_logging\nfrom gluon.utils import prepare_mx_context, prepare_model\nfrom gluon.dataset_utils import get_dataset_metainfo\nfrom gluon.dataset_utils import get_val_data_source\n\n\ndef add_eval_parser_arguments(parser):\n \"\"\"\n Create python script parameters (for eval specific subpart).\n\n Parameters:\n ----------\n parser : ArgumentParser\n ArgumentParser instance.\n \"\"\"\n parser.add_argument(\n \"--model\",\n type=str,\n required=True,\n help=\"type of model to use. see model_provider for options\")\n parser.add_argument(\n \"--use-pretrained\",\n action=\"store_true\",\n help=\"enable using pretrained model from github repo\")\n parser.add_argument(\n \"--dtype\",\n type=str,\n default=\"float32\",\n help=\"base data type for tensors\")\n parser.add_argument(\n \"--resume\",\n type=str,\n default=\"\",\n help=\"resume from previously saved parameters\")\n parser.add_argument(\n \"--calc-flops\",\n dest=\"calc_flops\",\n action=\"store_true\",\n help=\"calculate FLOPs\")\n parser.add_argument(\n \"--calc-flops-only\",\n dest=\"calc_flops_only\",\n action=\"store_true\",\n help=\"calculate FLOPs without quality estimation\")\n parser.add_argument(\n \"--data-subset\",\n type=str,\n default=\"val\",\n help=\"data subset. options are val and test\")\n\n parser.add_argument(\n \"--num-gpus\",\n type=int,\n default=0,\n help=\"number of gpus to use\")\n parser.add_argument(\n \"-j\",\n \"--num-data-workers\",\n dest=\"num_workers\",\n default=4,\n type=int,\n help=\"number of preprocessing workers\")\n\n parser.add_argument(\n \"--batch-size\",\n type=int,\n default=512,\n help=\"training batch size per device (CPU/GPU)\")\n\n parser.add_argument(\n \"--save-dir\",\n type=str,\n default=\"\",\n help=\"directory of saved models and log-files\")\n parser.add_argument(\n \"--logging-file-name\",\n type=str,\n default=\"train.log\",\n help=\"filename of training log\")\n\n parser.add_argument(\n \"--log-packages\",\n type=str,\n default=\"mxnet, numpy\",\n help=\"list of python packages for logging\")\n parser.add_argument(\n \"--log-pip-packages\",\n type=str,\n default=\"mxnet-cu100\",\n help=\"list of pip packages for logging\")\n\n parser.add_argument(\n \"--disable-cudnn-autotune\",\n action=\"store_true\",\n help=\"disable cudnn autotune for segmentation models\")\n parser.add_argument(\n \"--show-progress\",\n action=\"store_true\",\n help=\"show progress bar\")\n\n\ndef parse_args():\n \"\"\"\n Parse python script parameters (common part).\n\n Returns\n -------\n ArgumentParser\n Resulted args.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Evaluate a model for image matching (Gluon/HPatches)\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n \"--dataset\",\n type=str,\n default=\"HPatches\",\n help=\"dataset name\")\n parser.add_argument(\n \"--work-dir\",\n type=str,\n default=os.path.join(\"..\", \"imgclsmob_data\"),\n help=\"path to working directory only for dataset root path preset\")\n\n args, _ = parser.parse_known_args()\n dataset_metainfo = get_dataset_metainfo(dataset_name=args.dataset)\n dataset_metainfo.add_dataset_parser_arguments(\n parser=parser,\n work_dir_path=args.work_dir)\n\n add_eval_parser_arguments(parser)\n\n args = parser.parse_args()\n return args\n\n\ndef warp_keypoints(keypoints, H):\n num_points = keypoints.shape[0]\n homogeneous_points = np.concatenate([keypoints, np.ones((num_points, 1))], axis=1)\n warped_points = np.dot(homogeneous_points, np.transpose(H)).squeeze(axis=2)\n return warped_points[:, :2] / warped_points[:, 2:]\n\n\ndef keep_true_keypoints(points, H, shape):\n warped_points = warp_keypoints(points[:, [1, 0]], H)\n warped_points[:, [0, 1]] = warped_points[:, [1, 0]]\n mask = (warped_points[:, 0] >= 0) & (warped_points[:, 0] < shape[0]) &\\\n (warped_points[:, 1] >= 0) & (warped_points[:, 1] < shape[1])\n return points[mask, :]\n\n\ndef filter_keypoints(points, shape):\n mask = (points[:, 0] >= 0) & (points[:, 0] < shape[0]) &\\\n (points[:, 1] >= 0) & (points[:, 1] < shape[1])\n return points[mask, :]\n\n\ndef select_k_best(conf_pts,\n max_count=300):\n sorted_pts = conf_pts[conf_pts[:, 2].argsort(), :2]\n start = min(max_count, conf_pts.shape[0])\n return sorted_pts[-start:, :]\n\n\ndef calc_repeatability_np(src_pts,\n src_confs,\n dst_conf_pts,\n homography,\n src_shape,\n dst_shape):\n distance_thresh = 3\n\n filtered_warped_keypoints = keep_true_keypoints(dst_conf_pts, np.linalg.inv(homography), src_shape)\n\n true_warped_keypoints = warp_keypoints(src_pts[:, [1, 0]], homography)\n true_warped_keypoints = np.stack([true_warped_keypoints[:, 1], true_warped_keypoints[:, 0], src_confs], axis=-1)\n true_warped_keypoints = filter_keypoints(true_warped_keypoints, dst_shape)\n\n filtered_warped_keypoints = select_k_best(filtered_warped_keypoints)\n true_warped_keypoints = select_k_best(true_warped_keypoints)\n\n n1 = true_warped_keypoints.shape[0]\n n2 = filtered_warped_keypoints.shape[0]\n true_warped_keypoints = np.expand_dims(true_warped_keypoints, 1)\n filtered_warped_keypoints = np.expand_dims(filtered_warped_keypoints, 0)\n norm = np.linalg.norm(true_warped_keypoints - filtered_warped_keypoints, ord=None, axis=2)\n count1 = 0\n count2 = 0\n if n2 != 0:\n min1 = np.min(norm, axis=1)\n count1 = np.sum(min1 <= distance_thresh)\n if n1 != 0:\n min2 = np.min(norm, axis=0)\n count2 = np.sum(min2 <= distance_thresh)\n if n1 + n2 > 0:\n repeatability = (count1 + count2) / (n1 + n2)\n else:\n repeatability = 0\n\n return n1, n2, repeatability\n\n\ndef batch_fn(batch, ctx):\n data_src = split_and_load(batch[0], ctx_list=ctx, batch_axis=0)\n data_dst = split_and_load(batch[1], ctx_list=ctx, batch_axis=0)\n label = split_and_load(batch[2], ctx_list=ctx, batch_axis=0)\n return data_src, data_dst, label\n\n\ndef calc_detector_repeatability(test_data,\n net,\n ctx):\n tic = time.time()\n repeatabilities = []\n n1s = []\n n2s = []\n for batch in test_data:\n data_src_list, data_dst_list, labels_list = batch_fn(batch, ctx)\n outputs_src_list = [net(X) for X in data_src_list]\n outputs_dst_list = [net(X) for X in data_dst_list]\n for i in range(len(data_src_list)):\n homography = labels_list[i].asnumpy()\n\n data_src_i = data_src_list[i]\n data_dst_i = data_dst_list[i]\n\n src_shape = data_src_i.shape[2:]\n dst_shape = data_dst_i.shape[2:]\n\n src_pts, src_confs, src_desc_map = outputs_src_list[i]\n dst_pts, dst_confs, dst_desc_map = outputs_dst_list[i]\n\n # src_conf_pts = mx.nd.concat(src_pts[0], src_confs[0].reshape(shape=(-1, 1)), dim=1).asnumpy()\n src_pts_np = src_pts[0].asnumpy()\n src_confs_np = src_confs[0].asnumpy()\n dst_conf_pts = mx.nd.concat(dst_pts[0], dst_confs[0].reshape(shape=(-1, 1)), dim=1).asnumpy()\n\n n1, n2, repeatability = calc_repeatability_np(\n src_pts_np,\n src_confs_np,\n dst_conf_pts,\n homography,\n src_shape,\n dst_shape)\n n1s.append(n1)\n n2s.append(n2)\n repeatabilities.append(repeatability)\n\n logging.info(\"Average number of points in the first image: {}\".format(np.mean(n1s)))\n logging.info(\"Average number of points in the second image: {}\".format(np.mean(n2s)))\n logging.info(\"The repeatability: {:.4f}\".format(np.mean(repeatabilities)))\n logging.info(\"Time cost: {:.4f} sec\".format(time.time() - tic))\n\n\ndef main():\n \"\"\"\n Main body of script.\n \"\"\"\n args = parse_args()\n\n os.environ[\"MXNET_CUDNN_AUTOTUNE_DEFAULT\"] = \"0\"\n assert (args.batch_size == 1)\n\n _, log_file_exist = initialize_logging(\n logging_dir_path=args.save_dir,\n logging_file_name=args.logging_file_name,\n script_args=args,\n log_packages=args.log_packages,\n log_pip_packages=args.log_pip_packages)\n\n ds_metainfo = get_dataset_metainfo(dataset_name=args.dataset)\n ds_metainfo.update(args=args)\n\n ctx, batch_size = prepare_mx_context(\n num_gpus=args.num_gpus,\n batch_size=args.batch_size)\n\n net = prepare_model(\n model_name=args.model,\n use_pretrained=args.use_pretrained,\n pretrained_model_file_path=args.resume.strip(),\n dtype=args.dtype,\n net_extra_kwargs=ds_metainfo.test_net_extra_kwargs,\n load_ignore_extra=False,\n classes=args.num_classes,\n in_channels=args.in_channels,\n do_hybridize=False,\n ctx=ctx)\n\n test_data = get_val_data_source(\n ds_metainfo=ds_metainfo,\n batch_size=args.batch_size,\n num_workers=args.num_workers)\n\n calc_detector_repeatability(\n test_data=test_data,\n net=net,\n ctx=ctx)\n\n\nif __name__ == \"__main__\":\n main()\n",
"\"\"\"\n DARTS for ImageNet-1K, implemented in Gluon.\n Original paper: 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.\n\"\"\"\n\n__all__ = ['DARTS', 'darts']\n\nimport os\nfrom mxnet import cpu\nfrom mxnet.gluon import nn, HybridBlock\nfrom mxnet.gluon.contrib.nn import Identity\nfrom .common import conv1x1\nfrom .nasnet import nasnet_dual_path_sequential\n\n\nclass DwsConv(HybridBlock):\n \"\"\"\n Standard dilated depthwise separable convolution block with.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int\n Dilation value for convolution layer.\n use_bias : bool, default False\n Whether the layers use a bias vector.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n dilation,\n use_bias=False,\n **kwargs):\n super(DwsConv, self).__init__(**kwargs)\n with self.name_scope():\n self.dw_conv = nn.Conv2D(\n channels=in_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation=dilation,\n groups=in_channels,\n use_bias=use_bias,\n in_channels=in_channels)\n self.pw_conv = conv1x1(\n in_channels=in_channels,\n out_channels=out_channels,\n use_bias=use_bias)\n\n def hybrid_forward(self, F, x):\n x = self.dw_conv(x)\n x = self.pw_conv(x)\n return x\n\n\nclass DartsConv(HybridBlock):\n \"\"\"\n DARTS specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n activate=True,\n **kwargs):\n super(DartsConv, self).__init__(**kwargs)\n self.activate = activate\n\n with self.name_scope():\n if self.activate:\n self.activ = nn.Activation(\"relu\")\n self.conv = nn.Conv2D(\n channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n use_bias=False,\n in_channels=in_channels)\n self.bn = nn.BatchNorm(in_channels=out_channels)\n\n def hybrid_forward(self, F, x):\n if self.activate:\n x = self.activ(x)\n x = self.conv(x)\n x = self.bn(x)\n return x\n\n\ndef darts_conv1x1(in_channels,\n out_channels,\n activate=True):\n \"\"\"\n 1x1 version of the DARTS specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n return DartsConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n strides=1,\n padding=0,\n activate=activate)\n\n\ndef darts_conv3x3_s2(in_channels,\n out_channels,\n activate=True):\n \"\"\"\n 3x3 version of the DARTS specific convolution block with stride 2.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n return DartsConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n strides=2,\n padding=1,\n activate=activate)\n\n\nclass DartsDwsConv(HybridBlock):\n \"\"\"\n DARTS specific dilated convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int\n Dilation value for convolution layer.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n dilation,\n **kwargs):\n super(DartsDwsConv, self).__init__(**kwargs)\n with self.name_scope():\n self.activ = nn.Activation(\"relu\")\n self.conv = DwsConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation=dilation,\n use_bias=False)\n self.bn = nn.BatchNorm(in_channels=out_channels)\n\n def hybrid_forward(self, F, x):\n x = self.activ(x)\n x = self.conv(x)\n x = self.bn(x)\n return x\n\n\nclass DartsDwsBranch(HybridBlock):\n \"\"\"\n DARTS specific block with depthwise separable convolution layers.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n **kwargs):\n super(DartsDwsBranch, self).__init__(**kwargs)\n mid_channels = in_channels\n\n with self.name_scope():\n self.conv1 = DartsDwsConv(\n in_channels=in_channels,\n out_channels=mid_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation=1)\n self.conv2 = DartsDwsConv(\n in_channels=mid_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=1,\n padding=padding,\n dilation=1)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n\nclass DartsReduceBranch(HybridBlock):\n \"\"\"\n DARTS specific factorized reduce block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int, default 2\n Strides of the convolution.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides=2,\n **kwargs):\n super(DartsReduceBranch, self).__init__(**kwargs)\n assert (out_channels % 2 == 0)\n mid_channels = out_channels // 2\n\n with self.name_scope():\n self.activ = nn.Activation(\"relu\")\n self.conv1 = conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n strides=strides)\n self.conv2 = conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n strides=strides)\n self.bn = nn.BatchNorm(in_channels=out_channels)\n\n def hybrid_forward(self, F, x):\n x = self.activ(x)\n x1 = self.conv1(x)\n x = F.slice(x, begin=(None, None, 1, 1), end=(None, None, None, None))\n x2 = self.conv2(x)\n x = F.concat(x1, x2, dim=1)\n x = self.bn(x)\n return x\n\n\nclass Stem1Unit(HybridBlock):\n \"\"\"\n DARTS Stem1 unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n **kwargs):\n super(Stem1Unit, self).__init__(**kwargs)\n mid_channels = out_channels // 2\n\n with self.name_scope():\n self.conv1 = darts_conv3x3_s2(\n in_channels=in_channels,\n out_channels=mid_channels,\n activate=False)\n self.conv2 = darts_conv3x3_s2(\n in_channels=mid_channels,\n out_channels=out_channels,\n activate=True)\n\n def hybrid_forward(self, F, x):\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n\ndef stem2_unit(in_channels,\n out_channels):\n \"\"\"\n DARTS Stem2 unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n \"\"\"\n return darts_conv3x3_s2(\n in_channels=in_channels,\n out_channels=out_channels,\n activate=True)\n\n\ndef darts_maxpool3x3(channels,\n strides):\n \"\"\"\n DARTS specific 3x3 Max pooling layer.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels. Unused parameter.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n assert (channels > 0)\n return nn.MaxPool2D(\n pool_size=3,\n strides=strides,\n padding=1)\n\n\ndef darts_skip_connection(channels,\n strides):\n \"\"\"\n DARTS specific skip connection layer.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n assert (channels > 0)\n if strides == 1:\n return Identity()\n else:\n assert (strides == 2)\n return DartsReduceBranch(\n in_channels=channels,\n out_channels=channels,\n strides=strides)\n\n\ndef darts_dws_conv3x3(channels,\n strides):\n \"\"\"\n 3x3 version of DARTS specific dilated convolution block.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n return DartsDwsConv(\n in_channels=channels,\n out_channels=channels,\n kernel_size=3,\n strides=strides,\n padding=2,\n dilation=2)\n\n\ndef darts_dws_branch3x3(channels,\n strides):\n \"\"\"\n 3x3 version of DARTS specific dilated convolution branch.\n\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n return DartsDwsBranch(\n in_channels=channels,\n out_channels=channels,\n kernel_size=3,\n strides=strides,\n padding=1)\n\n\n# Set of operations in genotype.\nGENOTYPE_OPS = {\n 'max_pool_3x3': darts_maxpool3x3,\n 'skip_connect': darts_skip_connection,\n 'dil_conv_3x3': darts_dws_conv3x3,\n 'sep_conv_3x3': darts_dws_branch3x3,\n}\n\n\nclass DartsMainBlock(HybridBlock):\n \"\"\"\n DARTS main block, described by genotype.\n\n Parameters:\n ----------\n genotype : list of tuples (str, int)\n List of genotype elements (operations and linked indices).\n channels : int\n Number of input/output channels.\n reduction : bool\n Whether use reduction.\n \"\"\"\n def __init__(self,\n genotype,\n channels,\n reduction,\n **kwargs):\n super(DartsMainBlock, self).__init__(**kwargs)\n self.concat = [2, 3, 4, 5]\n op_names, indices = zip(*genotype)\n self.indices = indices\n self.steps = len(op_names) // 2\n\n with self.name_scope():\n for i, (name, index) in enumerate(zip(op_names, indices)):\n stride = 2 if reduction and index < 2 else 1\n setattr(self, \"ops{}\".format(i + 1), GENOTYPE_OPS[name](channels, stride))\n\n def hybrid_forward(self, F, x, x_prev):\n s0 = x_prev\n s1 = x\n states = [s0, s1]\n for i in range(self.steps):\n j1 = 2 * i\n j2 = 2 * i + 1\n op1 = getattr(self, \"ops{}\".format(j1 + 1))\n op2 = getattr(self, \"ops{}\".format(j2 + 1))\n y1 = states[self.indices[j1]]\n y2 = states[self.indices[j2]]\n y1 = op1(y1)\n y2 = op2(y2)\n s = y1 + y2\n states += [s]\n x_out = F.concat(*[states[i] for i in self.concat], dim=1)\n return x_out\n\n\nclass DartsUnit(HybridBlock):\n \"\"\"\n DARTS unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n prev_in_channels : int\n Number of input channels in previous input.\n out_channels : int\n Number of output channels.\n genotype : list of tuples (str, int)\n List of genotype elements (operations and linked indices).\n reduction : bool\n Whether use reduction.\n \"\"\"\n def __init__(self,\n in_channels,\n prev_in_channels,\n out_channels,\n genotype,\n reduction,\n prev_reduction,\n **kwargs):\n super(DartsUnit, self).__init__(**kwargs)\n mid_channels = out_channels // 4\n\n with self.name_scope():\n if prev_reduction:\n self.preprocess_prev = DartsReduceBranch(\n in_channels=prev_in_channels,\n out_channels=mid_channels)\n else:\n self.preprocess_prev = darts_conv1x1(\n in_channels=prev_in_channels,\n out_channels=mid_channels)\n\n self.preprocess = darts_conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels)\n\n self.body = DartsMainBlock(\n genotype=genotype,\n channels=mid_channels,\n reduction=reduction)\n\n def hybrid_forward(self, F, x, x_prev):\n x = self.preprocess(x)\n x_prev = self.preprocess_prev(x_prev)\n x_out = self.body(x, x_prev)\n return x_out\n\n\nclass DARTS(HybridBlock):\n \"\"\"\n DARTS model from 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n stem_blocks_channels : int\n Number of output channels for the Stem units.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n stem_blocks_channels,\n normal_genotype,\n reduce_genotype,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n **kwargs):\n super(DARTS, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n\n with self.name_scope():\n self.features = nasnet_dual_path_sequential(\n return_two=False,\n first_ordinals=2,\n last_ordinals=1)\n self.features.add(Stem1Unit(\n in_channels=in_channels,\n out_channels=stem_blocks_channels))\n in_channels = stem_blocks_channels\n self.features.add(stem2_unit(\n in_channels=in_channels,\n out_channels=stem_blocks_channels))\n prev_in_channels = in_channels\n in_channels = stem_blocks_channels\n\n for i, channels_per_stage in enumerate(channels):\n stage = nasnet_dual_path_sequential(prefix=\"stage{}_\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n reduction = (i != 0) and (j == 0)\n prev_reduction = ((i == 0) and (j == 0)) or ((i != 0) and (j == 1))\n genotype = reduce_genotype if reduction else normal_genotype\n stage.add(DartsUnit(\n in_channels=in_channels,\n prev_in_channels=prev_in_channels,\n out_channels=out_channels,\n genotype=genotype,\n reduction=reduction,\n prev_reduction=prev_reduction))\n prev_in_channels = in_channels\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(nn.AvgPool2D(\n pool_size=7,\n strides=1))\n\n self.output = nn.HybridSequential(prefix=\"\")\n self.output.add(nn.Flatten())\n self.output.add(nn.Dense(\n units=classes,\n in_units=in_channels))\n\n def hybrid_forward(self, F, x):\n x = self.features(x)\n x = self.output(x)\n return x\n\n\ndef get_darts(model_name=None,\n pretrained=False,\n ctx=cpu(),\n root=os.path.join(\"~\", \".mxnet\", \"models\"),\n **kwargs):\n \"\"\"\n Create DARTS model with specific parameters.\n\n Parameters:\n ----------\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n stem_blocks_channels = 48\n layers = [4, 5, 5]\n channels_per_layers = [192, 384, 768]\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n normal_genotype = [\n ('sep_conv_3x3', 0),\n ('sep_conv_3x3', 1),\n ('sep_conv_3x3', 0),\n ('sep_conv_3x3', 1),\n ('sep_conv_3x3', 1),\n ('skip_connect', 0),\n ('skip_connect', 0),\n ('dil_conv_3x3', 2)]\n reduce_genotype = [\n ('max_pool_3x3', 0),\n ('max_pool_3x3', 1),\n ('skip_connect', 2),\n ('max_pool_3x3', 1),\n ('max_pool_3x3', 0),\n ('skip_connect', 2),\n ('skip_connect', 2),\n ('max_pool_3x3', 1)]\n\n net = DARTS(\n channels=channels,\n stem_blocks_channels=stem_blocks_channels,\n normal_genotype=normal_genotype,\n reduce_genotype=reduce_genotype,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n net.load_parameters(\n filename=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n ctx=ctx)\n\n return net\n\n\ndef darts(**kwargs):\n \"\"\"\n DARTS model from 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\n root : str, default '~/.mxnet/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_darts(model_name=\"darts\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import mxnet as mx\n\n pretrained = False\n\n models = [\n darts,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n ctx = mx.cpu()\n if not pretrained:\n net.initialize(ctx=ctx)\n\n net_params = net.collect_params()\n weight_count = 0\n for param in net_params.values():\n if (param.shape is None) or (not param._differentiable):\n continue\n weight_count += np.prod(param.shape)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != darts or weight_count == 4718752)\n\n x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)\n y = net(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n DRN for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\"\"\"\n\n__all__ = ['DRN', 'drnc26', 'drnc42', 'drnc58', 'drnd22', 'drnd38', 'drnd54', 'drnd105']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import Conv2d, BatchNorm, flatten, is_channels_first\n\n\nclass DRNConv(nn.Layer):\n \"\"\"\n DRN specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int\n Dilation value for convolution layer.\n activate : bool\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n strides,\n padding,\n dilation,\n activate,\n data_format=\"channels_last\",\n **kwargs):\n super(DRNConv, self).__init__(**kwargs)\n self.activate = activate\n\n self.conv = Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n dilation=dilation,\n use_bias=False,\n data_format=data_format,\n name=\"conv\")\n self.bn = BatchNorm(\n data_format=data_format,\n name=\"bn\")\n if self.activate:\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n x = self.conv(x)\n x = self.bn(x, training=training)\n if self.activate:\n x = self.activ(x)\n return x\n\n\ndef drn_conv1x1(in_channels,\n out_channels,\n strides,\n activate,\n data_format=\"channels_last\",\n **kwargs):\n \"\"\"\n 1x1 version of the DRN specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n activate : bool\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n return DRNConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n strides=strides,\n padding=0,\n dilation=1,\n activate=activate,\n data_format=data_format,\n **kwargs)\n\n\ndef drn_conv3x3(in_channels,\n out_channels,\n strides,\n dilation,\n activate,\n data_format=\"channels_last\",\n **kwargs):\n \"\"\"\n 3x3 version of the DRN specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n dilation : int or tuple/list of 2 int\n Padding/dilation value for convolution layer.\n activate : bool\n Whether activate the convolution block.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n return DRNConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n strides=strides,\n padding=dilation,\n dilation=dilation,\n activate=activate,\n data_format=data_format,\n **kwargs)\n\n\nclass DRNBlock(nn.Layer):\n \"\"\"\n Simple DRN block for residual path in DRN unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n dilation : int or tuple/list of 2 int\n Padding/dilation value for convolution layers.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n dilation,\n data_format=\"channels_last\",\n **kwargs):\n super(DRNBlock, self).__init__(**kwargs)\n self.conv1 = drn_conv3x3(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=stride,\n dilation=dilation,\n activate=True,\n data_format=data_format,\n name=\"conv1\")\n self.conv2 = drn_conv3x3(\n in_channels=out_channels,\n out_channels=out_channels,\n strides=1,\n dilation=dilation,\n activate=False,\n data_format=data_format,\n name=\"conv2\")\n\n def call(self, x, training=None):\n x = self.conv1(x, training=training)\n x = self.conv2(x, training=training)\n return x\n\n\nclass DRNBottleneck(nn.Layer):\n \"\"\"\n DRN bottleneck block for residual path in DRN unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n dilation : int or tuple/list of 2 int\n Padding/dilation value for 3x3 convolution layer.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n dilation,\n data_format=\"channels_last\",\n **kwargs):\n super(DRNBottleneck, self).__init__(**kwargs)\n mid_channels = out_channels // 4\n\n self.conv1 = drn_conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n strides=1,\n activate=True,\n data_format=data_format,\n name=\"conv1\")\n self.conv2 = drn_conv3x3(\n in_channels=mid_channels,\n out_channels=mid_channels,\n strides=strides,\n dilation=dilation,\n activate=True,\n data_format=data_format,\n name=\"conv2\")\n self.conv3 = drn_conv1x1(\n in_channels=mid_channels,\n out_channels=out_channels,\n strides=1,\n activate=False,\n data_format=data_format,\n name=\"conv3\")\n\n def call(self, x, training=None):\n x = self.conv1(x, training=training)\n x = self.conv2(x, training=training)\n x = self.conv3(x, training=training)\n return x\n\n\nclass DRNUnit(nn.Layer):\n \"\"\"\n DRN unit with residual connection.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n dilation : int or tuple/list of 2 int\n Padding/dilation value for 3x3 convolution layers.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n simplified : bool\n Whether to use a simple or simplified block in units.\n residual : bool\n Whether do residual calculations.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n dilation,\n bottleneck,\n simplified,\n residual,\n data_format=\"channels_last\",\n **kwargs):\n super(DRNUnit, self).__init__(**kwargs)\n assert residual or (not bottleneck)\n assert (not (bottleneck and simplified))\n assert (not (residual and simplified))\n self.residual = residual\n self.resize_identity = ((in_channels != out_channels) or (strides != 1)) and self.residual and (not simplified)\n\n if bottleneck:\n self.body = DRNBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n dilation=dilation,\n data_format=data_format,\n name=\"body\")\n elif simplified:\n self.body = drn_conv3x3(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n dilation=dilation,\n activate=False,\n data_format=data_format,\n name=\"body\")\n else:\n self.body = DRNBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=strides,\n dilation=dilation,\n data_format=data_format,\n name=\"body\")\n if self.resize_identity:\n self.identity_conv = drn_conv1x1(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n activate=False,\n data_format=data_format,\n name=\"identity_conv\")\n self.activ = nn.ReLU()\n\n def call(self, x, training=None):\n if self.resize_identity:\n identity = self.identity_conv(x, training=training)\n else:\n identity = x\n x = self.body(x, training=training)\n if self.residual:\n x = x + identity\n x = self.activ(x)\n return x\n\n\ndef drn_init_block(in_channels,\n out_channels,\n data_format=\"channels_last\",\n **kwargs):\n \"\"\"\n DRN specific initial block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n return DRNConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=7,\n strides=1,\n padding=3,\n dilation=1,\n activate=True,\n data_format=data_format,\n **kwargs)\n\n\nclass DRN(tf.keras.Model):\n \"\"\"\n DRN-C&D model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n dilations : list of list of int\n Dilation values for 3x3 convolution layers for each unit.\n bottlenecks : list of list of int\n Whether to use a bottleneck or simple block in each unit.\n simplifieds : list of list of int\n Whether to use a simple or simplified block in each unit.\n residuals : list of list of int\n Whether to use residual block in each unit.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n dilations,\n bottlenecks,\n simplifieds,\n residuals,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(DRN, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = tf.keras.Sequential(name=\"features\")\n self.features.add(drn_init_block(\n in_channels=in_channels,\n out_channels=init_block_channels,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = tf.keras.Sequential(name=\"stage{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n strides = 2 if (j == 0) and (i != 0) else 1\n stage.add(DRNUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n dilation=dilations[i][j],\n bottleneck=(bottlenecks[i][j] == 1),\n simplified=(simplifieds[i][j] == 1),\n residual=(residuals[i][j] == 1),\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(nn.AveragePooling2D(\n pool_size=28,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = Conv2d(\n in_channels=in_channels,\n out_channels=classes,\n kernel_size=1,\n data_format=data_format,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = self.output1(x)\n x = flatten(x, self.data_format)\n return x\n\n\ndef get_drn(blocks,\n simplified=False,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create DRN-C or DRN-D model with specific parameters.\n\n Parameters:\n ----------\n blocks : int\n Number of blocks.\n simplified : bool, default False\n Whether to use simplified scheme (D architecture).\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if blocks == 22:\n assert simplified\n layers = [1, 1, 2, 2, 2, 2, 1, 1]\n elif blocks == 26:\n layers = [1, 1, 2, 2, 2, 2, 1, 1]\n elif blocks == 38:\n assert simplified\n layers = [1, 1, 3, 4, 6, 3, 1, 1]\n elif blocks == 42:\n layers = [1, 1, 3, 4, 6, 3, 1, 1]\n elif blocks == 54:\n assert simplified\n layers = [1, 1, 3, 4, 6, 3, 1, 1]\n elif blocks == 58:\n layers = [1, 1, 3, 4, 6, 3, 1, 1]\n elif blocks == 105:\n assert simplified\n layers = [1, 1, 3, 4, 23, 3, 1, 1]\n else:\n raise ValueError(\"Unsupported DRN with number of blocks: {}\".format(blocks))\n\n if blocks < 50:\n channels_per_layers = [16, 32, 64, 128, 256, 512, 512, 512]\n bottlenecks_per_layers = [0, 0, 0, 0, 0, 0, 0, 0]\n else:\n channels_per_layers = [16, 32, 256, 512, 1024, 2048, 512, 512]\n bottlenecks_per_layers = [0, 0, 1, 1, 1, 1, 0, 0]\n\n if simplified:\n simplifieds_per_layers = [1, 1, 0, 0, 0, 0, 1, 1]\n residuals_per_layers = [0, 0, 1, 1, 1, 1, 0, 0]\n else:\n simplifieds_per_layers = [0, 0, 0, 0, 0, 0, 0, 0]\n residuals_per_layers = [1, 1, 1, 1, 1, 1, 0, 0]\n\n dilations_per_layers = [1, 1, 1, 1, 2, 4, 2, 1]\n downsample = [0, 1, 1, 1, 0, 0, 0, 0]\n\n def expand(property_per_layers):\n from functools import reduce\n return reduce(\n lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],\n zip(property_per_layers, layers, downsample),\n [[]])\n\n channels = expand(channels_per_layers)\n dilations = expand(dilations_per_layers)\n bottlenecks = expand(bottlenecks_per_layers)\n residuals = expand(residuals_per_layers)\n simplifieds = expand(simplifieds_per_layers)\n\n init_block_channels = channels_per_layers[0]\n\n net = DRN(\n channels=channels,\n init_block_channels=init_block_channels,\n dilations=dilations,\n bottlenecks=bottlenecks,\n simplifieds=simplifieds,\n residuals=residuals,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef drnc26(**kwargs):\n \"\"\"\n DRN-C-26 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_drn(blocks=26, model_name=\"drnc26\", **kwargs)\n\n\ndef drnc42(**kwargs):\n \"\"\"\n DRN-C-42 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_drn(blocks=42, model_name=\"drnc42\", **kwargs)\n\n\ndef drnc58(**kwargs):\n \"\"\"\n DRN-C-58 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_drn(blocks=58, model_name=\"drnc58\", **kwargs)\n\n\ndef drnd22(**kwargs):\n \"\"\"\n DRN-D-58 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_drn(blocks=22, simplified=True, model_name=\"drnd22\", **kwargs)\n\n\ndef drnd38(**kwargs):\n \"\"\"\n DRN-D-38 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_drn(blocks=38, simplified=True, model_name=\"drnd38\", **kwargs)\n\n\ndef drnd54(**kwargs):\n \"\"\"\n DRN-D-54 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_drn(blocks=54, simplified=True, model_name=\"drnd54\", **kwargs)\n\n\ndef drnd105(**kwargs):\n \"\"\"\n DRN-D-105 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_drn(blocks=105, simplified=True, model_name=\"drnd105\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n drnc26,\n drnc42,\n drnc58,\n drnd22,\n drnd38,\n drnd54,\n drnd105,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch_saze = 14\n x = tf.random.normal((batch_saze, 3, 224, 224) if is_channels_first(data_format) else (batch_saze, 224, 224, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch_saze, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != drnc26 or weight_count == 21126584)\n assert (model != drnc42 or weight_count == 31234744)\n assert (model != drnc58 or weight_count == 40542008) # 41591608\n assert (model != drnd22 or weight_count == 16393752)\n assert (model != drnd38 or weight_count == 26501912)\n assert (model != drnd54 or weight_count == 35809176)\n assert (model != drnd105 or weight_count == 54801304)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n GhostNet for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907.\n\"\"\"\n\n__all__ = ['GhostNet', 'ghostnet']\n\nimport os\nimport math\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import round_channels, conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block,\\\n dwsconv3x3_block, SEBlock, get_channel_axis, flatten, is_channels_first\n\n\nclass GhostHSigmoid(nn.Layer):\n \"\"\"\n Approximated sigmoid function, specific for GhostNet.\n \"\"\"\n def __init__(self, **kwargs):\n super(GhostHSigmoid, self).__init__(**kwargs)\n\n def call(self, x, training=None):\n return tf.clip_by_value(x, 0.0, 1.0)\n\n\nclass GhostConvBlock(nn.Layer):\n \"\"\"\n GhostNet specific convolution block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n activation : function or str or None, default 'relu'\n Activation function or name of activation function.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n activation=\"relu\",\n data_format=\"channels_last\",\n **kwargs):\n super(GhostConvBlock, self).__init__(**kwargs)\n self.data_format = data_format\n main_out_channels = math.ceil(0.5 * out_channels)\n cheap_out_channels = out_channels - main_out_channels\n\n self.main_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=main_out_channels,\n activation=activation,\n data_format=data_format,\n name=\"main_conv\")\n self.cheap_conv = dwconv3x3_block(\n in_channels=main_out_channels,\n out_channels=cheap_out_channels,\n activation=activation,\n data_format=data_format,\n name=\"cheap_conv\")\n\n def call(self, x, training=None):\n x = self.main_conv(x, training=training)\n y = self.cheap_conv(x, training=training)\n return tf.concat([x, y], axis=get_channel_axis(self.data_format))\n\n\nclass GhostExpBlock(nn.Layer):\n \"\"\"\n GhostNet expansion block for residual path in GhostNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n use_kernel3 : bool\n Whether to use 3x3 (instead of 5x5) kernel.\n exp_factor : float\n Expansion factor.\n use_se : bool\n Whether to use SE-module.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n use_kernel3,\n exp_factor,\n use_se,\n data_format=\"channels_last\",\n **kwargs):\n super(GhostExpBlock, self).__init__(**kwargs)\n self.use_dw_conv = (strides != 1)\n self.use_se = use_se\n mid_channels = int(math.ceil(exp_factor * in_channels))\n\n self.exp_conv = GhostConvBlock(\n in_channels=in_channels,\n out_channels=mid_channels,\n name=\"exp_conv\")\n if self.use_dw_conv:\n dw_conv_class = dwconv3x3_block if use_kernel3 else dwconv5x5_block\n self.dw_conv = dw_conv_class(\n in_channels=mid_channels,\n out_channels=mid_channels,\n strides=strides,\n activation=None,\n data_format=data_format,\n name=\"dw_conv\")\n if self.use_se:\n self.se = SEBlock(\n channels=mid_channels,\n reduction=4,\n out_activation=GhostHSigmoid(),\n data_format=data_format,\n name=\"se\")\n self.pw_conv = GhostConvBlock(\n in_channels=mid_channels,\n out_channels=out_channels,\n activation=None,\n data_format=data_format,\n name=\"pw_conv\")\n\n def call(self, x, training=None):\n x = self.exp_conv(x, training=training)\n if self.use_dw_conv:\n x = self.dw_conv(x, training=training)\n if self.use_se:\n x = self.se(x)\n x = self.pw_conv(x, training=training)\n return x\n\n\nclass GhostUnit(nn.Layer):\n \"\"\"\n GhostNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n strides : int or tuple/list of 2 int\n Strides of the second convolution layer.\n use_kernel3 : bool\n Whether to use 3x3 (instead of 5x5) kernel.\n exp_factor : float\n Expansion factor.\n use_se : bool\n Whether to use SE-module.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n strides,\n use_kernel3,\n exp_factor,\n use_se,\n data_format=\"channels_last\",\n **kwargs):\n super(GhostUnit, self).__init__(**kwargs)\n self.resize_identity = (in_channels != out_channels) or (strides != 1)\n\n self.body = GhostExpBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n use_kernel3=use_kernel3,\n exp_factor=exp_factor,\n use_se=use_se,\n data_format=data_format,\n name=\"body\")\n if self.resize_identity:\n self.identity_conv = dwsconv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n pw_activation=None,\n data_format=data_format,\n name=\"identity_conv\")\n\n def call(self, x, training=None):\n if self.resize_identity:\n identity = self.identity_conv(x, training=training)\n else:\n identity = x\n x = self.body(x, training=training)\n x = x + identity\n return x\n\n\nclass GhostClassifier(nn.Layer):\n \"\"\"\n GhostNet classifier.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n mid_channels : int\n Number of middle channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n mid_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(GhostClassifier, self).__init__(**kwargs)\n self.conv1 = conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=\"conv1\")\n self.conv2 = conv1x1(\n in_channels=mid_channels,\n out_channels=out_channels,\n use_bias=True,\n data_format=data_format,\n name=\"conv2\")\n\n def call(self, x, training=None):\n x = self.conv1(x, training=training)\n x = self.conv2(x)\n return x\n\n\nclass GhostNet(tf.keras.Model):\n \"\"\"\n GhostNet model from 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n final_block_channels : int\n Number of output channels for the final block of the feature extractor.\n classifier_mid_channels : int\n Number of middle channels for classifier.\n kernels3 : list of list of int/bool\n Using 3x3 (instead of 5x5) kernel for each unit.\n exp_factors : list of list of int\n Expansion factor for each unit.\n use_se : list of list of int/bool\n Using SE-block flag for each unit.\n first_stride : bool\n Whether to use stride for the first stage.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n final_block_channels,\n classifier_mid_channels,\n kernels3,\n exp_factors,\n use_se,\n first_stride,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(GhostNet, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = tf.keras.Sequential(name=\"features\")\n self.features.add(conv3x3_block(\n in_channels=in_channels,\n out_channels=init_block_channels,\n strides=2,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = tf.keras.Sequential(name=\"stage{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n strides = 2 if (j == 0) and ((i != 0) or first_stride) else 1\n use_kernel3 = kernels3[i][j] == 1\n exp_factor = exp_factors[i][j]\n use_se_flag = use_se[i][j] == 1\n stage.add(GhostUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n use_kernel3=use_kernel3,\n exp_factor=exp_factor,\n use_se=use_se_flag,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(conv1x1_block(\n in_channels=in_channels,\n out_channels=final_block_channels,\n data_format=data_format,\n name=\"final_block\"))\n in_channels = final_block_channels\n self.features.add(nn.AveragePooling2D(\n pool_size=7,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = GhostClassifier(\n in_channels=in_channels,\n out_channels=classes,\n mid_channels=classifier_mid_channels,\n data_format=data_format,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = self.output1(x, training=training)\n x = flatten(x, self.data_format)\n return x\n\n\ndef get_ghostnet(width_scale=1.0,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create GhostNet model with specific parameters.\n\n Parameters:\n ----------\n width_scale : float, default 1.0\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n init_block_channels = 16\n channels = [[16], [24, 24], [40, 40], [80, 80, 80, 80, 112, 112], [160, 160, 160, 160, 160]]\n kernels3 = [[1], [1, 1], [0, 0], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0]]\n exp_factors = [[1], [3, 3], [3, 3], [6, 2.5, 2.3, 2.3, 6, 6], [6, 6, 6, 6, 6]]\n use_se = [[0], [0, 0], [1, 1], [0, 0, 0, 0, 1, 1], [1, 0, 1, 0, 1]]\n final_block_channels = 960\n classifier_mid_channels = 1280\n first_stride = False\n\n if width_scale != 1.0:\n channels = [[round_channels(cij * width_scale, divisor=4) for cij in ci] for ci in channels]\n init_block_channels = round_channels(init_block_channels * width_scale, divisor=4)\n if width_scale > 1.0:\n final_block_channels = round_channels(final_block_channels * width_scale, divisor=4)\n\n net = GhostNet(\n channels=channels,\n init_block_channels=init_block_channels,\n final_block_channels=final_block_channels,\n classifier_mid_channels=classifier_mid_channels,\n kernels3=kernels3,\n exp_factors=exp_factors,\n use_se=use_se,\n first_stride=first_stride,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef ghostnet(**kwargs):\n \"\"\"\n GhostNet model from 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_ghostnet(model_name=\"ghostnet\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n ghostnet,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch_saze = 14\n x = tf.random.normal((batch_saze, 3, 224, 224) if is_channels_first(data_format) else (batch_saze, 224, 224, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch_saze, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != ghostnet or weight_count == 5180840)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n SparseNet for ImageNet-1K, implemented in PyTorch.\n Original paper: 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.\n\"\"\"\n\n__all__ = ['SparseNet', 'sparsenet121', 'sparsenet161', 'sparsenet169', 'sparsenet201', 'sparsenet264']\n\nimport os\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom .common import pre_conv1x1_block, pre_conv3x3_block\nfrom .preresnet import PreResInitBlock, PreResActivation\nfrom .densenet import TransitionBlock\n\n\ndef sparsenet_exponential_fetch(lst):\n \"\"\"\n SparseNet's specific exponential fetch.\n\n Parameters:\n ----------\n lst : list\n List of something.\n\n Returns\n -------\n list\n Filtered list.\n \"\"\"\n return [lst[len(lst) - 2**i] for i in range(1 + math.floor(math.log(len(lst), 2)))]\n\n\nclass SparseBlock(nn.Module):\n \"\"\"\n SparseNet block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n dropout_rate : float\n Parameter of Dropout layer. Faction of the input units to drop.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n dropout_rate):\n super(SparseBlock, self).__init__()\n self.use_dropout = (dropout_rate != 0.0)\n bn_size = 4\n mid_channels = out_channels * bn_size\n\n self.conv1 = pre_conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels)\n self.conv2 = pre_conv3x3_block(\n in_channels=mid_channels,\n out_channels=out_channels)\n if self.use_dropout:\n self.dropout = nn.Dropout(p=dropout_rate)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n if self.use_dropout:\n x = self.dropout(x)\n return x\n\n\nclass SparseStage(nn.Module):\n \"\"\"\n SparseNet stage.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n channels_per_stage : list of int\n Number of output channels for each unit in stage.\n growth_rate : int\n Growth rate for blocks.\n dropout_rate : float\n Parameter of Dropout layer. Faction of the input units to drop.\n do_transition : bool\n Whether use transition block.\n \"\"\"\n def __init__(self,\n in_channels,\n channels_per_stage,\n growth_rate,\n dropout_rate,\n do_transition):\n super(SparseStage, self).__init__()\n self.do_transition = do_transition\n\n if self.do_transition:\n self.trans = TransitionBlock(\n in_channels=in_channels,\n out_channels=(in_channels // 2))\n in_channels = in_channels // 2\n self.blocks = nn.Sequential()\n for i, out_channels in enumerate(channels_per_stage):\n self.blocks.add_module(\"block{}\".format(i + 1), SparseBlock(\n in_channels=in_channels,\n out_channels=growth_rate,\n dropout_rate=dropout_rate))\n in_channels = out_channels\n\n def forward(self, x):\n if self.do_transition:\n x = self.trans(x)\n outs = [x]\n for block in self.blocks._modules.values():\n y = block(x)\n outs.append(y)\n flt_outs = sparsenet_exponential_fetch(outs)\n x = torch.cat(tuple(flt_outs), dim=1)\n return x\n\n\nclass SparseNet(nn.Module):\n \"\"\"\n SparseNet model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n growth_rate : int\n Growth rate for blocks.\n dropout_rate : float, default 0.0\n Parameter of Dropout layer. Faction of the input units to drop.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n num_classes : int, default 1000\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n growth_rate,\n dropout_rate=0.0,\n in_channels=3,\n in_size=(224, 224),\n num_classes=1000):\n super(SparseNet, self).__init__()\n self.in_size = in_size\n self.num_classes = num_classes\n\n self.features = nn.Sequential()\n self.features.add_module(\"init_block\", PreResInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = SparseStage(\n in_channels=in_channels,\n channels_per_stage=channels_per_stage,\n growth_rate=growth_rate,\n dropout_rate=dropout_rate,\n do_transition=(i != 0))\n in_channels = channels_per_stage[-1]\n self.features.add_module(\"stage{}\".format(i + 1), stage)\n self.features.add_module(\"post_activ\", PreResActivation(in_channels=in_channels))\n self.features.add_module(\"final_pool\", nn.AvgPool2d(\n kernel_size=7,\n stride=1))\n\n self.output = nn.Linear(\n in_features=in_channels,\n out_features=num_classes)\n\n self._init_params()\n\n def _init_params(self):\n for name, module in self.named_modules():\n if isinstance(module, nn.Conv2d):\n init.kaiming_uniform_(module.weight)\n if module.bias is not None:\n init.constant_(module.bias, 0)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.output(x)\n return x\n\n\ndef get_sparsenet(num_layers,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".torch\", \"models\"),\n **kwargs):\n \"\"\"\n Create SparseNet model with specific parameters.\n\n Parameters:\n ----------\n num_layers : int\n Number of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if num_layers == 121:\n init_block_channels = 64\n growth_rate = 32\n layers = [6, 12, 24, 16]\n elif num_layers == 161:\n init_block_channels = 96\n growth_rate = 48\n layers = [6, 12, 36, 24]\n elif num_layers == 169:\n init_block_channels = 64\n growth_rate = 32\n layers = [6, 12, 32, 32]\n elif num_layers == 201:\n init_block_channels = 64\n growth_rate = 32\n layers = [6, 12, 48, 32]\n elif num_layers == 264:\n init_block_channels = 64\n growth_rate = 32\n layers = [6, 12, 64, 48]\n else:\n raise ValueError(\"Unsupported SparseNet version with number of layers {}\".format(num_layers))\n\n from functools import reduce\n channels = reduce(\n lambda xi, yi: xi + [reduce(\n lambda xj, yj: xj + [sum(sparsenet_exponential_fetch([xj[0]] + [yj[0]] * (yj[1] + 1)))],\n zip([growth_rate] * yi, range(yi)),\n [xi[-1][-1] // 2])[1:]],\n layers,\n [[init_block_channels * 2]])[1:]\n\n net = SparseNet(\n channels=channels,\n init_block_channels=init_block_channels,\n growth_rate=growth_rate,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef sparsenet121(**kwargs):\n \"\"\"\n SparseNet-121 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sparsenet(num_layers=121, model_name=\"sparsenet121\", **kwargs)\n\n\ndef sparsenet161(**kwargs):\n \"\"\"\n SparseNet-161 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sparsenet(num_layers=161, model_name=\"sparsenet161\", **kwargs)\n\n\ndef sparsenet169(**kwargs):\n \"\"\"\n SparseNet-169 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sparsenet(num_layers=169, model_name=\"sparsenet169\", **kwargs)\n\n\ndef sparsenet201(**kwargs):\n \"\"\"\n SparseNet-201 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sparsenet(num_layers=201, model_name=\"sparsenet201\", **kwargs)\n\n\ndef sparsenet264(**kwargs):\n \"\"\"\n SparseNet-264 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_sparsenet(num_layers=264, model_name=\"sparsenet264\", **kwargs)\n\n\ndef _calc_width(net):\n import numpy as np\n net_params = filter(lambda p: p.requires_grad, net.parameters())\n weight_count = 0\n for param in net_params:\n weight_count += np.prod(param.size())\n return weight_count\n\n\ndef _test():\n import torch\n\n pretrained = False\n\n models = [\n sparsenet121,\n sparsenet161,\n sparsenet169,\n sparsenet201,\n sparsenet264,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n # net.train()\n net.eval()\n weight_count = _calc_width(net)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != sparsenet121 or weight_count == 3250824)\n assert (model != sparsenet161 or weight_count == 9853288)\n assert (model != sparsenet169 or weight_count == 4709864)\n assert (model != sparsenet201 or weight_count == 5703144)\n assert (model != sparsenet264 or weight_count == 7717224)\n\n x = torch.randn(1, 3, 224, 224)\n y = net(x)\n y.sum().backward()\n assert (tuple(y.size()) == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n MENet for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,'\n https://arxiv.org/abs/1803.09127.\n\"\"\"\n\n__all__ = ['MENet', 'menet108_8x1_g3', 'menet128_8x1_g4', 'menet160_8x1_g8', 'menet228_12x1_g3', 'menet256_12x1_g4',\n 'menet348_12x1_g3', 'menet352_12x1_g8', 'menet456_24x1_g3']\n\nimport os\nimport tensorflow as tf\nfrom .common import conv2d, conv1x1, conv3x3, depthwise_conv3x3, batchnorm, channel_shuffle, maxpool2d, avgpool2d,\\\n is_channels_first, get_channel_axis, flatten\n\n\ndef me_unit(x,\n in_channels,\n out_channels,\n side_channels,\n groups,\n downsample,\n ignore_group,\n training,\n data_format,\n name=\"me_unit\"):\n \"\"\"\n MENet unit.\n\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n side_channels : int\n Number of side channels.\n groups : int\n Number of groups in convolution layers.\n downsample : bool\n Whether do downsample.\n ignore_group : bool\n Whether ignore group value in the first convolution layer.\n training : bool, or a TensorFlow boolean scalar tensor\n Whether to return the output in training mode or in inference mode.\n data_format : str\n The ordering of the dimensions in tensors.\n name : str, default 'me_unit'\n Unit name.\n\n Returns\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n mid_channels = out_channels // 4\n\n if downsample:\n out_channels -= in_channels\n\n identity = x\n\n # pointwise group convolution 1\n x = conv1x1(\n x=x,\n in_channels=in_channels,\n out_channels=mid_channels,\n groups=(1 if ignore_group else groups),\n data_format=data_format,\n name=name + \"/compress_conv1\")\n x = batchnorm(\n x=x,\n training=training,\n data_format=data_format,\n name=name + \"/compress_bn1\")\n x = tf.nn.relu(x, name=name + \"/compress_activ\")\n\n assert (mid_channels % groups == 0)\n x = channel_shuffle(\n x=x,\n groups=groups,\n data_format=data_format)\n\n # merging\n y = conv1x1(\n x=x,\n in_channels=mid_channels,\n out_channels=side_channels,\n data_format=data_format,\n name=name + \"/s_merge_conv/conv\")\n y = batchnorm(\n x=y,\n training=training,\n data_format=data_format,\n name=name + \"/s_merge_bn\")\n y = tf.nn.relu(y, name=name + \"/s_merge_activ\")\n\n # depthwise convolution (bottleneck)\n x = depthwise_conv3x3(\n x=x,\n channels=mid_channels,\n strides=(2 if downsample else 1),\n data_format=data_format,\n name=name + \"/dw_conv2\")\n x = batchnorm(\n x=x,\n training=training,\n data_format=data_format,\n name=name + \"/dw_bn2\")\n\n # evolution\n y = conv3x3(\n x=y,\n in_channels=side_channels,\n out_channels=side_channels,\n strides=(2 if downsample else 1),\n data_format=data_format,\n name=name + \"/s_conv\")\n y = batchnorm(\n x=y,\n training=training,\n data_format=data_format,\n name=name + \"/s_conv_bn\")\n y = tf.nn.relu(y, name=name + \"/s_conv_activ\")\n\n y = conv1x1(\n x=y,\n in_channels=side_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=name + \"/s_evolve_conv/conv\")\n y = batchnorm(\n x=y,\n training=training,\n data_format=data_format,\n name=name + \"/s_evolve_bn\")\n y = tf.nn.sigmoid(y, name=name + \"/s_evolve_activ\")\n\n x = x * y\n\n # pointwise group convolution 2\n x = conv1x1(\n x=x,\n in_channels=mid_channels,\n out_channels=out_channels,\n groups=groups,\n data_format=data_format,\n name=name + \"/expand_conv3\")\n x = batchnorm(\n x=x,\n training=training,\n data_format=data_format,\n name=name + \"/expand_bn3\")\n\n if downsample:\n identity = avgpool2d(\n x=identity,\n pool_size=3,\n strides=2,\n padding=1,\n data_format=data_format,\n name=name + \"/avgpool\")\n x = tf.concat([x, identity], axis=get_channel_axis(data_format), name=name + \"/concat\")\n else:\n x = x + identity\n\n x = tf.nn.relu(x, name=name + \"/final_activ\")\n return x\n\n\ndef me_init_block(x,\n in_channels,\n out_channels,\n training,\n data_format,\n name=\"me_init_block\"):\n \"\"\"\n MENet specific initial block.\n\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n training : bool, or a TensorFlow boolean scalar tensor\n Whether to return the output in training mode or in inference mode.\n data_format : str\n The ordering of the dimensions in tensors.\n name : str, default 'me_init_block'\n Block name.\n\n Returns\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n x = conv2d(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n strides=2,\n padding=1,\n use_bias=False,\n data_format=data_format,\n name=name + \"/conv\")\n x = batchnorm(\n x=x,\n training=training,\n data_format=data_format,\n name=name + \"/bn\")\n x = tf.nn.relu(x, name=name + \"/activ\")\n x = maxpool2d(\n x=x,\n pool_size=3,\n strides=2,\n padding=1,\n data_format=data_format,\n name=name + \"/pool\")\n return x\n\n\nclass MENet(object):\n \"\"\"\n MENet model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,'\n https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n side_channels : int\n Number of side channels in a ME-unit.\n groups : int\n Number of groups in convolution layers.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n side_channels,\n groups,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(MENet, self).__init__(**kwargs)\n assert (data_format in [\"channels_last\", \"channels_first\"])\n self.channels = channels\n self.init_block_channels = init_block_channels\n self.side_channels = side_channels\n self.groups = groups\n self.in_channels = in_channels\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n def __call__(self,\n x,\n training=False):\n \"\"\"\n Build a model graph.\n\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n training : bool, or a TensorFlow boolean scalar tensor, default False\n Whether to return the output in training mode or in inference mode.\n\n Returns\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n in_channels = self.in_channels\n x = me_init_block(\n x=x,\n in_channels=in_channels,\n out_channels=self.init_block_channels,\n training=training,\n data_format=self.data_format,\n name=\"features/init_block\")\n in_channels = self.init_block_channels\n for i, channels_per_stage in enumerate(self.channels):\n for j, out_channels in enumerate(channels_per_stage):\n downsample = (j == 0)\n ignore_group = (i == 0) and (j == 0)\n x = me_unit(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n side_channels=self.side_channels,\n groups=self.groups,\n downsample=downsample,\n ignore_group=ignore_group,\n training=training,\n data_format=self.data_format,\n name=\"features/stage{}/unit{}\".format(i + 1, j + 1))\n in_channels = out_channels\n x = tf.keras.layers.AveragePooling2D(\n pool_size=7,\n strides=1,\n data_format=self.data_format,\n name=\"features/final_pool\")(x)\n\n # x = tf.layers.flatten(x)\n x = flatten(\n x=x,\n data_format=self.data_format)\n x = tf.keras.layers.Dense(\n units=self.classes,\n name=\"output\")(x)\n\n return x\n\n\ndef get_menet(first_stage_channels,\n side_channels,\n groups,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create MENet model with specific parameters.\n\n Parameters:\n ----------\n first_stage_channels : int\n Number of output channels at the first stage.\n side_channels : int\n Number of side channels in a ME-unit.\n groups : int\n Number of groups in convolution layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n\n layers = [4, 8, 4]\n\n if first_stage_channels == 108:\n init_block_channels = 12\n channels_per_layers = [108, 216, 432]\n elif first_stage_channels == 128:\n init_block_channels = 12\n channels_per_layers = [128, 256, 512]\n elif first_stage_channels == 160:\n init_block_channels = 16\n channels_per_layers = [160, 320, 640]\n elif first_stage_channels == 228:\n init_block_channels = 24\n channels_per_layers = [228, 456, 912]\n elif first_stage_channels == 256:\n init_block_channels = 24\n channels_per_layers = [256, 512, 1024]\n elif first_stage_channels == 348:\n init_block_channels = 24\n channels_per_layers = [348, 696, 1392]\n elif first_stage_channels == 352:\n init_block_channels = 24\n channels_per_layers = [352, 704, 1408]\n elif first_stage_channels == 456:\n init_block_channels = 48\n channels_per_layers = [456, 912, 1824]\n else:\n raise ValueError(\"The {} of `first_stage_channels` is not supported\".format(first_stage_channels))\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n net = MENet(\n channels=channels,\n init_block_channels=init_block_channels,\n side_channels=side_channels,\n groups=groups,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_state_dict\n net.state_dict, net.file_path = download_state_dict(\n model_name=model_name,\n local_model_store_dir_path=root)\n else:\n net.state_dict = None\n net.file_path = None\n\n return net\n\n\ndef menet108_8x1_g3(**kwargs):\n \"\"\"\n 108-MENet-8x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=108, side_channels=8, groups=3, model_name=\"menet108_8x1_g3\", **kwargs)\n\n\ndef menet128_8x1_g4(**kwargs):\n \"\"\"\n 128-MENet-8x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=128, side_channels=8, groups=4, model_name=\"menet128_8x1_g4\", **kwargs)\n\n\ndef menet160_8x1_g8(**kwargs):\n \"\"\"\n 160-MENet-8x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=160, side_channels=8, groups=8, model_name=\"menet160_8x1_g8\", **kwargs)\n\n\ndef menet228_12x1_g3(**kwargs):\n \"\"\"\n 228-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=228, side_channels=12, groups=3, model_name=\"menet228_12x1_g3\", **kwargs)\n\n\ndef menet256_12x1_g4(**kwargs):\n \"\"\"\n 256-MENet-12x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=256, side_channels=12, groups=4, model_name=\"menet256_12x1_g4\", **kwargs)\n\n\ndef menet348_12x1_g3(**kwargs):\n \"\"\"\n 348-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=348, side_channels=12, groups=3, model_name=\"menet348_12x1_g3\", **kwargs)\n\n\ndef menet352_12x1_g8(**kwargs):\n \"\"\"\n 352-MENet-12x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=352, side_channels=12, groups=8, model_name=\"menet352_12x1_g8\", **kwargs)\n\n\ndef menet456_24x1_g3(**kwargs):\n \"\"\"\n 456-MENet-24x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile\n Applications,' https://arxiv.org/abs/1803.09127.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n\n Returns\n -------\n functor\n Functor for model graph creation with extra fields.\n \"\"\"\n return get_menet(first_stage_channels=456, side_channels=24, groups=3, model_name=\"menet456_24x1_g3\", **kwargs)\n\n\ndef _test():\n import numpy as np\n\n data_format = \"channels_last\"\n pretrained = False\n\n models = [\n menet108_8x1_g3,\n menet128_8x1_g4,\n menet160_8x1_g8,\n menet228_12x1_g3,\n menet256_12x1_g4,\n menet348_12x1_g3,\n menet352_12x1_g8,\n menet456_24x1_g3,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n x = tf.placeholder(\n dtype=tf.float32,\n shape=(None, 3, 224, 224) if is_channels_first(data_format) else (None, 224, 224, 3),\n name=\"xx\")\n y_net = net(x)\n\n weight_count = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != menet108_8x1_g3 or weight_count == 654516)\n assert (model != menet128_8x1_g4 or weight_count == 750796)\n assert (model != menet160_8x1_g8 or weight_count == 850120)\n assert (model != menet228_12x1_g3 or weight_count == 1806568)\n assert (model != menet256_12x1_g4 or weight_count == 1888240)\n assert (model != menet348_12x1_g3 or weight_count == 3368128)\n assert (model != menet352_12x1_g8 or weight_count == 2272872)\n assert (model != menet456_24x1_g3 or weight_count == 5304784)\n\n with tf.Session() as sess:\n if pretrained:\n from .model_store import init_variables_from_state_dict\n init_variables_from_state_dict(sess=sess, state_dict=net.state_dict)\n else:\n sess.run(tf.global_variables_initializer())\n x_value = np.zeros((1, 3, 224, 224) if is_channels_first(data_format) else (1, 224, 224, 3), np.float32)\n y = sess.run(y_net, feed_dict={x: x_value})\n assert (y.shape == (1, 1000))\n tf.reset_default_graph()\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n ResNeXt for CIFAR/SVHN, implemented in TensorFlow.\n Original paper: 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.\n\"\"\"\n\n__all__ = ['CIFARResNeXt', 'resnext20_1x64d_cifar10', 'resnext20_1x64d_cifar100', 'resnext20_1x64d_svhn',\n 'resnext20_2x32d_cifar10', 'resnext20_2x32d_cifar100', 'resnext20_2x32d_svhn',\n 'resnext20_2x64d_cifar10', 'resnext20_2x64d_cifar100', 'resnext20_2x64d_svhn',\n 'resnext20_4x16d_cifar10', 'resnext20_4x16d_cifar100', 'resnext20_4x16d_svhn',\n 'resnext20_4x32d_cifar10', 'resnext20_4x32d_cifar100', 'resnext20_4x32d_svhn',\n 'resnext20_8x8d_cifar10', 'resnext20_8x8d_cifar100', 'resnext20_8x8d_svhn',\n 'resnext20_8x16d_cifar10', 'resnext20_8x16d_cifar100', 'resnext20_8x16d_svhn',\n 'resnext20_16x4d_cifar10', 'resnext20_16x4d_cifar100', 'resnext20_16x4d_svhn',\n 'resnext20_16x8d_cifar10', 'resnext20_16x8d_cifar100', 'resnext20_16x8d_svhn',\n 'resnext20_32x2d_cifar10', 'resnext20_32x2d_cifar100', 'resnext20_32x2d_svhn',\n 'resnext20_32x4d_cifar10', 'resnext20_32x4d_cifar100', 'resnext20_32x4d_svhn',\n 'resnext20_64x1d_cifar10', 'resnext20_64x1d_cifar100', 'resnext20_64x1d_svhn',\n 'resnext20_64x2d_cifar10', 'resnext20_64x2d_cifar100', 'resnext20_64x2d_svhn',\n 'resnext29_32x4d_cifar10', 'resnext29_32x4d_cifar100', 'resnext29_32x4d_svhn',\n 'resnext29_16x64d_cifar10', 'resnext29_16x64d_cifar100', 'resnext29_16x64d_svhn',\n 'resnext56_1x64d_cifar10', 'resnext56_1x64d_cifar100', 'resnext56_1x64d_svhn',\n 'resnext56_2x32d_cifar10', 'resnext56_2x32d_cifar100', 'resnext56_2x32d_svhn',\n 'resnext56_4x16d_cifar10', 'resnext56_4x16d_cifar100', 'resnext56_4x16d_svhn',\n 'resnext56_8x8d_cifar10', 'resnext56_8x8d_cifar100', 'resnext56_8x8d_svhn',\n 'resnext56_16x4d_cifar10', 'resnext56_16x4d_cifar100', 'resnext56_16x4d_svhn',\n 'resnext56_32x2d_cifar10', 'resnext56_32x2d_cifar100', 'resnext56_32x2d_svhn',\n 'resnext56_64x1d_cifar10', 'resnext56_64x1d_cifar100', 'resnext56_64x1d_svhn',\n 'resnext272_1x64d_cifar10', 'resnext272_1x64d_cifar100', 'resnext272_1x64d_svhn',\n 'resnext272_2x32d_cifar10', 'resnext272_2x32d_cifar100', 'resnext272_2x32d_svhn']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import conv3x3_block, flatten, is_channels_first\nfrom .resnext import ResNeXtUnit\n\n\nclass CIFARResNeXt(tf.keras.Model):\n \"\"\"\n ResNeXt model for CIFAR from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n cardinality: int\n Number of groups.\n bottleneck_width: int\n Width of bottleneck block.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (32, 32)\n Spatial size of the expected input image.\n classes : int, default 10\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n cardinality,\n bottleneck_width,\n in_channels=3,\n in_size=(32, 32),\n classes=10,\n data_format=\"channels_last\",\n **kwargs):\n super(CIFARResNeXt, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = tf.keras.Sequential(name=\"features\")\n self.features.add(conv3x3_block(\n in_channels=in_channels,\n out_channels=init_block_channels,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = tf.keras.Sequential(name=\"stage{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n strides = 2 if (j == 0) and (i != 0) else 1\n stage.add(ResNeXtUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=strides,\n cardinality=cardinality,\n bottleneck_width=bottleneck_width,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(nn.AveragePooling2D(\n pool_size=8,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = flatten(x, self.data_format)\n x = self.output1(x)\n return x\n\n\ndef get_resnext_cifar(classes,\n blocks,\n cardinality,\n bottleneck_width,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n ResNeXt model for CIFAR with specific parameters.\n\n Parameters:\n ----------\n classes : int\n Number of classification classes.\n blocks : int\n Number of blocks.\n cardinality: int\n Number of groups.\n bottleneck_width: int\n Width of bottleneck block.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n assert (blocks - 2) % 9 == 0\n layers = [(blocks - 2) // 9] * 3\n channels_per_layers = [256, 512, 1024]\n init_block_channels = 64\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n net = CIFARResNeXt(\n channels=channels,\n init_block_channels=init_block_channels,\n cardinality=cardinality,\n bottleneck_width=bottleneck_width,\n classes=classes,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef resnext20_1x64d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (1x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=1, bottleneck_width=64,\n model_name=\"resnext20_1x64d_cifar10\", **kwargs)\n\n\ndef resnext20_1x64d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (1x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=1, bottleneck_width=64,\n model_name=\"resnext20_1x64d_cifar100\", **kwargs)\n\n\ndef resnext20_1x64d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (1x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=1, bottleneck_width=64,\n model_name=\"resnext20_1x64d_svhn\", **kwargs)\n\n\ndef resnext20_2x32d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (2x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=32,\n model_name=\"resnext20_2x32d_cifar10\", **kwargs)\n\n\ndef resnext20_2x32d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (2x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=32,\n model_name=\"resnext20_2x32d_cifar100\", **kwargs)\n\n\ndef resnext20_2x32d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (2x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=32,\n model_name=\"resnext20_2x32d_svhn\", **kwargs)\n\n\ndef resnext20_2x64d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (2x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64,\n model_name=\"resnext20_2x64d_cifar10\", **kwargs)\n\n\ndef resnext20_2x64d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (2x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64,\n model_name=\"resnext20_2x64d_cifar100\", **kwargs)\n\n\ndef resnext20_2x64d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (2x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64,\n model_name=\"resnext20_2x64d_svhn\", **kwargs)\n\n\ndef resnext20_4x16d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (4x16d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=16,\n model_name=\"resnext20_4x16d_cifar10\", **kwargs)\n\n\ndef resnext20_4x16d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (4x16d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=16,\n model_name=\"resnext20_4x16d_cifar100\", **kwargs)\n\n\ndef resnext20_4x16d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (4x16d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=16,\n model_name=\"resnext20_4x16d_svhn\", **kwargs)\n\n\ndef resnext20_4x32d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (4x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=32,\n model_name=\"resnext20_4x32d_cifar10\", **kwargs)\n\n\ndef resnext20_4x32d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (4x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=32,\n model_name=\"resnext20_4x32d_cifar100\", **kwargs)\n\n\ndef resnext20_4x32d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (4x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=32,\n model_name=\"resnext20_4x32d_svhn\", **kwargs)\n\n\ndef resnext20_8x8d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (8x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=8,\n model_name=\"resnext20_8x8d_cifar10\", **kwargs)\n\n\ndef resnext20_8x8d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (8x8d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=8,\n model_name=\"resnext20_8x8d_cifar100\", **kwargs)\n\n\ndef resnext20_8x8d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (8x8d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=8,\n model_name=\"resnext20_8x8d_svhn\", **kwargs)\n\n\ndef resnext20_8x16d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (8x16d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=16,\n model_name=\"resnext20_8x16d_cifar10\", **kwargs)\n\n\ndef resnext20_8x16d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (8x16d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=16,\n model_name=\"resnext20_8x16d_cifar100\", **kwargs)\n\n\ndef resnext20_8x16d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (8x16d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=16,\n model_name=\"resnext20_8x16d_svhn\", **kwargs)\n\n\ndef resnext20_16x4d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (16x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=4,\n model_name=\"resnext20_16x4d_cifar10\", **kwargs)\n\n\ndef resnext20_16x4d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (16x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=4,\n model_name=\"resnext20_16x4d_cifar100\", **kwargs)\n\n\ndef resnext20_16x4d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (16x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=4,\n model_name=\"resnext20_16x4d_svhn\", **kwargs)\n\n\ndef resnext20_16x8d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (16x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=8,\n model_name=\"resnext20_16x8d_cifar10\", **kwargs)\n\n\ndef resnext20_16x8d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (16x8d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=8,\n model_name=\"resnext20_16x8d_cifar100\", **kwargs)\n\n\ndef resnext20_16x8d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (16x8d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=8,\n model_name=\"resnext20_16x8d_svhn\", **kwargs)\n\n\ndef resnext20_32x2d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=2,\n model_name=\"resnext20_32x2d_cifar10\", **kwargs)\n\n\ndef resnext20_32x2d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (32x2d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=2,\n model_name=\"resnext20_32x2d_cifar100\", **kwargs)\n\n\ndef resnext20_32x2d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (32x2d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=2,\n model_name=\"resnext20_32x2d_svhn\", **kwargs)\n\n\ndef resnext20_32x4d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (32x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=4,\n model_name=\"resnext20_32x4d_cifar10\", **kwargs)\n\n\ndef resnext20_32x4d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (32x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=4,\n model_name=\"resnext20_32x4d_cifar100\", **kwargs)\n\n\ndef resnext20_32x4d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (32x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=4,\n model_name=\"resnext20_32x4d_svhn\", **kwargs)\n\n\ndef resnext20_64x1d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (64x1d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=1,\n model_name=\"resnext20_64x1d_cifar10\", **kwargs)\n\n\ndef resnext20_64x1d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (64x1d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=1,\n model_name=\"resnext20_64x1d_cifar100\", **kwargs)\n\n\ndef resnext20_64x1d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (64x1d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=1,\n model_name=\"resnext20_64x1d_svhn\", **kwargs)\n\n\ndef resnext20_64x2d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (64x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=2,\n model_name=\"resnext20_64x2d_cifar10\", **kwargs)\n\n\ndef resnext20_64x2d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-20 (64x2d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=2,\n model_name=\"resnext20_64x2d_cifar100\", **kwargs)\n\n\ndef resnext20_64x2d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-20 (64x1d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=2,\n model_name=\"resnext20_64x2d_svhn\", **kwargs)\n\n\ndef resnext29_32x4d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-29 (32x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=29, cardinality=32, bottleneck_width=4,\n model_name=\"resnext29_32x4d_cifar10\", **kwargs)\n\n\ndef resnext29_32x4d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-29 (32x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=29, cardinality=32, bottleneck_width=4,\n model_name=\"resnext29_32x4d_cifar100\", **kwargs)\n\n\ndef resnext29_32x4d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-29 (32x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=29, cardinality=32, bottleneck_width=4,\n model_name=\"resnext29_32x4d_svhn\", **kwargs)\n\n\ndef resnext29_16x64d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-29 (16x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=29, cardinality=16, bottleneck_width=64,\n model_name=\"resnext29_16x64d_cifar10\", **kwargs)\n\n\ndef resnext29_16x64d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-29 (16x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=29, cardinality=16, bottleneck_width=64,\n model_name=\"resnext29_16x64d_cifar100\", **kwargs)\n\n\ndef resnext29_16x64d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-29 (16x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=29, cardinality=16, bottleneck_width=64,\n model_name=\"resnext29_16x64d_svhn\", **kwargs)\n\n\ndef resnext56_1x64d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (1x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=1, bottleneck_width=64,\n model_name=\"resnext56_1x64d_cifar10\", **kwargs)\n\n\ndef resnext56_1x64d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-56 (1x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=1, bottleneck_width=64,\n model_name=\"resnext56_1x64d_cifar100\", **kwargs)\n\n\ndef resnext56_1x64d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (1x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=1, bottleneck_width=64,\n model_name=\"resnext56_1x64d_svhn\", **kwargs)\n\n\ndef resnext56_2x32d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (2x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=2, bottleneck_width=32,\n model_name=\"resnext56_2x32d_cifar10\", **kwargs)\n\n\ndef resnext56_2x32d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-56 (2x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=2, bottleneck_width=32,\n model_name=\"resnext56_2x32d_cifar100\", **kwargs)\n\n\ndef resnext56_2x32d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (2x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=2, bottleneck_width=32,\n model_name=\"resnext56_2x32d_svhn\", **kwargs)\n\n\ndef resnext56_4x16d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (4x16d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=4, bottleneck_width=16,\n model_name=\"resnext56_4x16d_cifar10\", **kwargs)\n\n\ndef resnext56_4x16d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-56 (4x16d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=4, bottleneck_width=16,\n model_name=\"resnext56_4x16d_cifar100\", **kwargs)\n\n\ndef resnext56_4x16d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (4x16d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=4, bottleneck_width=16,\n model_name=\"resnext56_4x16d_svhn\", **kwargs)\n\n\ndef resnext56_8x8d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (8x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=8, bottleneck_width=8,\n model_name=\"resnext56_8x8d_cifar10\", **kwargs)\n\n\ndef resnext56_8x8d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-56 (8x8d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=8, bottleneck_width=8,\n model_name=\"resnext56_8x8d_cifar100\", **kwargs)\n\n\ndef resnext56_8x8d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (8x8d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=8, bottleneck_width=8,\n model_name=\"resnext56_8x8d_svhn\", **kwargs)\n\n\ndef resnext56_16x4d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (16x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=16, bottleneck_width=4,\n model_name=\"resnext56_16x4d_cifar10\", **kwargs)\n\n\ndef resnext56_16x4d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-56 (16x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=16, bottleneck_width=4,\n model_name=\"resnext56_16x4d_cifar100\", **kwargs)\n\n\ndef resnext56_16x4d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (16x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=16, bottleneck_width=4,\n model_name=\"resnext56_16x4d_svhn\", **kwargs)\n\n\ndef resnext56_32x2d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=32, bottleneck_width=2,\n model_name=\"resnext56_32x2d_cifar10\", **kwargs)\n\n\ndef resnext56_32x2d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-56 (32x2d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=32, bottleneck_width=2,\n model_name=\"resnext56_32x2d_cifar100\", **kwargs)\n\n\ndef resnext56_32x2d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (32x2d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=32, bottleneck_width=2,\n model_name=\"resnext56_32x2d_svhn\", **kwargs)\n\n\ndef resnext56_64x1d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (64x1d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=64, bottleneck_width=1,\n model_name=\"resnext56_64x1d_cifar10\", **kwargs)\n\n\ndef resnext56_64x1d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-56 (64x1d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=64, bottleneck_width=1,\n model_name=\"resnext56_64x1d_cifar100\", **kwargs)\n\n\ndef resnext56_64x1d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-56 (64x1d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=56, cardinality=64, bottleneck_width=1,\n model_name=\"resnext56_64x1d_svhn\", **kwargs)\n\n\ndef resnext272_1x64d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-272 (1x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=272, cardinality=1, bottleneck_width=64,\n model_name=\"resnext272_1x64d_cifar10\", **kwargs)\n\n\ndef resnext272_1x64d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-272 (1x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=272, cardinality=1, bottleneck_width=64,\n model_name=\"resnext272_1x64d_cifar100\", **kwargs)\n\n\ndef resnext272_1x64d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-272 (1x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=272, cardinality=1, bottleneck_width=64,\n model_name=\"resnext272_1x64d_svhn\", **kwargs)\n\n\ndef resnext272_2x32d_cifar10(classes=10, **kwargs):\n \"\"\"\n ResNeXt-272 (2x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=272, cardinality=2, bottleneck_width=32,\n model_name=\"resnext272_2x32d_cifar10\", **kwargs)\n\n\ndef resnext272_2x32d_cifar100(classes=100, **kwargs):\n \"\"\"\n ResNeXt-272 (2x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 100\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=272, cardinality=2, bottleneck_width=32,\n model_name=\"resnext272_2x32d_cifar100\", **kwargs)\n\n\ndef resnext272_2x32d_svhn(classes=10, **kwargs):\n \"\"\"\n ResNeXt-272 (2x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'\n http://arxiv.org/abs/1611.05431.\n\n Parameters:\n ----------\n classes : int, default 10\n Number of classification classes.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnext_cifar(classes=classes, blocks=272, cardinality=2, bottleneck_width=32,\n model_name=\"resnext272_2x32d_svhn\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n data_format = \"channels_last\"\n # data_format = \"channels_first\"\n pretrained = False\n\n models = [\n (resnext20_1x64d_cifar10, 10),\n (resnext20_1x64d_cifar100, 100),\n (resnext20_1x64d_svhn, 10),\n (resnext20_2x32d_cifar10, 10),\n (resnext20_2x32d_cifar100, 100),\n (resnext20_2x32d_svhn, 10),\n (resnext20_2x64d_cifar10, 10),\n (resnext20_2x64d_cifar100, 100),\n (resnext20_2x64d_svhn, 10),\n (resnext20_4x16d_cifar10, 10),\n (resnext20_4x16d_cifar100, 100),\n (resnext20_4x16d_svhn, 10),\n (resnext20_4x32d_cifar10, 10),\n (resnext20_4x32d_cifar100, 100),\n (resnext20_4x32d_svhn, 10),\n (resnext20_8x8d_cifar10, 10),\n (resnext20_8x8d_cifar100, 100),\n (resnext20_8x8d_svhn, 10),\n (resnext20_8x16d_cifar10, 10),\n (resnext20_8x16d_cifar100, 100),\n (resnext20_8x16d_svhn, 10),\n (resnext20_16x4d_cifar10, 10),\n (resnext20_16x4d_cifar100, 100),\n (resnext20_16x4d_svhn, 10),\n (resnext20_16x8d_cifar10, 10),\n (resnext20_16x8d_cifar100, 100),\n (resnext20_16x8d_svhn, 10),\n (resnext20_32x2d_cifar10, 10),\n (resnext20_32x2d_cifar100, 100),\n (resnext20_32x2d_svhn, 10),\n (resnext20_32x4d_cifar10, 10),\n (resnext20_32x4d_cifar100, 100),\n (resnext20_32x4d_svhn, 10),\n (resnext20_64x1d_cifar10, 10),\n (resnext20_64x1d_cifar100, 100),\n (resnext20_64x1d_svhn, 10),\n (resnext20_64x2d_cifar10, 10),\n (resnext20_64x2d_cifar100, 100),\n (resnext20_64x2d_svhn, 10),\n (resnext29_32x4d_cifar10, 10),\n (resnext29_32x4d_cifar100, 100),\n (resnext29_32x4d_svhn, 10),\n (resnext29_16x64d_cifar10, 10),\n (resnext29_16x64d_cifar100, 100),\n (resnext29_16x64d_svhn, 10),\n (resnext56_1x64d_cifar10, 10),\n (resnext56_1x64d_cifar100, 100),\n (resnext56_1x64d_svhn, 10),\n (resnext56_2x32d_cifar10, 10),\n (resnext56_2x32d_cifar100, 100),\n (resnext56_2x32d_svhn, 10),\n (resnext56_4x16d_cifar10, 10),\n (resnext56_4x16d_cifar100, 100),\n (resnext56_4x16d_svhn, 10),\n (resnext56_8x8d_cifar10, 10),\n (resnext56_8x8d_cifar100, 100),\n (resnext56_8x8d_svhn, 10),\n (resnext56_16x4d_cifar10, 10),\n (resnext56_16x4d_cifar100, 100),\n (resnext56_16x4d_svhn, 10),\n (resnext56_32x2d_cifar10, 10),\n (resnext56_32x2d_cifar100, 100),\n (resnext56_32x2d_svhn, 10),\n (resnext56_64x1d_cifar10, 10),\n (resnext56_64x1d_cifar100, 100),\n (resnext56_64x1d_svhn, 10),\n (resnext272_1x64d_cifar10, 10),\n (resnext272_1x64d_cifar100, 100),\n (resnext272_1x64d_svhn, 10),\n (resnext272_2x32d_cifar10, 10),\n (resnext272_2x32d_cifar100, 100),\n (resnext272_2x32d_svhn, 10),\n ]\n\n for model, classes in models:\n\n net = model(pretrained=pretrained, data_format=data_format)\n\n batch_saze = 14\n x = tf.random.normal((batch_saze, 3, 32, 32) if is_channels_first(data_format) else (batch_saze, 32, 32, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch_saze, classes))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != resnext20_1x64d_cifar10 or weight_count == 3446602)\n assert (model != resnext20_1x64d_cifar100 or weight_count == 3538852)\n assert (model != resnext20_1x64d_svhn or weight_count == 3446602)\n assert (model != resnext20_2x32d_cifar10 or weight_count == 2672458)\n assert (model != resnext20_2x32d_cifar100 or weight_count == 2764708)\n assert (model != resnext20_2x32d_svhn or weight_count == 2672458)\n assert (model != resnext20_2x64d_cifar10 or weight_count == 6198602)\n assert (model != resnext20_2x64d_cifar100 or weight_count == 6290852)\n assert (model != resnext20_2x64d_svhn or weight_count == 6198602)\n assert (model != resnext20_4x16d_cifar10 or weight_count == 2285386)\n assert (model != resnext20_4x16d_cifar100 or weight_count == 2377636)\n assert (model != resnext20_4x16d_svhn or weight_count == 2285386)\n assert (model != resnext20_4x32d_cifar10 or weight_count == 4650314)\n assert (model != resnext20_4x32d_cifar100 or weight_count == 4742564)\n assert (model != resnext20_4x32d_svhn or weight_count == 4650314)\n assert (model != resnext20_8x8d_cifar10 or weight_count == 2091850)\n assert (model != resnext20_8x8d_cifar100 or weight_count == 2184100)\n assert (model != resnext20_8x8d_svhn or weight_count == 2091850)\n assert (model != resnext20_8x16d_cifar10 or weight_count == 3876170)\n assert (model != resnext20_8x16d_cifar100 or weight_count == 3968420)\n assert (model != resnext20_8x16d_svhn or weight_count == 3876170)\n assert (model != resnext20_16x4d_cifar10 or weight_count == 1995082)\n assert (model != resnext20_16x4d_cifar100 or weight_count == 2087332)\n assert (model != resnext20_16x4d_svhn or weight_count == 1995082)\n assert (model != resnext20_16x8d_cifar10 or weight_count == 3489098)\n assert (model != resnext20_16x8d_cifar100 or weight_count == 3581348)\n assert (model != resnext20_16x8d_svhn or weight_count == 3489098)\n assert (model != resnext20_32x2d_cifar10 or weight_count == 1946698)\n assert (model != resnext20_32x2d_cifar100 or weight_count == 2038948)\n assert (model != resnext20_32x2d_svhn or weight_count == 1946698)\n assert (model != resnext20_32x4d_cifar10 or weight_count == 3295562)\n assert (model != resnext20_32x4d_cifar100 or weight_count == 3387812)\n assert (model != resnext20_32x4d_svhn or weight_count == 3295562)\n assert (model != resnext20_64x1d_cifar10 or weight_count == 1922506)\n assert (model != resnext20_64x1d_cifar100 or weight_count == 2014756)\n assert (model != resnext20_64x1d_svhn or weight_count == 1922506)\n assert (model != resnext20_64x2d_cifar10 or weight_count == 3198794)\n assert (model != resnext20_64x2d_cifar100 or weight_count == 3291044)\n assert (model != resnext20_64x2d_svhn or weight_count == 3198794)\n assert (model != resnext29_32x4d_cifar10 or weight_count == 4775754)\n assert (model != resnext29_32x4d_cifar100 or weight_count == 4868004)\n assert (model != resnext29_32x4d_svhn or weight_count == 4775754)\n assert (model != resnext29_16x64d_cifar10 or weight_count == 68155210)\n assert (model != resnext29_16x64d_cifar100 or weight_count == 68247460)\n assert (model != resnext29_16x64d_svhn or weight_count == 68155210)\n assert (model != resnext56_1x64d_cifar10 or weight_count == 9317194)\n assert (model != resnext56_1x64d_cifar100 or weight_count == 9409444)\n assert (model != resnext56_1x64d_svhn or weight_count == 9317194)\n assert (model != resnext56_2x32d_cifar10 or weight_count == 6994762)\n assert (model != resnext56_2x32d_cifar100 or weight_count == 7087012)\n assert (model != resnext56_2x32d_svhn or weight_count == 6994762)\n assert (model != resnext56_4x16d_cifar10 or weight_count == 5833546)\n assert (model != resnext56_4x16d_cifar100 or weight_count == 5925796)\n assert (model != resnext56_4x16d_svhn or weight_count == 5833546)\n assert (model != resnext56_8x8d_cifar10 or weight_count == 5252938)\n assert (model != resnext56_8x8d_cifar100 or weight_count == 5345188)\n assert (model != resnext56_8x8d_svhn or weight_count == 5252938)\n assert (model != resnext56_16x4d_cifar10 or weight_count == 4962634)\n assert (model != resnext56_16x4d_cifar100 or weight_count == 5054884)\n assert (model != resnext56_16x4d_svhn or weight_count == 4962634)\n assert (model != resnext56_32x2d_cifar10 or weight_count == 4817482)\n assert (model != resnext56_32x2d_cifar100 or weight_count == 4909732)\n assert (model != resnext56_32x2d_svhn or weight_count == 4817482)\n assert (model != resnext56_64x1d_cifar10 or weight_count == 4744906)\n assert (model != resnext56_64x1d_cifar100 or weight_count == 4837156)\n assert (model != resnext56_64x1d_svhn or weight_count == 4744906)\n assert (model != resnext272_1x64d_cifar10 or weight_count == 44540746)\n assert (model != resnext272_1x64d_cifar100 or weight_count == 44632996)\n assert (model != resnext272_1x64d_svhn or weight_count == 44540746)\n assert (model != resnext272_2x32d_cifar10 or weight_count == 32928586)\n assert (model != resnext272_2x32d_cifar100 or weight_count == 33020836)\n assert (model != resnext272_2x32d_svhn or weight_count == 32928586)\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n Pascal VOC2012 semantic segmentation dataset.\n\"\"\"\n\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom chainer import get_dtype\nfrom .seg_dataset import SegDataset\nfrom .dataset_metainfo import DatasetMetaInfo\n\n\nclass VOCSegDataset(SegDataset):\n \"\"\"\n Pascal VOC2012 semantic segmentation dataset.\n\n Parameters\n ----------\n root : str\n Path to VOCdevkit folder.\n mode : str, default 'train'\n 'train', 'val', 'test', or 'demo'.\n transform : callable, optional\n A function that transforms the image.\n \"\"\"\n def __init__(self,\n root,\n mode=\"train\",\n transform=None,\n **kwargs):\n super(VOCSegDataset, self).__init__(\n root=root,\n mode=mode,\n transform=transform,\n **kwargs)\n\n base_dir_path = os.path.join(root, \"VOC2012\")\n image_dir_path = os.path.join(base_dir_path, \"JPEGImages\")\n mask_dir_path = os.path.join(base_dir_path, \"SegmentationClass\")\n\n splits_dir_path = os.path.join(base_dir_path, \"ImageSets\", \"Segmentation\")\n if mode == \"train\":\n split_file_path = os.path.join(splits_dir_path, \"train.txt\")\n elif mode in (\"val\", \"test\", \"demo\"):\n split_file_path = os.path.join(splits_dir_path, \"val.txt\")\n else:\n raise RuntimeError(\"Unknown dataset splitting mode\")\n\n self.images = []\n self.masks = []\n with open(os.path.join(split_file_path), \"r\") as lines:\n for line in lines:\n image_file_path = os.path.join(image_dir_path, line.rstrip('\\n') + \".jpg\")\n assert os.path.isfile(image_file_path)\n self.images.append(image_file_path)\n mask_file_path = os.path.join(mask_dir_path, line.rstrip('\\n') + \".png\")\n assert os.path.isfile(mask_file_path)\n self.masks.append(mask_file_path)\n\n assert (len(self.images) == len(self.masks))\n\n # self.images = self.images[:10]\n # self.masks = self.masks[:10]\n\n self.add_getter('img', self._get_image)\n self.add_getter('label', self._get_label)\n\n def _get_image(self, i):\n image = Image.open(self.images[i]).convert(\"RGB\")\n assert (self.mode in (\"test\", \"demo\"))\n image = self._img_transform(image)\n if self.transform is not None:\n image = self.transform(image)\n return image\n\n def _get_label(self, i):\n if self.mode == \"demo\":\n return os.path.basename(self.images[i])\n assert (self.mode == \"test\")\n mask = Image.open(self.masks[i])\n mask = self._mask_transform(mask)\n return mask\n\n classes = 21\n vague_idx = 255\n use_vague = True\n background_idx = 0\n ignore_bg = True\n\n @staticmethod\n def _mask_transform(mask):\n np_mask = np.array(mask).astype(np.int32)\n # np_mask[np_mask == 255] = VOCSegDataset.vague_idx\n return np_mask\n\n def __len__(self):\n return len(self.images)\n\n\nclass VOCSegTrainTransform(object):\n \"\"\"\n ImageNet-1K training transform.\n \"\"\"\n def __init__(self,\n ds_metainfo,\n mean_rgb=(0.485, 0.456, 0.406),\n std_rgb=(0.229, 0.224, 0.225)):\n assert (ds_metainfo is not None)\n self.mean = np.array(mean_rgb, np.float32)[:, np.newaxis, np.newaxis]\n self.std = np.array(std_rgb, np.float32)[:, np.newaxis, np.newaxis]\n\n def __call__(self, img):\n dtype = get_dtype(None)\n img = img.transpose(2, 0, 1)\n img = img.astype(dtype)\n img *= 1.0 / 255.0\n\n img -= self.mean\n img /= self.std\n return img\n\n\nclass VOCSegTestTransform(object):\n \"\"\"\n ImageNet-1K validation transform.\n \"\"\"\n def __init__(self,\n ds_metainfo,\n mean_rgb=(0.485, 0.456, 0.406),\n std_rgb=(0.229, 0.224, 0.225)):\n assert (ds_metainfo is not None)\n self.mean = np.array(mean_rgb, np.float32)[:, np.newaxis, np.newaxis]\n self.std = np.array(std_rgb, np.float32)[:, np.newaxis, np.newaxis]\n\n def __call__(self, img):\n dtype = get_dtype(None)\n img = img.transpose(2, 0, 1)\n img = img.astype(dtype)\n img *= 1.0 / 255.0\n\n img -= self.mean\n img /= self.std\n return img\n\n\nclass VOCMetaInfo(DatasetMetaInfo):\n def __init__(self):\n super(VOCMetaInfo, self).__init__()\n self.label = \"VOC\"\n self.short_label = \"voc\"\n self.root_dir_name = \"voc\"\n self.dataset_class = VOCSegDataset\n self.num_training_samples = None\n self.in_channels = 3\n self.num_classes = VOCSegDataset.classes\n self.input_image_size = (480, 480)\n self.train_metric_capts = None\n self.train_metric_names = None\n self.train_metric_extra_kwargs = None\n self.val_metric_capts = None\n self.val_metric_names = None\n self.test_metric_extra_kwargs = None\n self.test_metric_capts = [\"Val.PixAcc\", \"Val.IoU\"]\n self.test_metric_names = [\"PixelAccuracyMetric\", \"MeanIoUMetric\"]\n self.test_metric_extra_kwargs = [\n {\"vague_idx\": VOCSegDataset.vague_idx,\n \"use_vague\": VOCSegDataset.use_vague,\n \"macro_average\": False},\n {\"num_classes\": VOCSegDataset.classes,\n \"vague_idx\": VOCSegDataset.vague_idx,\n \"use_vague\": VOCSegDataset.use_vague,\n \"bg_idx\": VOCSegDataset.background_idx,\n \"ignore_bg\": VOCSegDataset.ignore_bg,\n \"macro_average\": False}]\n self.saver_acc_ind = 1\n self.train_transform = VOCSegTrainTransform\n self.val_transform = VOCSegTestTransform\n self.test_transform = VOCSegTestTransform\n self.ml_type = \"imgseg\"\n self.allow_hybridize = False\n self.net_extra_kwargs = {\"aux\": False, \"fixed_size\": False}\n self.load_ignore_extra = True\n self.image_base_size = 520\n self.image_crop_size = 480\n\n def add_dataset_parser_arguments(self,\n parser,\n work_dir_path):\n super(VOCMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)\n parser.add_argument(\n \"--image-base-size\",\n type=int,\n default=520,\n help=\"base image size\")\n parser.add_argument(\n \"--image-crop-size\",\n type=int,\n default=480,\n help=\"crop image size\")\n\n def update(self,\n args):\n super(VOCMetaInfo, self).update(args)\n self.image_base_size = args.image_base_size\n self.image_crop_size = args.image_crop_size\n",
"\"\"\"\n COCO semantic segmentation dataset.\n\"\"\"\n\nimport os\nimport logging\nimport numpy as np\nimport mxnet as mx\nfrom PIL import Image\nfrom tqdm import trange\nfrom .seg_dataset import SegDataset\nfrom .voc_seg_dataset import VOCMetaInfo\n\n\nclass CocoSegDataset(SegDataset):\n \"\"\"\n COCO semantic segmentation dataset.\n\n Parameters\n ----------\n root : string\n Path to `annotations`, `train2017`, and `val2017` folders.\n mode : string, default 'train'\n 'train', 'val', 'test', or 'demo'.\n transform : callable, optional\n A function that transforms the image.\n \"\"\"\n def __init__(self,\n root,\n mode=\"train\",\n transform=None,\n **kwargs):\n super(CocoSegDataset, self).__init__(\n root=root,\n mode=mode,\n transform=transform,\n **kwargs)\n\n year = \"2017\"\n mode_name = \"train\" if mode == \"train\" else \"val\"\n annotations_dir_path = os.path.join(root, \"annotations\")\n annotations_file_path = os.path.join(annotations_dir_path, \"instances_\" + mode_name + year + \".json\")\n idx_file_path = os.path.join(annotations_dir_path, mode_name + \"_idx.npy\")\n self.image_dir_path = os.path.join(root, mode_name + year)\n\n from pycocotools.coco import COCO\n from pycocotools import mask as coco_mask\n self.coco = COCO(annotations_file_path)\n self.coco_mask = coco_mask\n if os.path.exists(idx_file_path):\n self.idx = np.load(idx_file_path)\n else:\n idx_list = list(self.coco.imgs.keys())\n self.idx = self._filter_idx(idx_list, idx_file_path)\n\n def __getitem__(self, index):\n image_id = int(self.idx[index])\n image_metadata = self.coco.loadImgs(image_id)[0]\n image_file_name = image_metadata[\"file_name\"]\n\n image_file_path = os.path.join(self.image_dir_path, image_file_name)\n image = Image.open(image_file_path).convert(\"RGB\")\n if self.mode == \"demo\":\n image = self._img_transform(image)\n if self.transform is not None:\n image = self.transform(image)\n return image, os.path.basename(image_file_path)\n\n coco_target = self.coco.loadAnns(self.coco.getAnnIds(imgIds=image_id))\n mask = Image.fromarray(self._gen_seg_mask(\n target=coco_target,\n height=image_metadata[\"height\"],\n width=image_metadata[\"width\"]))\n\n if self.mode == \"train\":\n image, mask = self._train_sync_transform(image, mask)\n elif self.mode == \"val\":\n image, mask = self._val_sync_transform(image, mask)\n else:\n assert (self.mode == \"test\")\n image, mask = self._img_transform(image), self._mask_transform(mask)\n\n if self.transform is not None:\n image = self.transform(image)\n\n return image, mask\n\n def _gen_seg_mask(self, target, height, width):\n cat_list = [0, 5, 2, 16, 9, 44, 6, 3, 17, 62, 21, 67, 18, 19, 4, 1, 64, 20, 63, 7, 72]\n mask = np.zeros((height, width), dtype=np.uint8)\n for instance in target:\n rle = self.coco_mask.frPyObjects(instance[\"segmentation\"], height, width)\n m = self.coco_mask.decode(rle)\n cat = instance[\"category_id\"]\n if cat in cat_list:\n c = cat_list.index(cat)\n else:\n continue\n if len(m.shape) < 3:\n mask[:, :] += (mask == 0) * (m * c)\n else:\n mask[:, :] += (mask == 0) * (((np.sum(m, axis=2)) > 0) * c).astype(np.uint8)\n return mask\n\n def _filter_idx(self,\n idx_list,\n idx_file_path,\n pixels_thr=1000):\n logging.info(\"Filtering mask index:\")\n tbar = trange(len(idx_list))\n filtered_idx = []\n for i in tbar:\n img_id = idx_list[i]\n coco_target = self.coco.loadAnns(self.coco.getAnnIds(imgIds=img_id))\n img_metadata = self.coco.loadImgs(img_id)[0]\n mask = self._gen_seg_mask(\n coco_target,\n img_metadata[\"height\"],\n img_metadata[\"width\"])\n if (mask > 0).sum() > pixels_thr:\n filtered_idx.append(img_id)\n tbar.set_description(\"Doing: {}/{}, got {} qualified images\".format(i, len(idx_list), len(filtered_idx)))\n logging.info(\"Found number of qualified images: {}\".format(len(filtered_idx)))\n np.save(idx_file_path, np.array(filtered_idx, np.int32))\n return filtered_idx\n\n classes = 21\n vague_idx = -1\n use_vague = False\n background_idx = 0\n ignore_bg = True\n\n @staticmethod\n def _mask_transform(mask, ctx=mx.cpu()):\n np_mask = np.array(mask).astype(np.int32)\n # print(\"min={}, max={}\".format(np_mask.min(), np_mask.max()))\n return mx.nd.array(np_mask, ctx=ctx)\n\n def __len__(self):\n return len(self.idx)\n\n\nclass CocoSegMetaInfo(VOCMetaInfo):\n def __init__(self):\n super(CocoSegMetaInfo, self).__init__()\n self.label = \"COCO\"\n self.short_label = \"coco\"\n self.root_dir_name = \"coco\"\n self.dataset_class = CocoSegDataset\n self.num_classes = CocoSegDataset.classes\n self.train_metric_extra_kwargs = [\n {\"vague_idx\": CocoSegDataset.vague_idx,\n \"use_vague\": CocoSegDataset.use_vague,\n \"macro_average\": False,\n \"aux\": self.train_aux}]\n self.val_metric_extra_kwargs = [\n {\"vague_idx\": CocoSegDataset.vague_idx,\n \"use_vague\": CocoSegDataset.use_vague,\n \"macro_average\": False},\n {\"num_classes\": CocoSegDataset.classes,\n \"vague_idx\": CocoSegDataset.vague_idx,\n \"use_vague\": CocoSegDataset.use_vague,\n \"bg_idx\": CocoSegDataset.background_idx,\n \"ignore_bg\": CocoSegDataset.ignore_bg,\n \"macro_average\": False}]\n self.test_metric_extra_kwargs = self.val_metric_extra_kwargs\n",
"import random\nimport threading\nimport numpy as np\nfrom PIL import Image, ImageOps, ImageFilter\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, DirectoryIterator\n\n\nclass SegDataset(object):\n \"\"\"\n Segmentation base dataset.\n\n Parameters\n ----------\n root : str\n Path to data folder.\n mode : str\n 'train', 'val', 'test', or 'demo'.\n transform : callable\n A function that transforms the image.\n \"\"\"\n def __init__(self,\n root,\n mode,\n transform,\n base_size=520,\n crop_size=480):\n super(SegDataset, self).__init__()\n assert (mode in (\"train\", \"val\", \"test\", \"demo\"))\n assert (mode in (\"test\", \"demo\"))\n self.root = root\n self.mode = mode\n self.transform = transform\n self.base_size = base_size\n self.crop_size = crop_size\n\n def _val_sync_transform(self, image, mask):\n outsize = self.crop_size\n short_size = outsize\n w, h = image.size\n if w > h:\n oh = short_size\n ow = int(1.0 * w * oh / h)\n else:\n ow = short_size\n oh = int(1.0 * h * ow / w)\n image = image.resize((ow, oh), Image.BILINEAR)\n mask = mask.resize((ow, oh), Image.NEAREST)\n # center crop\n w, h = image.size\n x1 = int(round(0.5 * (w - outsize)))\n y1 = int(round(0.5 * (h - outsize)))\n image = image.crop((x1, y1, x1 + outsize, y1 + outsize))\n mask = mask.crop((x1, y1, x1 + outsize, y1 + outsize))\n # final transform\n image, mask = self._img_transform(image), self._mask_transform(mask)\n return image, mask\n\n def _sync_transform(self, image, mask):\n # random mirror\n if random.random() < 0.5:\n image = image.transpose(Image.FLIP_LEFT_RIGHT)\n mask = mask.transpose(Image.FLIP_LEFT_RIGHT)\n crop_size = self.crop_size\n # random scale (short edge)\n short_size = random.randint(int(self.base_size * 0.5), int(self.base_size * 2.0))\n w, h = image.size\n if h > w:\n ow = short_size\n oh = int(1.0 * h * ow / w)\n else:\n oh = short_size\n ow = int(1.0 * w * oh / h)\n image = image.resize((ow, oh), Image.BILINEAR)\n mask = mask.resize((ow, oh), Image.NEAREST)\n # pad crop\n if short_size < crop_size:\n padh = crop_size - oh if oh < crop_size else 0\n padw = crop_size - ow if ow < crop_size else 0\n image = ImageOps.expand(image, border=(0, 0, padw, padh), fill=0)\n mask = ImageOps.expand(mask, border=(0, 0, padw, padh), fill=0)\n # random crop crop_size\n w, h = image.size\n x1 = random.randint(0, w - crop_size)\n y1 = random.randint(0, h - crop_size)\n image = image.crop((x1, y1, x1 + crop_size, y1 + crop_size))\n mask = mask.crop((x1, y1, x1 + crop_size, y1 + crop_size))\n # gaussian blur as in PSP\n if random.random() < 0.5:\n image = image.filter(ImageFilter.GaussianBlur(\n radius=random.random()))\n # final transform\n image, mask = self._img_transform(image), self._mask_transform(mask)\n return image, mask\n\n @staticmethod\n def _img_transform(image):\n return np.array(image)\n\n @staticmethod\n def _mask_transform(mask):\n return np.array(mask).astype(np.int32)\n\n def __getitem__(self, index):\n raise NotImplementedError\n\n def __len__(self):\n raise NotImplementedError\n\n\nclass SegDirectoryIterator(DirectoryIterator):\n allowed_class_modes = {'categorical', 'binary', 'sparse', 'input', None}\n\n def __init__(self,\n directory,\n image_data_generator,\n target_size=(256, 256),\n color_mode='rgb',\n classes=None,\n class_mode='categorical',\n batch_size=32,\n shuffle=True,\n seed=None,\n data_format='channels_last',\n save_to_dir=None,\n save_prefix='',\n save_format='png',\n follow_links=False,\n subset=None,\n interpolation='nearest',\n dtype='float32',\n dataset=None):\n super(SegDirectoryIterator, self).set_processing_attrs(\n image_data_generator,\n target_size,\n color_mode,\n data_format,\n save_to_dir,\n save_prefix,\n save_format,\n subset,\n interpolation)\n\n self.dataset = dataset\n self.class_mode = class_mode\n self.dtype = dtype\n\n self.n = len(self.dataset)\n self.batch_size = batch_size\n self.seed = seed\n self.shuffle = shuffle\n self.batch_index = 0\n self.total_batches_seen = 0\n self.lock = threading.Lock()\n self.index_array = None\n self.index_generator = self._flow_index()\n\n def _get_batches_of_transformed_samples(self, index_array):\n \"\"\"Gets a batch of transformed samples.\n\n # Arguments\n index_array: Array of sample indices to include in batch.\n\n # Returns\n A batch of transformed samples.\n \"\"\"\n # batch_x = np.zeros((len(index_array),) + self.image_shape, dtype=self.dtype)\n # batch_y = np.zeros((len(index_array),) + self.image_shape, dtype=np.int32)\n batch_x = None\n batch_y = None\n for i, j in enumerate(index_array):\n x, y = self.dataset[j]\n if batch_x is None:\n batch_x = np.zeros((len(index_array),) + x.shape, dtype=self.dtype)\n batch_y = np.zeros((len(index_array),) + y.shape, dtype=np.int32)\n # if self.data_format == \"channel_first\":\n # print(\"*\")\n # print(\"batch_x.shape={}\".format(batch_x.shape))\n # print(\"batch_y.shape={}\".format(batch_y.shape))\n # print(\"x.shape={}\".format(x.shape))\n # print(\"y.shape={}\".format(y.shape))\n batch_x[i] = x\n batch_y[i] = y\n return batch_x, batch_y\n\n\nclass SegImageDataGenerator(ImageDataGenerator):\n\n def flow_from_directory(self,\n directory,\n target_size=(256, 256),\n color_mode='rgb',\n classes=None,\n class_mode='categorical',\n batch_size=32,\n shuffle=True,\n seed=None,\n save_to_dir=None,\n save_prefix='',\n save_format='png',\n follow_links=False,\n subset=None,\n interpolation='nearest',\n dataset=None):\n return SegDirectoryIterator(\n directory,\n self,\n target_size=target_size,\n color_mode=color_mode,\n classes=classes,\n class_mode=class_mode,\n data_format=self.data_format,\n batch_size=batch_size,\n shuffle=shuffle,\n seed=seed,\n save_to_dir=save_to_dir,\n save_prefix=save_prefix,\n save_format=save_format,\n follow_links=follow_links,\n subset=subset,\n interpolation=interpolation,\n dataset=dataset)\n",
"\"\"\"\n ResNet for ImageNet-1K, implemented in PyTorch.\n Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n\"\"\"\n\n__all__ = ['ResNet', 'resnet10', 'resnet12', 'resnet14', 'resnetbc14b', 'resnet16', 'resnet18_wd4', 'resnet18_wd2',\n 'resnet18_w3d4', 'resnet18', 'resnet26', 'resnetbc26b', 'resnet34', 'resnetbc38b', 'resnet50', 'resnet50b',\n 'resnet101', 'resnet101b', 'resnet152', 'resnet152b', 'resnet200', 'resnet200b', 'ResBlock', 'ResBottleneck',\n 'ResUnit', 'ResInitBlock']\n\nimport os\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom .common import conv1x1_block, conv3x3_block, conv7x7_block\n\n\nclass ResBlock(nn.Module):\n \"\"\"\n Simple ResNet block for residual path in ResNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n bias=False,\n use_bn=True):\n super(ResBlock, self).__init__()\n self.conv1 = conv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bias=bias,\n use_bn=use_bn)\n self.conv2 = conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n bias=bias,\n use_bn=use_bn,\n activation=None)\n\n def forward(self, x, identity=None):\n x = self.conv1(x)\n if identity is not None:\n # print('adding shorter skip connection)\n x = x + identity # Shorter skip connection - LIV\n x = self.conv2(x)\n return x\n\n\nclass ResBottleneck(nn.Module):\n \"\"\"\n ResNet bottleneck block for residual path in ResNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for the second convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for the second convolution layer.\n conv1_stride : bool, default False\n Whether to use stride in the first or the second convolution layer of the block.\n bottleneck_factor : int, default 4\n Bottleneck factor.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n padding=1,\n dilation=1,\n conv1_stride=False,\n bottleneck_factor=4):\n super(ResBottleneck, self).__init__()\n mid_channels = out_channels // bottleneck_factor\n\n self.conv1 = conv1x1_block(\n in_channels=in_channels,\n out_channels=mid_channels,\n stride=(stride if conv1_stride else 1))\n self.conv2 = conv3x3_block(\n in_channels=mid_channels,\n out_channels=mid_channels,\n stride=(1 if conv1_stride else stride),\n padding=padding,\n dilation=dilation)\n self.conv3 = conv1x1_block(\n in_channels=mid_channels,\n out_channels=out_channels,\n activation=None)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n return x\n\n\nclass ResUnit(nn.Module):\n \"\"\"\n ResNet unit with residual connection.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for the second convolution layer in bottleneck.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for the second convolution layer in bottleneck.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bottleneck : bool, default True\n Whether to use a bottleneck or simple block in units.\n conv1_stride : bool, default False\n Whether to use stride in the first or the second convolution layer of the block.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n padding=1,\n dilation=1,\n bias=False,\n use_bn=True,\n bottleneck=True,\n conv1_stride=False):\n super(ResUnit, self).__init__()\n self.resize_identity = (in_channels != out_channels) or (stride != 1)\n\n if bottleneck:\n self.body = ResBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n padding=padding,\n dilation=dilation,\n conv1_stride=conv1_stride)\n else:\n self.body = ResBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bias=bias,\n use_bn=use_bn)\n if self.resize_identity:\n self.identity_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bias=bias,\n use_bn=use_bn,\n activation=None)\n self.activ = nn.ReLU(inplace=True)\n\n def forward(self, x):\n if self.resize_identity:\n identity = self.identity_conv(x)\n else:\n identity = x\n x = self.body(x, None) # Needed for original skip connection AND need line below: x = x + identity\n # x = self.body(x, identity) # creates shorter skip connection - LIV\n # Don't need skip connection bc shorter skip connection now in ResBlock() - LIV\n x = x + identity \n x = self.activ(x)\n return x\n\n\n\"\"\"\nLIV\n\"\"\"\nclass NonResBlock(nn.Module):\n \"\"\"\n Simple ResNet block for residual path in ResNet unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n bias=False,\n use_bn=True):\n super(NonResBlock, self).__init__()\n self.conv1 = conv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bias=bias,\n use_bn=use_bn)\n self.conv2 = conv3x3_block(\n in_channels=out_channels,\n out_channels=out_channels,\n bias=bias,\n use_bn=use_bn,\n activation=None)\n\n def forward(self, x):\n x = self.conv1(x)\n # NO skip connections at all\n # if identity is not None:\n # # print('adding shorter skip connection)\n # x = x + identity # Shorter skip connection - LIV\n x = self.conv2(x)\n return x\n\n\nclass NonResUnit(nn.Module):\n \"\"\"\n ResNet unit with residual connection.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for the second convolution layer in bottleneck.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for the second convolution layer in bottleneck.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bottleneck : bool, default True\n Whether to use a bottleneck or simple block in units.\n conv1_stride : bool, default False\n Whether to use stride in the first or the second convolution layer of the block.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n stride,\n padding=1,\n dilation=1,\n bias=False,\n use_bn=True,\n bottleneck=True,\n conv1_stride=False):\n super(NonResUnit, self).__init__()\n self.resize_identity = (in_channels != out_channels) or (stride != 1)\n\n if bottleneck:\n self.body = ResBottleneck(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n padding=padding,\n dilation=dilation,\n conv1_stride=conv1_stride)\n else:\n self.body = NonResBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bias=bias,\n use_bn=use_bn)\n self.activ = nn.ReLU(inplace=True)\n\n def forward(self, x):\n # if self.resize_identity:\n # identity = self.identity_conv(x)\n # else:\n # identity = x\n x = self.body(x)\n # No skip connection\n # x = x + identity\n x = self.activ(x)\n return x\n\n\n\"\"\"\nLIV END\n\"\"\"\n\n\nclass ResInitBlock(nn.Module):\n \"\"\"\n ResNet specific initial block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels):\n super(ResInitBlock, self).__init__()\n self.conv = conv7x7_block(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=2)\n self.pool = nn.MaxPool2d(\n kernel_size=3,\n stride=2,\n padding=1)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.pool(x)\n return x\n\n\nclass ResNet(nn.Module):\n \"\"\"\n ResNet model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n bottleneck : bool\n Whether to use a bottleneck or simple block in units.\n conv1_stride : bool\n Whether to use stride in the first or the second convolution layer in units.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n num_classes : int, default 1000\n Number of classification classes.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n bottleneck,\n conv1_stride,\n in_channels=3,\n in_size=(224, 224),\n num_classes=1000):\n super(ResNet, self).__init__()\n self.in_size = in_size\n self.num_classes = num_classes\n\n self.features = nn.Sequential()\n self.features.add_module(\"init_block\", ResInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = nn.Sequential()\n for j, out_channels in enumerate(channels_per_stage):\n stride = 2 if (j == 0) and (i != 0) else 1\n stage.add_module(\"unit{}\".format(j + 1), ResUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n stride=stride,\n bottleneck=bottleneck,\n conv1_stride=conv1_stride))\n in_channels = out_channels\n self.features.add_module(\"stage{}\".format(i + 1), stage)\n self.features.add_module(\"final_pool\", nn.AvgPool2d(\n kernel_size=7,\n stride=1))\n\n self.output = nn.Linear(\n in_features=in_channels,\n out_features=num_classes)\n\n self._init_params()\n\n def _init_params(self):\n for name, module in self.named_modules():\n if isinstance(module, nn.Conv2d):\n init.kaiming_uniform_(module.weight)\n if module.bias is not None:\n init.constant_(module.bias, 0)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.output(x)\n return x\n\n\ndef get_resnet(blocks,\n bottleneck=None,\n conv1_stride=True,\n width_scale=1.0,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".torch\", \"models\"),\n **kwargs):\n \"\"\"\n Create ResNet model with specific parameters.\n\n Parameters:\n ----------\n blocks : int\n Number of blocks.\n bottleneck : bool, default None\n Whether to use a bottleneck or simple block in units.\n conv1_stride : bool, default True\n Whether to use stride in the first or the second convolution layer in units.\n width_scale : float, default 1.0\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n if bottleneck is None:\n bottleneck = (blocks >= 50)\n\n if blocks == 10:\n layers = [1, 1, 1, 1]\n elif blocks == 12:\n layers = [2, 1, 1, 1]\n elif blocks == 14 and not bottleneck:\n layers = [2, 2, 1, 1]\n elif (blocks == 14) and bottleneck:\n layers = [1, 1, 1, 1]\n elif blocks == 16:\n layers = [2, 2, 2, 1]\n elif blocks == 18:\n layers = [2, 2, 2, 2]\n elif (blocks == 26) and not bottleneck:\n layers = [3, 3, 3, 3]\n elif (blocks == 26) and bottleneck:\n layers = [2, 2, 2, 2]\n elif blocks == 34:\n layers = [3, 4, 6, 3]\n elif (blocks == 38) and bottleneck:\n layers = [3, 3, 3, 3]\n elif blocks == 50:\n layers = [3, 4, 6, 3]\n elif blocks == 101:\n layers = [3, 4, 23, 3]\n elif blocks == 152:\n layers = [3, 8, 36, 3]\n elif blocks == 200:\n layers = [3, 24, 36, 3]\n else:\n raise ValueError(\"Unsupported ResNet with number of blocks: {}\".format(blocks))\n\n if bottleneck:\n assert (sum(layers) * 3 + 2 == blocks)\n else:\n assert (sum(layers) * 2 + 2 == blocks)\n\n init_block_channels = 64\n channels_per_layers = [64, 128, 256, 512]\n\n if bottleneck:\n bottleneck_factor = 4\n channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n if width_scale != 1.0:\n channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij\n for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]\n init_block_channels = int(init_block_channels * width_scale)\n\n net = ResNet(\n channels=channels,\n init_block_channels=init_block_channels,\n bottleneck=bottleneck,\n conv1_stride=conv1_stride,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef resnet10(**kwargs):\n \"\"\"\n ResNet-10 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=10, model_name=\"resnet10\", **kwargs)\n\n\ndef resnet12(**kwargs):\n \"\"\"\n ResNet-12 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=12, model_name=\"resnet12\", **kwargs)\n\n\ndef resnet14(**kwargs):\n \"\"\"\n ResNet-14 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=14, model_name=\"resnet14\", **kwargs)\n\n\ndef resnetbc14b(**kwargs):\n \"\"\"\n ResNet-BC-14b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model (bottleneck compressed).\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=14, bottleneck=True, conv1_stride=False, model_name=\"resnetbc14b\", **kwargs)\n\n\ndef resnet16(**kwargs):\n \"\"\"\n ResNet-16 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=16, model_name=\"resnet16\", **kwargs)\n\n\ndef resnet18_wd4(**kwargs):\n \"\"\"\n ResNet-18 model with 0.25 width scale from 'Deep Residual Learning for Image Recognition,'\n https://arxiv.org/abs/1512.03385. It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=18, width_scale=0.25, model_name=\"resnet18_wd4\", **kwargs)\n\n\ndef resnet18_wd2(**kwargs):\n \"\"\"\n ResNet-18 model with 0.5 width scale from 'Deep Residual Learning for Image Recognition,'\n https://arxiv.org/abs/1512.03385. It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=18, width_scale=0.5, model_name=\"resnet18_wd2\", **kwargs)\n\n\ndef resnet18_w3d4(**kwargs):\n \"\"\"\n ResNet-18 model with 0.75 width scale from 'Deep Residual Learning for Image Recognition,'\n https://arxiv.org/abs/1512.03385. It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=18, width_scale=0.75, model_name=\"resnet18_w3d4\", **kwargs)\n\n\ndef resnet18(**kwargs):\n \"\"\"\n ResNet-18 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=18, model_name=\"resnet18\", **kwargs)\n\n\ndef resnet26(**kwargs):\n \"\"\"\n ResNet-26 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=26, bottleneck=False, model_name=\"resnet26\", **kwargs)\n\n\ndef resnetbc26b(**kwargs):\n \"\"\"\n ResNet-BC-26b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model (bottleneck compressed).\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=26, bottleneck=True, conv1_stride=False, model_name=\"resnetbc26b\", **kwargs)\n\n\ndef resnet34(**kwargs):\n \"\"\"\n ResNet-34 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=34, model_name=\"resnet34\", **kwargs)\n\n\ndef resnetbc38b(**kwargs):\n \"\"\"\n ResNet-BC-38b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model (bottleneck compressed).\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=38, bottleneck=True, conv1_stride=False, model_name=\"resnetbc38b\", **kwargs)\n\n\ndef resnet50(**kwargs):\n \"\"\"\n ResNet-50 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=50, model_name=\"resnet50\", **kwargs)\n\n\ndef resnet50b(**kwargs):\n \"\"\"\n ResNet-50 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image\n Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=50, conv1_stride=False, model_name=\"resnet50b\", **kwargs)\n\n\ndef resnet101(**kwargs):\n \"\"\"\n ResNet-101 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=101, model_name=\"resnet101\", **kwargs)\n\n\ndef resnet101b(**kwargs):\n \"\"\"\n ResNet-101 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image\n Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=101, conv1_stride=False, model_name=\"resnet101b\", **kwargs)\n\n\ndef resnet152(**kwargs):\n \"\"\"\n ResNet-152 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=152, model_name=\"resnet152\", **kwargs)\n\n\ndef resnet152b(**kwargs):\n \"\"\"\n ResNet-152 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image\n Recognition,' https://arxiv.org/abs/1512.03385.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=152, conv1_stride=False, model_name=\"resnet152b\", **kwargs)\n\n\ndef resnet200(**kwargs):\n \"\"\"\n ResNet-200 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.\n It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=200, model_name=\"resnet200\", **kwargs)\n\n\ndef resnet200b(**kwargs):\n \"\"\"\n ResNet-200 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image\n Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.torch/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_resnet(blocks=200, conv1_stride=False, model_name=\"resnet200b\", **kwargs)\n\n\ndef _calc_width(net):\n import numpy as np\n net_params = filter(lambda p: p.requires_grad, net.parameters())\n weight_count = 0\n for param in net_params:\n weight_count += np.prod(param.size())\n return weight_count\n\n\ndef _test():\n import torch\n\n pretrained = False\n\n models = [\n resnet10,\n resnet12,\n resnet14,\n resnetbc14b,\n resnet16,\n resnet18_wd4,\n resnet18_wd2,\n resnet18_w3d4,\n resnet18,\n resnet26,\n resnetbc26b,\n resnet34,\n resnetbc38b,\n resnet50,\n resnet50b,\n resnet101,\n resnet101b,\n resnet152,\n resnet152b,\n resnet200,\n resnet200b,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n # net.train()\n net.eval()\n weight_count = _calc_width(net)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != resnet10 or weight_count == 5418792)\n assert (model != resnet12 or weight_count == 5492776)\n assert (model != resnet14 or weight_count == 5788200)\n assert (model != resnetbc14b or weight_count == 10064936)\n assert (model != resnet16 or weight_count == 6968872)\n assert (model != resnet18_wd4 or weight_count == 3937400)\n assert (model != resnet18_wd2 or weight_count == 5804296)\n assert (model != resnet18_w3d4 or weight_count == 8476056)\n assert (model != resnet18 or weight_count == 11689512)\n assert (model != resnet26 or weight_count == 17960232)\n assert (model != resnetbc26b or weight_count == 15995176)\n assert (model != resnet34 or weight_count == 21797672)\n assert (model != resnetbc38b or weight_count == 21925416)\n assert (model != resnet50 or weight_count == 25557032)\n assert (model != resnet50b or weight_count == 25557032)\n assert (model != resnet101 or weight_count == 44549160)\n assert (model != resnet101b or weight_count == 44549160)\n assert (model != resnet152 or weight_count == 60192808)\n assert (model != resnet152b or weight_count == 60192808)\n assert (model != resnet200 or weight_count == 64673832)\n assert (model != resnet200b or weight_count == 64673832)\n\n x = torch.randn(1, 3, 224, 224)\n y = net(x)\n y.sum().backward()\n assert (tuple(y.size()) == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n",
"\"\"\"\n SVHN classification dataset.\n\"\"\"\n\nimport os\nimport hashlib\nimport numpy as np\nfrom .cifar10_cls_dataset import CIFAR10MetaInfo\n\n\ndef _download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True):\n \"\"\"Download an given URL\n\n Parameters\n ----------\n url : str\n URL to download\n path : str, optional\n Destination path to store downloaded file. By default stores to the\n current directory with same name as in url.\n overwrite : bool, optional\n Whether to overwrite destination file if already exists.\n sha1_hash : str, optional\n Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified\n but doesn't match.\n retries : integer, default 5\n The number of times to attempt the download in case of failure or non 200 return codes\n verify_ssl : bool, default True\n Verify SSL certificates.\n\n Returns\n -------\n str\n The file path of the downloaded file.\n \"\"\"\n import warnings\n try:\n import requests\n except ImportError:\n class requests_failed_to_import(object):\n pass\n requests = requests_failed_to_import\n\n if path is None:\n fname = url.split(\"/\")[-1]\n # Empty filenames are invalid\n assert fname, \"Can't construct file-name from this URL. Please set the `path` option manually.\"\n else:\n path = os.path.expanduser(path)\n if os.path.isdir(path):\n fname = os.path.join(path, url.split(\"/\")[-1])\n else:\n fname = path\n assert retries >= 0, \"Number of retries should be at least 0\"\n\n if not verify_ssl:\n warnings.warn(\n \"Unverified HTTPS request is being made (verify_ssl=False). \"\n \"Adding certificate verification is strongly advised.\")\n\n if overwrite or not os.path.exists(fname) or (sha1_hash and not _check_sha1(fname, sha1_hash)):\n dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname)))\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n while retries + 1 > 0:\n # Disable pyling too broad Exception\n # pylint: disable=W0703\n try:\n print(\"Downloading {} from {}...\".format(fname, url))\n r = requests.get(url, stream=True, verify=verify_ssl)\n if r.status_code != 200:\n raise RuntimeError(\"Failed downloading url {}\".format(url))\n with open(fname, \"wb\") as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n if sha1_hash and not _check_sha1(fname, sha1_hash):\n raise UserWarning(\"File {} is downloaded but the content hash does not match.\"\n \" The repo may be outdated or download may be incomplete. \"\n \"If the 'repo_url' is overridden, consider switching to \"\n \"the default repo.\".format(fname))\n break\n except Exception as e:\n retries -= 1\n if retries <= 0:\n raise e\n else:\n print(\"download failed, retrying, {} attempt{} left\"\n .format(retries, \"s\" if retries > 1 else \"\"))\n\n return fname\n\n\ndef _check_sha1(filename, sha1_hash):\n \"\"\"Check whether the sha1 hash of the file content matches the expected hash.\n\n Parameters\n ----------\n filename : str\n Path to the file.\n sha1_hash : str\n Expected sha1 hash in hexadecimal digits.\n\n Returns\n -------\n bool\n Whether the file content matches the expected hash.\n \"\"\"\n sha1 = hashlib.sha1()\n with open(filename, \"rb\") as f:\n while True:\n data = f.read(1048576)\n if not data:\n break\n sha1.update(data)\n\n return sha1.hexdigest() == sha1_hash\n\n\ndef get_svhn_data(root,\n mode):\n \"\"\"\n SVHN image classification dataset from http://ufldl.stanford.edu/housenumbers/.\n Each sample is an image (in 3D NDArray) with shape (32, 32, 3).\n Note: The SVHN dataset assigns the label `10` to the digit `0`. However, in this Dataset,\n we assign the label `0` to the digit `0`.\n\n Parameters\n ----------\n root : str\n Path to temp folder for storing data.\n mode : str\n 'train', 'val', or 'test'.\n \"\"\"\n _train_data = [(\"http://ufldl.stanford.edu/housenumbers/train_32x32.mat\", \"train_32x32.mat\",\n \"e6588cae42a1a5ab5efe608cc5cd3fb9aaffd674\")]\n _test_data = [(\"http://ufldl.stanford.edu/housenumbers/test_32x32.mat\", \"test_32x32.mat\",\n \"29b312382ca6b9fba48d41a7b5c19ad9a5462b20\")]\n\n if any(not os.path.exists(path) or not _check_sha1(path, sha1) for path, sha1 in\n ((os.path.join(root, name), sha1) for _, name, sha1 in _train_data + _test_data)):\n for url, _, sha1 in _train_data + _test_data:\n _download(url=url, path=root, sha1_hash=sha1)\n\n if mode == \"train\":\n data_files = _train_data[0]\n else:\n data_files = _test_data[0]\n\n import scipy.io as sio\n loaded_mat = sio.loadmat(os.path.join(root, data_files[1]))\n\n data = loaded_mat[\"X\"]\n data = np.transpose(data, (3, 0, 1, 2))\n label = loaded_mat[\"y\"].astype(np.int32).squeeze()\n np.place(label, label == 10, 0)\n\n return data, label\n\n\nclass SVHNMetaInfo(CIFAR10MetaInfo):\n def __init__(self):\n super(SVHNMetaInfo, self).__init__()\n self.label = \"SVHN\"\n self.root_dir_name = \"svhn\"\n self.dataset_class = None\n self.num_training_samples = 73257\n self.train_generator = svhn_train_generator\n self.val_generator = svhn_val_generator\n self.test_generator = svhn_val_generator\n\n\ndef svhn_train_generator(data_generator,\n ds_metainfo,\n batch_size):\n \"\"\"\n Create image generator for training subset.\n\n Parameters:\n ----------\n data_generator : ImageDataGenerator\n Image transform sequence.\n ds_metainfo : DatasetMetaInfo\n ImageNet-1K dataset metainfo.\n batch_size : int\n Batch size.\n\n Returns\n -------\n Sequential\n Image transform sequence.\n \"\"\"\n assert(ds_metainfo is not None)\n x_train, y_train = get_svhn_data(\n root=ds_metainfo.root_dir_path,\n mode=\"train\")\n generator = data_generator.flow(\n x=x_train,\n y=y_train,\n batch_size=batch_size,\n shuffle=False)\n return generator\n\n\ndef svhn_val_generator(data_generator,\n ds_metainfo,\n batch_size):\n \"\"\"\n Create image generator for validation subset.\n\n Parameters:\n ----------\n data_generator : ImageDataGenerator\n Image transform sequence.\n ds_metainfo : DatasetMetaInfo\n ImageNet-1K dataset metainfo.\n batch_size : int\n Batch size.\n\n Returns\n -------\n Sequential\n Image transform sequence.\n \"\"\"\n assert(ds_metainfo is not None)\n x_test, y_test = get_svhn_data(\n root=ds_metainfo.root_dir_path,\n mode=\"val\")\n generator = data_generator.flow(\n x=x_test,\n y=y_test,\n batch_size=batch_size,\n shuffle=False)\n return generator\n"
] |
[
[
"numpy.zeros"
],
[
"numpy.expand_dims",
"numpy.min",
"numpy.linalg.inv",
"numpy.linalg.norm",
"numpy.stack",
"numpy.ones",
"numpy.mean",
"numpy.transpose",
"numpy.sum"
],
[
"numpy.prod"
],
[
"tensorflow.keras.backend.get_value",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.Sequential"
],
[
"tensorflow.clip_by_value",
"tensorflow.keras.backend.get_value",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.Sequential"
],
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.nn.init.constant_",
"torch.randn",
"torch.nn.init.kaiming_uniform_",
"torch.nn.Linear",
"torch.nn.AvgPool2d"
],
[
"tensorflow.nn.relu",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.nn.sigmoid",
"tensorflow.keras.layers.Dense",
"tensorflow.global_variables_initializer",
"tensorflow.reset_default_graph",
"tensorflow.Session",
"tensorflow.trainable_variables"
],
[
"tensorflow.keras.backend.get_value",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.keras.Sequential"
],
[
"numpy.array"
],
[
"numpy.load",
"numpy.array",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.array"
],
[
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.randn",
"torch.nn.init.kaiming_uniform_",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.ReLU"
],
[
"numpy.place",
"numpy.transpose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gely/coseis
|
[
"8b608a5f7a5eab570bbd17a6d6caf278e787ada0"
] |
[
"cst/waveform.py"
] |
[
"\"\"\"\nWaveform data tools.\n\"\"\"\nimport numpy\n\n\ndef csmip_vol2(filename, max_year=2050):\n \"\"\"\n Read strong motion record in CSMIP Volume 2 format.\n\n California Strong Motion Instrumentation Program:\n http://www.strongmotioncenter.org\n \"\"\"\n\n # read file\n ss = open(filename).readlines()\n j = 0\n\n # text header\n t = ss[j+4][59:69]\n m = int(ss[j+4][49:51])\n d = int(ss[j+4][52:54])\n y = int(ss[j+4][55:57]) + 2000\n if y > max_year:\n y -= 100\n time = '%04d/%02d/%02dT%s' % (y, m, d, t)\n lon = ss[j+5][29:36]\n lat = ss[j+5][20:26]\n data = {'time': time, 'lon': lon, 'lat': lat}\n\n # loop over channels\n while j < len(ss):\n\n # integer-value header\n j += 25\n ihdr = []\n n = 5\n while len(ihdr) < 100:\n ihdr += [int(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)]\n j += 1\n orient = ihdr[26]\n\n # real-value header\n rhdr = []\n n = 10\n while len(rhdr) < 100:\n rhdr += [float(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)]\n j += 1\n data['dt'] = rhdr[52]\n\n # data\n n = 10\n for w in 'avd':\n m = int(ss[j][:6])\n v = []\n j += 1\n while len(v) < m:\n v += [float(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)]\n j += 1\n k = '%s%03d' % (w, orient)\n data[k] = numpy.array(v)\n\n # trailer\n j += 1\n\n return data\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
acq4/acq4
|
[
"c77636a76d68ffa1bc7dbd41edc522e523b909b8",
"c77636a76d68ffa1bc7dbd41edc522e523b909b8",
"c77636a76d68ffa1bc7dbd41edc522e523b909b8"
] |
[
"acq4/devices/Sensapex.py",
"acq4/devices/MultiClamp/multiclamp.py",
"acq4/devices/Stage/calibration.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport numpy as np\nimport pyqtgraph as pg\nfrom pyqtgraph import ptime, Transform3D, solve3DTransform\n\nfrom acq4.util import Qt\nfrom acq4.drivers.sensapex import UMP\nfrom .Stage import Stage, MoveFuture, ManipulatorAxesCalibrationWindow, StageAxesCalibrationWindow\n\n\nclass Sensapex(Stage):\n \"\"\"\n A Sensapex manipulator.\n \"\"\"\n\n _sigRestartUpdateTimer = Qt.Signal(object) # timeout duration\n\n devices = {}\n\n def __init__(self, man, config: dict, name):\n self.devid = config.get(\"deviceId\")\n config.setdefault(\"isManipulator\", self.devid < 20)\n self.scale = config.pop(\"scale\", (1e-6, 1e-6, 1e-6))\n self.xPitch = config.pop(\"xPitch\", 0) # angle of x-axis. 0=parallel to xy plane, 90=pointing downward\n self.maxMoveError = config.pop(\"maxError\", 1e-6)\n self._force_linear_movement = config.get(\"forceLinearMovement\", False)\n\n address = config.pop(\"address\", None)\n address = None if address is None else address.encode()\n group = config.pop(\"group\", None)\n ump = UMP.get_ump(address=address, group=group)\n # create handle to this manipulator\n self.dev = ump.get_device(self.devid)\n\n Stage.__init__(self, man, config, name)\n # Read position updates on a timer to rate-limit\n self._updateTimer = Qt.QTimer()\n self._updateTimer.timeout.connect(self._getPosition)\n self._lastUpdate = 0\n\n self._sigRestartUpdateTimer.connect(self._restartUpdateTimer)\n\n # note: n_axes is used in cases where the device is not capable of answering this on its own\n if \"nAxes\" in config:\n self.dev.set_n_axes(config[\"nAxes\"])\n if \"maxAcceleration\" in config:\n self.dev.set_max_acceleration(config[\"maxAcceleration\"])\n\n self.dev.add_callback(self._positionChanged)\n\n # force cache update for this device.\n # This should also verify that we have a valid device ID\n self.dev.get_pos()\n\n self._lastMove = None\n man.sigAbortAll.connect(self.stop)\n\n # clear cached position for this device and re-read to generate an initial position update\n self._lastPos = None\n self.getPosition(refresh=True)\n\n # TODO: set any extra parameters specified in the config\n Sensapex.devices[self.devid] = self\n\n def axes(self):\n return \"x\", \"y\", \"z\"\n\n def capabilities(self):\n \"\"\"Return a structure describing the capabilities of this device\"\"\"\n if \"capabilities\" in self.config:\n return self.config[\"capabilities\"]\n else:\n return {\n \"getPos\": (True, True, True),\n \"setPos\": (True, True, True),\n \"limits\": (False, False, False),\n }\n\n def axisTransform(self):\n if self._axisTransform is None:\n # sensapex manipulators do not have orthogonal axes, so we set up a 3D transform to compensate:\n a = self.xPitch * np.pi / 180.0\n s = self.scale\n pts1 = np.array([ # unit vector in sensapex space\n [0, 0, 0],\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n ])\n pts2 = np.array([ # corresponding vector in global space\n [0, 0, 0],\n [s[0] * np.cos(a), 0, -s[0] * np.sin(a)],\n [0, s[1], 0],\n [0, 0, s[2]],\n ])\n tr = solve3DTransform(pts1, pts2)\n tr[3, 3] = 1\n self._axisTransform = Transform3D(tr)\n self._inverseAxisTransform = None\n return self._axisTransform\n\n def stop(self):\n \"\"\"Stop the manipulator immediately.\n \"\"\"\n with self.lock:\n self.dev.stop()\n self._lastMove = None\n\n def _getPosition(self):\n # Called by superclass when user requests position refresh\n with self.lock:\n # using timeout=0 forces read from cache (the monitor thread ensures\n # these values are up to date)\n pos = self.dev.get_pos(timeout=0)[:3]\n self._lastUpdate = ptime.time()\n if self._lastPos is not None:\n dif = np.linalg.norm(np.array(pos, dtype=float) - np.array(self._lastPos, dtype=float))\n\n # do not report changes < 100 nm\n if self._lastPos is None or dif > 0.1:\n self._lastPos = pos\n emit = True\n else:\n emit = False\n\n if emit:\n # don't emit signal while locked\n self.posChanged(pos)\n\n return pos\n\n def _positionChanged(self, dev, newPos, oldPos):\n # called by driver poller when position has changed\n now = ptime.time()\n # rate limit updates to 10 Hz\n wait = 100e-3 - (now - self._lastUpdate)\n if wait > 0:\n self._sigRestartUpdateTimer.emit(wait)\n else:\n self._getPosition()\n\n def _restartUpdateTimer(self, wait):\n self._updateTimer.start(int(wait * 1000))\n\n def targetPosition(self):\n with self.lock:\n if self._lastMove is None or self._lastMove.isDone():\n return self.getPosition()\n else:\n return self._lastMove.targetPos\n\n def quit(self):\n Sensapex.devices.pop(self.devid, None)\n if len(Sensapex.devices) == 0:\n UMP.get_ump().poller.stop()\n Stage.quit(self)\n\n def _move(self, pos, speed, linear):\n with self.lock:\n speed = self._interpretSpeed(speed)\n self._lastMove = SensapexMoveFuture(self, pos, speed, self._force_linear_movement or linear)\n return self._lastMove\n\n def deviceInterface(self, win):\n return SensapexInterface(self, win)\n\n\nclass SensapexMoveFuture(MoveFuture):\n \"\"\"Provides access to a move-in-progress on a Sensapex manipulator.\n \"\"\"\n\n def __init__(self, dev, pos, speed, linear):\n MoveFuture.__init__(self, dev, pos, speed)\n self._linear = linear\n self._interrupted = False\n self._errorMsg = None\n self._finished = False\n self._moveReq = self.dev.dev.goto_pos(pos, speed * 1e6, simultaneous=linear, linear=linear)\n self._checked = False\n\n def wasInterrupted(self):\n \"\"\"Return True if the move was interrupted before completing.\n \"\"\"\n return self._moveReq.interrupted\n\n def isDone(self):\n \"\"\"Return True if the move is complete.\n \"\"\"\n return self._moveReq.finished\n\n def _checkError(self):\n if self._checked or not self.isDone():\n return\n\n # interrupted?\n if self._moveReq.interrupted:\n self._errorMsg = self._moveReq.interrupt_reason\n else:\n # did we reach target?\n pos = self._moveReq.last_pos\n dif = np.linalg.norm(np.array(pos) - np.array(self.targetPos))\n if dif > self.dev.maxMoveError * 1e9: # require 1um accuracy\n # missed\n self._errorMsg = \"{} stopped before reaching target (start={}, target={}, position={}, dif={}, speed={}).\".format(\n self.dev.name(), self.startPos, self.targetPos, pos, dif, self.speed\n )\n\n self._checked = True\n\n def wait(self, timeout=None, updates=False):\n \"\"\"Block until the move has completed, has been interrupted, or the\n specified timeout has elapsed.\n\n If *updates* is True, process Qt events while waiting.\n\n If the move did not complete, raise an exception.\n \"\"\"\n if updates is False:\n # if we don't need gui updates, then block on the finished_event for better performance\n if not self._moveReq.finished_event.wait(timeout=timeout):\n raise self.Timeout(\"Timed out waiting for %s move to complete.\" % self.dev.name())\n self._raiseError()\n else:\n return MoveFuture.wait(self, timeout=timeout, updates=updates)\n\n def errorMessage(self):\n self._checkError()\n return self._errorMsg\n\n\n# class SensapexGUI(StageInterface):\n# def __init__(self, dev, win):\n# StageInterface.__init__(self, dev, win)\n#\n# # Insert Sensapex-specific controls into GUI\n# self.zeroBtn = Qt.QPushButton('Zero position')\n# self.layout.addWidget(self.zeroBtn, self.nextRow, 0, 1, 2)\n# self.nextRow += 1\n#\n# self.psGroup = Qt.QGroupBox('Rotary Controller')\n# self.layout.addWidget(self.psGroup, self.nextRow, 0, 1, 2)\n# self.nextRow += 1\n#\n# self.psLayout = Qt.QGridLayout()\n# self.psGroup.setLayout(self.psLayout)\n# self.speedLabel = Qt.QLabel('Speed')\n# self.speedSpin = SpinBox(value=self.dev.userSpeed, suffix='m/turn', siPrefix=True, dec=True, limits=[1e-6, 10e-3])\n# self.psLayout.addWidget(self.speedLabel, 0, 0)\n# self.psLayout.addWidget(self.speedSpin, 0, 1)\n#\n# self.zeroBtn.clicked.connect(self.dev.dev.zeroPosition)\n# # UNSAFE lambdas with self prevent GC\n# # self.speedSpin.valueChanged.connect(lambda v: self.dev.setDefaultSpeed(v))\n\n\nclass SensapexInterface(Qt.QWidget):\n def __init__(self, dev, win):\n Qt.QWidget.__init__(self)\n self.win = win\n self.dev = dev\n\n self.layout = Qt.QGridLayout()\n self.setLayout(self.layout)\n self.axCtrls = {}\n self.posLabels = {}\n\n self.positionLabelWidget = Qt.QWidget()\n self.layout.addWidget(self.positionLabelWidget, 0, 0)\n self.positionLabelLayout = Qt.QGridLayout()\n self.positionLabelWidget.setLayout(self.positionLabelLayout)\n self.positionLabelLayout.setContentsMargins(0, 0, 0, 0)\n\n self.globalLabel = Qt.QLabel(\"global\")\n self.positionLabelLayout.addWidget(self.globalLabel, 0, 1)\n self.stageLabel = Qt.QLabel(\"stage\")\n self.positionLabelLayout.addWidget(self.stageLabel, 0, 2)\n\n self.btnContainer = Qt.QWidget()\n self.btnLayout = Qt.QGridLayout()\n self.btnContainer.setLayout(self.btnLayout)\n self.layout.addWidget(self.btnContainer, self.layout.rowCount(), 0)\n self.btnLayout.setContentsMargins(0, 0, 0, 0)\n\n self.goHomeBtn = Qt.QPushButton(\"Home\")\n self.btnLayout.addWidget(self.goHomeBtn, 0, 0)\n self.goHomeBtn.clicked.connect(self.goHomeClicked)\n\n self.setHomeBtn = Qt.QPushButton(\"Set Home\")\n self.btnLayout.addWidget(self.setHomeBtn, 0, 1)\n self.setHomeBtn.clicked.connect(self.setHomeClicked)\n\n self.calibrateBtn = Qt.QPushButton(\"Calibrate\")\n self.btnLayout.addWidget(self.calibrateBtn, 0, 2)\n self.calibrateBtn.clicked.connect(self.calibrateClicked)\n\n self.stopBtn = Qt.QPushButton(\"Stop!\")\n self.btnLayout.addWidget(self.stopBtn, 1, 0)\n self.stopBtn.clicked.connect(self.stopClicked)\n self.stopBtn.setStyleSheet(\"QPushButton {background-color:red; color:white}\")\n\n self.calibrateZeroBtn = Qt.QPushButton(\"Run Zero Calibration\")\n self.btnLayout.addWidget(self.calibrateZeroBtn, 1, 1)\n self.calibrateZeroBtn.clicked.connect(self.calibrateZeroClicked)\n\n self.calibrateLoadBtn = Qt.QPushButton(\"Run Load Calibration\")\n self.btnLayout.addWidget(self.calibrateLoadBtn, 1, 2)\n self.calibrateLoadBtn.clicked.connect(self.calibrateLoadClicked)\n\n self.softStartValue = Qt.QLineEdit()\n\n self.btnLayout.addWidget(self.softStartValue, 2, 1)\n self.softStartValue.editingFinished.connect(self.softstartChanged)\n self.getSoftStartValue()\n\n self.softStartBtn = Qt.QPushButton(\"Soft Start Enabled\")\n self.softStartBtn.setCheckable(True)\n self.softStartBtn.setStyleSheet(\"QPushButton:checked{background-color:lightgreen; color:black}\")\n self.btnLayout.addWidget(self.softStartBtn, 2, 0)\n self.softStartBtn.clicked.connect(self.softstartClicked)\n self.getSoftStartState()\n\n self.calibrateWindow = None\n\n cap = dev.capabilities()\n for axis, axisName in enumerate(self.dev.axes()):\n if cap[\"getPos\"][axis]:\n axLabel = Qt.QLabel(axisName)\n axLabel.setMaximumWidth(15)\n globalPosLabel = Qt.QLabel(\"0\")\n stagePosLabel = Qt.QLabel(\"0\")\n self.posLabels[axis] = (globalPosLabel, stagePosLabel)\n widgets = [axLabel, globalPosLabel, stagePosLabel]\n if cap[\"limits\"][axis]:\n minCheck = Qt.QCheckBox(\"Min:\")\n minCheck.tag = (axis, 0)\n maxCheck = Qt.QCheckBox(\"Max:\")\n maxCheck.tag = (axis, 1)\n self.limitChecks[axis] = (minCheck, maxCheck)\n widgets.extend([minCheck, maxCheck])\n for check in (minCheck, maxCheck):\n check.clicked.connect(self.limitCheckClicked)\n\n nextRow = self.positionLabelLayout.rowCount()\n for i, w in enumerate(widgets):\n self.positionLabelLayout.addWidget(w, nextRow, i)\n self.axCtrls[axis] = widgets\n self.dev.sigPositionChanged.connect(self.update)\n\n self.update()\n\n def update(self):\n globalPos = self.dev.globalPosition()\n stagePos = self.dev.getPosition()\n for i in self.posLabels:\n text = pg.siFormat(globalPos[i], suffix=\"m\", precision=5)\n self.posLabels[i][0].setText(text)\n self.posLabels[i][1].setText(str(stagePos[i]))\n\n def goHomeClicked(self):\n self.dev.goHome()\n\n def setHomeClicked(self):\n self.dev.setHomePosition()\n\n def calibrateClicked(self):\n if self.calibrateWindow is None:\n if self.dev.isManipulator:\n self.calibrateWindow = ManipulatorAxesCalibrationWindow(self.dev)\n else:\n self.calibrateWindow = StageAxesCalibrationWindow(self.dev)\n self.calibrateWindow.show()\n self.calibrateWindow.raise_()\n\n def calibrateZeroClicked(self):\n self.dev.dev.calibrate_zero_position()\n\n def calibrateLoadClicked(self):\n self.dev.dev.calibrate_load()\n\n def stopClicked(self):\n self.dev.dev.stop()\n\n def getSoftStartState(self):\n state = self.dev.dev.get_soft_start_state()\n\n if state == 1:\n self.softStartBtn.setChecked(True)\n self.softStartBtn.setText(\"Soft Start Enabled\")\n self.softStartValue.setVisible(True)\n self.getSoftStartValue()\n return True\n\n self.softStartBtn.setChecked(False)\n self.softStartBtn.setText(\"Soft Start Disabled\")\n self.softStartValue.setVisible(False)\n return False\n\n def softstartClicked(self):\n checked = self.getSoftStartState()\n if checked:\n self.dev.dev.set_soft_start_state(0)\n else:\n self.dev.dev.set_soft_start_state(1)\n\n self.getSoftStartState()\n\n def softstartChanged(self):\n value = int(self.softStartValue.text())\n self.dev.dev.set_soft_start_value(value)\n\n def getSoftStartValue(self):\n value = self.dev.dev.get_soft_start_value()\n self.softStartValue.setText(str(value))\n",
"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom __future__ import with_statement\n\nimport time\n\nimport numpy as np\n\nfrom acq4.Manager import logMsg\nfrom acq4.devices.PatchClamp import PatchClamp\nfrom pyqtgraph import multiprocess\nfrom acq4.util.Mutex import Mutex\nfrom pyqtgraph.metaarray import MetaArray, axis\nfrom .DeviceGui import MCDeviceGui\nfrom .taskGUI import MultiClampTaskGui\nfrom ..Device import DeviceTask\nfrom ...util.debug import printExc\n\n\nclass MultiClamp(PatchClamp):\n\n # inherited signals: sigStateChanged, sigHoldingChanged\n\n # remote process used to connect to commander from 32-bit python\n proc = None\n\n def __init__(self, dm, config, name):\n PatchClamp.__init__(self, dm, config, name)\n self.config = config\n self.index = None\n self.devRackGui = None\n self.mc = None\n\n # Cache MC parameters because they are very expensive to retrieve\n # (especially with multiple channels)\n self._paramCache = {}\n\n # device parameters that are expected to change when the clamp mode changes\n self.mode_dependent_params = [\n 'PrimarySignal', 'SecondarySignal',\n 'PrimarySignalGain', 'SecondarySignalGain',\n 'Holding', 'HoldingEnable',\n 'PipetteOffset',\n ]\n\n self.stateLock = Mutex(Mutex.Recursive) ## only for locking self.lastState and self.lastMode\n self.lastState = {}\n self.lastMode = None\n self._switchingToMode = None\n\n # default holding state\n self.holding = {\n 'VC': -50e-3,\n 'IC': 0.0,\n 'I=0': 0.0\n }\n\n # Get a handle to the multiclamp driver object, whether that is hosted locally or in a remote process.\n executable = self.config.get('pythonExecutable', None)\n if executable is not None:\n # Run a remote python process to connect to the MC commander.\n # This is used on 64-bit systems where the MC connection must be run with\n # 32-bit python.\n if MultiClamp.proc is False:\n raise Exception(\"Already connected to multiclamp locally; cannot connect via remote process at the same time.\")\n if MultiClamp.proc is None:\n MultiClamp.proc = multiprocess.Process(executable=executable, copySysPath=False)\n try:\n self.proc.mc_mod = self.proc._import('acq4.drivers.MultiClamp')\n self.proc.mc_mod._setProxyOptions(deferGetattr=False)\n except:\n MultiClamp.proc.close()\n MultiClamp.proc = None\n raise\n mcmod = self.proc.mc_mod\n else:\n if MultiClamp.proc not in (None, False):\n raise Exception(\"Already connected to multiclamp via remote process; cannot connect locally at the same time.\")\n else:\n # don't allow remote process to be used for other channels.\n MultiClamp.proc = False\n\n try:\n import acq4.drivers.MultiClamp as MultiClampDriver\n except RuntimeError as exc:\n if \"32-bit\" in exc.message:\n raise Exception(\"MultiClamp commander does not support access by 64-bit processes. To circumvent this problem, \"\n \"Use the 'pythonExecutable' device configuration option to connect via a 32-bit python instead.\")\n else:\n raise\n mcmod = MultiClampDriver\n\n # Ask driver to use a specific DLL if specified in config\n dllPath = self.config.get('dllPath', None)\n if dllPath is not None:\n mcmod.getAxlib(dllPath)\n\n # Create driver instance\n mc = mcmod.MultiClamp.instance()\n\n # get a handle to our specific multiclamp channel\n if executable is not None:\n self.mc = mc.getChannel(self.config['channelID'], multiprocess.proxy(self.mcUpdate, callSync='off'))\n else:\n self.mc = mc.getChannel(self.config['channelID'], self.mcUpdate)\n \n ## wait for first update..\n start = time.time()\n while self.mc.getState() is None:\n time.sleep(0.1)\n if time.time() - start > 10:\n raise Exception(\"Timed out waiting for first update from multi clamp commander.\")\n \n print(\"Created MultiClamp device\", self.config['channelID'])\n\n ## set configured holding values\n if 'vcHolding' in self.config:\n self.holding['VC'] = self.config['vcHolding']\n if 'icHolding' in self.config:\n self.holding['IC'] = self.config['icHolding']\n\n ## Set up default MC settings for each mode, then leave MC in I=0 mode\n # look for 'defaults', followed by 'settings' (for backward compatibility)\n defaults = self.config.get('defaults', self.config.get('settings', None))\n for mode in ['IC', 'VC']:\n self.setMode(mode) # Set mode even if we have no parameters to set;\n # this ensures that self.lastState is filled.\n if defaults is not None and mode in defaults:\n self.mc.setParams(defaults[mode])\n self.setMode('I=0') ## safest mode to leave clamp in\n\n \n dm.declareInterface(name, ['clamp'], self)\n\n def listChannels(self):\n chans = {}\n for ch in ['commandChannel', 'primaryChannel', 'secondaryChannel']:\n chans[ch] = self.config[ch].copy()\n return chans\n\n def quit(self):\n if self.mc is not None:\n self.mc.mc.quit()\n\n def mcUpdate(self, state=None, mode=None):\n \"\"\"MC state (or internal holding state) has changed, handle the update.\"\"\"\n with self.stateLock:\n self._paramCache = {} # not sure if this is necessary or helpful\n if state is None:\n state = self.lastState[mode]\n mode = state['mode']\n state['holding'] = self.holding[mode]\n self.lastState[mode] = state.copy()\n if self.lastMode != state['mode']:\n if self.lastMode is not None and state['mode'] != self._switchingToMode and state['mode'] != 'I=0':\n # User changed the mode manually; we need to update the holding value immediately.\n self.setHolding(state['mode'])\n logMsg(\"Warning: MultiClamp mode should be changed from ACQ4, not from the MultiClamp Commander window.\", msgType='error')\n\n self.lastMode = state['mode']\n self._switchingToMode = None\n\n self.sigStateChanged.emit(state)\n \n def getLastState(self, mode=None):\n \"\"\"Return the last known state for the given mode.\"\"\"\n if mode is None:\n mode = self.mc.getMode()\n with self.stateLock:\n if mode in self.lastState:\n return self.lastState[mode]\n \n def extCmdScale(self, mode):\n \"\"\"Return our best guess as to the external command sensitivity for the given mode.\"\"\"\n s = self.getLastState(mode)\n if s is not None:\n return s['extCmdScale']\n else:\n if mode == 'VC':\n return 50\n else:\n return 2.5e9\n \n def getState(self):\n return self.mc.getState()\n\n def getParam(self, param):\n if param not in self._paramCache:\n val = self.mc.getParam(param)\n if self.config.get('enableParameterCache', False):\n self._paramCache[param] = val\n return self._paramCache[param]\n\n def setParam(self, param, value):\n if self.config.get('enableParameterCache', False):\n if param in self._paramCache and self._paramCache[param] == value:\n return\n # use special setters for primary / secondary signals due to MCC bugs\n if param == 'PrimarySignal':\n self.mc.setPrimarySignal(value)\n elif param == 'SecondarySignal':\n self.mc.setSecondarySignal(value)\n else:\n self.mc.setParam(param, value)\n self._paramCache.pop(param)\n self.getParam(param)\n else:\n self.mc.setParam(param, value)\n\n def deviceInterface(self, win):\n return MCDeviceGui(self, win)\n\n def taskInterface(self, taskRunner):\n return MultiClampTaskGui(self, taskRunner)\n \n def createTask(self, cmd, parentTask):\n return MultiClampTask(self, cmd, parentTask)\n \n def getHolding(self, mode=None):\n if mode is None: ## If no mode is specified, use the current mode\n mode = self.mc.getMode()\n if mode == 'I=0':\n return 0.0\n else:\n return self.holding[mode]\n \n def setHolding(self, mode=None, value=None):\n \"\"\"Define and/or set the holding values for this device. \n\n Note--these are ACQ4-controlled holding values, NOT the holding values used by the amplifier.\n It is important to have this because the amplifier's holding values cannot be changed\n before switching modes.\n \"\"\" \n with self.dm.reserveDevices([self, self.config['commandChannel']['device']]):\n currentMode = self.mc.getMode()\n if mode is None: ## If no mode is specified, use the current mode\n mode = currentMode\n if mode == 'I=0': ## ..and if the current mode is I=0, do nothing.\n return\n if mode == 'I=0':\n raise Exception(\"Can't set holding value for I=0 mode.\")\n \n ## Update stored holding value if value is supplied\n if value is not None:\n if self.holding[mode] == value:\n return\n self.holding[mode] = value\n state = self.lastState[mode]\n state['holding'] = value\n if mode == currentMode:\n self.sigStateChanged.emit(state)\n self.sigHoldingChanged.emit(self, mode)\n \n ## We only want to set the actual DAQ channel if:\n ## - currently in I=0, or \n ## - currently in the mode that was changed\n if mode != currentMode and currentMode != 'I=0':\n return\n \n holding = self.holding[mode]\n daq = self.getDAQName('command')\n chan = self.config['commandChannel']['channel']\n daqDev = self.dm.getDevice(daq)\n s = self.extCmdScale(mode) ## use the scale for the last remembered state from this mode\n if s == 0:\n if holding == 0.0:\n s = 1.0\n else:\n raise Exception('Can not set holding value for multiclamp--external command sensitivity is disabled by commander.')\n scale = 1.0 / s\n daqDev.setChannelValue(chan, holding*scale, block=False)\n\n def autoPipetteOffset(self):\n with self.dm.reserveDevices([self]):\n self.mc.autoPipetteOffset()\n \n def autoBridgeBalance(self):\n with self.dm.reserveDevices([self]):\n self.mc.autoBridgeBal()\n\n def autoCapComp(self):\n with self.dm.reserveDevices([self]):\n self.mc.autoFastComp()\n self.mc.autoSlowComp()\n\n def listSignals(self, mode):\n return self.mc.listSignals(mode)\n \n def getMode(self):\n return self.mc.getMode()\n\n def setMode(self, mode):\n \"\"\"Set the mode for a multiclamp channel, gracefully switching between VC and IC modes.\"\"\"\n mode = mode.upper()\n if mode not in ['VC', 'IC', 'I=0']:\n raise Exception('MultiClamp mode \"%s\" not recognized.' % mode)\n\n # these parameters change with clamp mode; need to invalidate cache\n for param in self.mode_dependent_params:\n self._paramCache.pop(param, None)\n\n with self.dm.reserveDevices([self, self.config['commandChannel']['device']]):\n mcMode = self.mc.getMode()\n if mcMode == mode: ## Mode is already correct\n return\n\n ## If switching ic <-> vc, switch to i=0 first\n if (mcMode=='IC' and mode=='VC') or (mcMode=='VC' and mode=='IC'):\n self._switchingToMode = 'I=0'\n self.mc.setMode('I=0')\n mcMode = 'I=0'\n #print \" set intermediate i0\"\n if mcMode=='I=0':\n ## Set holding level before leaving I=0 mode\n #print \" set holding\"\n self.setHolding(mode)\n #print \" set mode\"\n self._switchingToMode = mode\n self.mc.setMode(mode)\n\n # MC requires 200-400 ms to mode switch; don't allow anyone else to access during that time.\n time.sleep(0.5)\n\n def getDAQName(self, channel):\n \"\"\"Return the DAQ name used by this device. (assumes there is only one DAQ for now)\"\"\"\n return self.config[channel + 'Channel']['device']\n\n\nclass MultiClampTask(DeviceTask):\n recordParams = [\n 'BridgeBalEnable',\n 'BridgeBalResist',\n 'FastCompCap',\n 'FastCompTau',\n 'Holding',\n 'HoldingEnable',\n 'LeakSubEnable',\n 'LeakSubResist',\n 'NeutralizationCap',\n 'NeutralizationEnable',\n 'OutputZeroAmplitude',\n 'OutputZeroEnable',\n 'PipetteOffset',\n 'PrimarySignalHPF',\n 'PrimarySignalLPF',\n 'RsCompBandwidth',\n 'RsCompCorrection',\n 'RsCompEnable',\n 'SlowCompCap',\n 'SlowCompTau',\n 'WholeCellCompCap',\n 'WholeCellCompEnable',\n 'WholeCellCompResist',\n ]\n\n def __init__(self, dev, cmd, parentTask):\n DeviceTask.__init__(self, dev, cmd, parentTask)\n self.cmd = cmd\n\n self.usedChannels = None\n self.daqTasks = {}\n\n ## Sanity checks and default values for command:\n \n if ('mode' not in self.cmd) or (type(self.cmd['mode']) is not str) or (self.cmd['mode'].upper() not in ['IC', 'VC', 'I=0']):\n raise Exception(\"Multiclamp command must specify clamp mode (IC, VC, or I=0)\")\n self.cmd['mode'] = self.cmd['mode'].upper()\n \n for ch in ['primary', 'secondary']:\n if ch not in self.cmd:\n self.cmd[ch] = None # defaultModes[self.cmd['mode']][ch]\n\n def getConfigOrder(self):\n \"\"\"return lists of devices that should be configured (before, after) this device\"\"\"\n return ([], [self.dev.getDAQName(\"primary\")])\n\n def configure(self):\n \"\"\"Sets the state of a remote multiclamp to prepare for a program run.\"\"\"\n #print \"mc configure\"\n \n #from debug import Profiler\n #prof = Profiler()\n ## Set state of clamp\n \n ## set holding level\n if 'holding' in self.cmd and self.cmd['mode'] != 'I=0':\n self.dev.setHolding(self.cmd['mode'], self.cmd['holding'])\n \n self.dev.setMode(self.cmd['mode'])\n if self.cmd['primary'] is not None:\n self.dev.setPrimarySignal(self.cmd['primary'])\n if self.cmd['secondary'] is not None:\n self.dev.setSecondarySignal(self.cmd['secondary'])\n\n #prof.mark(' Multiclamp: set state') ## ~300ms if the commander has to do a page-switch.\n\n if 'primaryGain' in self.cmd:\n self.dev.mc.setParam('PrimarySignalGain', self.cmd['primaryGain'])\n if 'secondaryGain' in self.cmd:\n try:\n ## this is likely to fail..\n self.dev.mc.setParam('SecondarySignalGain', self.cmd['secondaryGain'])\n except:\n printExc(\"Warning -- set secondary signal gain failed.\")\n\n #prof.mark(' Multiclamp: set gains')\n\n if 'parameters' in self.cmd:\n self.dev.mc.setParams(self.cmd['parameters'])\n\n #prof.mark(' Multiclamp: set params')\n\n #self.state = self.dev.mc.getState()\n self.state = self.dev.getLastState()\n \n #prof.mark(' Multiclamp: get state')\n \n recordState = self.cmd.get('recordState', False)\n if recordState is not False:\n if recordState is True:\n recordParams = MultiClampTask.recordParams\n elif isinstance(recordState, list):\n recordParams = recordState\n else:\n raise TypeError(\"MultiClamp task command['recordParams'] must be bool or list\")\n\n exState = self.dev.mc.getParams(recordParams)\n self.state['ClampParams'] = {}\n for k in exState:\n self.state['ClampParams'][k] = exState[k]\n \n #prof.mark(' Multiclamp: recordState?')\n \n self.holdingVal = self.dev.getHolding(self.cmd['mode'])\n \n #print \"mc configure complete\"\n #prof.mark(' Multiclamp: set holding')\n \n def getUsedChannels(self):\n \"\"\"Return a list of the channels this task uses\"\"\"\n if self.usedChannels is None:\n self.usedChannels = ['primary']\n if self.cmd.get('recordSecondary', True):\n self.usedChannels.append('secondary')\n if 'command' in self.cmd:\n self.usedChannels.append('command')\n \n return self.usedChannels \n \n def createChannels(self, daqTask):\n ## Is this the correct DAQ device for any of my channels?\n ## create needed channels + info\n ## write waveform to command channel if needed\n \n ## NOTE: no guarantee that self.configure has been run before createChannels is called! \n for ch in self.getUsedChannels():\n chConf = self.dev.config[ch+'Channel']\n \n if chConf['device'] == daqTask.devName():\n if ch == 'command':\n daqTask.addChannel(chConf['channel'], chConf['type'])\n scale = self.state['extCmdScale']\n #scale = self.dev.config['cmdScale'][self.cmd['mode']]\n if scale == 0.:\n raise Exception('Can not execute command--external command sensitivity is disabled by MultiClamp commander!', 'ExtCmdSensOff') ## The second string is a hint for modules that don't care when this happens.\n cmdData = self.cmd['command'] / scale\n daqTask.setWaveform(chConf['channel'], cmdData)\n else:\n mode = chConf.get('mode', None)\n daqTask.addChannel(chConf['channel'], chConf['type'], mode)\n self.daqTasks[ch] = daqTask\n \n def start(self):\n ## possibly nothing required here, DAQ will start recording.\n pass\n \n def isDone(self):\n ## DAQ task handles this for us.\n return True\n \n def getResult(self):\n ## Access data recorded from DAQ task\n ## create MetaArray and fill with MC state info\n channels = self.getUsedChannels()\n #print channels\n result = {}\n #result['info'] = self.state\n for ch in channels:\n chConf = self.dev.config[ch+'Channel']\n result[ch] = self.daqTasks[ch].getData(chConf['channel'])\n # print result[ch]\n nPts = result[ch]['info']['numPts']\n rate = result[ch]['info']['rate']\n if ch == 'command':\n #result[ch]['data'] = result[ch]['data'] / self.dev.config['cmdScale'][self.cmd['mode']]\n result[ch]['data'] = result[ch]['data'] * self.state['extCmdScale']\n result[ch]['name'] = 'command'\n if self.cmd['mode'] == 'VC':\n result[ch]['units'] = 'V'\n else:\n result[ch]['units'] = 'A'\n else:\n #scale = 1.0 / self.state[ch + 'Signal'][1]\n scale = self.state[ch + 'ScaleFactor']\n result[ch]['data'] = result[ch]['data'] * scale\n #result[ch]['units'] = self.state[ch + 'Signal'][2]\n result[ch]['units'] = self.state[ch + 'Units']\n result[ch]['name'] = ch\n # print result\n \n if len(result) == 0:\n return None\n \n ## Copy state from first channel (assume this is the same for all channels)\n #firstChInfo = result[channels[0]]['info']\n #for k in firstChInfo:\n #self.state[k] = firstChInfo[k]\n daqState = {}\n for ch in result:\n daqState[ch] = result[ch]['info']\n \n ## record command holding value\n if 'command' not in daqState:\n daqState['command'] = {}\n daqState['command']['holding'] = self.holdingVal\n \n #timeVals = linspace(0, float(self.state['numPts']-1) / float(self.state['rate']), self.state['numPts'])\n timeVals = np.linspace(0, float(nPts-1) / float(rate), nPts)\n chanList = [np.atleast_2d(result[x]['data']) for x in result]\n # for l in chanList:\n # print l.shape\n cols = [(result[x]['name'], result[x]['units']) for x in result]\n # print cols\n #print [a.shape for a in chanList]\n try:\n arr = np.concatenate(chanList)\n except:\n for a in chanList:\n print(a.shape)\n raise\n \n info = [axis(name='Channel', cols=cols), axis(name='Time', units='s', values=timeVals)] + [{'ClampState': self.state, 'DAQ': daqState}]\n \n taskInfo = self.cmd.copy()\n if 'command' in taskInfo:\n del taskInfo['command']\n info[-1]['Protocol'] = taskInfo\n info[-1]['startTime'] = result[list(result.keys())[0]]['info']['startTime']\n \n marr = MetaArray(arr, info=info)\n \n return marr\n \n def stop(self, abort=False):\n ## This is just a bit sketchy, but these tasks have to be stopped before the holding level can be reset.\n for ch in self.daqTasks:\n self.daqTasks[ch].stop(abort=abort)\n self.dev.setHolding()\n",
"from __future__ import print_function\n\nimport numpy as np\nimport scipy.optimize\nimport scipy.stats\nfrom six.moves import range\nfrom six.moves import zip\n\nimport pyqtgraph as pg\nfrom acq4.Manager import getManager\nfrom acq4.devices.Stage import Stage\nfrom acq4.util import Qt\nfrom acq4.util.HelpfulException import HelpfulException\nfrom acq4.util.target import Target\n\n\nclass StageAxesCalibrationWindow(Qt.QWidget):\n def __init__(self, device: Stage):\n super(StageAxesCalibrationWindow, self).__init__()\n self._dev = device\n self._camera = device.getPreferredImagingDevice()\n self._automation = AutomatedStageCalibration(device)\n self.setWindowTitle(\"Calibrate Axes for %s\" % device.name())\n self._layout = Qt.QGridLayout()\n self.setLayout(self._layout)\n self.resize(600, 300)\n\n self._viewDocsButton = Qt.QPushButton(\"View Documentation (manual only)\")\n self._layout.addWidget(self._viewDocsButton, 0, 0)\n self._viewDocsButton.clicked.connect(self._viewDocsButtonClicked)\n\n def _viewDocsButtonClicked(self, *args):\n # TODO point this at the real docs once they're done\n url = \"https://docs.google.com/document/d/1YtrAK3Gk8FvSrXxcjEd6sm7wyTAhjw4u5NtMXHhta3k/edit?usp=sharing\"\n Qt.QDesktopServices.openUrl(Qt.QUrl(url))\n\n def _eventual_todo_init(self):\n # TODO what belongs in this window?\n # * current orientation, scale and angle of stage\n # * link to documentation\n # * text which should be pasted into the devices.cfg to save this calibration :bleh:\n # * \"Save\" button that puts transform in config/devices/Stage_config/transform\n # * pop up instructions to remove manual transform if that is in the way\n # * pop that up at config-read time, too, in case things are in conflict\n\n # TODO eventually\n # * wizard instructions for current step e.g. \"move the stage to the right relative to the operator\"\n # * indication of which parts of the transform have been calibrated, or is currently being calibrated\n\n self._btnPanel = Qt.QWidget()\n self._btnPanelLayout = Qt.QHBoxLayout()\n self._btnPanelLayout.setContentsMargins(0, 0, 0, 0)\n self._btnPanel.setLayout(self._btnPanelLayout)\n self._layout.addWidget(self._btnPanel, 1, 0)\n\n self._autodetectButton = Qt.QPushButton(\"Autodetect\")\n self._btnPanelLayout.addWidget(self._autodetectButton)\n self._autodetectButton.clicked.connect(self.autodetectClicked)\n\n self._saveButton = Qt.QPushButton(\"Save\")\n self._saveButton.setEnabled(False)\n self._btnPanelLayout.addWidget(self._saveButton)\n self._saveButton.clicked.connect(self.saveClicked)\n\n def autodetectClicked(self):\n # TODO\n # * make sure Camera module is open\n # * button should toggle and be cancelable\n # * appropriate hardware should be locked\n self._automation.calibrate()\n\n def saveClicked(self):\n pass # TODO\n\n\nclass ManipulatorAxesCalibrationWindow(Qt.QWidget):\n def __init__(self, device: Stage):\n self.dev = device\n self._cammod = None\n self._camdev = None\n self.transform = None\n self.calibration = None\n\n Qt.QWidget.__init__(self)\n self.resize(600, 300)\n self.setWindowTitle(\"Calibrate Axes for %s\" % device.name())\n\n self.layout = Qt.QGridLayout()\n self.setLayout(self.layout)\n\n # tree columns:\n # stage x, y, z global x, y, z error\n self.pointTree = Qt.QTreeWidget()\n self.pointTree.setHeaderLabels([\"stage pos\", \"parent pos\", \"error\"])\n self.pointTree.setColumnCount(3)\n self.layout.addWidget(self.pointTree, 0, 0)\n self.pointTree.setColumnWidth(0, 200)\n self.pointTree.setColumnWidth(1, 200)\n self.pointTree.itemClicked.connect(self.enableRemoveBtnIfPossible)\n\n self.btnPanel = Qt.QWidget()\n self.btnPanelLayout = Qt.QHBoxLayout()\n self.btnPanelLayout.setContentsMargins(0, 0, 0, 0)\n self.btnPanel.setLayout(self.btnPanelLayout)\n self.layout.addWidget(self.btnPanel, 1, 0)\n\n self.addPointBtn = Qt.QPushButton(\"add point\")\n self.addPointBtn.setCheckable(True)\n self.btnPanelLayout.addWidget(self.addPointBtn)\n\n self.removePointBtn = Qt.QPushButton(\"remove point\")\n self.removePointBtn.setEnabled(False)\n self.btnPanelLayout.addWidget(self.removePointBtn)\n\n self.saveBtn = Qt.QPushButton(\"save calibration\")\n self.btnPanelLayout.addWidget(self.saveBtn)\n\n self.addPointBtn.toggled.connect(self.addPointToggled)\n self.removePointBtn.clicked.connect(self.removePointClicked)\n self.saveBtn.clicked.connect(self.saveClicked)\n\n # TODO eventually: more controls\n # * Show calibration points (in camera module)\n # * Force orthogonal on any pair of axes: xy, xz, yz\n\n self.loadCalibrationFromDevice()\n\n cam = self.getCameraDevice()\n cam.sigGlobalTransformChanged.connect(self.cameraTransformChanged)\n\n def addPointToggled(self):\n cammod = self.getCameraModule()\n if self.addPointBtn.isChecked():\n cammod.window().getView().scene().sigMouseClicked.connect(self.cameraModuleClicked)\n self.addPointBtn.setText(\"click new point..\")\n else:\n pg.disconnect(cammod.window().getView().scene().sigMouseClicked, self.cameraModuleClicked)\n self.addPointBtn.setText(\"add point\")\n\n def cameraModuleClicked(self, ev):\n if ev.button() != Qt.Qt.LeftButton:\n return\n\n camera = self.getCameraDevice()\n cameraPos = camera.mapToGlobal([0, 0, 0])\n\n globalPos = self._cammod.window().getView().mapSceneToView(ev.scenePos())\n globalPos = [globalPos.x(), globalPos.y(), cameraPos[2]]\n parentDev = self.dev.parentDevice()\n if parentDev is None:\n parentPos = globalPos\n else:\n parentPos = parentDev.mapFromGlobal(globalPos)\n\n stagePos = self.dev.getPosition()\n\n self.calibration[\"points\"].append((stagePos, parentPos))\n item = self._addCalibrationPoint(stagePos, parentPos)\n\n target = Target(movable=False)\n self._cammod.window().addItem(target)\n target.setPos(pg.Point(globalPos[:2]))\n target.setDepth(globalPos[2])\n target.setFocusDepth(globalPos[2])\n item.target = target\n\n self.addPointBtn.setChecked(False)\n self.recalculate()\n self.saveBtn.setText(\"*save calibration*\")\n\n def cameraTransformChanged(self):\n cam = self.getCameraDevice()\n fdepth = cam.mapToGlobal([0, 0, 0])[2]\n\n items = [self.pointTree.topLevelItem(i) for i in range(self.pointTree.topLevelItemCount())]\n for item in items:\n if item.target is None:\n continue\n item.target.setFocusDepth(fdepth)\n\n def enableRemoveBtnIfPossible(self):\n self.removePointBtn.setEnabled(len(self.pointTree.selectedItems()) > 0)\n\n def removePointClicked(self):\n selected_items = self.pointTree.selectedItems()\n if len(selected_items) <= 0:\n raise HelpfulException(\"No points selected for removal\")\n sel = selected_items[0]\n index = self.pointTree.indexOfTopLevelItem(sel)\n self.pointTree.takeTopLevelItem(index)\n if sel.target is not None:\n sel.target.scene().removeItem(sel.target)\n items = [self.pointTree.topLevelItem(i) for i in range(self.pointTree.topLevelItemCount())]\n self.calibration[\"points\"] = [(item.stagePos, item.parentPos) for item in items]\n self.recalculate()\n self.enableRemoveBtnIfPossible()\n self.saveBtn.setText(\"*save calibration*\")\n\n def saveClicked(self):\n self.saveCalibrationToDevice()\n\n def loadCalibrationFromDevice(self):\n self.calibration = self.dev.readConfigFile(\"calibration\")\n self.calibration.setdefault(\"points\", [])\n for stagePos, parentPos in self.calibration[\"points\"]:\n self._addCalibrationPoint(stagePos, parentPos)\n self.recalculate()\n\n def saveCalibrationToDevice(self):\n self.recalculate(raiseOnInsufficientPoints=True)\n self.calibration[\"transform\"] = (\n None if self.transform is None else [list(row) for row in self.transform.matrix()]\n )\n self.dev.writeConfigFile(self.calibration, \"calibration\")\n self.saveBtn.setText(\"save calibration\")\n\n def _addCalibrationPoint(self, stagePos, parentPos):\n item = Qt.QTreeWidgetItem(\n [\"%0.3g, %0.3g, %0.3g\" % tuple(stagePos), \"%0.3g, %0.3g, %0.3g\" % tuple(parentPos), \"\"]\n )\n self.pointTree.addTopLevelItem(item)\n item.stagePos = stagePos\n item.parentPos = parentPos\n item.target = None\n return item\n\n def recalculate(self, raiseOnInsufficientPoints=False):\n # identity affine axis transform matrix\n\n # method: user generates many calibration points that are all colinear along each of the\n # stage axes. In this way, we can independently determine the orientation of each stage axis,\n # and combine these into a full transformation matrix.\n\n parentPos, stagePos = self._unzippedCalibrationPoints()\n\n axisPoints = self._groupPointsByAxis(stagePos)\n if not self._hasSufficientPoints(axisPoints):\n self._clearCalibration()\n if raiseOnInsufficientPoints:\n raise Exception(\"Could not find colinear points along all 3 axes\")\n else:\n return\n\n axStagePos = [stagePos[list(axisPoints[ax]), ax] for ax in (0, 1, 2)]\n axParentPos = [parentPos[list(axisPoints[ax])] for ax in (0, 1, 2)]\n\n # find optimal linear mapping for each axis\n m = np.eye(4)\n for i in (0, 1, 2):\n for j in (0, 1, 2):\n line = scipy.stats.linregress(axStagePos[j], axParentPos[j][:, i])\n m[i, j] = line.slope\n\n transform = pg.Transform3D(m)\n\n # find optimal offset\n offset = (parentPos - pg.transformCoordinates(transform, stagePos, transpose=True)).mean(axis=0)\n m[:3, 3] = offset\n self.transform = pg.Transform3D(m)\n\n # measure and display errors for each point\n def mapPoint(axisTr, _stage_pos, localPos):\n # given a stage position and axis transform, map from localPos to parent coordinate system\n if isinstance(axisTr, np.ndarray):\n ident = np.eye(4)\n ident[:3] = axisTr.reshape(3, 4)\n axisTr = pg.Transform3D(ident)\n st = self.dev._makeStageTransform(_stage_pos, axisTr)[0]\n tr = pg.Transform3D(self.dev.baseTransform() * st)\n return tr.map(localPos)\n\n def mapError(axisTr, _stage_pos, _parent_pos):\n # Goal is to map origin to parent position correctly\n return [mapPoint(axisTr, sp, [0, 0, 0]) - pp for sp, pp in zip(_stage_pos, _parent_pos)]\n\n error = mapError(self.transform, stagePos, parentPos)\n for i in range(len(self.calibration[\"points\"])):\n item = self.pointTree.topLevelItem(i)\n dist = np.linalg.norm(error[i])\n item.setText(2, \"%0.2f um (%0.3g, %0.3g, %0.3g)\" % (1e6 * dist, error[i][0], error[i][1], error[i][2]))\n\n # send new transform to device\n self.dev._axisTransform = self.transform\n self.dev._inverseAxisTransform = None\n self.dev._updateTransform()\n\n def _unzippedCalibrationPoints(self):\n npts = len(self.calibration[\"points\"])\n stagePos = np.empty((npts, 3))\n parentPos = np.empty((npts, 3))\n for i, pt in enumerate(self.calibration[\"points\"]):\n stagePos[i] = pt[0]\n parentPos[i] = pt[1]\n return parentPos, stagePos\n\n @staticmethod\n def _groupPointsByAxis(points):\n def changeAxis(p1, p2):\n # Which single axis has changed between 2 points?\n diff = np.abs(p2 - p1)\n dist = np.linalg.norm(diff)\n axis = np.argmax(diff)\n if diff[axis] > dist * 0.99:\n return axis\n else:\n return None\n\n axisPoints = [set(), set(), set()]\n for i in range(1, len(points)):\n currentAxis = changeAxis(points[i - 1], points[i])\n if currentAxis is None:\n continue\n axisPoints[currentAxis].add(i - 1)\n axisPoints[currentAxis].add(i)\n\n # Choose longest contiguous group of calibration points for each axis\n for axis, pts in enumerate(axisPoints):\n current_group = []\n contig_groups = [current_group]\n for p in sorted(pts):\n if len(current_group) == 0 or current_group[-1] == p - 1:\n current_group.append(p)\n else:\n current_group = [p]\n contig_groups.append(current_group)\n idx_at_longest = np.argmax([len(g) for g in contig_groups])\n axisPoints[axis] = contig_groups[idx_at_longest]\n return axisPoints\n\n @staticmethod\n def _hasSufficientPoints(axisPoints):\n return all(len(axisPoints[ax]) > 2 for ax in (0, 1, 2))\n\n def _clearCalibration(self):\n for i in range(len(self.calibration[\"points\"])):\n item = self.pointTree.topLevelItem(i)\n item.setText(2, \"\")\n self.transform = None\n\n def getCameraModule(self):\n if self._cammod is None:\n manager = getManager()\n mods = manager.listInterfaces(\"cameraModule\")\n if len(mods) == 0:\n raise Exception(\"Calibration requires an open camera module\")\n self._cammod = manager.getModule(mods[0])\n return self._cammod\n\n def getCameraDevice(self):\n if self._camdev is None:\n self._camdev = self.dev.getPreferredImagingDevice()\n return self._camdev\n\n def closeEvent(self, ev):\n for i in range(self.pointTree.topLevelItemCount()):\n target = self.pointTree.topLevelItem(i).target\n if target is not None:\n target.hide()\n\n def show(self):\n Qt.QWidget.show(self)\n for i in range(self.pointTree.topLevelItemCount()):\n target = self.pointTree.topLevelItem(i).target\n if target is not None:\n target.show()\n\n\nclass AutomatedStageCalibration(object):\n sigFinished = Qt.Signal()\n\n def __init__(self, stage: Stage):\n self._stage = stage\n self._frame_delay = None\n self._is_running = False\n self._steps_per_axis = 10\n self._move = None\n self._camera = stage.getPreferredImagingDevice()\n self._offsets = np.empty((2, self._steps_per_axis, 2))\n self._frames = ([], [])\n self._axis_index = 0\n self._frame_index = 0\n self._positions = None\n\n def calibrate(self):\n if self._is_running:\n raise RuntimeError(\"Automated axes calibration is already running\")\n self._is_running = True\n self._build_movement_plan()\n self._camera.sigNewFrame.connect(self.handleNewFrame)\n\n def _build_movement_plan(self):\n step_size = 10e-6 # TODO this should be magnification-dependent\n # current stage position\n pos = self._stage.getPosition()\n # where to move on each update\n if len(self._stage.axes()) == 2:\n self._positions = np.zeros((2, self._steps_per_axis, 2))\n else:\n self._positions = np.zeros((2, self._steps_per_axis, 3))\n self._positions[:, :, 2] = pos[2]\n self._positions[0, :, 0] = pos[0] + np.arange(self._steps_per_axis) * step_size\n self._positions[0, :, 1] = pos[1]\n self._positions[1, :, 0] = pos[0]\n self._positions[1, :, 1] = pos[1] + np.arange(self._steps_per_axis) * step_size\n\n def handleNewFrame(self, frame):\n try:\n if self._move is not None and not self._move.isDone():\n # stage is still moving; ignore frame\n return\n\n if self._frame_delay is None:\n # stage has stopped; ignore 2 more frames to be sure\n # we get the right image.\n self._frame_delay = pg.ptime.time() + 1.0 / frame.info()[\"fps\"]\n elif self._frame_delay < frame.info()[\"time\"]:\n # now we are ready to keep this frame.\n self._frame_delay = None\n self._addFrameForAnalysis(frame)\n except Exception:\n pg.disconnect(self._camera.sigNewFrame, self.handleNewFrame)\n self.sigFinished.emit()\n raise\n\n def _addFrameForAnalysis(self, frame):\n index = self._frame_index\n axis_index = index // self._steps_per_axis\n step_index = index % self._steps_per_axis\n self._frames[axis_index].append(frame)\n\n # update index for next iteration\n self._frame_index += 1\n\n # decide whether to move the stage\n finished = self._frame_index >= self._steps_per_axis * 2\n if not finished:\n self._move = self._stage.move(self.positions[self.index], \"slow\")\n\n self._offsets[axis_index, step_index] = self._calculate_offset(axis_index, step_index)\n\n # finish up if there are no more positions\n if finished:\n pg.disconnect(self._camera.sigNewFrame, self.handleNewFrame)\n self.analyze()\n\n def _calculate_offset(self, axis_index: int, step_index: int):\n \"\"\"calculate offset (while stage moves to next location)\"\"\"\n import imreg_dft # FFT image registration by Chris Gohlke; available via pip\n\n frame = self._frames[axis_index][step_index]\n if step_index == 0:\n return 0, 0\n\n compareIndex = max(0, step_index - 5)\n translation = imreg_dft.translation(frame.getImage(), self._frames[compareIndex].getImage())\n if not translation[\"success\"]:\n raise RuntimeError(f\"Could not determine offset at frame ({axis_index}, {step_index})\")\n offset = translation[\"tvec\"]\n px = self._camera.getPixelSize()\n return self._offsets[axis_index, compareIndex] + offset.astype(float) * px\n\n def analyze(self):\n self._do_x_axis_analysis()\n\n def _do_x_axis_analysis(self):\n # linear regression to determine scale between stage steps and camera microns\n axis_index = 0 # x\n pos_real = self._positions[axis_index, :, :2] # exclude z axis if present\n pos_real -= pos_real[0] # shift everything so that we start at 0\n pos_real = (pos_real ** 2).sum(axis=1) ** 0.5\n\n pos_measured = (self._offsets[axis_index] ** 2).sum(axis=1) ** 0.5\n lin_regress = scipy.stats.linregress(pos_real, pos_measured)\n\n # subtract linear approximation to get residual error\n pos_prediction = pos_real * lin_regress.slope + lin_regress.intercept\n error = pos_measured - pos_prediction\n errorPlot = pg.plot(\n pos_real,\n error,\n title=f\"X axis error (slope = {lin_regress.slope * 1e6:0.2f} um/step)\",\n labels={\"left\": (\"Error\", \"m\"), \"bottom\": (\"position\", \"steps\")},\n )\n\n # TODO what is this for?\n # fit residual to combination of sine waves\n def fn(p, x):\n return (\n p[2] * np.sin((x + p[0]) * 1 * p[1])\n + p[3] * np.sin((x + p[0]) * 2 * p[1])\n + p[4] * np.sin((x + p[0]) * 3 * p[1])\n + p[5] * np.sin((x + p[0]) * 4 * p[1])\n )\n\n def erf(p, x, y):\n return fn(p, x) - y\n\n f0 = 6 * np.pi / pos_real.max() # guess there are 3 cycles in the data\n amp = error.max()\n # noinspection PyTypeChecker\n fit = scipy.optimize.leastsq(erf, [0, f0, amp, amp, amp, amp], (pos_real, error))[0]\n errorPlot.plot(pos_real, fn(fit, pos_real), pen=\"g\")\n self.sigFinished.emit()\n"
] |
[
[
"numpy.array",
"numpy.cos",
"numpy.sin"
],
[
"numpy.concatenate",
"numpy.atleast_2d"
],
[
"numpy.abs",
"numpy.arange",
"numpy.eye",
"numpy.linalg.norm",
"numpy.sin",
"numpy.argmax",
"numpy.zeros",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jmorlana/pixloc
|
[
"90f7e968398252e8557b284803ee774cb8d80cd0"
] |
[
"pixloc/utils/eval.py"
] |
[
"import logging\n\nfrom pathlib import Path\nfrom typing import Union, Dict, Tuple, Optional\nimport numpy as np\nfrom .io import parse_image_list\nfrom .colmap import qvec2rotmat, read_images_binary, read_images_text\n\nlogger = logging.getLogger(__name__)\n\n\ndef evaluate(gt_sfm_model: Path, predictions: Union[Dict, Path],\n test_file_list: Optional[Path] = None,\n only_localized: bool = False):\n \"\"\"Compute the evaluation metrics for 7Scenes and Cambridge Landmarks.\n The other datasets are evaluated on visuallocalization.net\n \"\"\"\n if not isinstance(predictions, dict):\n predictions = parse_image_list(predictions, with_poses=True)\n predictions = {n: (im.qvec, im.tvec) for n, im in predictions}\n\n # ground truth poses from the sfm model\n images_bin = gt_sfm_model / 'images.bin'\n images_txt = gt_sfm_model / 'images.txt'\n if images_bin.exists():\n images = read_images_binary(images_bin)\n elif images_txt.exists():\n images = read_images_text(images_txt)\n else:\n raise ValueError(gt_sfm_model)\n name2id = {image.name: i for i, image in images.items()}\n\n if test_file_list is None:\n test_names = list(name2id)\n else:\n with open(test_file_list, 'r') as f:\n test_names = f.read().rstrip().split('\\n')\n\n # translation and rotation errors\n errors_t = []\n errors_R = []\n for name in test_names:\n if name not in predictions:\n if only_localized:\n continue\n e_t = np.inf\n e_R = 180.\n else:\n image = images[name2id[name]]\n R_gt, t_gt = image.qvec2rotmat(), image.tvec\n qvec, t = predictions[name]\n R = qvec2rotmat(qvec)\n e_t = np.linalg.norm(-R_gt.T @ t_gt + R.T @ t, axis=0)\n cos = np.clip((np.trace(np.dot(R_gt.T, R)) - 1) / 2, -1., 1.)\n e_R = np.rad2deg(np.abs(np.arccos(cos)))\n errors_t.append(e_t)\n errors_R.append(e_R)\n\n errors_t = np.array(errors_t)\n errors_R = np.array(errors_R)\n med_t = np.median(errors_t)\n med_R = np.median(errors_R)\n out = f'\\nMedian errors: {med_t:.3f}m, {med_R:.3f}deg'\n\n out += '\\nPercentage of test images localized within:'\n threshs_t = [0.01, 0.02, 0.03, 0.05, 0.25, 0.5, 5.0]\n threshs_R = [1.0, 2.0, 3.0, 5.0, 2.0, 5.0, 10.0]\n for th_t, th_R in zip(threshs_t, threshs_R):\n ratio = np.mean((errors_t < th_t) & (errors_R < th_R))\n out += f'\\n\\t{th_t*100:.0f}cm, {th_R:.0f}deg : {ratio*100:.2f}%'\n logger.info(out)\n\n\ndef cumulative_recall(errors: np.ndarray) -> Tuple[np.ndarray]:\n sort_idx = np.argsort(errors)\n errors = np.array(errors.copy())[sort_idx]\n recall = (np.arange(len(errors)) + 1) / len(errors)\n errors = np.r_[0., errors]\n recall = np.r_[0., recall]\n return errors, recall*100\n"
] |
[
[
"numpy.dot",
"numpy.median",
"numpy.linalg.norm",
"numpy.arccos",
"numpy.mean",
"numpy.argsort",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wang-yuhao/On-the-topological-propertyof-dynamic-transaction-graph
|
[
"8dc8c3870befb82581099e3a6edc9f9734c23f31"
] |
[
"4-Informer/chainInformer/data/merge_2018_2020_data.py"
] |
[
"# Merge 2018-2020 data for Informer\n# This process will generate merged base, betti, betti_deri, and fl files in PRICESSED_DIR.\n\nimport pandas as pd\nimport os\nfrom sklearn.decomposition import PCA\nimport datetime\nimport math \nimport pandas as pd\nimport numpy as np\nimport torch\n\nBETTI_NUMBER_DIR = \"/content/drive/MyDrive/aliyun/betti_number/\"\nAMOMAT_DIR = \"/content/drive/MyDrive/aliyun/amoMat/\"\nOCCMAT_DIR = \"/content/drive/MyDrive/aliyun/occMat/\"\nPRICE_PATH = \"/content/drive/MyDrive/aliyun/bitcoin_2018_2020.csv\"\nPROCESSED_DIR = \"/content/drive/MyDrive/aliyun/processed_data/2018_2020/\"\nTOTALTX_DIR = \"/content/drive/MyDrive/aliyun/bitcoin_totaltx_2018_2020.csv\"\nPERIOD = [2018, 2019, 2020]\n\ndef getBetweenDay(begin_date, end_date):\n date_list = []\n date_arr = []\n date_unix_list = []\n begin_date = datetime.datetime.strptime(begin_date, \"%Y-%m-%d\")\n print(\"begin_date:\",begin_date)\n # end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), \"%Y-%m-%d\")\n end_date = datetime.datetime.strptime(end_date, \"%Y-%m-%d\")\n print(\"end_date:\",end_date)\n while begin_date <= end_date:\n date_unix = math.trunc(begin_date.replace(tzinfo=datetime.timezone.utc).timestamp()*1000)\n date_unix_list.append(date_unix)\n date_str = begin_date.strftime(\"%Y-%m-%d\")\n date_list.append(date_str)\n date_arr.append([date_str, date_unix])\n begin_date += datetime.timedelta(days=1) \n return np.asarray(date_arr)\n\ndef combine_features_with_data(dataset_model):\n data_price = pd.read_csv(PRICE_PATH)\n btc_price_2018_2020 = data_price.Open.str.replace(\",\",\"\")\n total_tx = pd.read_csv(TOTALTX_DIR, index_col=0)\n date_arr = pd.DataFrame(getBetweenDay(\"2018-01-01\", \"2020-12-31\"))[0]\n btc_2018_2020 = pd.concat([total_tx, btc_price_2018_2020, date_arr], axis = 1)\n btc_2018_2020.columns = [\"totaltx\", \"price\", \"date\"]\n print(\"btc_2018_2020:\",btc_2018_2020)\n data_feature = pd.DataFrame([])\n \n if dataset_model == \"betti\":\n for YEAR in PERIOD:\n #for file_name in os.listdir(BETTI_NUMBER_DIR):\n feature_betti_0 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + \"_betti_0.csv\", index_col=0).loc[:, \"0\":\"49\"]\n feature_betti_1 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + \"_betti_1.csv\", index_col=0).loc[:, \"0\":\"49\"]\n feature_betti_number = pd.concat([feature_betti_0,feature_betti_1], axis = 1)\n data_feature = pd.concat([data_feature,feature_betti_number]).reset_index(drop=True)\n data_feature.to_csv(\"data_feature.csv\")\n print(\"data_feature:\",data_feature)\n elif dataset_model == \"betti_der\":\n for YEAR in PERIOD:\n feature_betti_0 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + \"_betti_0.csv\", index_col=0).loc[:, \"0\":\"49\"]\n feature_betti_1 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + \"_betti_1.csv\", index_col=0).loc[:, \"0\":\"49\"]\n feature_betti_0_der = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + \"_betti_0.csv\", index_col=0).diff(axis=1)\n feature_betti_1_der = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + \"_betti_1.csv\", index_col=0).diff(axis=1)\n feature_betti_0_der_50 = feature_betti_0_der.loc[:, \"1\":\"50\"]\n feature_betti_1_der_50 = feature_betti_1_der.loc[:, \"1\":\"50\"]\n feature_betti_total = pd.concat([feature_betti_0, feature_betti_1, feature_betti_0_der_50, feature_betti_1_der_50], axis=1)\n data_feature = pd.concat([data_feature,feature_betti_total]).reset_index(drop=True)\n\n elif dataset_model == \"fl\":\n for year in PERIOD:\n for day in getBetweenDay(str(year) + \"-01-01\", str(year) + \"-12-31\"):\n feature = pd.read_csv(OCCMAT_DIR + str(year) + \"/occ\" + day[0] + '.csv', index_col=0).to_numpy()\n feature = pd.DataFrame(feature.flatten()).T\n data_feature = pd.concat([data_feature,feature], axis = 0)\n\n data_feature.to_csv(PROCESSED_DIR + dataset_model+\"_orig.csv\")\n print(\"data_feature:\",data_feature)\n if len(data_feature) > 0:\n pca = PCA(n_components = 20)\n pca.fit(data_feature)\n data_feature = pd.DataFrame(pca.transform(data_feature))\n print(\"pca data_feature:\",data_feature)\n\n data_combined = pd.concat([btc_2018_2020,data_feature], axis=1)\n cols = data_combined.columns.tolist()\n cols = cols[2:] + cols[:2]\n data_combined = data_combined[cols] \n data_combined.to_csv(PROCESSED_DIR + dataset_model+\".csv\", index=False)\n print(data_combined)\n\nfor dataset_model in [\"base\", \"betti\",\"betti_der\", \"fl\"]:\n combine_features_with_data(dataset_model)\n\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"numpy.asarray",
"pandas.DataFrame",
"sklearn.decomposition.PCA"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
LouisTsiattalou/tfidf_matcher
|
[
"e95139f16329d149a2a3c1002d5b9bfe6da3b116"
] |
[
"tfidf_matcher/matcher.py"
] |
[
"# AUTHOR: Louis Tsiattalou\n# DESCRIPTION: Match list items to closest tf-idf match in second list.\n\nimport pandas as pd\nfrom tfidf_matcher.ngrams import ngrams\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.neighbors import NearestNeighbors\n\ndef matcher(original = [], lookup = [], k_matches = 5, ngram_length = 3):\n \"\"\"Takes two lists, returns top `k` matches from `lookup` dataset.\n\n This function does this by:\n - Splitting the `lookup` list into ngrams.\n - Transforming the resulting ngram list into a TF-IDF Sparse Matrix.\n - Fit a NearestNeighbours Model to the matrix using the lookup data.\n - Transform the `original` list into a TF-IDF Sparse Matrix.\n - Calculates distances to all the `n-matches` nearest neighbours\n - Then extract the `original`, `n-matches` closest lookups, and calculate\n a match score (abs(1 - Distance to Nearest Neighbour))\n\n :param original: List of strings to generate ngrams from.\n :type original: list (of strings), or Pandas Series.\n :param lookup: List of strings to match against.\n :type lookup: list (of strings), or Pandas Series.\n :param k_matches: Number of matches to return.\n :type k_matches: int\n :param ngram_length: Length of Ngrams returned by `tfidf_matcher.ngrams` callable\n :type ngram_length: int\n :raises AssertionError: Throws an error if the datatypes in `original` aren't strings.\n :raises AssertionError: Throws an error if the datatypes in `lookup` aren't strings.\n :raises AssertionError: Throws an error if `k_matches` isn't an integer.\n :raises AssertionError: Throws an error if k_matches > len(lookup)\n :raises AssertionError: Throws an error if ngram_length isn't an integer\n :return: Returns a Pandas dataframe with the `original` list,\n `k_matches` columns containing the closest matches from `lookup`,\n as well as a Match Score for the closest of these matches.\n :rtype: Pandas dataframe\n \"\"\"\n\n # Assertions\n assert all([type(x) == type(\"string\") for x in original]), \"Original contains non-str elements!\"\n assert all([type(x) == type(\"string\") for x in lookup]), \"Lookup contains non-str elements!\"\n assert type(k_matches) == type(0), \"k_matches must be an integer\"\n assert k_matches <= len(lookup), \"k_matches must be shorter or equal to the total length of the lookup list\"\n assert type(ngram_length) == type(0), \"ngram_length must be an integer\"\n\n # Enforce listtype, set to lower\n original = list(original)\n lookup = list(lookup)\n original_lower = [x.lower() for x in original]\n lookup_lower = [x.lower() for x in lookup]\n\n # Set ngram length for TfidfVectorizer callable\n def ngrams_user(string, n = ngram_length):\n return ngrams(string, n)\n\n # Generate Sparse TFIDF matrix from Lookup corpus\n vectorizer = TfidfVectorizer(min_df = 1,\n analyzer = ngrams_user)\n tf_idf_lookup = vectorizer.fit_transform(lookup_lower)\n\n # Fit KNN model to sparse TFIDF matrix generated from Lookup\n nbrs = NearestNeighbors(n_neighbors=k_matches,\n n_jobs=-1, metric='cosine').fit(tf_idf_lookup)\n\n # Use nbrs model to obtain nearest matches in lookup dataset. Vectorize first.\n tf_idf_original = vectorizer.transform(original_lower)\n distances, indices = nbrs.kneighbors(tf_idf_original)\n\n # Extract top Match Score (which is just the distance to the nearest neighbour),\n # Original match item, and Lookup matches.\n meta_list= []\n lookup_list= []\n for i,idx in enumerate(indices): # i is 0:len(original), j is list of lists of matches\n metadata = [round(distances[i][0], 2), original[i]] # Original match and Match Score\n lookups = [lookup[x] for x in idx] # Lookup columns\n meta_list.append(metadata)\n lookup_list.append(lookups)\n\n # Convert to df\n df_metadata = pd.DataFrame(meta_list, columns = ['Match Confidence', 'Original Name'])\n df_lookups = pd.DataFrame(lookup_list,\n columns=['Lookup ' + str(x+1) for x in range(0,k_matches)])\n\n # bind columns, transform Match Confidence to {0,1} with 1 a guaranteed match.\n matches = pd.concat([df_metadata, df_lookups], axis = 1)\n matches['Match Confidence'] = abs(matches['Match Confidence'] - 1)\n\n return matches\n"
] |
[
[
"pandas.concat",
"sklearn.neighbors.NearestNeighbors",
"sklearn.feature_extraction.text.TfidfVectorizer",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Quentin-kt/efficientdet-pytorch
|
[
"6a013481f9264a065ff1e3c5affe3102ef6066ce"
] |
[
"nets/efficientdet.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom utils.anchors import Anchors\n\nfrom nets.efficientnet import EfficientNet as EffNet\nfrom nets.layers import (Conv2dStaticSamePadding, MaxPool2dStaticSamePadding,\n MemoryEfficientSwish, Swish)\n\n\n#----------------------------------#\n# Xception中深度可分离卷积\n# 先3x3的深度可分离卷积\n# 再1x1的普通卷积\n#----------------------------------#\nclass SeparableConvBlock(nn.Module):\n def __init__(self, in_channels, out_channels=None, norm=True, activation=False, onnx_export=False):\n super(SeparableConvBlock, self).__init__()\n if out_channels is None:\n out_channels = in_channels\n\n self.depthwise_conv = Conv2dStaticSamePadding(in_channels, in_channels,\n kernel_size=3, stride=1, groups=in_channels, bias=False)\n self.pointwise_conv = Conv2dStaticSamePadding(in_channels, out_channels, kernel_size=1, stride=1)\n\n self.norm = norm\n if self.norm:\n self.bn = nn.BatchNorm2d(num_features=out_channels, momentum=0.01, eps=1e-3)\n\n self.activation = activation\n if self.activation:\n self.swish = MemoryEfficientSwish() if not onnx_export else Swish()\n\n def forward(self, x):\n x = self.depthwise_conv(x)\n x = self.pointwise_conv(x)\n\n if self.norm:\n x = self.bn(x)\n\n if self.activation:\n x = self.swish(x)\n\n return x\n\n\nclass BiFPN(nn.Module):\n def __init__(self, num_channels, conv_channels, first_time=False, epsilon=1e-4, onnx_export=False, attention=True):\n super(BiFPN, self).__init__()\n self.epsilon = epsilon\n self.conv6_up = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n self.conv5_up = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n self.conv4_up = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n self.conv3_up = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n\n self.conv4_down = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n self.conv5_down = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n self.conv6_down = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n self.conv7_down = SeparableConvBlock(num_channels, onnx_export=onnx_export)\n\n self.p6_upsample = nn.Upsample(scale_factor=2, mode='nearest')\n self.p5_upsample = nn.Upsample(scale_factor=2, mode='nearest')\n self.p4_upsample = nn.Upsample(scale_factor=2, mode='nearest')\n self.p3_upsample = nn.Upsample(scale_factor=2, mode='nearest')\n\n self.p4_downsample = MaxPool2dStaticSamePadding(3, 2)\n self.p5_downsample = MaxPool2dStaticSamePadding(3, 2)\n self.p6_downsample = MaxPool2dStaticSamePadding(3, 2)\n self.p7_downsample = MaxPool2dStaticSamePadding(3, 2)\n\n self.swish = MemoryEfficientSwish() if not onnx_export else Swish()\n\n self.first_time = first_time\n if self.first_time:\n # 获取到了efficientnet的最后三层,对其进行通道的下压缩\n self.p5_down_channel = nn.Sequential(\n Conv2dStaticSamePadding(conv_channels[2], num_channels, 1),\n nn.BatchNorm2d(num_channels, momentum=0.01, eps=1e-3),\n )\n self.p4_down_channel = nn.Sequential(\n Conv2dStaticSamePadding(conv_channels[1], num_channels, 1),\n nn.BatchNorm2d(num_channels, momentum=0.01, eps=1e-3),\n )\n self.p3_down_channel = nn.Sequential(\n Conv2dStaticSamePadding(conv_channels[0], num_channels, 1),\n nn.BatchNorm2d(num_channels, momentum=0.01, eps=1e-3),\n )\n\n # 对输入进来的p5进行宽高的下采样\n self.p5_to_p6 = nn.Sequential(\n Conv2dStaticSamePadding(conv_channels[2], num_channels, 1),\n nn.BatchNorm2d(num_channels, momentum=0.01, eps=1e-3),\n MaxPool2dStaticSamePadding(3, 2)\n )\n self.p6_to_p7 = nn.Sequential(\n MaxPool2dStaticSamePadding(3, 2)\n )\n\n # BIFPN第一轮的时候,跳线那里并不是同一个in\n self.p4_down_channel_2 = nn.Sequential(\n Conv2dStaticSamePadding(conv_channels[1], num_channels, 1),\n nn.BatchNorm2d(num_channels, momentum=0.01, eps=1e-3),\n )\n self.p5_down_channel_2 = nn.Sequential(\n Conv2dStaticSamePadding(conv_channels[2], num_channels, 1),\n nn.BatchNorm2d(num_channels, momentum=0.01, eps=1e-3),\n )\n\n # 简易注意力机制的weights\n self.p6_w1 = nn.Parameter(torch.ones(2, dtype=torch.float32), requires_grad=True)\n self.p6_w1_relu = nn.ReLU()\n self.p5_w1 = nn.Parameter(torch.ones(2, dtype=torch.float32), requires_grad=True)\n self.p5_w1_relu = nn.ReLU()\n self.p4_w1 = nn.Parameter(torch.ones(2, dtype=torch.float32), requires_grad=True)\n self.p4_w1_relu = nn.ReLU()\n self.p3_w1 = nn.Parameter(torch.ones(2, dtype=torch.float32), requires_grad=True)\n self.p3_w1_relu = nn.ReLU()\n\n self.p4_w2 = nn.Parameter(torch.ones(3, dtype=torch.float32), requires_grad=True)\n self.p4_w2_relu = nn.ReLU()\n self.p5_w2 = nn.Parameter(torch.ones(3, dtype=torch.float32), requires_grad=True)\n self.p5_w2_relu = nn.ReLU()\n self.p6_w2 = nn.Parameter(torch.ones(3, dtype=torch.float32), requires_grad=True)\n self.p6_w2_relu = nn.ReLU()\n self.p7_w2 = nn.Parameter(torch.ones(2, dtype=torch.float32), requires_grad=True)\n self.p7_w2_relu = nn.ReLU()\n\n self.attention = attention\n\n def forward(self, inputs):\n \"\"\" bifpn模块结构示意图\n P7_0 -------------------------> P7_2 -------->\n |-------------| ↑\n ↓ |\n P6_0 ---------> P6_1 ---------> P6_2 -------->\n |-------------|--------------↑ ↑\n ↓ |\n P5_0 ---------> P5_1 ---------> P5_2 -------->\n |-------------|--------------↑ ↑\n ↓ |\n P4_0 ---------> P4_1 ---------> P4_2 -------->\n |-------------|--------------↑ ↑\n |--------------↓ |\n P3_0 -------------------------> P3_2 -------->\n \"\"\"\n if self.attention:\n p3_out, p4_out, p5_out, p6_out, p7_out = self._forward_fast_attention(inputs)\n else:\n p3_out, p4_out, p5_out, p6_out, p7_out = self._forward(inputs)\n\n return p3_out, p4_out, p5_out, p6_out, p7_out\n\n def _forward_fast_attention(self, inputs):\n #------------------------------------------------#\n # 当phi=1、2、3、4、5的时候使用fast_attention\n # 获得三个shape的有效特征层\n # 分别是C3 64, 64, 40\n # C4 32, 32, 112\n # C5 16, 16, 320\n #------------------------------------------------#\n if self.first_time:\n #------------------------------------------------------------------------#\n # 第一次BIFPN需要 下采样 与 调整通道 获得 p3_in p4_in p5_in p6_in p7_in\n #------------------------------------------------------------------------#\n p3, p4, p5 = inputs\n #-------------------------------------------#\n # 首先对通道数进行调整\n # C3 64, 64, 40 -> 64, 64, 64\n #-------------------------------------------#\n p3_in = self.p3_down_channel(p3)\n\n #-------------------------------------------#\n # 首先对通道数进行调整\n # C4 32, 32, 112 -> 32, 32, 64\n # -> 32, 32, 64\n #-------------------------------------------#\n p4_in_1 = self.p4_down_channel(p4)\n p4_in_2 = self.p4_down_channel_2(p4)\n\n #-------------------------------------------#\n # 首先对通道数进行调整\n # C5 16, 16, 320 -> 16, 16, 64\n # -> 16, 16, 64\n #-------------------------------------------#\n p5_in_1 = self.p5_down_channel(p5)\n p5_in_2 = self.p5_down_channel_2(p5)\n \n #-------------------------------------------#\n # 对C5进行下采样,调整通道数与宽高\n # C5 16, 16, 320 -> 8, 8, 64\n #-------------------------------------------#\n p6_in = self.p5_to_p6(p5)\n #-------------------------------------------#\n # 对P6_in进行下采样,调整宽高\n # P6_in 8, 8, 64 -> 4, 4, 64\n #-------------------------------------------#\n p7_in = self.p6_to_p7(p6_in)\n\n # 简单的注意力机制,用于确定更关注p7_in还是p6_in\n p6_w1 = self.p6_w1_relu(self.p6_w1)\n weight = p6_w1 / (torch.sum(p6_w1, dim=0) + self.epsilon)\n p6_td= self.conv6_up(self.swish(weight[0] * p6_in + weight[1] * self.p6_upsample(p7_in)))\n\n # 简单的注意力机制,用于确定更关注p6_up还是p5_in\n p5_w1 = self.p5_w1_relu(self.p5_w1)\n weight = p5_w1 / (torch.sum(p5_w1, dim=0) + self.epsilon)\n p5_td= self.conv5_up(self.swish(weight[0] * p5_in_1 + weight[1] * self.p5_upsample(p6_td)))\n\n # 简单的注意力机制,用于确定更关注p5_up还是p4_in\n p4_w1 = self.p4_w1_relu(self.p4_w1)\n weight = p4_w1 / (torch.sum(p4_w1, dim=0) + self.epsilon)\n p4_td= self.conv4_up(self.swish(weight[0] * p4_in_1 + weight[1] * self.p4_upsample(p5_td)))\n\n # 简单的注意力机制,用于确定更关注p4_up还是p3_in\n p3_w1 = self.p3_w1_relu(self.p3_w1)\n weight = p3_w1 / (torch.sum(p3_w1, dim=0) + self.epsilon)\n p3_out = self.conv3_up(self.swish(weight[0] * p3_in + weight[1] * self.p3_upsample(p4_td)))\n\n # 简单的注意力机制,用于确定更关注p4_in_2还是p4_up还是p3_out\n p4_w2 = self.p4_w2_relu(self.p4_w2)\n weight = p4_w2 / (torch.sum(p4_w2, dim=0) + self.epsilon)\n p4_out = self.conv4_down(\n self.swish(weight[0] * p4_in_2 + weight[1] * p4_td+ weight[2] * self.p4_downsample(p3_out)))\n\n # 简单的注意力机制,用于确定更关注p5_in_2还是p5_up还是p4_out\n p5_w2 = self.p5_w2_relu(self.p5_w2)\n weight = p5_w2 / (torch.sum(p5_w2, dim=0) + self.epsilon)\n p5_out = self.conv5_down(\n self.swish(weight[0] * p5_in_2 + weight[1] * p5_td+ weight[2] * self.p5_downsample(p4_out)))\n\n # 简单的注意力机制,用于确定更关注p6_in还是p6_up还是p5_out\n p6_w2 = self.p6_w2_relu(self.p6_w2)\n weight = p6_w2 / (torch.sum(p6_w2, dim=0) + self.epsilon)\n p6_out = self.conv6_down(\n self.swish(weight[0] * p6_in + weight[1] * p6_td+ weight[2] * self.p6_downsample(p5_out)))\n\n # 简单的注意力机制,用于确定更关注p7_in还是p7_up还是p6_out\n p7_w2 = self.p7_w2_relu(self.p7_w2)\n weight = p7_w2 / (torch.sum(p7_w2, dim=0) + self.epsilon)\n p7_out = self.conv7_down(self.swish(weight[0] * p7_in + weight[1] * self.p7_downsample(p6_out)))\n else:\n p3_in, p4_in, p5_in, p6_in, p7_in = inputs\n\n # 简单的注意力机制,用于确定更关注p7_in还是p6_in\n p6_w1 = self.p6_w1_relu(self.p6_w1)\n weight = p6_w1 / (torch.sum(p6_w1, dim=0) + self.epsilon)\n p6_td= self.conv6_up(self.swish(weight[0] * p6_in + weight[1] * self.p6_upsample(p7_in)))\n\n # 简单的注意力机制,用于确定更关注p6_up还是p5_in\n p5_w1 = self.p5_w1_relu(self.p5_w1)\n weight = p5_w1 / (torch.sum(p5_w1, dim=0) + self.epsilon)\n p5_td= self.conv5_up(self.swish(weight[0] * p5_in + weight[1] * self.p5_upsample(p6_td)))\n\n # 简单的注意力机制,用于确定更关注p5_up还是p4_in\n p4_w1 = self.p4_w1_relu(self.p4_w1)\n weight = p4_w1 / (torch.sum(p4_w1, dim=0) + self.epsilon)\n p4_td= self.conv4_up(self.swish(weight[0] * p4_in + weight[1] * self.p4_upsample(p5_td)))\n\n # 简单的注意力机制,用于确定更关注p4_up还是p3_in\n p3_w1 = self.p3_w1_relu(self.p3_w1)\n weight = p3_w1 / (torch.sum(p3_w1, dim=0) + self.epsilon)\n p3_out = self.conv3_up(self.swish(weight[0] * p3_in + weight[1] * self.p3_upsample(p4_td)))\n\n # 简单的注意力机制,用于确定更关注p4_in还是p4_up还是p3_out\n p4_w2 = self.p4_w2_relu(self.p4_w2)\n weight = p4_w2 / (torch.sum(p4_w2, dim=0) + self.epsilon)\n p4_out = self.conv4_down(\n self.swish(weight[0] * p4_in + weight[1] * p4_td+ weight[2] * self.p4_downsample(p3_out)))\n\n # 简单的注意力机制,用于确定更关注p5_in还是p5_up还是p4_out\n p5_w2 = self.p5_w2_relu(self.p5_w2)\n weight = p5_w2 / (torch.sum(p5_w2, dim=0) + self.epsilon)\n p5_out = self.conv5_down(\n self.swish(weight[0] * p5_in + weight[1] * p5_td+ weight[2] * self.p5_downsample(p4_out)))\n\n # 简单的注意力机制,用于确定更关注p6_in还是p6_up还是p5_out\n p6_w2 = self.p6_w2_relu(self.p6_w2)\n weight = p6_w2 / (torch.sum(p6_w2, dim=0) + self.epsilon)\n p6_out = self.conv6_down(\n self.swish(weight[0] * p6_in + weight[1] * p6_td+ weight[2] * self.p6_downsample(p5_out)))\n\n # 简单的注意力机制,用于确定更关注p7_in还是p7_up还是p6_out\n p7_w2 = self.p7_w2_relu(self.p7_w2)\n weight = p7_w2 / (torch.sum(p7_w2, dim=0) + self.epsilon)\n p7_out = self.conv7_down(self.swish(weight[0] * p7_in + weight[1] * self.p7_downsample(p6_out)))\n\n return p3_out, p4_out, p5_out, p6_out, p7_out\n\n def _forward(self, inputs):\n # 当phi=6、7的时候使用_forward\n if self.first_time:\n # 第一次BIFPN需要下采样与降通道获得\n # p3_in p4_in p5_in p6_in p7_in\n p3, p4, p5 = inputs\n p3_in = self.p3_down_channel(p3)\n p4_in_1 = self.p4_down_channel(p4)\n p4_in_2 = self.p4_down_channel_2(p4)\n p5_in_1 = self.p5_down_channel(p5)\n p5_in_2 = self.p5_down_channel_2(p5)\n p6_in = self.p5_to_p6(p5)\n p7_in = self.p6_to_p7(p6_in)\n\n p6_td= self.conv6_up(self.swish(p6_in + self.p6_upsample(p7_in)))\n\n p5_td= self.conv5_up(self.swish(p5_in_1 + self.p5_upsample(p6_td)))\n\n p4_td= self.conv4_up(self.swish(p4_in_1 + self.p4_upsample(p5_td)))\n\n p3_out = self.conv3_up(self.swish(p3_in + self.p3_upsample(p4_td)))\n\n p4_out = self.conv4_down(\n self.swish(p4_in_2 + p4_td+ self.p4_downsample(p3_out)))\n\n p5_out = self.conv5_down(\n self.swish(p5_in_2 + p5_td+ self.p5_downsample(p4_out)))\n\n p6_out = self.conv6_down(\n self.swish(p6_in + p6_td+ self.p6_downsample(p5_out)))\n\n p7_out = self.conv7_down(self.swish(p7_in + self.p7_downsample(p6_out)))\n\n else:\n p3_in, p4_in, p5_in, p6_in, p7_in = inputs\n\n p6_td= self.conv6_up(self.swish(p6_in + self.p6_upsample(p7_in)))\n\n p5_td= self.conv5_up(self.swish(p5_in + self.p5_upsample(p6_td)))\n\n p4_td= self.conv4_up(self.swish(p4_in + self.p4_upsample(p5_td)))\n\n p3_out = self.conv3_up(self.swish(p3_in + self.p3_upsample(p4_td)))\n\n p4_out = self.conv4_down(\n self.swish(p4_in + p4_td+ self.p4_downsample(p3_out)))\n\n p5_out = self.conv5_down(\n self.swish(p5_in + p5_td+ self.p5_downsample(p4_out)))\n\n p6_out = self.conv6_down(\n self.swish(p6_in + p6_td+ self.p6_downsample(p5_out)))\n\n p7_out = self.conv7_down(self.swish(p7_in + self.p7_downsample(p6_out)))\n\n\n\n\n return p3_out, p4_out, p5_out, p6_out, p7_out\n\n\nclass BoxNet(nn.Module):\n def __init__(self, in_channels, num_anchors, num_layers, onnx_export=False):\n super(BoxNet, self).__init__()\n self.num_layers = num_layers\n\n self.conv_list = nn.ModuleList(\n [SeparableConvBlock(in_channels, in_channels, norm=False, activation=False) for i in range(num_layers)])\n # 每一个有效特征层对应的Batchnor不同\n self.bn_list = nn.ModuleList(\n [nn.ModuleList([nn.BatchNorm2d(in_channels, momentum=0.01, eps=1e-3) for i in range(num_layers)]) for j in range(5)])\n # 9\n # 4 中心,宽高\n self.header = SeparableConvBlock(in_channels, num_anchors * 4, norm=False, activation=False)\n self.swish = MemoryEfficientSwish() if not onnx_export else Swish()\n\n def forward(self, inputs):\n feats = []\n # 对每个特征层循环\n for feat, bn_list in zip(inputs, self.bn_list):\n # 每个特征层需要进行num_layer次卷积+标准化+激活函数\n for i, bn, conv in zip(range(self.num_layers), bn_list, self.conv_list):\n feat = conv(feat)\n feat = bn(feat)\n feat = self.swish(feat)\n feat = self.header(feat)\n\n feat = feat.permute(0, 2, 3, 1)\n feat = feat.contiguous().view(feat.shape[0], -1, 4)\n \n feats.append(feat)\n # 进行一个堆叠\n feats = torch.cat(feats, dim=1)\n\n return feats\n\n\nclass ClassNet(nn.Module):\n def __init__(self, in_channels, num_anchors, num_classes, num_layers, onnx_export=False):\n super(ClassNet, self).__init__()\n self.num_anchors = num_anchors\n self.num_classes = num_classes\n self.num_layers = num_layers\n self.conv_list = nn.ModuleList(\n [SeparableConvBlock(in_channels, in_channels, norm=False, activation=False) for i in range(num_layers)])\n # 每一个有效特征层对应的BatchNorm2d不同\n self.bn_list = nn.ModuleList(\n [nn.ModuleList([nn.BatchNorm2d(in_channels, momentum=0.01, eps=1e-3) for i in range(num_layers)]) for j in range(5)])\n # num_anchors = 9\n # num_anchors num_classes\n self.header = SeparableConvBlock(in_channels, num_anchors * num_classes, norm=False, activation=False)\n self.swish = MemoryEfficientSwish() if not onnx_export else Swish()\n\n def forward(self, inputs):\n feats = []\n # 对每个特征层循环\n for feat, bn_list in zip(inputs, self.bn_list):\n for i, bn, conv in zip(range(self.num_layers), bn_list, self.conv_list):\n # 每个特征层需要进行num_layer次卷积+标准化+激活函数\n feat = conv(feat)\n feat = bn(feat)\n feat = self.swish(feat)\n feat = self.header(feat)\n\n feat = feat.permute(0, 2, 3, 1)\n feat = feat.contiguous().view(feat.shape[0], feat.shape[1], feat.shape[2], self.num_anchors, self.num_classes)\n feat = feat.contiguous().view(feat.shape[0], -1, self.num_classes)\n\n feats.append(feat)\n # 进行一个堆叠\n feats = torch.cat(feats, dim=1)\n # 取sigmoid表示概率\n feats = feats.sigmoid()\n\n return feats\n\n\nclass EfficientNet(nn.Module):\n def __init__(self, phi, load_weights=False):\n super(EfficientNet, self).__init__()\n model = EffNet.from_pretrained(f'efficientnet-b{phi}', load_weights)\n del model._conv_head\n del model._bn1\n del model._avg_pooling\n del model._dropout\n del model._fc\n self.model = model\n\n def forward(self, x):\n x = self.model._conv_stem(x)\n x = self.model._bn0(x)\n x = self.model._swish(x)\n feature_maps = []\n\n last_x = None\n for idx, block in enumerate(self.model._blocks):\n drop_connect_rate = self.model._global_params.drop_connect_rate\n if drop_connect_rate:\n drop_connect_rate *= float(idx) / len(self.model._blocks)\n x = block(x, drop_connect_rate=drop_connect_rate)\n\n #------------------------------------------------------#\n # 取出对应的特征层,如果某个EffcientBlock的步长为2的话\n # 意味着它的前一个特征层为有效特征层\n # 除此之外,最后一个EffcientBlock的输出为有效特征层\n #------------------------------------------------------#\n if block._depthwise_conv.stride == [2, 2]:\n feature_maps.append(last_x)\n elif idx == len(self.model._blocks) - 1:\n feature_maps.append(x)\n last_x = x\n del last_x\n return feature_maps[1:]\n\n\nclass EfficientDetBackbone(nn.Module):\n def __init__(self, num_classes=80, phi=0, load_weights=False):\n super(EfficientDetBackbone, self).__init__()\n #--------------------------------#\n # phi指的是efficientdet的版本\n #--------------------------------#\n self.phi = phi\n #---------------------------------------------------#\n # backbone_phi指的是该efficientdet对应的efficient\n #---------------------------------------------------#\n self.backbone_phi = [0, 1, 2, 3, 4, 5, 6, 6]\n #--------------------------------#\n # BiFPN所用的通道数\n #--------------------------------#\n self.fpn_num_filters = [64, 88, 112, 160, 224, 288, 384, 384]\n #--------------------------------#\n # BiFPN的重复次数\n #--------------------------------#\n self.fpn_cell_repeats = [3, 4, 5, 6, 7, 7, 8, 8]\n #---------------------------------------------------#\n # Effcient Head卷积重复次数\n #---------------------------------------------------#\n self.box_class_repeats = [3, 3, 3, 4, 4, 4, 5, 5]\n #---------------------------------------------------#\n # 基础的先验框大小\n #---------------------------------------------------#\n self.anchor_scale = [4., 4., 4., 4., 4., 4., 4., 5.]\n num_anchors = 9\n conv_channel_coef = {\n 0: [40, 112, 320],\n 1: [40, 112, 320],\n 2: [48, 120, 352],\n 3: [48, 136, 384],\n 4: [56, 160, 448],\n 5: [64, 176, 512],\n 6: [72, 200, 576],\n 7: [72, 200, 576],\n }\n\n #------------------------------------------------------#\n # 在经过多次BiFPN模块的堆叠后,我们获得的fpn_features\n # 假设我们使用的是efficientdet-D0包括五个有效特征层:\n # P3_out 64,64,64\n # P4_out 32,32,64\n # P5_out 16,16,64\n # P6_out 8,8,64\n # P7_out 4,4,64\n #------------------------------------------------------#\n self.bifpn = nn.Sequential(\n *[BiFPN(self.fpn_num_filters[self.phi],\n conv_channel_coef[phi],\n True if _ == 0 else False,\n attention=True if phi < 6 else False)\n for _ in range(self.fpn_cell_repeats[phi])])\n\n self.num_classes = num_classes\n #------------------------------------------------------#\n # 创建efficient head\n # 可以将特征层转换成预测结果\n #------------------------------------------------------#\n self.regressor = BoxNet(in_channels=self.fpn_num_filters[self.phi], num_anchors=num_anchors,\n num_layers=self.box_class_repeats[self.phi])\n\n self.classifier = ClassNet(in_channels=self.fpn_num_filters[self.phi], num_anchors=num_anchors,\n num_classes=num_classes, num_layers=self.box_class_repeats[self.phi])\n\n self.anchors = Anchors(anchor_scale=self.anchor_scale[phi])\n\n #-------------------------------------------#\n # 获得三个shape的有效特征层\n # 分别是C3 64, 64, 40\n # C4 32, 32, 112\n # C5 16, 16, 320\n #-------------------------------------------#\n self.backbone_net = EfficientNet(self.backbone_phi[phi], load_weights)\n\n def freeze_bn(self):\n for m in self.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.eval()\n\n def forward(self, inputs):\n _, p3, p4, p5 = self.backbone_net(inputs)\n\n features = (p3, p4, p5)\n features = self.bifpn(features)\n\n regression = self.regressor(features)\n classification = self.classifier(features)\n anchors = self.anchors(inputs)\n \n return features, regression, classification, anchors\n\n"
] |
[
[
"torch.ones",
"torch.cat",
"torch.sum",
"torch.nn.Upsample",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
isi-vista/adam-visual-perception
|
[
"8ad6ed883b184b5407a1bf793617b226c78b3a13"
] |
[
"adam_visual_perception/head_gaze_estimator.py"
] |
[
"from adam_visual_perception import LandmarkDetector\nfrom adam_visual_perception.utility import *\nimport numpy as np\nimport math\nimport cv2\nimport os\nimport sys\n\n\nclass HeadGazeEstimator:\n \"\"\" A class for estimating gaze ray from facial landmarks \"\"\"\n\n def __init__(self, write_video=False):\n # 3D model points.\n self.model_points = np.array(\n [\n (0.0, 0.0, 0.0), # Nose tip\n (0.0, -330.0, -65.0), # Chin\n (-225.0, 170.0, -135.0), # Left eye left corner\n (225.0, 170.0, -135.0), # Right eye right corne\n (-150.0, -150.0, -125.0), # Left Mouth corner\n (150.0, -150.0, -125.0), # Right mouth corner\n ]\n )\n self.dist_coeffs = np.zeros((4, 1)) # Assuming no lens distortion\n \"\"\"\n Parameters\n ----------\n write_video : bool, optional\n Write the resulting OpenCV video\n \"\"\"\n\n self.write_video = write_video\n self.landmark_detector = LandmarkDetector(write_video=False)\n\n def get_gaze_rays(self, filename, bbox_history=None, show=True):\n \"\"\"\n Get the gaze rays for the given video file\n \"\"\"\n # Get the landmarks for the entire video\n landmark_map = self.landmark_detector.detect(filename, show=False)\n\n # Capture the video\n cap = cv2.VideoCapture(filename)\n frame_no = 0\n\n gaze_angles = {}\n\n # Loop over the frames from the video stream\n while True:\n success, frame = cap.read()\n\n if not success:\n if frame_no == 0:\n print(\"Failed to read video\")\n sys.exit(1)\n else:\n break\n\n if frame_no == 0:\n # Camera internals\n size = frame.shape\n focal_length = size[1]\n center = (size[1] / 2, size[0] / 2)\n camera_matrix = np.array(\n [\n [focal_length, 0, center[0]],\n [0, focal_length, center[1]],\n [0, 0, 1],\n ],\n dtype=\"double\",\n )\n\n if self.write_video:\n # Initialize our video writer\n fourcc = cv2.VideoWriter_fourcc(*\"mp4v\")\n par_path = os.path.abspath(os.path.join(filename, os.pardir))\n dir_path = par_path + \"_pnp\"\n if not os.path.isdir(dir_path):\n os.makedirs(dir_path)\n video_path = os.path.join(dir_path, os.path.basename(filename))\n writer = cv2.VideoWriter(\n video_path, fourcc, 30, (frame.shape[1], frame.shape[0]), True\n )\n\n if frame_no in landmark_map:\n # 2D image points.\n image_points = np.array(\n [\n landmark_map[frame_no][33], # Nose tip\n landmark_map[frame_no][8], # Chin\n landmark_map[frame_no][36], # Left eye left corner\n landmark_map[frame_no][45], # Right eye right corne\n landmark_map[frame_no][48], # Left Mouth corner\n landmark_map[frame_no][54], # Right mouth corner\n ],\n dtype=\"double\",\n )\n\n # We use this to draw a line sticking out of the nose\n success, rotation_vector, translation_vector = cv2.solvePnP(\n self.model_points,\n image_points,\n camera_matrix,\n self.dist_coeffs,\n flags=cv2.SOLVEPNP_ITERATIVE,\n )\n\n nose_end_point2D, jacobian = cv2.projectPoints(\n np.array([(0.0, 0.0, 1000.0)]),\n rotation_vector,\n translation_vector,\n camera_matrix,\n self.dist_coeffs,\n )\n\n for p in image_points:\n cv2.circle(frame, (int(p[0]), int(p[1])), 1, (255, 0, 0), -1)\n\n for p in landmark_map[frame_no]:\n if p in image_points:\n continue\n cv2.circle(frame, (int(p[0]), int(p[1])), 1, (0, 0, 255), -1)\n\n p1 = (int(image_points[0][0]), int(image_points[0][1]))\n p2 = (int(nose_end_point2D[0][0][0]), int(nose_end_point2D[0][0][1]))\n\n lenAB = math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n length = lenAB * 3\n C_x = int(p2[0] + (p2[0] - p1[0]) / lenAB * length)\n C_y = int(p2[1] + (p2[1] - p1[1]) / lenAB * length)\n\n cv2.line(frame, p1, (C_x, C_y), (0, 255, 0), 2)\n\n if bbox_history is not None and (self.write_video or show):\n bboxes = bbox_history[frame_no]\n for i, bbox in enumerate(bboxes):\n x, y = int(bbox[0]), int(bbox[1])\n w, h = int(bbox[2]), int(bbox[3])\n\n cv2.circle(\n frame, (int(x + w / 2), int(y + h / 2)), 5, (0, 0, 255), -1\n )\n\n # Store in the return dictionary\n gaze_angles[frame_no] = (p1, p2)\n\n # Show the frame if the flag is on\n if show:\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # Write the video if the flag is on\n if self.write_video:\n writer.write(frame)\n\n frame_no += 1\n\n # Cleanup\n cv2.destroyAllWindows()\n\n if self.write_video:\n writer.release()\n\n return gaze_angles\n"
] |
[
[
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bobcy2015/ml-agents
|
[
"5d02292ad889f1884fa98bd92f127f17cbfe0112"
] |
[
"ml-agents/mlagents/trainers/tests/test_ghost.py"
] |
[
"import pytest\n\nimport numpy as np\n\nfrom mlagents.trainers.ghost.trainer import GhostTrainer\nfrom mlagents.trainers.ghost.controller import GhostController\nfrom mlagents.trainers.behavior_id_utils import BehaviorIdentifiers\nfrom mlagents.trainers.ppo.trainer import PPOTrainer\nfrom mlagents.trainers.brain import BrainParameters\nfrom mlagents.trainers.agent_processor import AgentManagerQueue\nfrom mlagents.trainers.tests import mock_brain as mb\nfrom mlagents.trainers.tests.test_trajectory import make_fake_trajectory\nfrom mlagents.trainers.settings import TrainerSettings, SelfPlaySettings\n\n\[email protected]\ndef dummy_config():\n return TrainerSettings(self_play=SelfPlaySettings())\n\n\nVECTOR_ACTION_SPACE = [1]\nVECTOR_OBS_SPACE = 8\nDISCRETE_ACTION_SPACE = [3, 3, 3, 2]\nBUFFER_INIT_SAMPLES = 513\nNUM_AGENTS = 12\n\n\[email protected](\"use_discrete\", [True, False])\ndef test_load_and_set(dummy_config, use_discrete):\n mock_brain = mb.setup_mock_brain(\n use_discrete,\n False,\n vector_action_space=VECTOR_ACTION_SPACE,\n vector_obs_space=VECTOR_OBS_SPACE,\n discrete_action_space=DISCRETE_ACTION_SPACE,\n )\n\n trainer_params = dummy_config\n trainer = PPOTrainer(mock_brain.brain_name, 0, trainer_params, True, False, 0, \"0\")\n trainer.seed = 1\n policy = trainer.create_policy(mock_brain.brain_name, mock_brain)\n policy.create_tf_graph()\n trainer.seed = 20 # otherwise graphs are the same\n to_load_policy = trainer.create_policy(mock_brain.brain_name, mock_brain)\n to_load_policy.create_tf_graph()\n to_load_policy.init_load_weights()\n\n weights = policy.get_weights()\n load_weights = to_load_policy.get_weights()\n try:\n for w, lw in zip(weights, load_weights):\n np.testing.assert_array_equal(w, lw)\n except AssertionError:\n pass\n\n to_load_policy.load_weights(weights)\n load_weights = to_load_policy.get_weights()\n\n for w, lw in zip(weights, load_weights):\n np.testing.assert_array_equal(w, lw)\n\n\ndef test_process_trajectory(dummy_config):\n brain_params_team0 = BrainParameters(\n brain_name=\"test_brain?team=0\",\n vector_observation_space_size=1,\n camera_resolutions=[],\n vector_action_space_size=[2],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n\n brain_name = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team0.brain_name\n ).brain_name\n\n brain_params_team1 = BrainParameters(\n brain_name=\"test_brain?team=1\",\n vector_observation_space_size=1,\n camera_resolutions=[],\n vector_action_space_size=[2],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, \"0\")\n controller = GhostController(100)\n trainer = GhostTrainer(\n ppo_trainer, brain_name, controller, 0, dummy_config, True, \"0\"\n )\n\n # first policy encountered becomes policy trained by wrapped PPO\n parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team0.brain_name\n )\n policy = trainer.create_policy(parsed_behavior_id0, brain_params_team0)\n trainer.add_policy(parsed_behavior_id0, policy)\n trajectory_queue0 = AgentManagerQueue(brain_params_team0.brain_name)\n trainer.subscribe_trajectory_queue(trajectory_queue0)\n\n # Ghost trainer should ignore this queue because off policy\n parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team1.brain_name\n )\n policy = trainer.create_policy(parsed_behavior_id1, brain_params_team1)\n trainer.add_policy(parsed_behavior_id1, policy)\n trajectory_queue1 = AgentManagerQueue(brain_params_team1.brain_name)\n trainer.subscribe_trajectory_queue(trajectory_queue1)\n\n time_horizon = 15\n trajectory = make_fake_trajectory(\n length=time_horizon,\n max_step_complete=True,\n vec_obs_size=1,\n num_vis_obs=0,\n action_space=[2],\n )\n trajectory_queue0.put(trajectory)\n trainer.advance()\n\n # Check that trainer put trajectory in update buffer\n assert trainer.trainer.update_buffer.num_experiences == 15\n\n trajectory_queue1.put(trajectory)\n trainer.advance()\n\n # Check that ghost trainer ignored off policy queue\n assert trainer.trainer.update_buffer.num_experiences == 15\n # Check that it emptied the queue\n assert trajectory_queue1.empty()\n\n\ndef test_publish_queue(dummy_config):\n brain_params_team0 = BrainParameters(\n brain_name=\"test_brain?team=0\",\n vector_observation_space_size=8,\n camera_resolutions=[],\n vector_action_space_size=[1],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n\n parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team0.brain_name\n )\n\n brain_name = parsed_behavior_id0.brain_name\n\n brain_params_team1 = BrainParameters(\n brain_name=\"test_brain?team=1\",\n vector_observation_space_size=8,\n camera_resolutions=[],\n vector_action_space_size=[1],\n vector_action_descriptions=[],\n vector_action_space_type=0,\n )\n ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, \"0\")\n controller = GhostController(100)\n trainer = GhostTrainer(\n ppo_trainer, brain_name, controller, 0, dummy_config, True, \"0\"\n )\n\n # First policy encountered becomes policy trained by wrapped PPO\n # This queue should remain empty after swap snapshot\n policy = trainer.create_policy(parsed_behavior_id0, brain_params_team0)\n trainer.add_policy(parsed_behavior_id0, policy)\n policy_queue0 = AgentManagerQueue(brain_params_team0.brain_name)\n trainer.publish_policy_queue(policy_queue0)\n\n # Ghost trainer should use this queue for ghost policy swap\n parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(\n brain_params_team1.brain_name\n )\n policy = trainer.create_policy(parsed_behavior_id1, brain_params_team1)\n trainer.add_policy(parsed_behavior_id1, policy)\n policy_queue1 = AgentManagerQueue(brain_params_team1.brain_name)\n trainer.publish_policy_queue(policy_queue1)\n\n # check ghost trainer swap pushes to ghost queue and not trainer\n assert policy_queue0.empty() and policy_queue1.empty()\n trainer._swap_snapshots()\n assert policy_queue0.empty() and not policy_queue1.empty()\n # clear\n policy_queue1.get_nowait()\n\n mock_brain = mb.setup_mock_brain(\n False,\n False,\n vector_action_space=VECTOR_ACTION_SPACE,\n vector_obs_space=VECTOR_OBS_SPACE,\n discrete_action_space=DISCRETE_ACTION_SPACE,\n )\n\n buffer = mb.simulate_rollout(BUFFER_INIT_SAMPLES, mock_brain)\n # Mock out reward signal eval\n buffer[\"extrinsic_rewards\"] = buffer[\"environment_rewards\"]\n buffer[\"extrinsic_returns\"] = buffer[\"environment_rewards\"]\n buffer[\"extrinsic_value_estimates\"] = buffer[\"environment_rewards\"]\n buffer[\"curiosity_rewards\"] = buffer[\"environment_rewards\"]\n buffer[\"curiosity_returns\"] = buffer[\"environment_rewards\"]\n buffer[\"curiosity_value_estimates\"] = buffer[\"environment_rewards\"]\n buffer[\"advantages\"] = buffer[\"environment_rewards\"]\n trainer.trainer.update_buffer = buffer\n\n # when ghost trainer advance and wrapped trainer buffers full\n # the wrapped trainer pushes updated policy to correct queue\n assert policy_queue0.empty() and policy_queue1.empty()\n trainer.advance()\n assert not policy_queue0.empty() and policy_queue1.empty()\n\n\nif __name__ == \"__main__\":\n pytest.main()\n"
] |
[
[
"numpy.testing.assert_array_equal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lcx366/SphericalPolygon
|
[
"5594f54bcc2aef2c0ff2aca26a710f76548f050e"
] |
[
"sphericalpolygon/inertia.py"
] |
[
"import numpy as np\nfrom scipy.integrate import dblquad\nfrom .excess_area import polygon_excess\nfrom .functions import *\n\ndef polygon_inertia(vertices):\n '''\n Calculate the geometrical inertia tensor of a spherical polygon over a unit sphere.\n\n Usage:\n inertia = polygon_inertia(vertices)\n\n Inputs:\n vertices -> [float 2d array] Vertices of the spherical polygon in form of [[lat_0,lon_0],..,[lat_n,lon_n]] with unit of degrees.\n Vertices can be arranged either counterclockwise or clockwise.\n\n Outputs:\n inertia -> [float array with 6 elements] geometrical inertia tensor; it is symmetrical and has six independent components.\n\n Note: The spherical polygon has a latitude range of [-90°,90°] and a longitude range of [-180°,180°] or [0°,360°].\n ''' \n N = len(vertices)\n \n # Initialize the 6 components of the geometrical inertia tensor\n sum11,sum22,sum33,sum12,sum13,sum23 = np.zeros(6)\n\n for i in range(N - 1):\n p1 = np.radians(vertices[i])\n p2 = np.radians(vertices[i+1]) \n \n pdlon = p2[1]-p1[1]\n if pdlon < -np.pi: p2[1] = p2[1] + 2*np.pi \n if pdlon > np.pi: p2[1] = p2[1] - 2*np.pi \n \n # If two adjacent vertices are close enough(coincident), do nothing. \n if np.abs(pdlon) < 1e-6: continue \n \n c1,c2,c3= integrate_coeffs(p1,p2) \n\n # Calculate the geometrical inertia tensor \n s11 = dblquad(f11, p1[1], p2[1], fs_low,fs_up)\n s22 = dblquad(f22, p1[1], p2[1], fs_low,fs_up)\n s33 = dblquad(f33, p1[1], p2[1], fs_low,fs_up)\n s12 = dblquad(f12, p1[1], p2[1], fs_low,fs_up)\n s13 = dblquad(f13, p1[1], p2[1], fs_low,fs_up)\n s23 = dblquad(f23, p1[1], p2[1], fs_low,fs_up)\n \n sum11 += s11[0] \n sum22 += s22[0]\n sum33 += s33[0] \n sum12 += s12[0] \n sum13 += s13[0] \n sum23 += s23[0] \n \n excess = polygon_excess(vertices) \n \n # For counterclockwise arrangement\n if excess > 0 and excess < 2*np.pi: \n inertia11 = excess - sum11 \n inertia22 = excess - sum22 \n inertia33 = excess - sum33 \n \n inertia12 = -sum12 \n inertia13 = -sum13 \n inertia23 = -sum23 \n \n if excess >= 2*np.pi: \n inertia11 = 8/3*np.pi - (excess - sum11)\n inertia22 = 8/3*np.pi - (excess - sum22)\n inertia33 = 8/3*np.pi - (excess - sum33) \n \n inertia12 = sum12 \n inertia13 = sum13 \n inertia23 = sum23 \n \n # For clockwise arrangement\n if excess < 0 and excess > -2*np.pi: \n inertia11 = -excess + sum11\n inertia22 = -excess + sum22\n inertia33 = -excess + sum33 \n \n inertia12 = sum12 \n inertia13 = sum13 \n inertia23 = sum23 \n \n if excess <= -2*np.pi: \n inertia11 = 8/3*np.pi - (-excess + sum11)\n inertia22 = 8/3*np.pi - (-excess + sum22)\n inertia33 = 8/3*np.pi - (-excess + sum33)\n \n inertia12 = -sum12 \n inertia13 = -sum13 \n inertia23 = -sum23 \n \n return np.array([inertia11,inertia22,inertia33,inertia12,inertia13,inertia23])"
] |
[
[
"numpy.radians",
"numpy.abs",
"scipy.integrate.dblquad",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
liyupeng/Paddle-Lite
|
[
"e821d4d6f62f71534f594afc74560738bf02a879"
] |
[
"lite/tests/unittest_py/op/test_generate_proposals_op.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 sys\nsys.path.append('../')\n\nfrom auto_scan_test import AutoScanTest, IgnoreReasons\nfrom program_config import TensorConfig, ProgramConfig, OpConfig, CxxConfig, TargetType, PrecisionType, DataLayoutType, Place\nimport unittest\n\nimport hypothesis\nfrom hypothesis import given, settings, seed, example, assume\n\nimport numpy as np\nfrom functools import partial\nimport hypothesis.strategies as st\n\n\nclass TestGenerateProposalsOp(AutoScanTest):\n def __init__(self, *args, **kwargs):\n AutoScanTest.__init__(self, *args, **kwargs)\n self.enable_testing_on_place(TargetType.Host, PrecisionType.FP32, DataLayoutType.NCHW, thread=[1, 4])\n\n def is_program_valid(self, program_config: ProgramConfig , predictor_config: CxxConfig) -> bool:\n return True\n\n def sample_program_configs(self, draw):\n in_shape = draw(st.lists(st.integers(min_value=16, max_value=32), min_size=4, max_size=4))\n in_shape[0] = 1\n anchor_sizes = draw(st.sampled_from([[32.0], [32.0, 64.0], [64.0, 128.0], [32.0, 64.0, 128.0]]))\n aspect_ratios = draw(st.sampled_from([[1.0], [1.0, 2.0], [0.5, 1.0, 2.0]])) \n variances = draw(st.lists(st.floats(min_value=0.5, max_value=1.5), min_size=4, max_size=4))\n stride = draw(st.sampled_from([[16.0, 16.0], [24.0, 24.0], [16.0, 24.0]]))\n num_anchors = len(anchor_sizes) * len(aspect_ratios)\n\n anchor_generator_op = OpConfig(\n type = \"anchor_generator\",\n inputs = {\"Input\" : [\"input_data\"]},\n outputs = {\"Anchors\": [\"anchors_data\"],\n \"Variances\": [\"variance_data\"]},\n attrs = {\"anchor_sizes\": anchor_sizes,\n \"aspect_ratios\": aspect_ratios,\n \"stride\": stride,\n \"variances\": variances,\n \"offset\": 0.5\n }) \n\n scale = draw(st.floats(min_value=1, max_value=1))\n scores_shape = [in_shape[0], num_anchors, in_shape[2], in_shape[3]]\n bbox_delta_shape = [scores_shape[0], scores_shape[1] * 4, scores_shape[2], scores_shape[3]]\n\n pre_nms_topN = draw(st.integers(min_value=2000, max_value=8000))\n post_nms_topN = draw(st.integers(min_value=1000, max_value=1500))\n nms_thresh = draw(st.floats(min_value=0.5, max_value=0.8))\n min_size = draw(st.floats(min_value=2, max_value=4))\n eta = draw(st.floats(min_value=0.5, max_value=1.5))\n\n def generate_im_info(*args, **kwargs):\n return np.array([in_shape[2] * stride[0], in_shape[3] * stride[1], scale]).astype(np.float32)\n\n generate_proposals_op = OpConfig(\n type = \"generate_proposals\",\n inputs = {\n \"Scores\" : [\"scores_data\"], \n \"BboxDeltas\" : [\"bbox_delta_data\"], \n \"ImInfo\" : [\"im_info_data\"], \n \"Anchors\" : [\"anchors_data\"],\n \"Variances\" : [\"variance_data\"]\n },\n outputs = {\n \"RpnRois\": [\"rpn_rois_data\"], \n \"RpnRoiProbs\" : [\"rpn_rois_probs_data\"],\n \"RpnRoisNum\" : [\"rpn_rois_num_data\"]\n },\n attrs = {\n \"pre_nms_topN\" : pre_nms_topN,\n \"post_nms_topN\" : post_nms_topN,\n \"nms_thresh\" : nms_thresh,\n \"min_size\" : min_size,\n \"eta\" : eta\n })\n program_config = ProgramConfig(\n ops=[anchor_generator_op, generate_proposals_op],\n weights={},\n inputs={\n \"input_data\":\n TensorConfig(shape=in_shape),\n \"scores_data\":\n TensorConfig(shape=scores_shape),\n \"bbox_delta_data\":\n TensorConfig(shape=bbox_delta_shape),\n \"im_info_data\":\n TensorConfig(data_gen=partial(generate_im_info))\n },\n outputs=[\"rpn_rois_data\", \"rpn_rois_probs_data\", \"rpn_rois_num_data\"])\n return program_config\n\n def sample_predictor_configs(self):\n return self.get_predictor_configs(), [\"anchor_generator\"], (1e-5, 1e-5)\n\n def add_ignore_pass_case(self):\n pass\n\n def test(self, *args, **kwargs):\n self.run_and_statis(quant=False, max_examples=25)\n\nif __name__ == \"__main__\":\n unittest.main(argv=[''])\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shalarewicz/pandas
|
[
"070341cf4958652343f798c74c04a8c15de2fd04",
"070341cf4958652343f798c74c04a8c15de2fd04"
] |
[
"pandas/core/strings/accessor.py",
"pandas/core/reshape/reshape.py"
] |
[
"import codecs\nfrom functools import wraps\nimport re\nfrom typing import (\n Dict,\n List,\n Optional,\n)\nimport warnings\n\nimport numpy as np\n\nimport pandas._libs.lib as lib\nfrom pandas.util._decorators import Appender\n\nfrom pandas.core.dtypes.common import (\n ensure_object,\n is_bool_dtype,\n is_categorical_dtype,\n is_integer,\n is_list_like,\n is_re,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCIndex,\n ABCMultiIndex,\n ABCSeries,\n)\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas.core.base import NoNewAttributesMixin\n\n_shared_docs: Dict[str, str] = {}\n_cpython_optimized_encoders = (\n \"utf-8\",\n \"utf8\",\n \"latin-1\",\n \"latin1\",\n \"iso-8859-1\",\n \"mbcs\",\n \"ascii\",\n)\n_cpython_optimized_decoders = _cpython_optimized_encoders + (\"utf-16\", \"utf-32\")\n\n\ndef forbid_nonstring_types(forbidden, name=None):\n \"\"\"\n Decorator to forbid specific types for a method of StringMethods.\n\n For calling `.str.{method}` on a Series or Index, it is necessary to first\n initialize the :class:`StringMethods` object, and then call the method.\n However, different methods allow different input types, and so this can not\n be checked during :meth:`StringMethods.__init__`, but must be done on a\n per-method basis. This decorator exists to facilitate this process, and\n make it explicit which (inferred) types are disallowed by the method.\n\n :meth:`StringMethods.__init__` allows the *union* of types its different\n methods allow (after skipping NaNs; see :meth:`StringMethods._validate`),\n namely: ['string', 'empty', 'bytes', 'mixed', 'mixed-integer'].\n\n The default string types ['string', 'empty'] are allowed for all methods.\n For the additional types ['bytes', 'mixed', 'mixed-integer'], each method\n then needs to forbid the types it is not intended for.\n\n Parameters\n ----------\n forbidden : list-of-str or None\n List of forbidden non-string types, may be one or more of\n `['bytes', 'mixed', 'mixed-integer']`.\n name : str, default None\n Name of the method to use in the error message. By default, this is\n None, in which case the name from the method being wrapped will be\n copied. However, for working with further wrappers (like _pat_wrapper\n and _noarg_wrapper), it is necessary to specify the name.\n\n Returns\n -------\n func : wrapper\n The method to which the decorator is applied, with an added check that\n enforces the inferred type to not be in the list of forbidden types.\n\n Raises\n ------\n TypeError\n If the inferred type of the underlying data is in `forbidden`.\n \"\"\"\n # deal with None\n forbidden = [] if forbidden is None else forbidden\n\n allowed_types = {\"string\", \"empty\", \"bytes\", \"mixed\", \"mixed-integer\"} - set(\n forbidden\n )\n\n def _forbid_nonstring_types(func):\n func_name = func.__name__ if name is None else name\n\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n if self._inferred_dtype not in allowed_types:\n msg = (\n f\"Cannot use .str.{func_name} with values of \"\n f\"inferred dtype '{self._inferred_dtype}'.\"\n )\n raise TypeError(msg)\n return func(self, *args, **kwargs)\n\n wrapper.__name__ = func_name\n return wrapper\n\n return _forbid_nonstring_types\n\n\ndef _map_and_wrap(name, docstring):\n @forbid_nonstring_types([\"bytes\"], name=name)\n def wrapper(self):\n result = getattr(self._data.array, f\"_str_{name}\")()\n return self._wrap_result(result)\n\n wrapper.__doc__ = docstring\n return wrapper\n\n\nclass StringMethods(NoNewAttributesMixin):\n \"\"\"\n Vectorized string functions for Series and Index.\n\n NAs stay NA unless handled otherwise by a particular method.\n Patterned after Python's string methods, with some inspiration from\n R's stringr package.\n\n Examples\n --------\n >>> s = pd.Series([\"A_Str_Series\"])\n >>> s\n 0 A_Str_Series\n dtype: object\n\n >>> s.str.split(\"_\")\n 0 [A, Str, Series]\n dtype: object\n\n >>> s.str.replace(\"_\", \"\")\n 0 AStrSeries\n dtype: object\n \"\"\"\n\n # Note: see the docstring in pandas.core.strings.__init__\n # for an explanation of the implementation.\n # TODO: Dispatch all the methods\n # Currently the following are not dispatched to the array\n # * cat\n # * extract\n # * extractall\n\n def __init__(self, data):\n from pandas.core.arrays.string_ import StringDtype\n from pandas.core.arrays.string_arrow import ArrowStringDtype\n\n self._inferred_dtype = self._validate(data)\n self._is_categorical = is_categorical_dtype(data.dtype)\n self._is_string = isinstance(data.dtype, (StringDtype, ArrowStringDtype))\n self._data = data\n\n self._index = self._name = None\n if isinstance(data, ABCSeries):\n self._index = data.index\n self._name = data.name\n\n # ._values.categories works for both Series/Index\n self._parent = data._values.categories if self._is_categorical else data\n # save orig to blow up categoricals to the right type\n self._orig = data\n self._freeze()\n\n @staticmethod\n def _validate(data):\n \"\"\"\n Auxiliary function for StringMethods, infers and checks dtype of data.\n\n This is a \"first line of defence\" at the creation of the StringMethods-\n object, and just checks that the dtype is in the\n *union* of the allowed types over all string methods below; this\n restriction is then refined on a per-method basis using the decorator\n @forbid_nonstring_types (more info in the corresponding docstring).\n\n This really should exclude all series/index with any non-string values,\n but that isn't practical for performance reasons until we have a str\n dtype (GH 9343 / 13877)\n\n Parameters\n ----------\n data : The content of the Series\n\n Returns\n -------\n dtype : inferred dtype of data\n \"\"\"\n if isinstance(data, ABCMultiIndex):\n raise AttributeError(\n \"Can only use .str accessor with Index, not MultiIndex\"\n )\n\n # see _libs/lib.pyx for list of inferred types\n allowed_types = [\"string\", \"empty\", \"bytes\", \"mixed\", \"mixed-integer\"]\n\n values = getattr(data, \"values\", data) # Series / Index\n values = getattr(values, \"categories\", values) # categorical / normal\n\n inferred_dtype = lib.infer_dtype(values, skipna=True)\n\n if inferred_dtype not in allowed_types:\n raise AttributeError(\"Can only use .str accessor with string values!\")\n return inferred_dtype\n\n def __getitem__(self, key):\n result = self._data.array._str_getitem(key)\n return self._wrap_result(result)\n\n def __iter__(self):\n warnings.warn(\n \"Columnar iteration over characters will be deprecated in future releases.\",\n FutureWarning,\n stacklevel=2,\n )\n i = 0\n g = self.get(i)\n while g.notna().any():\n yield g\n i += 1\n g = self.get(i)\n\n def _wrap_result(\n self,\n result,\n name=None,\n expand=None,\n fill_value=np.nan,\n returns_string=True,\n ):\n from pandas import (\n Index,\n MultiIndex,\n )\n\n if not hasattr(result, \"ndim\") or not hasattr(result, \"dtype\"):\n if isinstance(result, ABCDataFrame):\n result = result.__finalize__(self._orig, name=\"str\")\n return result\n assert result.ndim < 3\n\n # We can be wrapping a string / object / categorical result, in which\n # case we'll want to return the same dtype as the input.\n # Or we can be wrapping a numeric output, in which case we don't want\n # to return a StringArray.\n # Ideally the array method returns the right array type.\n if expand is None:\n # infer from ndim if expand is not specified\n expand = result.ndim != 1\n\n elif expand is True and not isinstance(self._orig, ABCIndex):\n # required when expand=True is explicitly specified\n # not needed when inferred\n\n def cons_row(x):\n if is_list_like(x):\n return x\n else:\n return [x]\n\n result = [cons_row(x) for x in result]\n if result:\n # propagate nan values to match longest sequence (GH 18450)\n max_len = max(len(x) for x in result)\n result = [\n x * max_len if len(x) == 0 or x[0] is np.nan else x for x in result\n ]\n\n if not isinstance(expand, bool):\n raise ValueError(\"expand must be True or False\")\n\n if expand is False:\n # if expand is False, result should have the same name\n # as the original otherwise specified\n if name is None:\n name = getattr(result, \"name\", None)\n if name is None:\n # do not use logical or, _orig may be a DataFrame\n # which has \"name\" column\n name = self._orig.name\n\n # Wait until we are sure result is a Series or Index before\n # checking attributes (GH 12180)\n if isinstance(self._orig, ABCIndex):\n # if result is a boolean np.array, return the np.array\n # instead of wrapping it into a boolean Index (GH 8875)\n if is_bool_dtype(result):\n return result\n\n if expand:\n result = list(result)\n out = MultiIndex.from_tuples(result, names=name)\n if out.nlevels == 1:\n # We had all tuples of length-one, which are\n # better represented as a regular Index.\n out = out.get_level_values(0)\n return out\n else:\n return Index(result, name=name)\n else:\n index = self._orig.index\n # This is a mess.\n dtype: Optional[str]\n if self._is_string and returns_string:\n dtype = self._orig.dtype\n else:\n dtype = None\n\n if expand:\n cons = self._orig._constructor_expanddim\n result = cons(result, columns=name, index=index, dtype=dtype)\n else:\n # Must be a Series\n cons = self._orig._constructor\n result = cons(result, name=name, index=index)\n result = result.__finalize__(self._orig, method=\"str\")\n if name is not None and result.ndim == 1:\n # __finalize__ might copy over the original name, but we may\n # want the new name (e.g. str.extract).\n result.name = name\n return result\n\n def _get_series_list(self, others):\n \"\"\"\n Auxiliary function for :meth:`str.cat`. Turn potentially mixed input\n into a list of Series (elements without an index must match the length\n of the calling Series/Index).\n\n Parameters\n ----------\n others : Series, DataFrame, np.ndarray, list-like or list-like of\n Objects that are either Series, Index or np.ndarray (1-dim).\n\n Returns\n -------\n list of Series\n Others transformed into list of Series.\n \"\"\"\n from pandas import (\n DataFrame,\n Series,\n )\n\n # self._orig is either Series or Index\n idx = self._orig if isinstance(self._orig, ABCIndex) else self._orig.index\n\n # Generally speaking, all objects without an index inherit the index\n # `idx` of the calling Series/Index - i.e. must have matching length.\n # Objects with an index (i.e. Series/Index/DataFrame) keep their own.\n if isinstance(others, ABCSeries):\n return [others]\n elif isinstance(others, ABCIndex):\n return [Series(others._values, index=idx)]\n elif isinstance(others, ABCDataFrame):\n return [others[x] for x in others]\n elif isinstance(others, np.ndarray) and others.ndim == 2:\n others = DataFrame(others, index=idx)\n return [others[x] for x in others]\n elif is_list_like(others, allow_sets=False):\n others = list(others) # ensure iterators do not get read twice etc\n\n # in case of list-like `others`, all elements must be\n # either Series/Index/np.ndarray (1-dim)...\n if all(\n isinstance(x, (ABCSeries, ABCIndex))\n or (isinstance(x, np.ndarray) and x.ndim == 1)\n for x in others\n ):\n los: List[Series] = []\n while others: # iterate through list and append each element\n los = los + self._get_series_list(others.pop(0))\n return los\n # ... or just strings\n elif all(not is_list_like(x) for x in others):\n return [Series(others, index=idx)]\n raise TypeError(\n \"others must be Series, Index, DataFrame, np.ndarray \"\n \"or list-like (either containing only strings or \"\n \"containing only objects of type Series/Index/\"\n \"np.ndarray[1-dim])\"\n )\n\n @forbid_nonstring_types([\"bytes\", \"mixed\", \"mixed-integer\"])\n def cat(self, others=None, sep=None, na_rep=None, join=\"left\"):\n \"\"\"\n Concatenate strings in the Series/Index with given separator.\n\n If `others` is specified, this function concatenates the Series/Index\n and elements of `others` element-wise.\n If `others` is not passed, then all values in the Series/Index are\n concatenated into a single string with a given `sep`.\n\n Parameters\n ----------\n others : Series, Index, DataFrame, np.ndarray or list-like\n Series, Index, DataFrame, np.ndarray (one- or two-dimensional) and\n other list-likes of strings must have the same length as the\n calling Series/Index, with the exception of indexed objects (i.e.\n Series/Index/DataFrame) if `join` is not None.\n\n If others is a list-like that contains a combination of Series,\n Index or np.ndarray (1-dim), then all elements will be unpacked and\n must satisfy the above criteria individually.\n\n If others is None, the method returns the concatenation of all\n strings in the calling Series/Index.\n sep : str, default ''\n The separator between the different elements/columns. By default\n the empty string `''` is used.\n na_rep : str or None, default None\n Representation that is inserted for all missing values:\n\n - If `na_rep` is None, and `others` is None, missing values in the\n Series/Index are omitted from the result.\n - If `na_rep` is None, and `others` is not None, a row containing a\n missing value in any of the columns (before concatenation) will\n have a missing value in the result.\n join : {'left', 'right', 'outer', 'inner'}, default 'left'\n Determines the join-style between the calling Series/Index and any\n Series/Index/DataFrame in `others` (objects without an index need\n to match the length of the calling Series/Index). To disable\n alignment, use `.values` on any Series/Index/DataFrame in `others`.\n\n .. versionadded:: 0.23.0\n .. versionchanged:: 1.0.0\n Changed default of `join` from None to `'left'`.\n\n Returns\n -------\n str, Series or Index\n If `others` is None, `str` is returned, otherwise a `Series/Index`\n (same type as caller) of objects is returned.\n\n See Also\n --------\n split : Split each string in the Series/Index.\n join : Join lists contained as elements in the Series/Index.\n\n Examples\n --------\n When not passing `others`, all values are concatenated into a single\n string:\n\n >>> s = pd.Series(['a', 'b', np.nan, 'd'])\n >>> s.str.cat(sep=' ')\n 'a b d'\n\n By default, NA values in the Series are ignored. Using `na_rep`, they\n can be given a representation:\n\n >>> s.str.cat(sep=' ', na_rep='?')\n 'a b ? d'\n\n If `others` is specified, corresponding values are concatenated with\n the separator. Result will be a Series of strings.\n\n >>> s.str.cat(['A', 'B', 'C', 'D'], sep=',')\n 0 a,A\n 1 b,B\n 2 NaN\n 3 d,D\n dtype: object\n\n Missing values will remain missing in the result, but can again be\n represented using `na_rep`\n\n >>> s.str.cat(['A', 'B', 'C', 'D'], sep=',', na_rep='-')\n 0 a,A\n 1 b,B\n 2 -,C\n 3 d,D\n dtype: object\n\n If `sep` is not specified, the values are concatenated without\n separation.\n\n >>> s.str.cat(['A', 'B', 'C', 'D'], na_rep='-')\n 0 aA\n 1 bB\n 2 -C\n 3 dD\n dtype: object\n\n Series with different indexes can be aligned before concatenation. The\n `join`-keyword works as in other methods.\n\n >>> t = pd.Series(['d', 'a', 'e', 'c'], index=[3, 0, 4, 2])\n >>> s.str.cat(t, join='left', na_rep='-')\n 0 aa\n 1 b-\n 2 -c\n 3 dd\n dtype: object\n >>>\n >>> s.str.cat(t, join='outer', na_rep='-')\n 0 aa\n 1 b-\n 2 -c\n 3 dd\n 4 -e\n dtype: object\n >>>\n >>> s.str.cat(t, join='inner', na_rep='-')\n 0 aa\n 2 -c\n 3 dd\n dtype: object\n >>>\n >>> s.str.cat(t, join='right', na_rep='-')\n 3 dd\n 0 aa\n 4 -e\n 2 -c\n dtype: object\n\n For more examples, see :ref:`here <text.concatenate>`.\n \"\"\"\n # TODO: dispatch\n from pandas import (\n Index,\n Series,\n concat,\n )\n\n if isinstance(others, str):\n raise ValueError(\"Did you mean to supply a `sep` keyword?\")\n if sep is None:\n sep = \"\"\n\n if isinstance(self._orig, ABCIndex):\n data = Series(self._orig, index=self._orig)\n else: # Series\n data = self._orig\n\n # concatenate Series/Index with itself if no \"others\"\n if others is None:\n # error: Incompatible types in assignment (expression has type\n # \"ndarray\", variable has type \"Series\")\n data = ensure_object(data) # type: ignore[assignment]\n na_mask = isna(data)\n if na_rep is None and na_mask.any():\n data = data[~na_mask]\n elif na_rep is not None and na_mask.any():\n data = np.where(na_mask, na_rep, data)\n return sep.join(data)\n\n try:\n # turn anything in \"others\" into lists of Series\n others = self._get_series_list(others)\n except ValueError as err: # do not catch TypeError raised by _get_series_list\n raise ValueError(\n \"If `others` contains arrays or lists (or other \"\n \"list-likes without an index), these must all be \"\n \"of the same length as the calling Series/Index.\"\n ) from err\n\n # align if required\n if any(not data.index.equals(x.index) for x in others):\n # Need to add keys for uniqueness in case of duplicate columns\n others = concat(\n others,\n axis=1,\n join=(join if join == \"inner\" else \"outer\"),\n keys=range(len(others)),\n sort=False,\n copy=False,\n )\n data, others = data.align(others, join=join)\n others = [others[x] for x in others] # again list of Series\n\n all_cols = [ensure_object(x) for x in [data] + others]\n na_masks = np.array([isna(x) for x in all_cols])\n union_mask = np.logical_or.reduce(na_masks, axis=0)\n\n if na_rep is None and union_mask.any():\n # no na_rep means NaNs for all rows where any column has a NaN\n # only necessary if there are actually any NaNs\n result = np.empty(len(data), dtype=object)\n np.putmask(result, union_mask, np.nan)\n\n not_masked = ~union_mask\n result[not_masked] = cat_safe([x[not_masked] for x in all_cols], sep)\n elif na_rep is not None and union_mask.any():\n # fill NaNs with na_rep in case there are actually any NaNs\n all_cols = [\n np.where(nm, na_rep, col) for nm, col in zip(na_masks, all_cols)\n ]\n result = cat_safe(all_cols, sep)\n else:\n # no NaNs - can just concatenate\n result = cat_safe(all_cols, sep)\n\n if isinstance(self._orig, ABCIndex):\n # add dtype for case that result is all-NA\n\n # error: Incompatible types in assignment (expression has type\n # \"Index\", variable has type \"ndarray\")\n result = Index( # type: ignore[assignment]\n result, dtype=object, name=self._orig.name\n )\n else: # Series\n if is_categorical_dtype(self._orig.dtype):\n # We need to infer the new categories.\n dtype = None\n else:\n dtype = self._orig.dtype\n # error: Incompatible types in assignment (expression has type\n # \"Series\", variable has type \"ndarray\")\n result = Series( # type: ignore[assignment]\n result, dtype=dtype, index=data.index, name=self._orig.name\n )\n # error: \"ndarray\" has no attribute \"__finalize__\"\n result = result.__finalize__( # type: ignore[attr-defined]\n self._orig, method=\"str_cat\"\n )\n return result\n\n _shared_docs[\n \"str_split\"\n ] = r\"\"\"\n Split strings around given separator/delimiter.\n\n Splits the string in the Series/Index from the %(side)s,\n at the specified delimiter string. Equivalent to :meth:`str.%(method)s`.\n\n Parameters\n ----------\n pat : str, optional\n String or regular expression to split on.\n If not specified, split on whitespace.\n n : int, default -1 (all)\n Limit number of splits in output.\n ``None``, 0 and -1 will be interpreted as return all splits.\n expand : bool, default False\n Expand the split strings into separate columns.\n\n * If ``True``, return DataFrame/MultiIndex expanding dimensionality.\n * If ``False``, return Series/Index, containing lists of strings.\n\n Returns\n -------\n Series, Index, DataFrame or MultiIndex\n Type matches caller unless ``expand=True`` (see Notes).\n\n See Also\n --------\n Series.str.split : Split strings around given separator/delimiter.\n Series.str.rsplit : Splits string around given separator/delimiter,\n starting from the right.\n Series.str.join : Join lists contained as elements in the Series/Index\n with passed delimiter.\n str.split : Standard library version for split.\n str.rsplit : Standard library version for rsplit.\n\n Notes\n -----\n The handling of the `n` keyword depends on the number of found splits:\n\n - If found splits > `n`, make first `n` splits only\n - If found splits <= `n`, make all splits\n - If for a certain row the number of found splits < `n`,\n append `None` for padding up to `n` if ``expand=True``\n\n If using ``expand=True``, Series and Index callers return DataFrame and\n MultiIndex objects, respectively.\n\n Examples\n --------\n >>> s = pd.Series(\n ... [\n ... \"this is a regular sentence\",\n ... \"https://docs.python.org/3/tutorial/index.html\",\n ... np.nan\n ... ]\n ... )\n >>> s\n 0 this is a regular sentence\n 1 https://docs.python.org/3/tutorial/index.html\n 2 NaN\n dtype: object\n\n In the default setting, the string is split by whitespace.\n\n >>> s.str.split()\n 0 [this, is, a, regular, sentence]\n 1 [https://docs.python.org/3/tutorial/index.html]\n 2 NaN\n dtype: object\n\n Without the `n` parameter, the outputs of `rsplit` and `split`\n are identical.\n\n >>> s.str.rsplit()\n 0 [this, is, a, regular, sentence]\n 1 [https://docs.python.org/3/tutorial/index.html]\n 2 NaN\n dtype: object\n\n The `n` parameter can be used to limit the number of splits on the\n delimiter. The outputs of `split` and `rsplit` are different.\n\n >>> s.str.split(n=2)\n 0 [this, is, a regular sentence]\n 1 [https://docs.python.org/3/tutorial/index.html]\n 2 NaN\n dtype: object\n\n >>> s.str.rsplit(n=2)\n 0 [this is a, regular, sentence]\n 1 [https://docs.python.org/3/tutorial/index.html]\n 2 NaN\n dtype: object\n\n The `pat` parameter can be used to split by other characters.\n\n >>> s.str.split(pat=\"/\")\n 0 [this is a regular sentence]\n 1 [https:, , docs.python.org, 3, tutorial, index...\n 2 NaN\n dtype: object\n\n When using ``expand=True``, the split elements will expand out into\n separate columns. If NaN is present, it is propagated throughout\n the columns during the split.\n\n >>> s.str.split(expand=True)\n 0 1 2 3 4\n 0 this is a regular sentence\n 1 https://docs.python.org/3/tutorial/index.html None None None None\n 2 NaN NaN NaN NaN NaN\n\n For slightly more complex use cases like splitting the html document name\n from a url, a combination of parameter settings can be used.\n\n >>> s.str.rsplit(\"/\", n=1, expand=True)\n 0 1\n 0 this is a regular sentence None\n 1 https://docs.python.org/3/tutorial index.html\n 2 NaN NaN\n\n Remember to escape special characters when explicitly using regular\n expressions.\n\n >>> s = pd.Series([\"1+1=2\"])\n >>> s\n 0 1+1=2\n dtype: object\n >>> s.str.split(r\"\\+|=\", expand=True)\n 0 1 2\n 0 1 1 2\n \"\"\"\n\n @Appender(_shared_docs[\"str_split\"] % {\"side\": \"beginning\", \"method\": \"split\"})\n @forbid_nonstring_types([\"bytes\"])\n def split(self, pat=None, n=-1, expand=False):\n result = self._data.array._str_split(pat, n, expand)\n return self._wrap_result(result, returns_string=expand, expand=expand)\n\n @Appender(_shared_docs[\"str_split\"] % {\"side\": \"end\", \"method\": \"rsplit\"})\n @forbid_nonstring_types([\"bytes\"])\n def rsplit(self, pat=None, n=-1, expand=False):\n result = self._data.array._str_rsplit(pat, n=n)\n return self._wrap_result(result, expand=expand, returns_string=expand)\n\n _shared_docs[\n \"str_partition\"\n ] = \"\"\"\n Split the string at the %(side)s occurrence of `sep`.\n\n This method splits the string at the %(side)s occurrence of `sep`,\n and returns 3 elements containing the part before the separator,\n the separator itself, and the part after the separator.\n If the separator is not found, return %(return)s.\n\n Parameters\n ----------\n sep : str, default whitespace\n String to split on.\n expand : bool, default True\n If True, return DataFrame/MultiIndex expanding dimensionality.\n If False, return Series/Index.\n\n Returns\n -------\n DataFrame/MultiIndex or Series/Index of objects\n\n See Also\n --------\n %(also)s\n Series.str.split : Split strings around given separators.\n str.partition : Standard library version.\n\n Examples\n --------\n\n >>> s = pd.Series(['Linda van der Berg', 'George Pitt-Rivers'])\n >>> s\n 0 Linda van der Berg\n 1 George Pitt-Rivers\n dtype: object\n\n >>> s.str.partition()\n 0 1 2\n 0 Linda van der Berg\n 1 George Pitt-Rivers\n\n To partition by the last space instead of the first one:\n\n >>> s.str.rpartition()\n 0 1 2\n 0 Linda van der Berg\n 1 George Pitt-Rivers\n\n To partition by something different than a space:\n\n >>> s.str.partition('-')\n 0 1 2\n 0 Linda van der Berg\n 1 George Pitt - Rivers\n\n To return a Series containing tuples instead of a DataFrame:\n\n >>> s.str.partition('-', expand=False)\n 0 (Linda van der Berg, , )\n 1 (George Pitt, -, Rivers)\n dtype: object\n\n Also available on indices:\n\n >>> idx = pd.Index(['X 123', 'Y 999'])\n >>> idx\n Index(['X 123', 'Y 999'], dtype='object')\n\n Which will create a MultiIndex:\n\n >>> idx.str.partition()\n MultiIndex([('X', ' ', '123'),\n ('Y', ' ', '999')],\n )\n\n Or an index with tuples with ``expand=False``:\n\n >>> idx.str.partition(expand=False)\n Index([('X', ' ', '123'), ('Y', ' ', '999')], dtype='object')\n \"\"\"\n\n @Appender(\n _shared_docs[\"str_partition\"]\n % {\n \"side\": \"first\",\n \"return\": \"3 elements containing the string itself, followed by two \"\n \"empty strings\",\n \"also\": \"rpartition : Split the string at the last occurrence of `sep`.\",\n }\n )\n @forbid_nonstring_types([\"bytes\"])\n def partition(self, sep=\" \", expand=True):\n result = self._data.array._str_partition(sep, expand)\n return self._wrap_result(result, expand=expand, returns_string=expand)\n\n @Appender(\n _shared_docs[\"str_partition\"]\n % {\n \"side\": \"last\",\n \"return\": \"3 elements containing two empty strings, followed by the \"\n \"string itself\",\n \"also\": \"partition : Split the string at the first occurrence of `sep`.\",\n }\n )\n @forbid_nonstring_types([\"bytes\"])\n def rpartition(self, sep=\" \", expand=True):\n result = self._data.array._str_rpartition(sep, expand)\n return self._wrap_result(result, expand=expand, returns_string=expand)\n\n def get(self, i):\n \"\"\"\n Extract element from each component at specified position.\n\n Extract element from lists, tuples, or strings in each element in the\n Series/Index.\n\n Parameters\n ----------\n i : int\n Position of element to extract.\n\n Returns\n -------\n Series or Index\n\n Examples\n --------\n >>> s = pd.Series([\"String\",\n ... (1, 2, 3),\n ... [\"a\", \"b\", \"c\"],\n ... 123,\n ... -456,\n ... {1: \"Hello\", \"2\": \"World\"}])\n >>> s\n 0 String\n 1 (1, 2, 3)\n 2 [a, b, c]\n 3 123\n 4 -456\n 5 {1: 'Hello', '2': 'World'}\n dtype: object\n\n >>> s.str.get(1)\n 0 t\n 1 2\n 2 b\n 3 NaN\n 4 NaN\n 5 Hello\n dtype: object\n\n >>> s.str.get(-1)\n 0 g\n 1 3\n 2 c\n 3 NaN\n 4 NaN\n 5 None\n dtype: object\n \"\"\"\n result = self._data.array._str_get(i)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def join(self, sep):\n \"\"\"\n Join lists contained as elements in the Series/Index with passed delimiter.\n\n If the elements of a Series are lists themselves, join the content of these\n lists using the delimiter passed to the function.\n This function is an equivalent to :meth:`str.join`.\n\n Parameters\n ----------\n sep : str\n Delimiter to use between list entries.\n\n Returns\n -------\n Series/Index: object\n The list entries concatenated by intervening occurrences of the\n delimiter.\n\n Raises\n ------\n AttributeError\n If the supplied Series contains neither strings nor lists.\n\n See Also\n --------\n str.join : Standard library version of this method.\n Series.str.split : Split strings around given separator/delimiter.\n\n Notes\n -----\n If any of the list items is not a string object, the result of the join\n will be `NaN`.\n\n Examples\n --------\n Example with a list that contains non-string elements.\n\n >>> s = pd.Series([['lion', 'elephant', 'zebra'],\n ... [1.1, 2.2, 3.3],\n ... ['cat', np.nan, 'dog'],\n ... ['cow', 4.5, 'goat'],\n ... ['duck', ['swan', 'fish'], 'guppy']])\n >>> s\n 0 [lion, elephant, zebra]\n 1 [1.1, 2.2, 3.3]\n 2 [cat, nan, dog]\n 3 [cow, 4.5, goat]\n 4 [duck, [swan, fish], guppy]\n dtype: object\n\n Join all lists using a '-'. The lists containing object(s) of types other\n than str will produce a NaN.\n\n >>> s.str.join('-')\n 0 lion-elephant-zebra\n 1 NaN\n 2 NaN\n 3 NaN\n 4 NaN\n dtype: object\n \"\"\"\n result = self._data.array._str_join(sep)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def contains(self, pat, case=True, flags=0, na=None, regex=True):\n r\"\"\"\n Test if pattern or regex is contained within a string of a Series or Index.\n\n Return boolean Series or Index based on whether a given pattern or regex is\n contained within a string of a Series or Index.\n\n Parameters\n ----------\n pat : str\n Character sequence or regular expression.\n case : bool, default True\n If True, case sensitive.\n flags : int, default 0 (no flags)\n Flags to pass through to the re module, e.g. re.IGNORECASE.\n na : scalar, optional\n Fill value for missing values. The default depends on dtype of the\n array. For object-dtype, ``numpy.nan`` is used. For ``StringDtype``,\n ``pandas.NA`` is used.\n regex : bool, default True\n If True, assumes the pat is a regular expression.\n\n If False, treats the pat as a literal string.\n\n Returns\n -------\n Series or Index of boolean values\n A Series or Index of boolean values indicating whether the\n given pattern is contained within the string of each element\n of the Series or Index.\n\n See Also\n --------\n match : Analogous, but stricter, relying on re.match instead of re.search.\n Series.str.startswith : Test if the start of each string element matches a\n pattern.\n Series.str.endswith : Same as startswith, but tests the end of string.\n\n Examples\n --------\n Returning a Series of booleans using only a literal pattern.\n\n >>> s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN])\n >>> s1.str.contains('og', regex=False)\n 0 False\n 1 True\n 2 False\n 3 False\n 4 NaN\n dtype: object\n\n Returning an Index of booleans using only a literal pattern.\n\n >>> ind = pd.Index(['Mouse', 'dog', 'house and parrot', '23.0', np.NaN])\n >>> ind.str.contains('23', regex=False)\n Index([False, False, False, True, nan], dtype='object')\n\n Specifying case sensitivity using `case`.\n\n >>> s1.str.contains('oG', case=True, regex=True)\n 0 False\n 1 False\n 2 False\n 3 False\n 4 NaN\n dtype: object\n\n Specifying `na` to be `False` instead of `NaN` replaces NaN values\n with `False`. If Series or Index does not contain NaN values\n the resultant dtype will be `bool`, otherwise, an `object` dtype.\n\n >>> s1.str.contains('og', na=False, regex=True)\n 0 False\n 1 True\n 2 False\n 3 False\n 4 False\n dtype: bool\n\n Returning 'house' or 'dog' when either expression occurs in a string.\n\n >>> s1.str.contains('house|dog', regex=True)\n 0 False\n 1 True\n 2 True\n 3 False\n 4 NaN\n dtype: object\n\n Ignoring case sensitivity using `flags` with regex.\n\n >>> import re\n >>> s1.str.contains('PARROT', flags=re.IGNORECASE, regex=True)\n 0 False\n 1 False\n 2 True\n 3 False\n 4 NaN\n dtype: object\n\n Returning any digit using regular expression.\n\n >>> s1.str.contains('\\\\d', regex=True)\n 0 False\n 1 False\n 2 False\n 3 True\n 4 NaN\n dtype: object\n\n Ensure `pat` is a not a literal pattern when `regex` is set to True.\n Note in the following example one might expect only `s2[1]` and `s2[3]` to\n return `True`. However, '.0' as a regex matches any character\n followed by a 0.\n\n >>> s2 = pd.Series(['40', '40.0', '41', '41.0', '35'])\n >>> s2.str.contains('.0', regex=True)\n 0 True\n 1 True\n 2 False\n 3 True\n 4 False\n dtype: bool\n \"\"\"\n if regex and re.compile(pat).groups:\n warnings.warn(\n \"This pattern has match groups. To actually get the \"\n \"groups, use str.extract.\",\n UserWarning,\n stacklevel=3,\n )\n\n result = self._data.array._str_contains(pat, case, flags, na, regex)\n return self._wrap_result(result, fill_value=na, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def match(self, pat, case=True, flags=0, na=None):\n \"\"\"\n Determine if each string starts with a match of a regular expression.\n\n Parameters\n ----------\n pat : str\n Character sequence or regular expression.\n case : bool, default True\n If True, case sensitive.\n flags : int, default 0 (no flags)\n Regex module flags, e.g. re.IGNORECASE.\n na : scalar, optional\n Fill value for missing values. The default depends on dtype of the\n array. For object-dtype, ``numpy.nan`` is used. For ``StringDtype``,\n ``pandas.NA`` is used.\n\n Returns\n -------\n Series/array of boolean values\n\n See Also\n --------\n fullmatch : Stricter matching that requires the entire string to match.\n contains : Analogous, but less strict, relying on re.search instead of\n re.match.\n extract : Extract matched groups.\n \"\"\"\n result = self._data.array._str_match(pat, case=case, flags=flags, na=na)\n return self._wrap_result(result, fill_value=na, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def fullmatch(self, pat, case=True, flags=0, na=None):\n \"\"\"\n Determine if each string entirely matches a regular expression.\n\n .. versionadded:: 1.1.0\n\n Parameters\n ----------\n pat : str\n Character sequence or regular expression.\n case : bool, default True\n If True, case sensitive.\n flags : int, default 0 (no flags)\n Regex module flags, e.g. re.IGNORECASE.\n na : scalar, optional.\n Fill value for missing values. The default depends on dtype of the\n array. For object-dtype, ``numpy.nan`` is used. For ``StringDtype``,\n ``pandas.NA`` is used.\n\n Returns\n -------\n Series/array of boolean values\n\n See Also\n --------\n match : Similar, but also returns `True` when only a *prefix* of the string\n matches the regular expression.\n extract : Extract matched groups.\n \"\"\"\n result = self._data.array._str_fullmatch(pat, case=case, flags=flags, na=na)\n return self._wrap_result(result, fill_value=na, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):\n r\"\"\"\n Replace each occurrence of pattern/regex in the Series/Index.\n\n Equivalent to :meth:`str.replace` or :func:`re.sub`, depending on\n the regex value.\n\n Parameters\n ----------\n pat : str or compiled regex\n String can be a character sequence or regular expression.\n repl : str or callable\n Replacement string or a callable. The callable is passed the regex\n match object and must return a replacement string to be used.\n See :func:`re.sub`.\n n : int, default -1 (all)\n Number of replacements to make from start.\n case : bool, default None\n Determines if replace is case sensitive:\n\n - If True, case sensitive (the default if `pat` is a string)\n - Set to False for case insensitive\n - Cannot be set if `pat` is a compiled regex.\n\n flags : int, default 0 (no flags)\n Regex module flags, e.g. re.IGNORECASE. Cannot be set if `pat` is a compiled\n regex.\n regex : bool, default True\n Determines if assumes the passed-in pattern is a regular expression:\n\n - If True, assumes the passed-in pattern is a regular expression.\n - If False, treats the pattern as a literal string\n - Cannot be set to False if `pat` is a compiled regex or `repl` is\n a callable.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n Series or Index of object\n A copy of the object with all matching occurrences of `pat` replaced by\n `repl`.\n\n Raises\n ------\n ValueError\n * if `regex` is False and `repl` is a callable or `pat` is a compiled\n regex\n * if `pat` is a compiled regex and `case` or `flags` is set\n\n Notes\n -----\n When `pat` is a compiled regex, all flags should be included in the\n compiled regex. Use of `case`, `flags`, or `regex=False` with a compiled\n regex will raise an error.\n\n Examples\n --------\n When `pat` is a string and `regex` is True (the default), the given `pat`\n is compiled as a regex. When `repl` is a string, it replaces matching\n regex patterns as with :meth:`re.sub`. NaN value(s) in the Series are\n left as is:\n\n >>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f.', 'ba', regex=True)\n 0 bao\n 1 baz\n 2 NaN\n dtype: object\n\n When `pat` is a string and `regex` is False, every `pat` is replaced with\n `repl` as with :meth:`str.replace`:\n\n >>> pd.Series(['f.o', 'fuz', np.nan]).str.replace('f.', 'ba', regex=False)\n 0 bao\n 1 fuz\n 2 NaN\n dtype: object\n\n When `repl` is a callable, it is called on every `pat` using\n :func:`re.sub`. The callable should expect one positional argument\n (a regex object) and return a string.\n\n To get the idea:\n\n >>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f', repr)\n 0 <re.Match object; span=(0, 1), match='f'>oo\n 1 <re.Match object; span=(0, 1), match='f'>uz\n 2 NaN\n dtype: object\n\n Reverse every lowercase alphabetic word:\n\n >>> repl = lambda m: m.group(0)[::-1]\n >>> pd.Series(['foo 123', 'bar baz', np.nan]).str.replace(r'[a-z]+', repl)\n 0 oof 123\n 1 rab zab\n 2 NaN\n dtype: object\n\n Using regex groups (extract second group and swap case):\n\n >>> pat = r\"(?P<one>\\w+) (?P<two>\\w+) (?P<three>\\w+)\"\n >>> repl = lambda m: m.group('two').swapcase()\n >>> pd.Series(['One Two Three', 'Foo Bar Baz']).str.replace(pat, repl)\n 0 tWO\n 1 bAR\n dtype: object\n\n Using a compiled regex with flags\n\n >>> import re\n >>> regex_pat = re.compile(r'FUZ', flags=re.IGNORECASE)\n >>> pd.Series(['foo', 'fuz', np.nan]).str.replace(regex_pat, 'bar')\n 0 foo\n 1 bar\n 2 NaN\n dtype: object\n \"\"\"\n if regex is None:\n if isinstance(pat, str) and any(c in pat for c in \".+*|^$?[](){}\\\\\"):\n # warn only in cases where regex behavior would differ from literal\n msg = (\n \"The default value of regex will change from True to False \"\n \"in a future version.\"\n )\n if len(pat) == 1:\n msg += (\n \" In addition, single character regular expressions will\"\n \"*not* be treated as literal strings when regex=True.\"\n )\n warnings.warn(msg, FutureWarning, stacklevel=3)\n regex = True\n\n # Check whether repl is valid (GH 13438, GH 15055)\n if not (isinstance(repl, str) or callable(repl)):\n raise TypeError(\"repl must be a string or callable\")\n\n is_compiled_re = is_re(pat)\n if regex:\n if is_compiled_re:\n if (case is not None) or (flags != 0):\n raise ValueError(\n \"case and flags cannot be set when pat is a compiled regex\"\n )\n elif case is None:\n # not a compiled regex, set default case\n case = True\n\n elif is_compiled_re:\n raise ValueError(\n \"Cannot use a compiled regex as replacement pattern with regex=False\"\n )\n elif callable(repl):\n raise ValueError(\"Cannot use a callable replacement when regex=False\")\n\n result = self._data.array._str_replace(\n pat, repl, n=n, case=case, flags=flags, regex=regex\n )\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def repeat(self, repeats):\n \"\"\"\n Duplicate each string in the Series or Index.\n\n Parameters\n ----------\n repeats : int or sequence of int\n Same value for all (int) or different value per (sequence).\n\n Returns\n -------\n Series or Index of object\n Series or Index of repeated string objects specified by\n input parameter repeats.\n\n Examples\n --------\n >>> s = pd.Series(['a', 'b', 'c'])\n >>> s\n 0 a\n 1 b\n 2 c\n dtype: object\n\n Single int repeats string in Series\n\n >>> s.str.repeat(repeats=2)\n 0 aa\n 1 bb\n 2 cc\n dtype: object\n\n Sequence of int repeats corresponding string in Series\n\n >>> s.str.repeat(repeats=[1, 2, 3])\n 0 a\n 1 bb\n 2 ccc\n dtype: object\n \"\"\"\n result = self._data.array._str_repeat(repeats)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def pad(self, width, side=\"left\", fillchar=\" \"):\n \"\"\"\n Pad strings in the Series/Index up to width.\n\n Parameters\n ----------\n width : int\n Minimum width of resulting string; additional characters will be filled\n with character defined in `fillchar`.\n side : {'left', 'right', 'both'}, default 'left'\n Side from which to fill resulting string.\n fillchar : str, default ' '\n Additional character for filling, default is whitespace.\n\n Returns\n -------\n Series or Index of object\n Returns Series or Index with minimum number of char in object.\n\n See Also\n --------\n Series.str.rjust : Fills the left side of strings with an arbitrary\n character. Equivalent to ``Series.str.pad(side='left')``.\n Series.str.ljust : Fills the right side of strings with an arbitrary\n character. Equivalent to ``Series.str.pad(side='right')``.\n Series.str.center : Fills both sides of strings with an arbitrary\n character. Equivalent to ``Series.str.pad(side='both')``.\n Series.str.zfill : Pad strings in the Series/Index by prepending '0'\n character. Equivalent to ``Series.str.pad(side='left', fillchar='0')``.\n\n Examples\n --------\n >>> s = pd.Series([\"caribou\", \"tiger\"])\n >>> s\n 0 caribou\n 1 tiger\n dtype: object\n\n >>> s.str.pad(width=10)\n 0 caribou\n 1 tiger\n dtype: object\n\n >>> s.str.pad(width=10, side='right', fillchar='-')\n 0 caribou---\n 1 tiger-----\n dtype: object\n\n >>> s.str.pad(width=10, side='both', fillchar='-')\n 0 -caribou--\n 1 --tiger---\n dtype: object\n \"\"\"\n if not isinstance(fillchar, str):\n msg = f\"fillchar must be a character, not {type(fillchar).__name__}\"\n raise TypeError(msg)\n\n if len(fillchar) != 1:\n raise TypeError(\"fillchar must be a character, not str\")\n\n if not is_integer(width):\n msg = f\"width must be of integer type, not {type(width).__name__}\"\n raise TypeError(msg)\n\n result = self._data.array._str_pad(width, side=side, fillchar=fillchar)\n return self._wrap_result(result)\n\n _shared_docs[\n \"str_pad\"\n ] = \"\"\"\n Pad %(side)s side of strings in the Series/Index.\n\n Equivalent to :meth:`str.%(method)s`.\n\n Parameters\n ----------\n width : int\n Minimum width of resulting string; additional characters will be filled\n with ``fillchar``.\n fillchar : str\n Additional character for filling, default is whitespace.\n\n Returns\n -------\n filled : Series/Index of objects.\n \"\"\"\n\n @Appender(_shared_docs[\"str_pad\"] % {\"side\": \"left and right\", \"method\": \"center\"})\n @forbid_nonstring_types([\"bytes\"])\n def center(self, width, fillchar=\" \"):\n return self.pad(width, side=\"both\", fillchar=fillchar)\n\n @Appender(_shared_docs[\"str_pad\"] % {\"side\": \"right\", \"method\": \"ljust\"})\n @forbid_nonstring_types([\"bytes\"])\n def ljust(self, width, fillchar=\" \"):\n return self.pad(width, side=\"right\", fillchar=fillchar)\n\n @Appender(_shared_docs[\"str_pad\"] % {\"side\": \"left\", \"method\": \"rjust\"})\n @forbid_nonstring_types([\"bytes\"])\n def rjust(self, width, fillchar=\" \"):\n return self.pad(width, side=\"left\", fillchar=fillchar)\n\n @forbid_nonstring_types([\"bytes\"])\n def zfill(self, width):\n \"\"\"\n Pad strings in the Series/Index by prepending '0' characters.\n\n Strings in the Series/Index are padded with '0' characters on the\n left of the string to reach a total string length `width`. Strings\n in the Series/Index with length greater or equal to `width` are\n unchanged.\n\n Parameters\n ----------\n width : int\n Minimum length of resulting string; strings with length less\n than `width` be prepended with '0' characters.\n\n Returns\n -------\n Series/Index of objects.\n\n See Also\n --------\n Series.str.rjust : Fills the left side of strings with an arbitrary\n character.\n Series.str.ljust : Fills the right side of strings with an arbitrary\n character.\n Series.str.pad : Fills the specified sides of strings with an arbitrary\n character.\n Series.str.center : Fills both sides of strings with an arbitrary\n character.\n\n Notes\n -----\n Differs from :meth:`str.zfill` which has special handling\n for '+'/'-' in the string.\n\n Examples\n --------\n >>> s = pd.Series(['-1', '1', '1000', 10, np.nan])\n >>> s\n 0 -1\n 1 1\n 2 1000\n 3 10\n 4 NaN\n dtype: object\n\n Note that ``10`` and ``NaN`` are not strings, therefore they are\n converted to ``NaN``. The minus sign in ``'-1'`` is treated as a\n regular character and the zero is added to the left of it\n (:meth:`str.zfill` would have moved it to the left). ``1000``\n remains unchanged as it is longer than `width`.\n\n >>> s.str.zfill(3)\n 0 0-1\n 1 001\n 2 1000\n 3 NaN\n 4 NaN\n dtype: object\n \"\"\"\n result = self.pad(width, side=\"left\", fillchar=\"0\")\n return self._wrap_result(result)\n\n def slice(self, start=None, stop=None, step=None):\n \"\"\"\n Slice substrings from each element in the Series or Index.\n\n Parameters\n ----------\n start : int, optional\n Start position for slice operation.\n stop : int, optional\n Stop position for slice operation.\n step : int, optional\n Step size for slice operation.\n\n Returns\n -------\n Series or Index of object\n Series or Index from sliced substring from original string object.\n\n See Also\n --------\n Series.str.slice_replace : Replace a slice with a string.\n Series.str.get : Return element at position.\n Equivalent to `Series.str.slice(start=i, stop=i+1)` with `i`\n being the position.\n\n Examples\n --------\n >>> s = pd.Series([\"koala\", \"dog\", \"chameleon\"])\n >>> s\n 0 koala\n 1 dog\n 2 chameleon\n dtype: object\n\n >>> s.str.slice(start=1)\n 0 oala\n 1 og\n 2 hameleon\n dtype: object\n\n >>> s.str.slice(start=-1)\n 0 a\n 1 g\n 2 n\n dtype: object\n\n >>> s.str.slice(stop=2)\n 0 ko\n 1 do\n 2 ch\n dtype: object\n\n >>> s.str.slice(step=2)\n 0 kaa\n 1 dg\n 2 caeen\n dtype: object\n\n >>> s.str.slice(start=0, stop=5, step=3)\n 0 kl\n 1 d\n 2 cm\n dtype: object\n\n Equivalent behaviour to:\n\n >>> s.str[0:5:3]\n 0 kl\n 1 d\n 2 cm\n dtype: object\n \"\"\"\n result = self._data.array._str_slice(start, stop, step)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def slice_replace(self, start=None, stop=None, repl=None):\n \"\"\"\n Replace a positional slice of a string with another value.\n\n Parameters\n ----------\n start : int, optional\n Left index position to use for the slice. If not specified (None),\n the slice is unbounded on the left, i.e. slice from the start\n of the string.\n stop : int, optional\n Right index position to use for the slice. If not specified (None),\n the slice is unbounded on the right, i.e. slice until the\n end of the string.\n repl : str, optional\n String for replacement. If not specified (None), the sliced region\n is replaced with an empty string.\n\n Returns\n -------\n Series or Index\n Same type as the original object.\n\n See Also\n --------\n Series.str.slice : Just slicing without replacement.\n\n Examples\n --------\n >>> s = pd.Series(['a', 'ab', 'abc', 'abdc', 'abcde'])\n >>> s\n 0 a\n 1 ab\n 2 abc\n 3 abdc\n 4 abcde\n dtype: object\n\n Specify just `start`, meaning replace `start` until the end of the\n string with `repl`.\n\n >>> s.str.slice_replace(1, repl='X')\n 0 aX\n 1 aX\n 2 aX\n 3 aX\n 4 aX\n dtype: object\n\n Specify just `stop`, meaning the start of the string to `stop` is replaced\n with `repl`, and the rest of the string is included.\n\n >>> s.str.slice_replace(stop=2, repl='X')\n 0 X\n 1 X\n 2 Xc\n 3 Xdc\n 4 Xcde\n dtype: object\n\n Specify `start` and `stop`, meaning the slice from `start` to `stop` is\n replaced with `repl`. Everything before or after `start` and `stop` is\n included as is.\n\n >>> s.str.slice_replace(start=1, stop=3, repl='X')\n 0 aX\n 1 aX\n 2 aX\n 3 aXc\n 4 aXde\n dtype: object\n \"\"\"\n result = self._data.array._str_slice_replace(start, stop, repl)\n return self._wrap_result(result)\n\n def decode(self, encoding, errors=\"strict\"):\n \"\"\"\n Decode character string in the Series/Index using indicated encoding.\n\n Equivalent to :meth:`str.decode` in python2 and :meth:`bytes.decode` in\n python3.\n\n Parameters\n ----------\n encoding : str\n errors : str, optional\n\n Returns\n -------\n Series or Index\n \"\"\"\n # TODO: Add a similar _bytes interface.\n if encoding in _cpython_optimized_decoders:\n # CPython optimized implementation\n f = lambda x: x.decode(encoding, errors)\n else:\n decoder = codecs.getdecoder(encoding)\n f = lambda x: decoder(x, errors)[0]\n arr = self._data.array\n # assert isinstance(arr, (StringArray,))\n result = arr._str_map(f)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def encode(self, encoding, errors=\"strict\"):\n \"\"\"\n Encode character string in the Series/Index using indicated encoding.\n\n Equivalent to :meth:`str.encode`.\n\n Parameters\n ----------\n encoding : str\n errors : str, optional\n\n Returns\n -------\n encoded : Series/Index of objects\n \"\"\"\n result = self._data.array._str_encode(encoding, errors)\n return self._wrap_result(result, returns_string=False)\n\n _shared_docs[\n \"str_strip\"\n ] = r\"\"\"\n Remove %(position)s characters.\n\n Strip whitespaces (including newlines) or a set of specified characters\n from each string in the Series/Index from %(side)s.\n Equivalent to :meth:`str.%(method)s`.\n\n Parameters\n ----------\n to_strip : str or None, default None\n Specifying the set of characters to be removed.\n All combinations of this set of characters will be stripped.\n If None then whitespaces are removed.\n\n Returns\n -------\n Series or Index of object\n\n See Also\n --------\n Series.str.strip : Remove leading and trailing characters in Series/Index.\n Series.str.lstrip : Remove leading characters in Series/Index.\n Series.str.rstrip : Remove trailing characters in Series/Index.\n\n Examples\n --------\n >>> s = pd.Series(['1. Ant. ', '2. Bee!\\n', '3. Cat?\\t', np.nan])\n >>> s\n 0 1. Ant.\n 1 2. Bee!\\n\n 2 3. Cat?\\t\n 3 NaN\n dtype: object\n\n >>> s.str.strip()\n 0 1. Ant.\n 1 2. Bee!\n 2 3. Cat?\n 3 NaN\n dtype: object\n\n >>> s.str.lstrip('123.')\n 0 Ant.\n 1 Bee!\\n\n 2 Cat?\\t\n 3 NaN\n dtype: object\n\n >>> s.str.rstrip('.!? \\n\\t')\n 0 1. Ant\n 1 2. Bee\n 2 3. Cat\n 3 NaN\n dtype: object\n\n >>> s.str.strip('123.!? \\n\\t')\n 0 Ant\n 1 Bee\n 2 Cat\n 3 NaN\n dtype: object\n \"\"\"\n\n @Appender(\n _shared_docs[\"str_strip\"]\n % {\n \"side\": \"left and right sides\",\n \"method\": \"strip\",\n \"position\": \"leading and trailing\",\n }\n )\n @forbid_nonstring_types([\"bytes\"])\n def strip(self, to_strip=None):\n result = self._data.array._str_strip(to_strip)\n return self._wrap_result(result)\n\n @Appender(\n _shared_docs[\"str_strip\"]\n % {\"side\": \"left side\", \"method\": \"lstrip\", \"position\": \"leading\"}\n )\n @forbid_nonstring_types([\"bytes\"])\n def lstrip(self, to_strip=None):\n result = self._data.array._str_lstrip(to_strip)\n return self._wrap_result(result)\n\n @Appender(\n _shared_docs[\"str_strip\"]\n % {\"side\": \"right side\", \"method\": \"rstrip\", \"position\": \"trailing\"}\n )\n @forbid_nonstring_types([\"bytes\"])\n def rstrip(self, to_strip=None):\n result = self._data.array._str_rstrip(to_strip)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def wrap(self, width, **kwargs):\n r\"\"\"\n Wrap strings in Series/Index at specified line width.\n\n This method has the same keyword parameters and defaults as\n :class:`textwrap.TextWrapper`.\n\n Parameters\n ----------\n width : int\n Maximum line width.\n expand_tabs : bool, optional\n If True, tab characters will be expanded to spaces (default: True).\n replace_whitespace : bool, optional\n If True, each whitespace character (as defined by string.whitespace)\n remaining after tab expansion will be replaced by a single space\n (default: True).\n drop_whitespace : bool, optional\n If True, whitespace that, after wrapping, happens to end up at the\n beginning or end of a line is dropped (default: True).\n break_long_words : bool, optional\n If True, then words longer than width will be broken in order to ensure\n that no lines are longer than width. If it is false, long words will\n not be broken, and some lines may be longer than width (default: True).\n break_on_hyphens : bool, optional\n If True, wrapping will occur preferably on whitespace and right after\n hyphens in compound words, as it is customary in English. If false,\n only whitespaces will be considered as potentially good places for line\n breaks, but you need to set break_long_words to false if you want truly\n insecable words (default: True).\n\n Returns\n -------\n Series or Index\n\n Notes\n -----\n Internally, this method uses a :class:`textwrap.TextWrapper` instance with\n default settings. To achieve behavior matching R's stringr library str_wrap\n function, use the arguments:\n\n - expand_tabs = False\n - replace_whitespace = True\n - drop_whitespace = True\n - break_long_words = False\n - break_on_hyphens = False\n\n Examples\n --------\n >>> s = pd.Series(['line to be wrapped', 'another line to be wrapped'])\n >>> s.str.wrap(12)\n 0 line to be\\nwrapped\n 1 another line\\nto be\\nwrapped\n dtype: object\n \"\"\"\n result = self._data.array._str_wrap(width, **kwargs)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def get_dummies(self, sep=\"|\"):\n \"\"\"\n Return DataFrame of dummy/indicator variables for Series.\n\n Each string in Series is split by sep and returned as a DataFrame\n of dummy/indicator variables.\n\n Parameters\n ----------\n sep : str, default \"|\"\n String to split on.\n\n Returns\n -------\n DataFrame\n Dummy variables corresponding to values of the Series.\n\n See Also\n --------\n get_dummies : Convert categorical variable into dummy/indicator\n variables.\n\n Examples\n --------\n >>> pd.Series(['a|b', 'a', 'a|c']).str.get_dummies()\n a b c\n 0 1 1 0\n 1 1 0 0\n 2 1 0 1\n\n >>> pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies()\n a b c\n 0 1 1 0\n 1 0 0 0\n 2 1 0 1\n \"\"\"\n # we need to cast to Series of strings as only that has all\n # methods available for making the dummies...\n result, name = self._data.array._str_get_dummies(sep)\n return self._wrap_result(\n result,\n name=name,\n expand=True,\n returns_string=False,\n )\n\n @forbid_nonstring_types([\"bytes\"])\n def translate(self, table):\n \"\"\"\n Map all characters in the string through the given mapping table.\n\n Equivalent to standard :meth:`str.translate`.\n\n Parameters\n ----------\n table : dict\n Table is a mapping of Unicode ordinals to Unicode ordinals, strings, or\n None. Unmapped characters are left untouched.\n Characters mapped to None are deleted. :meth:`str.maketrans` is a\n helper function for making translation tables.\n\n Returns\n -------\n Series or Index\n \"\"\"\n result = self._data.array._str_translate(table)\n return self._wrap_result(result)\n\n @forbid_nonstring_types([\"bytes\"])\n def count(self, pat, flags=0):\n r\"\"\"\n Count occurrences of pattern in each string of the Series/Index.\n\n This function is used to count the number of times a particular regex\n pattern is repeated in each of the string elements of the\n :class:`~pandas.Series`.\n\n Parameters\n ----------\n pat : str\n Valid regular expression.\n flags : int, default 0, meaning no flags\n Flags for the `re` module. For a complete list, `see here\n <https://docs.python.org/3/howto/regex.html#compilation-flags>`_.\n **kwargs\n For compatibility with other string methods. Not used.\n\n Returns\n -------\n Series or Index\n Same type as the calling object containing the integer counts.\n\n See Also\n --------\n re : Standard library module for regular expressions.\n str.count : Standard library version, without regular expression support.\n\n Notes\n -----\n Some characters need to be escaped when passing in `pat`.\n eg. ``'$'`` has a special meaning in regex and must be escaped when\n finding this literal character.\n\n Examples\n --------\n >>> s = pd.Series(['A', 'B', 'Aaba', 'Baca', np.nan, 'CABA', 'cat'])\n >>> s.str.count('a')\n 0 0.0\n 1 0.0\n 2 2.0\n 3 2.0\n 4 NaN\n 5 0.0\n 6 1.0\n dtype: float64\n\n Escape ``'$'`` to find the literal dollar sign.\n\n >>> s = pd.Series(['$', 'B', 'Aab$', '$$ca', 'C$B$', 'cat'])\n >>> s.str.count('\\\\$')\n 0 1\n 1 0\n 2 1\n 3 2\n 4 2\n 5 0\n dtype: int64\n\n This is also available on Index\n\n >>> pd.Index(['A', 'A', 'Aaba', 'cat']).str.count('a')\n Int64Index([0, 0, 2, 1], dtype='int64')\n \"\"\"\n result = self._data.array._str_count(pat, flags)\n return self._wrap_result(result, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def startswith(self, pat, na=None):\n \"\"\"\n Test if the start of each string element matches a pattern.\n\n Equivalent to :meth:`str.startswith`.\n\n Parameters\n ----------\n pat : str\n Character sequence. Regular expressions are not accepted.\n na : object, default NaN\n Object shown if element tested is not a string. The default depends\n on dtype of the array. For object-dtype, ``numpy.nan`` is used.\n For ``StringDtype``, ``pandas.NA`` is used.\n\n Returns\n -------\n Series or Index of bool\n A Series of booleans indicating whether the given pattern matches\n the start of each string element.\n\n See Also\n --------\n str.startswith : Python standard library string method.\n Series.str.endswith : Same as startswith, but tests the end of string.\n Series.str.contains : Tests if string element contains a pattern.\n\n Examples\n --------\n >>> s = pd.Series(['bat', 'Bear', 'cat', np.nan])\n >>> s\n 0 bat\n 1 Bear\n 2 cat\n 3 NaN\n dtype: object\n\n >>> s.str.startswith('b')\n 0 True\n 1 False\n 2 False\n 3 NaN\n dtype: object\n\n Specifying `na` to be `False` instead of `NaN`.\n\n >>> s.str.startswith('b', na=False)\n 0 True\n 1 False\n 2 False\n 3 False\n dtype: bool\n \"\"\"\n result = self._data.array._str_startswith(pat, na=na)\n return self._wrap_result(result, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def endswith(self, pat, na=None):\n \"\"\"\n Test if the end of each string element matches a pattern.\n\n Equivalent to :meth:`str.endswith`.\n\n Parameters\n ----------\n pat : str\n Character sequence. Regular expressions are not accepted.\n na : object, default NaN\n Object shown if element tested is not a string. The default depends\n on dtype of the array. For object-dtype, ``numpy.nan`` is used.\n For ``StringDtype``, ``pandas.NA`` is used.\n\n Returns\n -------\n Series or Index of bool\n A Series of booleans indicating whether the given pattern matches\n the end of each string element.\n\n See Also\n --------\n str.endswith : Python standard library string method.\n Series.str.startswith : Same as endswith, but tests the start of string.\n Series.str.contains : Tests if string element contains a pattern.\n\n Examples\n --------\n >>> s = pd.Series(['bat', 'bear', 'caT', np.nan])\n >>> s\n 0 bat\n 1 bear\n 2 caT\n 3 NaN\n dtype: object\n\n >>> s.str.endswith('t')\n 0 True\n 1 False\n 2 False\n 3 NaN\n dtype: object\n\n Specifying `na` to be `False` instead of `NaN`.\n\n >>> s.str.endswith('t', na=False)\n 0 True\n 1 False\n 2 False\n 3 False\n dtype: bool\n \"\"\"\n result = self._data.array._str_endswith(pat, na=na)\n return self._wrap_result(result, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def findall(self, pat, flags=0):\n \"\"\"\n Find all occurrences of pattern or regular expression in the Series/Index.\n\n Equivalent to applying :func:`re.findall` to all the elements in the\n Series/Index.\n\n Parameters\n ----------\n pat : str\n Pattern or regular expression.\n flags : int, default 0\n Flags from ``re`` module, e.g. `re.IGNORECASE` (default is 0, which\n means no flags).\n\n Returns\n -------\n Series/Index of lists of strings\n All non-overlapping matches of pattern or regular expression in each\n string of this Series/Index.\n\n See Also\n --------\n count : Count occurrences of pattern or regular expression in each string\n of the Series/Index.\n extractall : For each string in the Series, extract groups from all matches\n of regular expression and return a DataFrame with one row for each\n match and one column for each group.\n re.findall : The equivalent ``re`` function to all non-overlapping matches\n of pattern or regular expression in string, as a list of strings.\n\n Examples\n --------\n >>> s = pd.Series(['Lion', 'Monkey', 'Rabbit'])\n\n The search for the pattern 'Monkey' returns one match:\n\n >>> s.str.findall('Monkey')\n 0 []\n 1 [Monkey]\n 2 []\n dtype: object\n\n On the other hand, the search for the pattern 'MONKEY' doesn't return any\n match:\n\n >>> s.str.findall('MONKEY')\n 0 []\n 1 []\n 2 []\n dtype: object\n\n Flags can be added to the pattern or regular expression. For instance,\n to find the pattern 'MONKEY' ignoring the case:\n\n >>> import re\n >>> s.str.findall('MONKEY', flags=re.IGNORECASE)\n 0 []\n 1 [Monkey]\n 2 []\n dtype: object\n\n When the pattern matches more than one string in the Series, all matches\n are returned:\n\n >>> s.str.findall('on')\n 0 [on]\n 1 [on]\n 2 []\n dtype: object\n\n Regular expressions are supported too. For instance, the search for all the\n strings ending with the word 'on' is shown next:\n\n >>> s.str.findall('on$')\n 0 [on]\n 1 []\n 2 []\n dtype: object\n\n If the pattern is found more than once in the same string, then a list of\n multiple strings is returned:\n\n >>> s.str.findall('b')\n 0 []\n 1 []\n 2 [b, b]\n dtype: object\n \"\"\"\n result = self._data.array._str_findall(pat, flags)\n return self._wrap_result(result, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def extract(self, pat, flags=0, expand=True):\n r\"\"\"\n Extract capture groups in the regex `pat` as columns in a DataFrame.\n\n For each subject string in the Series, extract groups from the\n first match of regular expression `pat`.\n\n Parameters\n ----------\n pat : str\n Regular expression pattern with capturing groups.\n flags : int, default 0 (no flags)\n Flags from the ``re`` module, e.g. ``re.IGNORECASE``, that\n modify regular expression matching for things like case,\n spaces, etc. For more details, see :mod:`re`.\n expand : bool, default True\n If True, return DataFrame with one column per capture group.\n If False, return a Series/Index if there is one capture group\n or DataFrame if there are multiple capture groups.\n\n Returns\n -------\n DataFrame or Series or Index\n A DataFrame with one row for each subject string, and one\n column for each group. Any capture group names in regular\n expression pat will be used for column names; otherwise\n capture group numbers will be used. The dtype of each result\n column is always object, even when no match is found. If\n ``expand=False`` and pat has only one capture group, then\n return a Series (if subject is a Series) or Index (if subject\n is an Index).\n\n See Also\n --------\n extractall : Returns all matches (not just the first match).\n\n Examples\n --------\n A pattern with two groups will return a DataFrame with two columns.\n Non-matches will be NaN.\n\n >>> s = pd.Series(['a1', 'b2', 'c3'])\n >>> s.str.extract(r'([ab])(\\d)')\n 0 1\n 0 a 1\n 1 b 2\n 2 NaN NaN\n\n A pattern may contain optional groups.\n\n >>> s.str.extract(r'([ab])?(\\d)')\n 0 1\n 0 a 1\n 1 b 2\n 2 NaN 3\n\n Named groups will become column names in the result.\n\n >>> s.str.extract(r'(?P<letter>[ab])(?P<digit>\\d)')\n letter digit\n 0 a 1\n 1 b 2\n 2 NaN NaN\n\n A pattern with one group will return a DataFrame with one column\n if expand=True.\n\n >>> s.str.extract(r'[ab](\\d)', expand=True)\n 0\n 0 1\n 1 2\n 2 NaN\n\n A pattern with one group will return a Series if expand=False.\n\n >>> s.str.extract(r'[ab](\\d)', expand=False)\n 0 1\n 1 2\n 2 NaN\n dtype: object\n \"\"\"\n # TODO: dispatch\n return str_extract(self, pat, flags, expand=expand)\n\n @forbid_nonstring_types([\"bytes\"])\n def extractall(self, pat, flags=0):\n r\"\"\"\n Extract capture groups in the regex `pat` as columns in DataFrame.\n\n For each subject string in the Series, extract groups from all\n matches of regular expression pat. When each subject string in the\n Series has exactly one match, extractall(pat).xs(0, level='match')\n is the same as extract(pat).\n\n Parameters\n ----------\n pat : str\n Regular expression pattern with capturing groups.\n flags : int, default 0 (no flags)\n A ``re`` module flag, for example ``re.IGNORECASE``. These allow\n to modify regular expression matching for things like case, spaces,\n etc. Multiple flags can be combined with the bitwise OR operator,\n for example ``re.IGNORECASE | re.MULTILINE``.\n\n Returns\n -------\n DataFrame\n A ``DataFrame`` with one row for each match, and one column for each\n group. Its rows have a ``MultiIndex`` with first levels that come from\n the subject ``Series``. The last level is named 'match' and indexes the\n matches in each item of the ``Series``. Any capture group names in\n regular expression pat will be used for column names; otherwise capture\n group numbers will be used.\n\n See Also\n --------\n extract : Returns first match only (not all matches).\n\n Examples\n --------\n A pattern with one group will return a DataFrame with one column.\n Indices with no matches will not appear in the result.\n\n >>> s = pd.Series([\"a1a2\", \"b1\", \"c1\"], index=[\"A\", \"B\", \"C\"])\n >>> s.str.extractall(r\"[ab](\\d)\")\n 0\n match\n A 0 1\n 1 2\n B 0 1\n\n Capture group names are used for column names of the result.\n\n >>> s.str.extractall(r\"[ab](?P<digit>\\d)\")\n digit\n match\n A 0 1\n 1 2\n B 0 1\n\n A pattern with two groups will return a DataFrame with two columns.\n\n >>> s.str.extractall(r\"(?P<letter>[ab])(?P<digit>\\d)\")\n letter digit\n match\n A 0 a 1\n 1 a 2\n B 0 b 1\n\n Optional groups that do not match are NaN in the result.\n\n >>> s.str.extractall(r\"(?P<letter>[ab])?(?P<digit>\\d)\")\n letter digit\n match\n A 0 a 1\n 1 a 2\n B 0 b 1\n C 0 NaN 1\n \"\"\"\n # TODO: dispatch\n return str_extractall(self._orig, pat, flags)\n\n _shared_docs[\n \"find\"\n ] = \"\"\"\n Return %(side)s indexes in each strings in the Series/Index.\n\n Each of returned indexes corresponds to the position where the\n substring is fully contained between [start:end]. Return -1 on\n failure. Equivalent to standard :meth:`str.%(method)s`.\n\n Parameters\n ----------\n sub : str\n Substring being searched.\n start : int\n Left edge index.\n end : int\n Right edge index.\n\n Returns\n -------\n Series or Index of int.\n\n See Also\n --------\n %(also)s\n \"\"\"\n\n @Appender(\n _shared_docs[\"find\"]\n % {\n \"side\": \"lowest\",\n \"method\": \"find\",\n \"also\": \"rfind : Return highest indexes in each strings.\",\n }\n )\n @forbid_nonstring_types([\"bytes\"])\n def find(self, sub, start=0, end=None):\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)\n\n result = self._data.array._str_find(sub, start, end)\n return self._wrap_result(result, returns_string=False)\n\n @Appender(\n _shared_docs[\"find\"]\n % {\n \"side\": \"highest\",\n \"method\": \"rfind\",\n \"also\": \"find : Return lowest indexes in each strings.\",\n }\n )\n @forbid_nonstring_types([\"bytes\"])\n def rfind(self, sub, start=0, end=None):\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)\n\n result = self._data.array._str_rfind(sub, start=start, end=end)\n return self._wrap_result(result, returns_string=False)\n\n @forbid_nonstring_types([\"bytes\"])\n def normalize(self, form):\n \"\"\"\n Return the Unicode normal form for the strings in the Series/Index.\n\n For more information on the forms, see the\n :func:`unicodedata.normalize`.\n\n Parameters\n ----------\n form : {'NFC', 'NFKC', 'NFD', 'NFKD'}\n Unicode form.\n\n Returns\n -------\n normalized : Series/Index of objects\n \"\"\"\n result = self._data.array._str_normalize(form)\n return self._wrap_result(result)\n\n _shared_docs[\n \"index\"\n ] = \"\"\"\n Return %(side)s indexes in each string in Series/Index.\n\n Each of the returned indexes corresponds to the position where the\n substring is fully contained between [start:end]. This is the same\n as ``str.%(similar)s`` except instead of returning -1, it raises a\n ValueError when the substring is not found. Equivalent to standard\n ``str.%(method)s``.\n\n Parameters\n ----------\n sub : str\n Substring being searched.\n start : int\n Left edge index.\n end : int\n Right edge index.\n\n Returns\n -------\n Series or Index of object\n\n See Also\n --------\n %(also)s\n \"\"\"\n\n @Appender(\n _shared_docs[\"index\"]\n % {\n \"side\": \"lowest\",\n \"similar\": \"find\",\n \"method\": \"index\",\n \"also\": \"rindex : Return highest indexes in each strings.\",\n }\n )\n @forbid_nonstring_types([\"bytes\"])\n def index(self, sub, start=0, end=None):\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)\n\n result = self._data.array._str_index(sub, start=start, end=end)\n return self._wrap_result(result, returns_string=False)\n\n @Appender(\n _shared_docs[\"index\"]\n % {\n \"side\": \"highest\",\n \"similar\": \"rfind\",\n \"method\": \"rindex\",\n \"also\": \"index : Return lowest indexes in each strings.\",\n }\n )\n @forbid_nonstring_types([\"bytes\"])\n def rindex(self, sub, start=0, end=None):\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)\n\n result = self._data.array._str_rindex(sub, start=start, end=end)\n return self._wrap_result(result, returns_string=False)\n\n def len(self):\n \"\"\"\n Compute the length of each element in the Series/Index.\n\n The element may be a sequence (such as a string, tuple or list) or a collection\n (such as a dictionary).\n\n Returns\n -------\n Series or Index of int\n A Series or Index of integer values indicating the length of each\n element in the Series or Index.\n\n See Also\n --------\n str.len : Python built-in function returning the length of an object.\n Series.size : Returns the length of the Series.\n\n Examples\n --------\n Returns the length (number of characters) in a string. Returns the\n number of entries for dictionaries, lists or tuples.\n\n >>> s = pd.Series(['dog',\n ... '',\n ... 5,\n ... {'foo' : 'bar'},\n ... [2, 3, 5, 7],\n ... ('one', 'two', 'three')])\n >>> s\n 0 dog\n 1\n 2 5\n 3 {'foo': 'bar'}\n 4 [2, 3, 5, 7]\n 5 (one, two, three)\n dtype: object\n >>> s.str.len()\n 0 3.0\n 1 0.0\n 2 NaN\n 3 1.0\n 4 4.0\n 5 3.0\n dtype: float64\n \"\"\"\n result = self._data.array._str_len()\n return self._wrap_result(result, returns_string=False)\n\n _shared_docs[\n \"casemethods\"\n ] = \"\"\"\n Convert strings in the Series/Index to %(type)s.\n %(version)s\n Equivalent to :meth:`str.%(method)s`.\n\n Returns\n -------\n Series or Index of object\n\n See Also\n --------\n Series.str.lower : Converts all characters to lowercase.\n Series.str.upper : Converts all characters to uppercase.\n Series.str.title : Converts first character of each word to uppercase and\n remaining to lowercase.\n Series.str.capitalize : Converts first character to uppercase and\n remaining to lowercase.\n Series.str.swapcase : Converts uppercase to lowercase and lowercase to\n uppercase.\n Series.str.casefold: Removes all case distinctions in the string.\n\n Examples\n --------\n >>> s = pd.Series(['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe'])\n >>> s\n 0 lower\n 1 CAPITALS\n 2 this is a sentence\n 3 SwApCaSe\n dtype: object\n\n >>> s.str.lower()\n 0 lower\n 1 capitals\n 2 this is a sentence\n 3 swapcase\n dtype: object\n\n >>> s.str.upper()\n 0 LOWER\n 1 CAPITALS\n 2 THIS IS A SENTENCE\n 3 SWAPCASE\n dtype: object\n\n >>> s.str.title()\n 0 Lower\n 1 Capitals\n 2 This Is A Sentence\n 3 Swapcase\n dtype: object\n\n >>> s.str.capitalize()\n 0 Lower\n 1 Capitals\n 2 This is a sentence\n 3 Swapcase\n dtype: object\n\n >>> s.str.swapcase()\n 0 LOWER\n 1 capitals\n 2 THIS IS A SENTENCE\n 3 sWaPcAsE\n dtype: object\n \"\"\"\n # Types:\n # cases:\n # upper, lower, title, capitalize, swapcase, casefold\n # boolean:\n # isalpha, isnumeric isalnum isdigit isdecimal isspace islower isupper istitle\n # _doc_args holds dict of strings to use in substituting casemethod docs\n _doc_args: Dict[str, Dict[str, str]] = {}\n _doc_args[\"lower\"] = {\"type\": \"lowercase\", \"method\": \"lower\", \"version\": \"\"}\n _doc_args[\"upper\"] = {\"type\": \"uppercase\", \"method\": \"upper\", \"version\": \"\"}\n _doc_args[\"title\"] = {\"type\": \"titlecase\", \"method\": \"title\", \"version\": \"\"}\n _doc_args[\"capitalize\"] = {\n \"type\": \"be capitalized\",\n \"method\": \"capitalize\",\n \"version\": \"\",\n }\n _doc_args[\"swapcase\"] = {\n \"type\": \"be swapcased\",\n \"method\": \"swapcase\",\n \"version\": \"\",\n }\n _doc_args[\"casefold\"] = {\n \"type\": \"be casefolded\",\n \"method\": \"casefold\",\n \"version\": \"\\n .. versionadded:: 0.25.0\\n\",\n }\n\n @Appender(_shared_docs[\"casemethods\"] % _doc_args[\"lower\"])\n @forbid_nonstring_types([\"bytes\"])\n def lower(self):\n result = self._data.array._str_lower()\n return self._wrap_result(result)\n\n @Appender(_shared_docs[\"casemethods\"] % _doc_args[\"upper\"])\n @forbid_nonstring_types([\"bytes\"])\n def upper(self):\n result = self._data.array._str_upper()\n return self._wrap_result(result)\n\n @Appender(_shared_docs[\"casemethods\"] % _doc_args[\"title\"])\n @forbid_nonstring_types([\"bytes\"])\n def title(self):\n result = self._data.array._str_title()\n return self._wrap_result(result)\n\n @Appender(_shared_docs[\"casemethods\"] % _doc_args[\"capitalize\"])\n @forbid_nonstring_types([\"bytes\"])\n def capitalize(self):\n result = self._data.array._str_capitalize()\n return self._wrap_result(result)\n\n @Appender(_shared_docs[\"casemethods\"] % _doc_args[\"swapcase\"])\n @forbid_nonstring_types([\"bytes\"])\n def swapcase(self):\n result = self._data.array._str_swapcase()\n return self._wrap_result(result)\n\n @Appender(_shared_docs[\"casemethods\"] % _doc_args[\"casefold\"])\n @forbid_nonstring_types([\"bytes\"])\n def casefold(self):\n result = self._data.array._str_casefold()\n return self._wrap_result(result)\n\n _shared_docs[\n \"ismethods\"\n ] = \"\"\"\n Check whether all characters in each string are %(type)s.\n\n This is equivalent to running the Python string method\n :meth:`str.%(method)s` for each element of the Series/Index. If a string\n has zero characters, ``False`` is returned for that check.\n\n Returns\n -------\n Series or Index of bool\n Series or Index of boolean values with the same length as the original\n Series/Index.\n\n See Also\n --------\n Series.str.isalpha : Check whether all characters are alphabetic.\n Series.str.isnumeric : Check whether all characters are numeric.\n Series.str.isalnum : Check whether all characters are alphanumeric.\n Series.str.isdigit : Check whether all characters are digits.\n Series.str.isdecimal : Check whether all characters are decimal.\n Series.str.isspace : Check whether all characters are whitespace.\n Series.str.islower : Check whether all characters are lowercase.\n Series.str.isupper : Check whether all characters are uppercase.\n Series.str.istitle : Check whether all characters are titlecase.\n\n Examples\n --------\n **Checks for Alphabetic and Numeric Characters**\n\n >>> s1 = pd.Series(['one', 'one1', '1', ''])\n\n >>> s1.str.isalpha()\n 0 True\n 1 False\n 2 False\n 3 False\n dtype: bool\n\n >>> s1.str.isnumeric()\n 0 False\n 1 False\n 2 True\n 3 False\n dtype: bool\n\n >>> s1.str.isalnum()\n 0 True\n 1 True\n 2 True\n 3 False\n dtype: bool\n\n Note that checks against characters mixed with any additional punctuation\n or whitespace will evaluate to false for an alphanumeric check.\n\n >>> s2 = pd.Series(['A B', '1.5', '3,000'])\n >>> s2.str.isalnum()\n 0 False\n 1 False\n 2 False\n dtype: bool\n\n **More Detailed Checks for Numeric Characters**\n\n There are several different but overlapping sets of numeric characters that\n can be checked for.\n\n >>> s3 = pd.Series(['23', '³', '⅕', ''])\n\n The ``s3.str.isdecimal`` method checks for characters used to form numbers\n in base 10.\n\n >>> s3.str.isdecimal()\n 0 True\n 1 False\n 2 False\n 3 False\n dtype: bool\n\n The ``s.str.isdigit`` method is the same as ``s3.str.isdecimal`` but also\n includes special digits, like superscripted and subscripted digits in\n unicode.\n\n >>> s3.str.isdigit()\n 0 True\n 1 True\n 2 False\n 3 False\n dtype: bool\n\n The ``s.str.isnumeric`` method is the same as ``s3.str.isdigit`` but also\n includes other characters that can represent quantities such as unicode\n fractions.\n\n >>> s3.str.isnumeric()\n 0 True\n 1 True\n 2 True\n 3 False\n dtype: bool\n\n **Checks for Whitespace**\n\n >>> s4 = pd.Series([' ', '\\\\t\\\\r\\\\n ', ''])\n >>> s4.str.isspace()\n 0 True\n 1 True\n 2 False\n dtype: bool\n\n **Checks for Character Case**\n\n >>> s5 = pd.Series(['leopard', 'Golden Eagle', 'SNAKE', ''])\n\n >>> s5.str.islower()\n 0 True\n 1 False\n 2 False\n 3 False\n dtype: bool\n\n >>> s5.str.isupper()\n 0 False\n 1 False\n 2 True\n 3 False\n dtype: bool\n\n The ``s5.str.istitle`` method checks for whether all words are in title\n case (whether only the first letter of each word is capitalized). Words are\n assumed to be as any sequence of non-numeric characters separated by\n whitespace characters.\n\n >>> s5.str.istitle()\n 0 False\n 1 True\n 2 False\n 3 False\n dtype: bool\n \"\"\"\n _doc_args[\"isalnum\"] = {\"type\": \"alphanumeric\", \"method\": \"isalnum\"}\n _doc_args[\"isalpha\"] = {\"type\": \"alphabetic\", \"method\": \"isalpha\"}\n _doc_args[\"isdigit\"] = {\"type\": \"digits\", \"method\": \"isdigit\"}\n _doc_args[\"isspace\"] = {\"type\": \"whitespace\", \"method\": \"isspace\"}\n _doc_args[\"islower\"] = {\"type\": \"lowercase\", \"method\": \"islower\"}\n _doc_args[\"isupper\"] = {\"type\": \"uppercase\", \"method\": \"isupper\"}\n _doc_args[\"istitle\"] = {\"type\": \"titlecase\", \"method\": \"istitle\"}\n _doc_args[\"isnumeric\"] = {\"type\": \"numeric\", \"method\": \"isnumeric\"}\n _doc_args[\"isdecimal\"] = {\"type\": \"decimal\", \"method\": \"isdecimal\"}\n # force _noarg_wrapper return type with dtype=np.dtype(bool) (GH 29624)\n\n isalnum = _map_and_wrap(\n \"isalnum\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"isalnum\"]\n )\n isalpha = _map_and_wrap(\n \"isalpha\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"isalpha\"]\n )\n isdigit = _map_and_wrap(\n \"isdigit\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"isdigit\"]\n )\n isspace = _map_and_wrap(\n \"isspace\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"isalnum\"]\n )\n islower = _map_and_wrap(\n \"islower\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"islower\"]\n )\n isupper = _map_and_wrap(\n \"isupper\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"isupper\"]\n )\n istitle = _map_and_wrap(\n \"istitle\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"istitle\"]\n )\n isnumeric = _map_and_wrap(\n \"isnumeric\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"isnumeric\"]\n )\n isdecimal = _map_and_wrap(\n \"isdecimal\", docstring=_shared_docs[\"ismethods\"] % _doc_args[\"isdecimal\"]\n )\n\n\ndef cat_safe(list_of_columns: List, sep: str):\n \"\"\"\n Auxiliary function for :meth:`str.cat`.\n\n Same signature as cat_core, but handles TypeErrors in concatenation, which\n happen if the arrays in list_of columns have the wrong dtypes or content.\n\n Parameters\n ----------\n list_of_columns : list of numpy arrays\n List of arrays to be concatenated with sep;\n these arrays may not contain NaNs!\n sep : string\n The separator string for concatenating the columns.\n\n Returns\n -------\n nd.array\n The concatenation of list_of_columns with sep.\n \"\"\"\n try:\n result = cat_core(list_of_columns, sep)\n except TypeError:\n # if there are any non-string values (wrong dtype or hidden behind\n # object dtype), np.sum will fail; catch and return with better message\n for column in list_of_columns:\n dtype = lib.infer_dtype(column, skipna=True)\n if dtype not in [\"string\", \"empty\"]:\n raise TypeError(\n \"Concatenation requires list-likes containing only \"\n \"strings (or missing values). Offending values found in \"\n f\"column {dtype}\"\n ) from None\n return result\n\n\ndef cat_core(list_of_columns: List, sep: str):\n \"\"\"\n Auxiliary function for :meth:`str.cat`\n\n Parameters\n ----------\n list_of_columns : list of numpy arrays\n List of arrays to be concatenated with sep;\n these arrays may not contain NaNs!\n sep : string\n The separator string for concatenating the columns.\n\n Returns\n -------\n nd.array\n The concatenation of list_of_columns with sep.\n \"\"\"\n if sep == \"\":\n # no need to interleave sep if it is empty\n arr_of_cols = np.asarray(list_of_columns, dtype=object)\n return np.sum(arr_of_cols, axis=0)\n list_with_sep = [sep] * (2 * len(list_of_columns) - 1)\n list_with_sep[::2] = list_of_columns\n arr_with_sep = np.asarray(list_with_sep, dtype=object)\n return np.sum(arr_with_sep, axis=0)\n\n\ndef _groups_or_na_fun(regex):\n \"\"\"Used in both extract_noexpand and extract_frame\"\"\"\n if regex.groups == 0:\n raise ValueError(\"pattern contains no capture groups\")\n empty_row = [np.nan] * regex.groups\n\n def f(x):\n if not isinstance(x, str):\n return empty_row\n m = regex.search(x)\n if m:\n return [np.nan if item is None else item for item in m.groups()]\n else:\n return empty_row\n\n return f\n\n\ndef _result_dtype(arr):\n # workaround #27953\n # ideally we just pass `dtype=arr.dtype` unconditionally, but this fails\n # when the list of values is empty.\n from pandas.core.arrays.string_ import StringDtype\n from pandas.core.arrays.string_arrow import ArrowStringDtype\n\n if isinstance(arr.dtype, (StringDtype, ArrowStringDtype)):\n return arr.dtype.name\n else:\n return object\n\n\ndef _get_single_group_name(rx):\n try:\n return list(rx.groupindex.keys()).pop()\n except IndexError:\n return None\n\n\ndef _str_extract_noexpand(arr, pat, flags=0):\n \"\"\"\n Find groups in each string in the Series using passed regular\n expression. This function is called from\n str_extract(expand=False), and can return Series, DataFrame, or\n Index.\n\n \"\"\"\n from pandas import (\n DataFrame,\n array as pd_array,\n )\n\n regex = re.compile(pat, flags=flags)\n groups_or_na = _groups_or_na_fun(regex)\n result_dtype = _result_dtype(arr)\n\n if regex.groups == 1:\n result = np.array([groups_or_na(val)[0] for val in arr], dtype=object)\n name = _get_single_group_name(regex)\n # not dispatching, so we have to reconstruct here.\n result = pd_array(result, dtype=result_dtype)\n else:\n if isinstance(arr, ABCIndex):\n raise ValueError(\"only one regex group is supported with Index\")\n name = None\n names = dict(zip(regex.groupindex.values(), regex.groupindex.keys()))\n columns = [names.get(1 + i, i) for i in range(regex.groups)]\n if arr.size == 0:\n # error: Incompatible types in assignment (expression has type\n # \"DataFrame\", variable has type \"ndarray\")\n result = DataFrame( # type: ignore[assignment]\n columns=columns, dtype=object\n )\n else:\n dtype = _result_dtype(arr)\n # error: Incompatible types in assignment (expression has type\n # \"DataFrame\", variable has type \"ndarray\")\n result = DataFrame( # type:ignore[assignment]\n [groups_or_na(val) for val in arr],\n columns=columns,\n index=arr.index,\n dtype=dtype,\n )\n return result, name\n\n\ndef _str_extract_frame(arr, pat, flags=0):\n \"\"\"\n For each subject string in the Series, extract groups from the\n first match of regular expression pat. This function is called from\n str_extract(expand=True), and always returns a DataFrame.\n\n \"\"\"\n from pandas import DataFrame\n\n regex = re.compile(pat, flags=flags)\n groups_or_na = _groups_or_na_fun(regex)\n names = dict(zip(regex.groupindex.values(), regex.groupindex.keys()))\n columns = [names.get(1 + i, i) for i in range(regex.groups)]\n\n if len(arr) == 0:\n return DataFrame(columns=columns, dtype=object)\n try:\n result_index = arr.index\n except AttributeError:\n result_index = None\n dtype = _result_dtype(arr)\n return DataFrame(\n [groups_or_na(val) for val in arr],\n columns=columns,\n index=result_index,\n dtype=dtype,\n )\n\n\ndef str_extract(arr, pat, flags=0, expand=True):\n if not isinstance(expand, bool):\n raise ValueError(\"expand must be True or False\")\n if expand:\n result = _str_extract_frame(arr._orig, pat, flags=flags)\n return result.__finalize__(arr._orig, method=\"str_extract\")\n else:\n result, name = _str_extract_noexpand(arr._orig, pat, flags=flags)\n return arr._wrap_result(result, name=name, expand=expand)\n\n\ndef str_extractall(arr, pat, flags=0):\n regex = re.compile(pat, flags=flags)\n # the regex must contain capture groups.\n if regex.groups == 0:\n raise ValueError(\"pattern contains no capture groups\")\n\n if isinstance(arr, ABCIndex):\n arr = arr.to_series().reset_index(drop=True)\n\n names = dict(zip(regex.groupindex.values(), regex.groupindex.keys()))\n columns = [names.get(1 + i, i) for i in range(regex.groups)]\n match_list = []\n index_list = []\n is_mi = arr.index.nlevels > 1\n\n for subject_key, subject in arr.items():\n if isinstance(subject, str):\n\n if not is_mi:\n subject_key = (subject_key,)\n\n for match_i, match_tuple in enumerate(regex.findall(subject)):\n if isinstance(match_tuple, str):\n match_tuple = (match_tuple,)\n na_tuple = [np.NaN if group == \"\" else group for group in match_tuple]\n match_list.append(na_tuple)\n result_key = tuple(subject_key + (match_i,))\n index_list.append(result_key)\n\n from pandas import MultiIndex\n\n index = MultiIndex.from_tuples(index_list, names=arr.index.names + [\"match\"])\n dtype = _result_dtype(arr)\n\n result = arr._constructor_expanddim(\n match_list, index=index, columns=columns, dtype=dtype\n )\n return result\n",
"from __future__ import annotations\n\nimport itertools\nfrom typing import (\n TYPE_CHECKING,\n cast,\n)\n\nimport numpy as np\n\nimport pandas._libs.reshape as libreshape\nfrom pandas._libs.sparse import IntIndex\nfrom pandas._typing import Dtype\nfrom pandas.util._decorators import cache_readonly\n\nfrom pandas.core.dtypes.cast import maybe_promote\nfrom pandas.core.dtypes.common import (\n ensure_platform_int,\n is_1d_only_ea_dtype,\n is_bool_dtype,\n is_extension_array_dtype,\n is_integer,\n is_integer_dtype,\n is_list_like,\n is_object_dtype,\n needs_i8_conversion,\n)\nfrom pandas.core.dtypes.missing import notna\n\nimport pandas.core.algorithms as algos\nfrom pandas.core.arrays import SparseArray\nfrom pandas.core.arrays.categorical import factorize_from_iterable\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.indexes.api import (\n Index,\n MultiIndex,\n)\nfrom pandas.core.series import Series\nfrom pandas.core.sorting import (\n compress_group_index,\n decons_obs_group_ids,\n get_compressed_ids,\n get_group_index,\n get_group_index_sorter,\n)\n\nif TYPE_CHECKING:\n from pandas.core.arrays import ExtensionArray\n\n\nclass _Unstacker:\n \"\"\"\n Helper class to unstack data / pivot with multi-level index\n\n Parameters\n ----------\n index : MultiIndex\n level : int or str, default last level\n Level to \"unstack\". Accepts a name for the level.\n fill_value : scalar, optional\n Default value to fill in missing values if subgroups do not have the\n same set of labels. By default, missing values will be replaced with\n the default fill value for that data type, NaN for float, NaT for\n datetimelike, etc. For integer types, by default data will converted to\n float and missing values will be set to NaN.\n constructor : object\n Pandas ``DataFrame`` or subclass used to create unstacked\n response. If None, DataFrame will be used.\n\n Examples\n --------\n >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),\n ... ('two', 'a'), ('two', 'b')])\n >>> s = pd.Series(np.arange(1, 5, dtype=np.int64), index=index)\n >>> s\n one a 1\n b 2\n two a 3\n b 4\n dtype: int64\n\n >>> s.unstack(level=-1)\n a b\n one 1 2\n two 3 4\n\n >>> s.unstack(level=0)\n one two\n a 1 3\n b 2 4\n\n Returns\n -------\n unstacked : DataFrame\n \"\"\"\n\n def __init__(self, index: MultiIndex, level=-1, constructor=None):\n\n if constructor is None:\n constructor = DataFrame\n self.constructor = constructor\n\n self.index = index.remove_unused_levels()\n\n self.level = self.index._get_level_number(level)\n\n # when index includes `nan`, need to lift levels/strides by 1\n self.lift = 1 if -1 in self.index.codes[self.level] else 0\n\n # Note: the \"pop\" below alters these in-place.\n self.new_index_levels = list(self.index.levels)\n self.new_index_names = list(self.index.names)\n\n self.removed_name = self.new_index_names.pop(self.level)\n self.removed_level = self.new_index_levels.pop(self.level)\n self.removed_level_full = index.levels[self.level]\n\n # Bug fix GH 20601\n # If the data frame is too big, the number of unique index combination\n # will cause int32 overflow on windows environments.\n # We want to check and raise an error before this happens\n num_rows = np.max([index_level.size for index_level in self.new_index_levels])\n num_columns = self.removed_level.size\n\n # GH20601: This forces an overflow if the number of cells is too high.\n num_cells = np.multiply(num_rows, num_columns, dtype=np.int32)\n\n if num_rows > 0 and num_columns > 0 and num_cells <= 0:\n raise ValueError(\"Unstacked DataFrame is too big, causing int32 overflow\")\n\n self._make_selectors()\n\n @cache_readonly\n def _indexer_and_to_sort(\n self,\n ) -> tuple[\n np.ndarray, # np.ndarray[np.intp]\n list[np.ndarray], # each has _some_ signed integer dtype\n ]:\n v = self.level\n\n codes = list(self.index.codes)\n levs = list(self.index.levels)\n to_sort = codes[:v] + codes[v + 1 :] + [codes[v]]\n sizes = tuple(len(x) for x in levs[:v] + levs[v + 1 :] + [levs[v]])\n\n comp_index, obs_ids = get_compressed_ids(to_sort, sizes)\n ngroups = len(obs_ids)\n\n indexer = get_group_index_sorter(comp_index, ngroups)\n return indexer, to_sort\n\n @cache_readonly\n def sorted_labels(self):\n indexer, to_sort = self._indexer_and_to_sort\n return [line.take(indexer) for line in to_sort]\n\n def _make_sorted_values(self, values: np.ndarray) -> np.ndarray:\n indexer, _ = self._indexer_and_to_sort\n\n sorted_values = algos.take_nd(values, indexer, axis=0)\n return sorted_values\n\n def _make_selectors(self):\n new_levels = self.new_index_levels\n\n # make the mask\n remaining_labels = self.sorted_labels[:-1]\n level_sizes = tuple(len(x) for x in new_levels)\n\n comp_index, obs_ids = get_compressed_ids(remaining_labels, level_sizes)\n ngroups = len(obs_ids)\n\n comp_index = ensure_platform_int(comp_index)\n stride = self.index.levshape[self.level] + self.lift\n self.full_shape = ngroups, stride\n\n selector = self.sorted_labels[-1] + stride * comp_index + self.lift\n # error: Argument 1 to \"zeros\" has incompatible type \"number\"; expected\n # \"Union[int, Sequence[int]]\"\n mask = np.zeros(np.prod(self.full_shape), dtype=bool) # type: ignore[arg-type]\n mask.put(selector, True)\n\n if mask.sum() < len(self.index):\n raise ValueError(\"Index contains duplicate entries, cannot reshape\")\n\n self.group_index = comp_index\n self.mask = mask\n self.unique_groups = obs_ids\n self.compressor = comp_index.searchsorted(np.arange(ngroups))\n\n def get_result(self, values, value_columns, fill_value):\n\n if values.ndim == 1:\n values = values[:, np.newaxis]\n\n if value_columns is None and values.shape[1] != 1: # pragma: no cover\n raise ValueError(\"must pass column labels for multi-column data\")\n\n values, _ = self.get_new_values(values, fill_value)\n columns = self.get_new_columns(value_columns)\n index = self.new_index\n\n return self.constructor(values, index=index, columns=columns)\n\n def get_new_values(self, values, fill_value=None):\n\n if values.ndim == 1:\n values = values[:, np.newaxis]\n\n sorted_values = self._make_sorted_values(values)\n\n # place the values\n length, width = self.full_shape\n stride = values.shape[1]\n result_width = width * stride\n result_shape = (length, result_width)\n mask = self.mask\n mask_all = mask.all()\n\n # we can simply reshape if we don't have a mask\n if mask_all and len(values):\n # TODO: Under what circumstances can we rely on sorted_values\n # matching values? When that holds, we can slice instead\n # of take (in particular for EAs)\n new_values = (\n sorted_values.reshape(length, width, stride)\n .swapaxes(1, 2)\n .reshape(result_shape)\n )\n new_mask = np.ones(result_shape, dtype=bool)\n return new_values, new_mask\n\n # if our mask is all True, then we can use our existing dtype\n if mask_all:\n dtype = values.dtype\n new_values = np.empty(result_shape, dtype=dtype)\n else:\n dtype, fill_value = maybe_promote(values.dtype, fill_value)\n new_values = np.empty(result_shape, dtype=dtype)\n new_values.fill(fill_value)\n\n new_mask = np.zeros(result_shape, dtype=bool)\n\n name = np.dtype(dtype).name\n\n # we need to convert to a basic dtype\n # and possibly coerce an input to our output dtype\n # e.g. ints -> floats\n if needs_i8_conversion(values.dtype):\n sorted_values = sorted_values.view(\"i8\")\n new_values = new_values.view(\"i8\")\n elif is_bool_dtype(values.dtype):\n sorted_values = sorted_values.astype(\"object\")\n new_values = new_values.astype(\"object\")\n else:\n sorted_values = sorted_values.astype(name, copy=False)\n\n # fill in our values & mask\n libreshape.unstack(\n sorted_values,\n mask.view(\"u1\"),\n stride,\n length,\n width,\n new_values,\n new_mask.view(\"u1\"),\n )\n\n # reconstruct dtype if needed\n if needs_i8_conversion(values.dtype):\n new_values = new_values.view(values.dtype)\n\n return new_values, new_mask\n\n def get_new_columns(self, value_columns):\n if value_columns is None:\n if self.lift == 0:\n return self.removed_level._rename(name=self.removed_name)\n\n lev = self.removed_level.insert(0, item=self.removed_level._na_value)\n return lev.rename(self.removed_name)\n\n stride = len(self.removed_level) + self.lift\n width = len(value_columns)\n propagator = np.repeat(np.arange(width), stride)\n if isinstance(value_columns, MultiIndex):\n new_levels = value_columns.levels + (self.removed_level_full,)\n new_names = value_columns.names + (self.removed_name,)\n\n new_codes = [lab.take(propagator) for lab in value_columns.codes]\n else:\n new_levels = [value_columns, self.removed_level_full]\n new_names = [value_columns.name, self.removed_name]\n new_codes = [propagator]\n\n # The two indices differ only if the unstacked level had unused items:\n if len(self.removed_level_full) != len(self.removed_level):\n # In this case, we remap the new codes to the original level:\n repeater = self.removed_level_full.get_indexer(self.removed_level)\n if self.lift:\n repeater = np.insert(repeater, 0, -1)\n else:\n # Otherwise, we just use each level item exactly once:\n repeater = np.arange(stride) - self.lift\n\n # The entire level is then just a repetition of the single chunk:\n new_codes.append(np.tile(repeater, width))\n return MultiIndex(\n levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False\n )\n\n @cache_readonly\n def new_index(self):\n # Does not depend on values or value_columns\n result_codes = [lab.take(self.compressor) for lab in self.sorted_labels[:-1]]\n\n # construct the new index\n if len(self.new_index_levels) == 1:\n level, level_codes = self.new_index_levels[0], result_codes[0]\n if (level_codes == -1).any():\n level = level.insert(len(level), level._na_value)\n return level.take(level_codes).rename(self.new_index_names[0])\n\n return MultiIndex(\n levels=self.new_index_levels,\n codes=result_codes,\n names=self.new_index_names,\n verify_integrity=False,\n )\n\n\ndef _unstack_multiple(data, clocs, fill_value=None):\n if len(clocs) == 0:\n return data\n\n # NOTE: This doesn't deal with hierarchical columns yet\n\n index = data.index\n\n # GH 19966 Make sure if MultiIndexed index has tuple name, they will be\n # recognised as a whole\n if clocs in index.names:\n clocs = [clocs]\n clocs = [index._get_level_number(i) for i in clocs]\n\n rlocs = [i for i in range(index.nlevels) if i not in clocs]\n\n clevels = [index.levels[i] for i in clocs]\n ccodes = [index.codes[i] for i in clocs]\n cnames = [index.names[i] for i in clocs]\n rlevels = [index.levels[i] for i in rlocs]\n rcodes = [index.codes[i] for i in rlocs]\n rnames = [index.names[i] for i in rlocs]\n\n shape = tuple(len(x) for x in clevels)\n group_index = get_group_index(ccodes, shape, sort=False, xnull=False)\n\n comp_ids, obs_ids = compress_group_index(group_index, sort=False)\n recons_codes = decons_obs_group_ids(comp_ids, obs_ids, shape, ccodes, xnull=False)\n\n if not rlocs:\n # Everything is in clocs, so the dummy df has a regular index\n dummy_index = Index(obs_ids, name=\"__placeholder__\")\n else:\n dummy_index = MultiIndex(\n levels=rlevels + [obs_ids],\n codes=rcodes + [comp_ids],\n names=rnames + [\"__placeholder__\"],\n verify_integrity=False,\n )\n\n if isinstance(data, Series):\n dummy = data.copy()\n dummy.index = dummy_index\n\n unstacked = dummy.unstack(\"__placeholder__\", fill_value=fill_value)\n new_levels = clevels\n new_names = cnames\n new_codes = recons_codes\n else:\n if isinstance(data.columns, MultiIndex):\n result = data\n for i in range(len(clocs)):\n val = clocs[i]\n result = result.unstack(val, fill_value=fill_value)\n clocs = [v if v < val else v - 1 for v in clocs]\n\n return result\n\n dummy = data.copy()\n dummy.index = dummy_index\n\n unstacked = dummy.unstack(\"__placeholder__\", fill_value=fill_value)\n if isinstance(unstacked, Series):\n unstcols = unstacked.index\n else:\n unstcols = unstacked.columns\n assert isinstance(unstcols, MultiIndex) # for mypy\n new_levels = [unstcols.levels[0]] + clevels\n new_names = [data.columns.name] + cnames\n\n new_codes = [unstcols.codes[0]]\n for rec in recons_codes:\n new_codes.append(rec.take(unstcols.codes[-1]))\n\n new_columns = MultiIndex(\n levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False\n )\n\n if isinstance(unstacked, Series):\n unstacked.index = new_columns\n else:\n unstacked.columns = new_columns\n\n return unstacked\n\n\ndef unstack(obj, level, fill_value=None):\n\n if isinstance(level, (tuple, list)):\n if len(level) != 1:\n # _unstack_multiple only handles MultiIndexes,\n # and isn't needed for a single level\n return _unstack_multiple(obj, level, fill_value=fill_value)\n else:\n level = level[0]\n\n # Prioritize integer interpretation (GH #21677):\n if not is_integer(level) and not level == \"__placeholder__\":\n level = obj.index._get_level_number(level)\n\n if isinstance(obj, DataFrame):\n if isinstance(obj.index, MultiIndex):\n return _unstack_frame(obj, level, fill_value=fill_value)\n else:\n return obj.T.stack(dropna=False)\n elif not isinstance(obj.index, MultiIndex):\n # GH 36113\n # Give nicer error messages when unstack a Series whose\n # Index is not a MultiIndex.\n raise ValueError(\n f\"index must be a MultiIndex to unstack, {type(obj.index)} was passed\"\n )\n else:\n if is_1d_only_ea_dtype(obj.dtype):\n return _unstack_extension_series(obj, level, fill_value)\n unstacker = _Unstacker(\n obj.index, level=level, constructor=obj._constructor_expanddim\n )\n return unstacker.get_result(\n obj._values, value_columns=None, fill_value=fill_value\n )\n\n\ndef _unstack_frame(obj, level, fill_value=None):\n if not obj._can_fast_transpose:\n unstacker = _Unstacker(obj.index, level=level)\n mgr = obj._mgr.unstack(unstacker, fill_value=fill_value)\n return obj._constructor(mgr)\n else:\n unstacker = _Unstacker(obj.index, level=level, constructor=obj._constructor)\n return unstacker.get_result(\n obj._values, value_columns=obj.columns, fill_value=fill_value\n )\n\n\ndef _unstack_extension_series(series, level, fill_value):\n \"\"\"\n Unstack an ExtensionArray-backed Series.\n\n The ExtensionDtype is preserved.\n\n Parameters\n ----------\n series : Series\n A Series with an ExtensionArray for values\n level : Any\n The level name or number.\n fill_value : Any\n The user-level (not physical storage) fill value to use for\n missing values introduced by the reshape. Passed to\n ``series.values.take``.\n\n Returns\n -------\n DataFrame\n Each column of the DataFrame will have the same dtype as\n the input Series.\n \"\"\"\n # Defer to the logic in ExtensionBlock._unstack\n df = series.to_frame()\n result = df.unstack(level=level, fill_value=fill_value)\n return result.droplevel(level=0, axis=1)\n\n\ndef stack(frame, level=-1, dropna=True):\n \"\"\"\n Convert DataFrame to Series with multi-level Index. Columns become the\n second level of the resulting hierarchical index\n\n Returns\n -------\n stacked : Series\n \"\"\"\n\n def factorize(index):\n if index.is_unique:\n return index, np.arange(len(index))\n codes, categories = factorize_from_iterable(index)\n return categories, codes\n\n N, K = frame.shape\n\n # Will also convert negative level numbers and check if out of bounds.\n level_num = frame.columns._get_level_number(level)\n\n if isinstance(frame.columns, MultiIndex):\n return _stack_multi_columns(frame, level_num=level_num, dropna=dropna)\n elif isinstance(frame.index, MultiIndex):\n new_levels = list(frame.index.levels)\n new_codes = [lab.repeat(K) for lab in frame.index.codes]\n\n clev, clab = factorize(frame.columns)\n new_levels.append(clev)\n new_codes.append(np.tile(clab, N).ravel())\n\n new_names = list(frame.index.names)\n new_names.append(frame.columns.name)\n new_index = MultiIndex(\n levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False\n )\n else:\n levels, (ilab, clab) = zip(*map(factorize, (frame.index, frame.columns)))\n codes = ilab.repeat(K), np.tile(clab, N).ravel()\n new_index = MultiIndex(\n levels=levels,\n codes=codes,\n names=[frame.index.name, frame.columns.name],\n verify_integrity=False,\n )\n\n if not frame.empty and frame._is_homogeneous_type:\n # For homogeneous EAs, frame._values will coerce to object. So\n # we concatenate instead.\n dtypes = list(frame.dtypes._values)\n dtype = dtypes[0]\n\n if is_extension_array_dtype(dtype):\n arr = dtype.construct_array_type()\n new_values = arr._concat_same_type(\n [col._values for _, col in frame.items()]\n )\n new_values = _reorder_for_extension_array_stack(new_values, N, K)\n else:\n # homogeneous, non-EA\n new_values = frame._values.ravel()\n\n else:\n # non-homogeneous\n new_values = frame._values.ravel()\n\n if dropna:\n mask = notna(new_values)\n new_values = new_values[mask]\n new_index = new_index[mask]\n\n return frame._constructor_sliced(new_values, index=new_index)\n\n\ndef stack_multiple(frame, level, dropna=True):\n # If all passed levels match up to column names, no\n # ambiguity about what to do\n if all(lev in frame.columns.names for lev in level):\n result = frame\n for lev in level:\n result = stack(result, lev, dropna=dropna)\n\n # Otherwise, level numbers may change as each successive level is stacked\n elif all(isinstance(lev, int) for lev in level):\n # As each stack is done, the level numbers decrease, so we need\n # to account for that when level is a sequence of ints\n result = frame\n # _get_level_number() checks level numbers are in range and converts\n # negative numbers to positive\n level = [frame.columns._get_level_number(lev) for lev in level]\n\n # Can't iterate directly through level as we might need to change\n # values as we go\n for index in range(len(level)):\n lev = level[index]\n result = stack(result, lev, dropna=dropna)\n # Decrement all level numbers greater than current, as these\n # have now shifted down by one\n updated_level = []\n for other in level:\n if other > lev:\n updated_level.append(other - 1)\n else:\n updated_level.append(other)\n level = updated_level\n\n else:\n raise ValueError(\n \"level should contain all level names or all level \"\n \"numbers, not a mixture of the two.\"\n )\n\n return result\n\n\ndef _stack_multi_column_index(columns: MultiIndex) -> MultiIndex:\n \"\"\"Creates a MultiIndex from the first N-1 levels of this MultiIndex.\"\"\"\n if len(columns.levels) <= 2:\n return columns.levels[0]._rename(name=columns.names[0])\n\n levs = [\n [lev[c] if c >= 0 else None for c in codes]\n for lev, codes in zip(columns.levels[:-1], columns.codes[:-1])\n ]\n\n # Remove duplicate tuples in the MultiIndex.\n tuples = zip(*levs)\n unique_tuples = (key for key, _ in itertools.groupby(tuples))\n new_levs = zip(*unique_tuples)\n\n # The dtype of each level must be explicitly set to avoid inferring the wrong type.\n # See GH-36991.\n return MultiIndex.from_arrays(\n [\n # Not all indices can accept None values.\n Index(new_lev, dtype=lev.dtype) if None not in new_lev else new_lev\n for new_lev, lev in zip(new_levs, columns.levels)\n ],\n names=columns.names[:-1],\n )\n\n\ndef _stack_multi_columns(frame, level_num=-1, dropna=True):\n def _convert_level_number(level_num, columns):\n \"\"\"\n Logic for converting the level number to something we can safely pass\n to swaplevel.\n\n If `level_num` matches a column name return the name from\n position `level_num`, otherwise return `level_num`.\n \"\"\"\n if level_num in columns.names:\n return columns.names[level_num]\n\n return level_num\n\n this = frame.copy()\n\n # this makes life much simpler\n if level_num != frame.columns.nlevels - 1:\n # roll levels to put selected level at end\n roll_columns = this.columns\n for i in range(level_num, frame.columns.nlevels - 1):\n # Need to check if the ints conflict with level names\n lev1 = _convert_level_number(i, roll_columns)\n lev2 = _convert_level_number(i + 1, roll_columns)\n roll_columns = roll_columns.swaplevel(lev1, lev2)\n this.columns = roll_columns\n\n if not this.columns._is_lexsorted():\n # Workaround the edge case where 0 is one of the column names,\n # which interferes with trying to sort based on the first\n # level\n level_to_sort = _convert_level_number(0, this.columns)\n this = this.sort_index(level=level_to_sort, axis=1)\n\n new_columns = _stack_multi_column_index(this.columns)\n\n # time to ravel the values\n new_data = {}\n level_vals = this.columns.levels[-1]\n level_codes = sorted(set(this.columns.codes[-1]))\n level_vals_nan = level_vals.insert(len(level_vals), None)\n\n level_vals_used = np.take(level_vals_nan, level_codes)\n levsize = len(level_codes)\n drop_cols = []\n for key in new_columns:\n try:\n loc = this.columns.get_loc(key)\n except KeyError:\n drop_cols.append(key)\n continue\n\n # can make more efficient?\n # we almost always return a slice\n # but if unsorted can get a boolean\n # indexer\n if not isinstance(loc, slice):\n slice_len = len(loc)\n else:\n slice_len = loc.stop - loc.start\n\n if slice_len != levsize:\n chunk = this.loc[:, this.columns[loc]]\n chunk.columns = level_vals_nan.take(chunk.columns.codes[-1])\n value_slice = chunk.reindex(columns=level_vals_used).values\n else:\n if frame._is_homogeneous_type and is_extension_array_dtype(\n frame.dtypes.iloc[0]\n ):\n dtype = this[this.columns[loc]].dtypes.iloc[0]\n subset = this[this.columns[loc]]\n\n value_slice = dtype.construct_array_type()._concat_same_type(\n [x._values for _, x in subset.items()]\n )\n N, K = this.shape\n idx = np.arange(N * K).reshape(K, N).T.ravel()\n value_slice = value_slice.take(idx)\n\n elif frame._is_mixed_type:\n value_slice = this[this.columns[loc]].values\n else:\n value_slice = this.values[:, loc]\n\n if value_slice.ndim > 1:\n # i.e. not extension\n value_slice = value_slice.ravel()\n\n new_data[key] = value_slice\n\n if len(drop_cols) > 0:\n new_columns = new_columns.difference(drop_cols)\n\n N = len(this)\n\n if isinstance(this.index, MultiIndex):\n new_levels = list(this.index.levels)\n new_names = list(this.index.names)\n new_codes = [lab.repeat(levsize) for lab in this.index.codes]\n else:\n old_codes, old_levels = factorize_from_iterable(this.index)\n new_levels = [old_levels]\n new_codes = [old_codes.repeat(levsize)]\n new_names = [this.index.name] # something better?\n\n new_levels.append(level_vals)\n new_codes.append(np.tile(level_codes, N))\n new_names.append(frame.columns.names[level_num])\n\n new_index = MultiIndex(\n levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False\n )\n\n result = frame._constructor(new_data, index=new_index, columns=new_columns)\n\n # more efficient way to go about this? can do the whole masking biz but\n # will only save a small amount of time...\n if dropna:\n result = result.dropna(axis=0, how=\"all\")\n\n return result\n\n\ndef get_dummies(\n data,\n prefix=None,\n prefix_sep=\"_\",\n dummy_na: bool = False,\n columns=None,\n sparse: bool = False,\n drop_first: bool = False,\n dtype: Dtype | None = None,\n) -> DataFrame:\n \"\"\"\n Convert categorical variable into dummy/indicator variables.\n\n Parameters\n ----------\n data : array-like, Series, or DataFrame\n Data of which to get dummy indicators.\n prefix : str, list of str, or dict of str, default None\n String to append DataFrame column names.\n Pass a list with length equal to the number of columns\n when calling get_dummies on a DataFrame. Alternatively, `prefix`\n can be a dictionary mapping column names to prefixes.\n prefix_sep : str, default '_'\n If appending prefix, separator/delimiter to use. Or pass a\n list or dictionary as with `prefix`.\n dummy_na : bool, default False\n Add a column to indicate NaNs, if False NaNs are ignored.\n columns : list-like, default None\n Column names in the DataFrame to be encoded.\n If `columns` is None then all the columns with\n `object` or `category` dtype will be converted.\n sparse : bool, default False\n Whether the dummy-encoded columns should be backed by\n a :class:`SparseArray` (True) or a regular NumPy array (False).\n drop_first : bool, default False\n Whether to get k-1 dummies out of k categorical levels by removing the\n first level.\n dtype : dtype, default np.uint8\n Data type for new columns. Only a single dtype is allowed.\n\n Returns\n -------\n DataFrame\n Dummy-coded data.\n\n See Also\n --------\n Series.str.get_dummies : Convert Series to dummy codes.\n\n Examples\n --------\n >>> s = pd.Series(list('abca'))\n\n >>> pd.get_dummies(s)\n a b c\n 0 1 0 0\n 1 0 1 0\n 2 0 0 1\n 3 1 0 0\n\n >>> s1 = ['a', 'b', np.nan]\n\n >>> pd.get_dummies(s1)\n a b\n 0 1 0\n 1 0 1\n 2 0 0\n\n >>> pd.get_dummies(s1, dummy_na=True)\n a b NaN\n 0 1 0 0\n 1 0 1 0\n 2 0 0 1\n\n >>> df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],\n ... 'C': [1, 2, 3]})\n\n >>> pd.get_dummies(df, prefix=['col1', 'col2'])\n C col1_a col1_b col2_a col2_b col2_c\n 0 1 1 0 0 1 0\n 1 2 0 1 1 0 0\n 2 3 1 0 0 0 1\n\n >>> pd.get_dummies(pd.Series(list('abcaa')))\n a b c\n 0 1 0 0\n 1 0 1 0\n 2 0 0 1\n 3 1 0 0\n 4 1 0 0\n\n >>> pd.get_dummies(pd.Series(list('abcaa')), drop_first=True)\n b c\n 0 0 0\n 1 1 0\n 2 0 1\n 3 0 0\n 4 0 0\n\n >>> pd.get_dummies(pd.Series(list('abc')), dtype=float)\n a b c\n 0 1.0 0.0 0.0\n 1 0.0 1.0 0.0\n 2 0.0 0.0 1.0\n \"\"\"\n from pandas.core.reshape.concat import concat\n\n dtypes_to_encode = [\"object\", \"category\"]\n\n if isinstance(data, DataFrame):\n # determine columns being encoded\n if columns is None:\n data_to_encode = data.select_dtypes(include=dtypes_to_encode)\n elif not is_list_like(columns):\n raise TypeError(\"Input must be a list-like for parameter `columns`\")\n else:\n data_to_encode = data[columns]\n\n # validate prefixes and separator to avoid silently dropping cols\n def check_len(item, name):\n\n if is_list_like(item):\n if not len(item) == data_to_encode.shape[1]:\n len_msg = (\n f\"Length of '{name}' ({len(item)}) did not match the \"\n \"length of the columns being encoded \"\n f\"({data_to_encode.shape[1]}).\"\n )\n raise ValueError(len_msg)\n\n check_len(prefix, \"prefix\")\n check_len(prefix_sep, \"prefix_sep\")\n\n if isinstance(prefix, str):\n prefix = itertools.cycle([prefix])\n if isinstance(prefix, dict):\n prefix = [prefix[col] for col in data_to_encode.columns]\n\n if prefix is None:\n prefix = data_to_encode.columns\n\n # validate separators\n if isinstance(prefix_sep, str):\n prefix_sep = itertools.cycle([prefix_sep])\n elif isinstance(prefix_sep, dict):\n prefix_sep = [prefix_sep[col] for col in data_to_encode.columns]\n\n with_dummies: list[DataFrame]\n if data_to_encode.shape == data.shape:\n # Encoding the entire df, do not prepend any dropped columns\n with_dummies = []\n elif columns is not None:\n # Encoding only cols specified in columns. Get all cols not in\n # columns to prepend to result.\n with_dummies = [data.drop(columns, axis=1)]\n else:\n # Encoding only object and category dtype columns. Get remaining\n # columns to prepend to result.\n with_dummies = [data.select_dtypes(exclude=dtypes_to_encode)]\n\n for (col, pre, sep) in zip(data_to_encode.items(), prefix, prefix_sep):\n # col is (column_name, column), use just column data here\n dummy = _get_dummies_1d(\n col[1],\n prefix=pre,\n prefix_sep=sep,\n dummy_na=dummy_na,\n sparse=sparse,\n drop_first=drop_first,\n dtype=dtype,\n )\n with_dummies.append(dummy)\n result = concat(with_dummies, axis=1)\n else:\n result = _get_dummies_1d(\n data,\n prefix,\n prefix_sep,\n dummy_na,\n sparse=sparse,\n drop_first=drop_first,\n dtype=dtype,\n )\n return result\n\n\ndef _get_dummies_1d(\n data,\n prefix,\n prefix_sep=\"_\",\n dummy_na: bool = False,\n sparse: bool = False,\n drop_first: bool = False,\n dtype: Dtype | None = None,\n) -> DataFrame:\n from pandas.core.reshape.concat import concat\n\n # Series avoids inconsistent NaN handling\n codes, levels = factorize_from_iterable(Series(data))\n\n if dtype is None:\n dtype = np.uint8\n # error: Argument 1 to \"dtype\" has incompatible type \"Union[ExtensionDtype, str,\n # dtype[Any], Type[object]]\"; expected \"Type[Any]\"\n dtype = np.dtype(dtype) # type: ignore[arg-type]\n\n if is_object_dtype(dtype):\n raise ValueError(\"dtype=object is not a valid dtype for get_dummies\")\n\n def get_empty_frame(data) -> DataFrame:\n if isinstance(data, Series):\n index = data.index\n else:\n index = np.arange(len(data))\n return DataFrame(index=index)\n\n # if all NaN\n if not dummy_na and len(levels) == 0:\n return get_empty_frame(data)\n\n codes = codes.copy()\n if dummy_na:\n codes[codes == -1] = len(levels)\n levels = np.append(levels, np.nan)\n\n # if dummy_na, we just fake a nan level. drop_first will drop it again\n if drop_first and len(levels) == 1:\n return get_empty_frame(data)\n\n number_of_cols = len(levels)\n\n if prefix is None:\n dummy_cols = levels\n else:\n dummy_cols = Index([f\"{prefix}{prefix_sep}{level}\" for level in levels])\n\n index: Index | None\n if isinstance(data, Series):\n index = data.index\n else:\n index = None\n\n if sparse:\n\n fill_value: bool | float | int\n if is_integer_dtype(dtype):\n fill_value = 0\n elif dtype == bool:\n fill_value = False\n else:\n fill_value = 0.0\n\n sparse_series = []\n N = len(data)\n sp_indices: list[list] = [[] for _ in range(len(dummy_cols))]\n mask = codes != -1\n codes = codes[mask]\n n_idx = np.arange(N)[mask]\n\n for ndx, code in zip(n_idx, codes):\n sp_indices[code].append(ndx)\n\n if drop_first:\n # remove first categorical level to avoid perfect collinearity\n # GH12042\n sp_indices = sp_indices[1:]\n dummy_cols = dummy_cols[1:]\n for col, ixs in zip(dummy_cols, sp_indices):\n sarr = SparseArray(\n np.ones(len(ixs), dtype=dtype),\n sparse_index=IntIndex(N, ixs),\n fill_value=fill_value,\n dtype=dtype,\n )\n sparse_series.append(Series(data=sarr, index=index, name=col))\n\n out = concat(sparse_series, axis=1, copy=False)\n # TODO: overload concat with Literal for axis\n out = cast(DataFrame, out)\n return out\n\n else:\n # take on axis=1 + transpose to ensure ndarray layout is column-major\n dummy_mat = np.eye(number_of_cols, dtype=dtype).take(codes, axis=1).T\n\n if not dummy_na:\n # reset NaN GH4446\n dummy_mat[codes == -1] = 0\n\n if drop_first:\n # remove first GH12042\n dummy_mat = dummy_mat[:, 1:]\n dummy_cols = dummy_cols[1:]\n return DataFrame(dummy_mat, index=index, columns=dummy_cols)\n\n\ndef _reorder_for_extension_array_stack(\n arr: ExtensionArray, n_rows: int, n_columns: int\n) -> ExtensionArray:\n \"\"\"\n Re-orders the values when stacking multiple extension-arrays.\n\n The indirect stacking method used for EAs requires a followup\n take to get the order correct.\n\n Parameters\n ----------\n arr : ExtensionArray\n n_rows, n_columns : int\n The number of rows and columns in the original DataFrame.\n\n Returns\n -------\n taken : ExtensionArray\n The original `arr` with elements re-ordered appropriately\n\n Examples\n --------\n >>> arr = np.array(['a', 'b', 'c', 'd', 'e', 'f'])\n >>> _reorder_for_extension_array_stack(arr, 2, 3)\n array(['a', 'c', 'e', 'b', 'd', 'f'], dtype='<U1')\n\n >>> _reorder_for_extension_array_stack(arr, 3, 2)\n array(['a', 'd', 'b', 'e', 'c', 'f'], dtype='<U1')\n \"\"\"\n # final take to get the order correct.\n # idx is an indexer like\n # [c0r0, c1r0, c2r0, ...,\n # c0r1, c1r1, c2r1, ...]\n idx = np.arange(n_rows * n_columns).reshape(n_columns, n_rows).T.ravel()\n return arr.take(idx)\n"
] |
[
[
"pandas.Series",
"numpy.asarray",
"pandas.MultiIndex.from_tuples",
"pandas.DataFrame",
"pandas.core.dtypes.common.ensure_object",
"numpy.where",
"pandas.Index",
"numpy.logical_or.reduce",
"pandas.core.dtypes.common.is_categorical_dtype",
"numpy.putmask",
"pandas.core.dtypes.common.is_list_like",
"pandas.util._decorators.Appender",
"pandas.array",
"numpy.sum",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas.core.dtypes.common.is_re",
"pandas.core.dtypes.common.is_integer",
"pandas.core.dtypes.missing.isna",
"pandas._libs.lib.infer_dtype"
],
[
"numpy.take",
"pandas.core.dtypes.common.is_extension_array_dtype",
"pandas._libs.sparse.IntIndex",
"numpy.dtype",
"pandas.core.sorting.get_group_index_sorter",
"pandas.core.dtypes.missing.notna",
"numpy.max",
"pandas.core.sorting.get_group_index",
"pandas.core.frame.DataFrame",
"pandas.core.arrays.categorical.factorize_from_iterable",
"pandas.core.series.Series",
"numpy.arange",
"numpy.eye",
"pandas.core.sorting.get_compressed_ids",
"numpy.insert",
"numpy.zeros",
"pandas.core.algorithms.take_nd",
"pandas.core.sorting.decons_obs_group_ids",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.core.dtypes.common.is_list_like",
"numpy.multiply",
"pandas.core.sorting.compress_group_index",
"pandas.core.dtypes.common.is_1d_only_ea_dtype",
"pandas.core.indexes.api.Index",
"numpy.append",
"pandas.core.dtypes.common.ensure_platform_int",
"pandas.core.dtypes.cast.maybe_promote",
"pandas.core.reshape.concat.concat",
"pandas.core.dtypes.common.needs_i8_conversion",
"pandas.core.dtypes.common.is_bool_dtype",
"numpy.tile",
"pandas.core.dtypes.common.is_integer",
"numpy.ones",
"pandas.core.indexes.api.MultiIndex",
"pandas.core.dtypes.common.is_object_dtype",
"numpy.prod",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
mpeven/Pytorch_Datasets
|
[
"6a1709bfb59739b5e7ce299c70350b0080209c82"
] |
[
"pytorch_datasets/datasets/object_net_3d.py"
] |
[
"import os\nimport glob\nfrom tqdm import tqdm\nfrom PIL import Image\nimport scipy.io as sio\nimport h5py\nimport torch\nimport pytorch_datasets.utils.cache_manager as cache\n\n\nclass ObjectNet3D(torch.utils.data.Dataset):\n dset_location = '/hdd/Datasets/ObjectNet3D/'\n dset_cached_location = dset_location + \"cached_dataset.pkl\"\n\n def __init__(self):\n self.dataset = self.create_dataset()\n\n def create_dataset(self):\n cached_dset = cache.retreive_from_cache(self.dset_cached_location)\n if cached_dset is not False:\n return cached_dset\n\n dataset = []\n for matfile in tqdm(glob.glob(self.dset_location + \"Annotations/*\")):\n try:\n x = sio.loadmat(matfile)\n except Exception:\n continue\n\n for obj in x['record']['objects'][0, 0][0]:\n # Get elevation (or fine-grained elevation if it exists)\n elevation = obj['viewpoint']['elevation_coarse'][0][0][0][0]\n if 'elevation' in obj['viewpoint'].dtype.names:\n if len(obj['viewpoint']['elevation'][0][0]) > 0:\n elevation = obj['viewpoint']['elevation'][0][0][0][0]\n\n # Get azimuth (or fine-grained azimuth if it exists)\n azimuth = obj['viewpoint']['azimuth_coarse'][0][0][0][0]\n if 'azimuth' in obj['viewpoint'].dtype.names:\n if len(obj['viewpoint']['azimuth'][0][0]) > 0:\n azimuth = obj['viewpoint']['azimuth'][0][0][0][0]\n\n dataset.append({\n 'image_file': self.dset_location + \"Images/\" + x['record']['filename'][0, 0][0],\n 'object_type': obj['class'][0],\n 'azimuth': azimuth,\n 'elevation': elevation,\n 'distance': obj['viewpoint']['distance'][0][0][0][0],\n 'theta': obj['viewpoint']['theta'][0][0][0][0],\n 'bbox': obj['bbox'][0],\n })\n\n cache.cache(dataset, self.dset_cached_location)\n return dataset\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, idx):\n datum = self.dataset[idx]\n datum['image'] = Image.open(datum['image_file']).convert('RGB')\n return datum\n"
] |
[
[
"scipy.io.loadmat"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
CAU-OSP-02/T03
|
[
"bd5e32eb76aa651d959c86439f13c07d7781004a"
] |
[
"handFiguration/hand_learning.py"
] |
[
"#!/usr/bin/env python3\n# v.1.1\n\nimport cv2\nimport mediapipe as mp\nimport numpy as np\n\ngesture = {\n 0:'fist', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five',\n 6:'six', 7:'rock', 8:'spiderman', 9:'yeah', 10:'ok'\n} #MediaPipe 제공 제스쳐\nhand_gesture = {\n 0:'fist', 1:'one', 2:'gun', 3:'three', 4:'four', 5:'five',\n 6:'promise', 7:'spiderman', 8:'niconiconi', 9:'two', 10:'ok',\n 11:'claws', 12:'good', 13:'fanxyChild', 14:'dog'\n} #게임에 사용할 NEW 제스처 세트 -> 추가할 것 하고 기존의 것은 알아보기 쉽게 이름을 정리\n\n#MediaPipe hands model\nmp_hands = mp.solutions.hands\nmp_drawing = mp.solutions.drawing_utils #웹캠에서 손가락 뼈마디 부분을 그리는 것\nhands = mp_hands.Hands(max_num_hands = 1, min_detection_confidence = 0.5, min_tracking_confidence = 0.5) #모드 세팅\n\n#Gesture recognition model\nfile = np.genfromtxt('gesture_trained.csv', delimiter=',') #csv 파일 받아와서 필요한 정보 뽑기 / 경로 주의!\n\n\ncam = cv2.VideoCapture(0) #캠켜기\n\ndef click(event, x, y, flags, param): #클릭 함수\n global data, file\n if event == cv2.EVENT_LBUTTONDOWN: #마우스 왼쪽 누를 시\n file = np.vstack((file, data)) #기존 파일에 새로운 데이터 추가\n print(file.shape) #행렬 펼치기\n\ncv2.namedWindow('Hand Cam') #? / 윈도우 이름이 아래 imshow()의 이름과 같아야함\ncv2.setMouseCallback('Hand Cam', click) #클릭 시..\n\nwhile cam.isOpened(): #카메라가 열려있으면..\n success, image = cam.read() #한 프레임 씩 읽어옴\n if not success: #success 못하면 다음 프레임으로..?\n continue\n #success하면 go\n \n image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB) #이미지 전처리(색상 형식 변경 & 이미지 한번 뒤집기)\n results = hands.process(image) #전처리 및 모델 추론을 함께 실행..\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) #출력을 위해 다시 색상 형식 바꿔주기\n\n if results.multi_hand_landmarks: #위 전처리를 통해 손이 인식 되면 참이됨\n for hand_landmarks in results.multi_hand_landmarks: #손 여러개 대비?? 예외처리 방지? with 써야되나?\n joint = np.zeros((21, 3)) #joint -> 빨간 점. 포인트 21개, xyz 3개. 생성\n for j, lm in enumerate(hand_landmarks.landmark):\n joint[j] = [lm.x, lm.y, lm.z] #값 입력\n \n #joint 인덱스끼리 빼줘서 뼈대의 벡터 구하기(Fig 3의 형태)\n v1 = joint[[0,1,2,3,0,5,6,7,0,9,10,11,0,13,14,15,0,17,18,19],:] # Parent joint\n v2 = joint[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],:] # Child joint\n v = v2 - v1 # [20,3]\n #벡터의 길이로.. Normalize v?\n v = v / np.linalg.norm(v, axis=1)[:, np.newaxis]\n \n # Get angle using arcos of dot product\n angle = np.arccos(np.einsum('nt,nt->n',\n v[[0,1,2,4,5,6,8,9,10,12,13,14,16,17,18],:],\n v[[1,2,3,5,6,7,9,10,11,13,14,15,17,18,19],:])) # [15,]\n \n angle = np.degrees(angle) # Convert radian to degree\n \n # Inference gesture / 데이터 바꿔주고 정리..\n data = np.array([angle], dtype=np.float32)\n data = np.append(data, 14) #ㅇㅇ번 인덱스의 손모양 데이터 추가\n# print(data)\n \n mp_drawing.draw_landmarks(image, hand_landmarks, mp_hands.HAND_CONNECTIONS) #마디마디에 그려주는\n \n cv2.imshow('Hand Cam', image) #윈도우 열기\n \n if cv2.waitKey(1) == ord('q'):\n break\n\nnp.savetxt('gesture_trained.csv', file, delimiter=',') #추가된 데이터 파일 저장\n"
] |
[
[
"numpy.einsum",
"numpy.degrees",
"numpy.linalg.norm",
"numpy.genfromtxt",
"numpy.append",
"numpy.savetxt",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
colin1alexander/zipline
|
[
"ba42e6d8b972dcce9271526562ceff0cddd3fa30",
"ba42e6d8b972dcce9271526562ceff0cddd3fa30"
] |
[
"zipline/examples/pairtrade.py",
"tests/pipeline/test_numerical_expression.py"
] |
[
"#!/usr/bin/env python\n#\n# Copyright 2013 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\nimport logbook\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport statsmodels.api as sm\nfrom datetime import datetime\nimport pytz\n\nfrom zipline.algorithm import TradingAlgorithm\nfrom zipline.transforms import batch_transform\nfrom zipline.utils.factory import load_from_yahoo\nfrom zipline.api import symbol\n\n\n@batch_transform\ndef ols_transform(data, sid1, sid2):\n \"\"\"Computes regression coefficient (slope and intercept)\n via Ordinary Least Squares between two SIDs.\n \"\"\"\n p0 = data.price[sid1].values\n p1 = sm.add_constant(data.price[sid2].values, prepend=True)\n slope, intercept = sm.OLS(p0, p1).fit().params\n\n return slope, intercept\n\n\nclass Pairtrade(TradingAlgorithm):\n \"\"\"Pairtrading relies on cointegration of two stocks.\n\n The expectation is that once the two stocks drifted apart\n (i.e. there is spread), they will eventually revert again. Thus,\n if we short the upward drifting stock and long the downward\n drifting stock (in short, we buy the spread) once the spread\n widened we can sell the spread with profit once they converged\n again. A nice property of this algorithm is that we enter the\n market in a neutral position.\n\n This specific algorithm tries to exploit the cointegration of\n Pepsi and Coca Cola by estimating the correlation between the\n two. Divergence of the spread is evaluated by z-scoring.\n \"\"\"\n\n def initialize(self, window_length=100):\n self.spreads = []\n self.invested = 0\n self.window_length = window_length\n self.ols_transform = ols_transform(refresh_period=self.window_length,\n window_length=self.window_length)\n self.PEP = self.symbol('PEP')\n self.KO = self.symbol('KO')\n\n def handle_data(self, data):\n ######################################################\n # 1. Compute regression coefficients between PEP and KO\n params = self.ols_transform.handle_data(data, self.PEP, self.KO)\n if params is None:\n return\n intercept, slope = params\n\n ######################################################\n # 2. Compute spread and zscore\n zscore = self.compute_zscore(data, slope, intercept)\n self.record(zscores=zscore,\n PEP=data[symbol('PEP')].price,\n KO=data[symbol('KO')].price)\n\n ######################################################\n # 3. Place orders\n self.place_orders(data, zscore)\n\n def compute_zscore(self, data, slope, intercept):\n \"\"\"1. Compute the spread given slope and intercept.\n 2. zscore the spread.\n \"\"\"\n spread = (data[self.PEP].price -\n (slope * data[self.KO].price + intercept))\n self.spreads.append(spread)\n spread_wind = self.spreads[-self.window_length:]\n zscore = (spread - np.mean(spread_wind)) / np.std(spread_wind)\n return zscore\n\n def place_orders(self, data, zscore):\n \"\"\"Buy spread if zscore is > 2, sell if zscore < .5.\n \"\"\"\n if zscore >= 2.0 and not self.invested:\n self.order(self.PEP, int(100 / data[self.PEP].price))\n self.order(self.KO, -int(100 / data[self.KO].price))\n self.invested = True\n elif zscore <= -2.0 and not self.invested:\n self.order(self.PEP, -int(100 / data[self.PEP].price))\n self.order(self.KO, int(100 / data[self.KO].price))\n self.invested = True\n elif abs(zscore) < .5 and self.invested:\n self.sell_spread()\n self.invested = False\n\n def sell_spread(self):\n \"\"\"\n decrease exposure, regardless of position long/short.\n buy for a short position, sell for a long.\n \"\"\"\n ko_amount = self.portfolio.positions[self.KO].amount\n self.order(self.KO, -1 * ko_amount)\n pep_amount = self.portfolio.positions[self.PEP].amount\n self.order(self.PEP, -1 * pep_amount)\n\n\n# Note: this function can be removed if running\n# this algorithm on quantopian.com\ndef analyze(context=None, results=None):\n ax1 = plt.subplot(211)\n plt.title('PepsiCo & Coca-Cola Co. share prices')\n results[['PEP', 'KO']].plot(ax=ax1)\n plt.ylabel('Price (USD)')\n plt.setp(ax1.get_xticklabels(), visible=False)\n\n ax2 = plt.subplot(212, sharex=ax1)\n results.zscores.plot(ax=ax2, color='r')\n plt.ylabel('Z-scored spread')\n\n plt.gcf().set_size_inches(18, 8)\n plt.show()\n\n\n# Note: this if-block should be removed if running\n# this algorithm on quantopian.com\nif __name__ == '__main__':\n logbook.StderrHandler().push_application()\n\n # Set the simulation start and end dates.\n start = datetime(2000, 1, 1, 0, 0, 0, 0, pytz.utc)\n end = datetime(2002, 1, 1, 0, 0, 0, 0, pytz.utc)\n\n # Load price data from yahoo.\n data = load_from_yahoo(stocks=['PEP', 'KO'], indexes={},\n start=start, end=end)\n\n # Create and run the algorithm.\n pairtrade = Pairtrade()\n results = pairtrade.run(data)\n\n # Plot the portfolio data.\n analyze(results=results)\n",
"from itertools import permutations\nfrom operator import (\n add,\n ge,\n gt,\n le,\n lt,\n methodcaller,\n mul,\n ne,\n)\nfrom unittest import TestCase\n\nimport numpy\nfrom numpy import (\n arange,\n array,\n eye,\n float64,\n full,\n isnan,\n zeros,\n)\nfrom pandas import (\n DataFrame,\n date_range,\n Int64Index,\n)\n\nfrom zipline.pipeline import Factor, Filter\nfrom zipline.pipeline.expression import (\n NumericalExpression,\n NUMEXPR_MATH_FUNCS,\n)\n\nfrom zipline.utils.numpy_utils import datetime64ns_dtype, float64_dtype\nfrom zipline.utils.test_utils import check_arrays\n\n\nclass F(Factor):\n dtype = float64_dtype\n inputs = ()\n window_length = 0\n\n\nclass G(Factor):\n dtype = float64_dtype\n inputs = ()\n window_length = 0\n\n\nclass H(Factor):\n dtype = float64_dtype\n inputs = ()\n window_length = 0\n\n\nclass NonExprFilter(Filter):\n inputs = ()\n window_length = 0\n\n\nclass DateFactor(Factor):\n dtype = datetime64ns_dtype\n inputs = ()\n window_length = 0\n\n\nclass NumericalExpressionTestCase(TestCase):\n\n def setUp(self):\n self.dates = date_range('2014-01-01', periods=5, freq='D')\n self.assets = Int64Index(range(5))\n self.f = F()\n self.g = G()\n self.h = H()\n self.d = DateFactor()\n self.fake_raw_data = {\n self.f: full((5, 5), 3, float),\n self.g: full((5, 5), 2, float),\n self.h: full((5, 5), 1, float),\n self.d: full((5, 5), 0, dtype='datetime64[ns]'),\n }\n self.mask = DataFrame(True, index=self.dates, columns=self.assets)\n\n def check_output(self, expr, expected):\n result = expr._compute(\n [self.fake_raw_data[input_] for input_ in expr.inputs],\n self.mask.index,\n self.mask.columns,\n self.mask.values,\n )\n check_arrays(result, expected)\n\n def check_constant_output(self, expr, expected):\n self.assertFalse(isnan(expected))\n return self.check_output(expr, full((5, 5), expected, float))\n\n def test_validate_good(self):\n f = self.f\n g = self.g\n\n NumericalExpression(\"x_0\", (f,), dtype=float64_dtype)\n NumericalExpression(\"x_0 \", (f,), dtype=float64_dtype)\n NumericalExpression(\"x_0 + x_0\", (f,), dtype=float64_dtype)\n NumericalExpression(\"x_0 + 2\", (f,), dtype=float64_dtype)\n NumericalExpression(\"2 * x_0\", (f,), dtype=float64_dtype)\n NumericalExpression(\"x_0 + x_1\", (f, g), dtype=float64_dtype)\n NumericalExpression(\"x_0 + x_1 + x_0\", (f, g), dtype=float64_dtype)\n NumericalExpression(\"x_0 + 1 + x_1\", (f, g), dtype=float64_dtype)\n\n def test_validate_bad(self):\n f, g, h = self.f, self.g, self.h\n\n # Too few inputs.\n with self.assertRaises(ValueError):\n NumericalExpression(\"x_0\", (), dtype=float64_dtype)\n with self.assertRaises(ValueError):\n NumericalExpression(\"x_0 + x_1\", (f,), dtype=float64_dtype)\n\n # Too many inputs.\n with self.assertRaises(ValueError):\n NumericalExpression(\"x_0\", (f, g), dtype=float64_dtype)\n with self.assertRaises(ValueError):\n NumericalExpression(\"x_0 + x_1\", (f, g, h), dtype=float64_dtype)\n\n # Invalid variable name.\n with self.assertRaises(ValueError):\n NumericalExpression(\"x_0x_1\", (f,), dtype=float64_dtype)\n with self.assertRaises(ValueError):\n NumericalExpression(\"x_0x_1\", (f, g), dtype=float64_dtype)\n\n # Variable index must start at 0.\n with self.assertRaises(ValueError):\n NumericalExpression(\"x_1\", (f,), dtype=float64_dtype)\n\n # Scalar operands must be numeric.\n with self.assertRaises(TypeError):\n \"2\" + f\n with self.assertRaises(TypeError):\n f + \"2\"\n with self.assertRaises(TypeError):\n f > \"2\"\n\n # Boolean binary operators must be between filters.\n with self.assertRaises(TypeError):\n f + (f > 2)\n with self.assertRaises(TypeError):\n (f > f) > f\n\n def test_combine_datetimes(self):\n with self.assertRaises(TypeError) as e:\n self.d + self.d\n message = e.exception.args[0]\n expected = (\n \"Don't know how to compute datetime64[ns] + datetime64[ns].\\n\"\n \"Arithmetic operators are only supported on Factors of dtype \"\n \"'float64'.\"\n )\n self.assertEqual(message, expected)\n\n # Confirm that * shows up in the error instead of +.\n with self.assertRaises(TypeError) as e:\n self.d * self.d\n message = e.exception.args[0]\n expected = (\n \"Don't know how to compute datetime64[ns] * datetime64[ns].\\n\"\n \"Arithmetic operators are only supported on Factors of dtype \"\n \"'float64'.\"\n )\n self.assertEqual(message, expected)\n\n def test_combine_datetime_with_float(self):\n # Test with both float-type factors and numeric values.\n for float_value in (self.f, float64(1.0), 1.0):\n for op, sym in ((add, '+'), (mul, '*')):\n with self.assertRaises(TypeError) as e:\n op(self.f, self.d)\n message = e.exception.args[0]\n expected = (\n \"Don't know how to compute float64 {sym} datetime64[ns].\\n\"\n \"Arithmetic operators are only supported on Factors of \"\n \"dtype 'float64'.\"\n ).format(sym=sym)\n self.assertEqual(message, expected)\n\n with self.assertRaises(TypeError) as e:\n op(self.d, self.f)\n message = e.exception.args[0]\n expected = (\n \"Don't know how to compute datetime64[ns] {sym} float64.\\n\"\n \"Arithmetic operators are only supported on Factors of \"\n \"dtype 'float64'.\"\n ).format(sym=sym)\n self.assertEqual(message, expected)\n\n def test_negate_datetime(self):\n with self.assertRaises(TypeError) as e:\n -self.d\n\n message = e.exception.args[0]\n expected = (\n \"Can't apply unary operator '-' to instance of \"\n \"'DateFactor' with dtype 'datetime64[ns]'.\\n\"\n \"'-' is only supported for Factors of dtype 'float64'.\"\n )\n self.assertEqual(message, expected)\n\n def test_negate(self):\n f, g = self.f, self.g\n\n self.check_constant_output(-f, -3.0)\n self.check_constant_output(--f, 3.0)\n self.check_constant_output(---f, -3.0)\n\n self.check_constant_output(-(f + f), -6.0)\n self.check_constant_output(-f + -f, -6.0)\n self.check_constant_output(-(-f + -f), 6.0)\n\n self.check_constant_output(f + -g, 1.0)\n self.check_constant_output(f - -g, 5.0)\n\n self.check_constant_output(-(f + g) + (f + g), 0.0)\n self.check_constant_output((f + g) + -(f + g), 0.0)\n self.check_constant_output(-(f + g) + -(f + g), -10.0)\n\n def test_add(self):\n f, g = self.f, self.g\n\n self.check_constant_output(f + g, 5.0)\n\n self.check_constant_output((1 + f) + g, 6.0)\n self.check_constant_output(1 + (f + g), 6.0)\n self.check_constant_output((f + 1) + g, 6.0)\n self.check_constant_output(f + (1 + g), 6.0)\n self.check_constant_output((f + g) + 1, 6.0)\n self.check_constant_output(f + (g + 1), 6.0)\n\n self.check_constant_output((f + f) + f, 9.0)\n self.check_constant_output(f + (f + f), 9.0)\n\n self.check_constant_output((f + g) + f, 8.0)\n self.check_constant_output(f + (g + f), 8.0)\n\n self.check_constant_output((f + g) + (f + g), 10.0)\n self.check_constant_output((f + g) + (g + f), 10.0)\n self.check_constant_output((g + f) + (f + g), 10.0)\n self.check_constant_output((g + f) + (g + f), 10.0)\n\n def test_subtract(self):\n f, g = self.f, self.g\n\n self.check_constant_output(f - g, 1.0) # 3 - 2\n\n self.check_constant_output((1 - f) - g, -4.) # (1 - 3) - 2\n self.check_constant_output(1 - (f - g), 0.0) # 1 - (3 - 2)\n self.check_constant_output((f - 1) - g, 0.0) # (3 - 1) - 2\n self.check_constant_output(f - (1 - g), 4.0) # 3 - (1 - 2)\n self.check_constant_output((f - g) - 1, 0.0) # (3 - 2) - 1\n self.check_constant_output(f - (g - 1), 2.0) # 3 - (2 - 1)\n\n self.check_constant_output((f - f) - f, -3.) # (3 - 3) - 3\n self.check_constant_output(f - (f - f), 3.0) # 3 - (3 - 3)\n\n self.check_constant_output((f - g) - f, -2.) # (3 - 2) - 3\n self.check_constant_output(f - (g - f), 4.0) # 3 - (2 - 3)\n\n self.check_constant_output((f - g) - (f - g), 0.0) # (3 - 2) - (3 - 2)\n self.check_constant_output((f - g) - (g - f), 2.0) # (3 - 2) - (2 - 3)\n self.check_constant_output((g - f) - (f - g), -2.) # (2 - 3) - (3 - 2)\n self.check_constant_output((g - f) - (g - f), 0.0) # (2 - 3) - (2 - 3)\n\n def test_multiply(self):\n f, g = self.f, self.g\n\n self.check_constant_output(f * g, 6.0)\n\n self.check_constant_output((2 * f) * g, 12.0)\n self.check_constant_output(2 * (f * g), 12.0)\n self.check_constant_output((f * 2) * g, 12.0)\n self.check_constant_output(f * (2 * g), 12.0)\n self.check_constant_output((f * g) * 2, 12.0)\n self.check_constant_output(f * (g * 2), 12.0)\n\n self.check_constant_output((f * f) * f, 27.0)\n self.check_constant_output(f * (f * f), 27.0)\n\n self.check_constant_output((f * g) * f, 18.0)\n self.check_constant_output(f * (g * f), 18.0)\n\n self.check_constant_output((f * g) * (f * g), 36.0)\n self.check_constant_output((f * g) * (g * f), 36.0)\n self.check_constant_output((g * f) * (f * g), 36.0)\n self.check_constant_output((g * f) * (g * f), 36.0)\n\n self.check_constant_output(f * f * f * 0 * f * f, 0.0)\n\n def test_divide(self):\n f, g = self.f, self.g\n\n self.check_constant_output(f / g, 3.0 / 2.0)\n\n self.check_constant_output(\n (2 / f) / g,\n (2 / 3.0) / 2.0\n )\n self.check_constant_output(\n 2 / (f / g),\n 2 / (3.0 / 2.0),\n )\n self.check_constant_output(\n (f / 2) / g,\n (3.0 / 2) / 2.0,\n )\n self.check_constant_output(\n f / (2 / g),\n 3.0 / (2 / 2.0),\n )\n self.check_constant_output(\n (f / g) / 2,\n (3.0 / 2.0) / 2,\n )\n self.check_constant_output(\n f / (g / 2),\n 3.0 / (2.0 / 2),\n )\n self.check_constant_output(\n (f / f) / f,\n (3.0 / 3.0) / 3.0\n )\n self.check_constant_output(\n f / (f / f),\n 3.0 / (3.0 / 3.0),\n )\n self.check_constant_output(\n (f / g) / f,\n (3.0 / 2.0) / 3.0,\n )\n self.check_constant_output(\n f / (g / f),\n 3.0 / (2.0 / 3.0),\n )\n\n self.check_constant_output(\n (f / g) / (f / g),\n (3.0 / 2.0) / (3.0 / 2.0),\n )\n self.check_constant_output(\n (f / g) / (g / f),\n (3.0 / 2.0) / (2.0 / 3.0),\n )\n self.check_constant_output(\n (g / f) / (f / g),\n (2.0 / 3.0) / (3.0 / 2.0),\n )\n self.check_constant_output(\n (g / f) / (g / f),\n (2.0 / 3.0) / (2.0 / 3.0),\n )\n\n def test_pow(self):\n f, g = self.f, self.g\n\n self.check_constant_output(f ** g, 3.0 ** 2)\n self.check_constant_output(2 ** f, 2.0 ** 3)\n self.check_constant_output(f ** 2, 3.0 ** 2)\n\n self.check_constant_output((f + g) ** 2, (3.0 + 2.0) ** 2)\n self.check_constant_output(2 ** (f + g), 2 ** (3.0 + 2.0))\n\n self.check_constant_output(f ** (f ** g), 3.0 ** (3.0 ** 2.0))\n self.check_constant_output((f ** f) ** g, (3.0 ** 3.0) ** 2.0)\n\n self.check_constant_output((f ** g) ** (f ** g), 9.0 ** 9.0)\n self.check_constant_output((f ** g) ** (g ** f), 9.0 ** 8.0)\n self.check_constant_output((g ** f) ** (f ** g), 8.0 ** 9.0)\n self.check_constant_output((g ** f) ** (g ** f), 8.0 ** 8.0)\n\n def test_mod(self):\n f, g = self.f, self.g\n\n self.check_constant_output(f % g, 3.0 % 2.0)\n self.check_constant_output(f % 2.0, 3.0 % 2.0)\n self.check_constant_output(g % f, 2.0 % 3.0)\n\n self.check_constant_output((f + g) % 2, (3.0 + 2.0) % 2)\n self.check_constant_output(2 % (f + g), 2 % (3.0 + 2.0))\n\n self.check_constant_output(f % (f % g), 3.0 % (3.0 % 2.0))\n self.check_constant_output((f % f) % g, (3.0 % 3.0) % 2.0)\n\n self.check_constant_output((f + g) % (f * g), 5.0 % 6.0)\n\n def test_math_functions(self):\n f, g = self.f, self.g\n\n fake_raw_data = self.fake_raw_data\n alt_fake_raw_data = {\n self.f: full((5, 5), .5),\n self.g: full((5, 5), -.5),\n }\n\n for funcname in NUMEXPR_MATH_FUNCS:\n method = methodcaller(funcname)\n func = getattr(numpy, funcname)\n\n # These methods have domains in [0, 1], so we need alternate inputs\n # that are in the domain.\n if funcname in ('arcsin', 'arccos', 'arctanh'):\n self.fake_raw_data = alt_fake_raw_data\n else:\n self.fake_raw_data = fake_raw_data\n\n f_val = self.fake_raw_data[f][0, 0]\n g_val = self.fake_raw_data[g][0, 0]\n\n self.check_constant_output(method(f), func(f_val))\n self.check_constant_output(method(g), func(g_val))\n\n self.check_constant_output(method(f) + 1, func(f_val) + 1)\n self.check_constant_output(1 + method(f), 1 + func(f_val))\n\n self.check_constant_output(method(f + .25), func(f_val + .25))\n self.check_constant_output(method(.25 + f), func(.25 + f_val))\n\n self.check_constant_output(\n method(f) + method(g),\n func(f_val) + func(g_val),\n )\n self.check_constant_output(\n method(f + g),\n func(f_val + g_val),\n )\n\n def test_comparisons(self):\n f, g, h = self.f, self.g, self.h\n self.fake_raw_data = {\n f: arange(25, dtype=float).reshape(5, 5),\n g: arange(25, dtype=float).reshape(5, 5) - eye(5),\n h: full((5, 5), 5, dtype=float),\n }\n f_data = self.fake_raw_data[f]\n g_data = self.fake_raw_data[g]\n\n cases = [\n # Sanity Check with hand-computed values.\n (f, g, eye(5), zeros((5, 5))),\n (f, 10, f_data, 10),\n (10, f, 10, f_data),\n (f, f, f_data, f_data),\n (f + 1, f, f_data + 1, f_data),\n (1 + f, f, 1 + f_data, f_data),\n (f, g, f_data, g_data),\n (f + 1, g, f_data + 1, g_data),\n (f, g + 1, f_data, g_data + 1),\n (f + 1, g + 1, f_data + 1, g_data + 1),\n ((f + g) / 2, f ** 2, (f_data + g_data) / 2, f_data ** 2),\n ]\n for op in (gt, ge, lt, le, ne):\n for expr_lhs, expr_rhs, expected_lhs, expected_rhs in cases:\n self.check_output(\n op(expr_lhs, expr_rhs),\n op(expected_lhs, expected_rhs),\n )\n\n def test_boolean_binops(self):\n f, g, h = self.f, self.g, self.h\n\n # Add a non-numexpr filter to ensure that we correctly handle\n # delegation to NumericalExpression.\n custom_filter = NonExprFilter()\n custom_filter_mask = array(\n [[0, 1, 0, 1, 0],\n [0, 0, 1, 0, 0],\n [1, 0, 0, 0, 0],\n [0, 0, 1, 1, 0],\n [0, 0, 0, 1, 0]],\n dtype=bool,\n )\n\n self.fake_raw_data = {\n f: arange(25, dtype=float).reshape(5, 5),\n g: arange(25, dtype=float).reshape(5, 5) - eye(5),\n h: full((5, 5), 5, dtype=float),\n custom_filter: custom_filter_mask,\n }\n\n # Should be True on the diagonal.\n eye_filter = (f > g)\n\n # Should be True in the first row only.\n first_row_filter = f < h\n\n eye_mask = eye(5, dtype=bool)\n\n first_row_mask = zeros((5, 5), dtype=bool)\n first_row_mask[0] = 1\n\n self.check_output(eye_filter, eye_mask)\n self.check_output(first_row_filter, first_row_mask)\n\n def gen_boolops(x, y, z):\n \"\"\"\n Generate all possible interleavings of & and | between all possible\n orderings of x, y, and z.\n \"\"\"\n for a, b, c in permutations([x, y, z]):\n yield (a & b) & c\n yield (a & b) | c\n yield (a | b) & c\n yield (a | b) | c\n yield a & (b & c)\n yield a & (b | c)\n yield a | (b & c)\n yield a | (b | c)\n\n exprs = gen_boolops(eye_filter, custom_filter, first_row_filter)\n arrays = gen_boolops(eye_mask, custom_filter_mask, first_row_mask)\n\n for expr, expected in zip(exprs, arrays):\n self.check_output(expr, expected)\n"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.gcf",
"numpy.std",
"matplotlib.pyplot.subplot",
"numpy.mean",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"numpy.isnan",
"numpy.arange",
"numpy.eye",
"pandas.DataFrame",
"numpy.full",
"numpy.float64",
"pandas.date_range",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
jaehwlee/K-wav2vec
|
[
"6ba33f0ef7d2399e4c52a3c80d83a092dac4daa9"
] |
[
"fairseq/options.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport argparse\nfrom typing import Callable, List, Optional\n\nimport torch\nfrom fairseq import utils\nfrom fairseq.data.indexed_dataset import get_available_dataset_impl\nfrom fairseq.dataclass.configs import (\n CheckpointConfig,\n CommonConfig,\n CommonEvalConfig,\n DatasetConfig,\n DistributedTrainingConfig,\n EvalLMConfig,\n GenerationConfig,\n InteractiveConfig,\n OptimizationConfig,\n)\nfrom fairseq.dataclass.utils import gen_parser_from_dataclass\n\n# this import is for backward compatibility\nfrom fairseq.utils import csv_str_list, eval_bool, eval_str_dict, eval_str_list # noqa\n\n\ndef get_preprocessing_parser(default_task=\"translation\"):\n parser = get_parser(\"Preprocessing\", default_task)\n add_preprocess_args(parser)\n return parser\n\n\ndef get_training_parser(default_task=\"translation\"):\n parser = get_parser(\"Trainer\", default_task)\n add_dataset_args(parser, train=True)\n add_distributed_training_args(parser)\n add_model_args(parser)\n add_optimization_args(parser)\n add_checkpoint_args(parser)\n return parser\n\n\ndef get_generation_parser(interactive=False, default_task=\"translation\"):\n parser = get_parser(\"Generation\", default_task)\n add_dataset_args(parser, gen=True)\n add_distributed_training_args(parser, default_world_size=1)\n add_generation_args(parser)\n add_checkpoint_args(parser)\n if interactive:\n add_interactive_args(parser)\n return parser\n\n\ndef get_interactive_generation_parser(default_task=\"translation\"):\n return get_generation_parser(interactive=True, default_task=default_task)\n\n\ndef get_eval_lm_parser(default_task=\"language_modeling\"):\n parser = get_parser(\"Evaluate Language Model\", default_task)\n add_dataset_args(parser, gen=True)\n add_distributed_training_args(parser, default_world_size=1)\n add_eval_lm_args(parser)\n return parser\n\n\ndef get_validation_parser(default_task=None):\n parser = get_parser(\"Validation\", default_task)\n add_dataset_args(parser, train=True)\n add_distributed_training_args(parser, default_world_size=1)\n group = parser.add_argument_group(\"Evaluation\")\n gen_parser_from_dataclass(group, CommonEvalConfig())\n return parser\n\n\ndef parse_args_and_arch(\n parser: argparse.ArgumentParser,\n input_args: List[str] = None,\n parse_known: bool = False,\n suppress_defaults: bool = False,\n modify_parser: Optional[Callable[[argparse.ArgumentParser], None]] = None,\n):\n \"\"\"\n Args:\n parser (ArgumentParser): the parser\n input_args (List[str]): strings to parse, defaults to sys.argv\n parse_known (bool): only parse known arguments, similar to\n `ArgumentParser.parse_known_args`\n suppress_defaults (bool): parse while ignoring all default values\n modify_parser (Optional[Callable[[ArgumentParser], None]]):\n function to modify the parser, e.g., to set default values\n \"\"\"\n if suppress_defaults:\n # Parse args without any default values. This requires us to parse\n # twice, once to identify all the necessary task/model args, and a second\n # time with all defaults set to None.\n args = parse_args_and_arch(\n parser,\n input_args=input_args,\n parse_known=parse_known,\n suppress_defaults=False,\n )\n suppressed_parser = argparse.ArgumentParser(add_help=False, parents=[parser])\n suppressed_parser.set_defaults(**{k: None for k, v in vars(args).items()})\n args = suppressed_parser.parse_args(input_args)\n return argparse.Namespace(\n **{k: v for k, v in vars(args).items() if v is not None}\n )\n\n from fairseq.models import ARCH_MODEL_REGISTRY, ARCH_CONFIG_REGISTRY, MODEL_REGISTRY\n\n # Before creating the true parser, we need to import optional user module\n # in order to eagerly import custom tasks, optimizers, architectures, etc.\n usr_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)\n usr_parser.add_argument(\"--user-dir\", default=None)\n usr_args, _ = usr_parser.parse_known_args(input_args)\n utils.import_user_module(usr_args)\n\n if modify_parser is not None:\n modify_parser(parser)\n\n # The parser doesn't know about model/criterion/optimizer-specific args, so\n # we parse twice. First we parse the model/criterion/optimizer, then we\n # parse a second time after adding the *-specific arguments.\n # If input_args is given, we will parse those args instead of sys.argv.\n args, _ = parser.parse_known_args(input_args)\n\n # Add model-specific args to parser.\n if hasattr(args, \"arch\"):\n model_specific_group = parser.add_argument_group(\n \"Model-specific configuration\",\n # Only include attributes which are explicitly given as command-line\n # arguments or which have default values.\n argument_default=argparse.SUPPRESS,\n )\n if args.arch in ARCH_MODEL_REGISTRY:\n ARCH_MODEL_REGISTRY[args.arch].add_args(model_specific_group)\n elif args.arch in MODEL_REGISTRY:\n MODEL_REGISTRY[args.arch].add_args(model_specific_group)\n else:\n raise RuntimeError()\n\n if hasattr(args, \"task\"):\n from fairseq.tasks import TASK_REGISTRY\n\n TASK_REGISTRY[args.task].add_args(parser)\n if getattr(args, \"use_bmuf\", False):\n # hack to support extra args for block distributed data parallelism\n from fairseq.optim.bmuf import FairseqBMUF\n\n FairseqBMUF.add_args(parser)\n\n # Add *-specific args to parser.\n from fairseq.registry import REGISTRIES\n\n for registry_name, REGISTRY in REGISTRIES.items():\n\n choice = getattr(args, registry_name, None)\n\n if choice is not None:\n cls = REGISTRY[\"registry\"][choice]\n if hasattr(cls, \"add_args\"):\n cls.add_args(parser)\n elif hasattr(cls, \"__dataclass\"):\n gen_parser_from_dataclass(parser, cls.__dataclass())\n\n # Modify the parser a second time, since defaults may have been reset\n if modify_parser is not None:\n modify_parser(parser)\n\n # Parse a second time.\n if parse_known:\n args, extra = parser.parse_known_args(input_args)\n else:\n args = parser.parse_args(input_args)\n extra = None\n # Post-process args.\n if (\n hasattr(args, \"batch_size_valid\") and args.batch_size_valid is None\n ) or not hasattr(args, \"batch_size_valid\"):\n args.batch_size_valid = args.batch_size\n if hasattr(args, \"max_tokens_valid\") and args.max_tokens_valid is None:\n args.max_tokens_valid = args.max_tokens\n if getattr(args, \"memory_efficient_fp16\", False):\n args.fp16 = True\n if getattr(args, \"memory_efficient_bf16\", False):\n args.bf16 = True\n args.tpu = getattr(args, \"tpu\", False)\n args.bf16 = getattr(args, \"bf16\", False)\n if args.bf16:\n args.tpu = True\n if args.tpu and args.fp16:\n raise ValueError(\"Cannot combine --fp16 and --tpu, use --bf16 on TPUs\")\n\n if getattr(args, \"seed\", None) is None:\n args.seed = 1 # default seed for training\n args.no_seed_provided = True\n else:\n args.no_seed_provided = False\n\n # Apply architecture configuration.\n if hasattr(args, \"arch\") and args.arch in ARCH_CONFIG_REGISTRY:\n ARCH_CONFIG_REGISTRY[args.arch](args)\n\n if parse_known:\n return args, extra\n else:\n return args\n\n\ndef get_parser(desc, default_task=\"translation\"):\n # Before creating the true parser, we need to import optional user module\n # in order to eagerly import custom tasks, optimizers, architectures, etc.\n usr_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)\n usr_parser.add_argument(\"--user-dir\", default=None)\n usr_args, _ = usr_parser.parse_known_args()\n utils.import_user_module(usr_args)\n\n parser = argparse.ArgumentParser(allow_abbrev=False)\n gen_parser_from_dataclass(parser, CommonConfig())\n\n from fairseq.registry import REGISTRIES\n\n for registry_name, REGISTRY in REGISTRIES.items():\n parser.add_argument(\n \"--\" + registry_name.replace(\"_\", \"-\"),\n default=REGISTRY[\"default\"],\n choices=REGISTRY[\"registry\"].keys(),\n )\n\n # Task definitions can be found under fairseq/tasks/\n from fairseq.tasks import TASK_REGISTRY\n\n parser.add_argument(\n \"--task\",\n metavar=\"TASK\",\n default=default_task,\n choices=TASK_REGISTRY.keys(),\n help=\"task\",\n )\n # fmt: on\n return parser\n\n\ndef add_preprocess_args(parser):\n group = parser.add_argument_group(\"Preprocessing\")\n # fmt: off\n group.add_argument(\"-s\", \"--source-lang\", default=None, metavar=\"SRC\",\n help=\"source language\")\n group.add_argument(\"-t\", \"--target-lang\", default=None, metavar=\"TARGET\",\n help=\"target language\")\n group.add_argument(\"--trainpref\", metavar=\"FP\", default=None,\n help=\"train file prefix (also used to build dictionaries)\")\n group.add_argument(\"--validpref\", metavar=\"FP\", default=None,\n help=\"comma separated, valid file prefixes \"\n \"(words missing from train set are replaced with <unk>)\")\n group.add_argument(\"--testpref\", metavar=\"FP\", default=None,\n help=\"comma separated, test file prefixes \"\n \"(words missing from train set are replaced with <unk>)\")\n group.add_argument(\"--align-suffix\", metavar=\"FP\", default=None,\n help=\"alignment file suffix\")\n group.add_argument(\"--destdir\", metavar=\"DIR\", default=\"data-bin\",\n help=\"destination dir\")\n group.add_argument(\"--thresholdtgt\", metavar=\"N\", default=0, type=int,\n help=\"map words appearing less than threshold times to unknown\")\n group.add_argument(\"--thresholdsrc\", metavar=\"N\", default=0, type=int,\n help=\"map words appearing less than threshold times to unknown\")\n group.add_argument(\"--tgtdict\", metavar=\"FP\",\n help=\"reuse given target dictionary\")\n group.add_argument(\"--srcdict\", metavar=\"FP\",\n help=\"reuse given source dictionary\")\n group.add_argument(\"--nwordstgt\", metavar=\"N\", default=-1, type=int,\n help=\"number of target words to retain\")\n group.add_argument(\"--nwordssrc\", metavar=\"N\", default=-1, type=int,\n help=\"number of source words to retain\")\n group.add_argument(\"--alignfile\", metavar=\"ALIGN\", default=None,\n help=\"an alignment file (optional)\")\n parser.add_argument('--dataset-impl', metavar='FORMAT', default='mmap',\n choices=get_available_dataset_impl(),\n help='output dataset implementation')\n group.add_argument(\"--joined-dictionary\", action=\"store_true\",\n help=\"Generate joined dictionary\")\n group.add_argument(\"--only-source\", action=\"store_true\",\n help=\"Only process the source language\")\n group.add_argument(\"--padding-factor\", metavar=\"N\", default=8, type=int,\n help=\"Pad dictionary size to be multiple of N\")\n group.add_argument(\"--workers\", metavar=\"N\", default=1, type=int,\n help=\"number of parallel workers\")\n # fmt: on\n return parser\n\n\ndef add_dataset_args(parser, train=False, gen=False):\n group = parser.add_argument_group(\"dataset_data_loading\")\n gen_parser_from_dataclass(group, DatasetConfig())\n # fmt: on\n return group\n\n\ndef add_distributed_training_args(parser, default_world_size=None):\n group = parser.add_argument_group(\"distributed_training\")\n if default_world_size is None:\n default_world_size = max(1, torch.cuda.device_count())\n gen_parser_from_dataclass(\n group, DistributedTrainingConfig(distributed_world_size=default_world_size)\n )\n return group\n\n\ndef add_optimization_args(parser):\n group = parser.add_argument_group(\"optimization\")\n # fmt: off\n gen_parser_from_dataclass(group, OptimizationConfig())\n # fmt: on\n return group\n\n\ndef add_checkpoint_args(parser):\n group = parser.add_argument_group(\"checkpoint\")\n # fmt: off\n gen_parser_from_dataclass(group, CheckpointConfig())\n # fmt: on\n return group\n\n\ndef add_common_eval_args(group):\n gen_parser_from_dataclass(group, CommonEvalConfig())\n\n\ndef add_eval_lm_args(parser):\n group = parser.add_argument_group(\"LM Evaluation\")\n add_common_eval_args(group)\n gen_parser_from_dataclass(group, EvalLMConfig())\n\n\ndef add_generation_args(parser):\n group = parser.add_argument_group(\"Generation\")\n add_common_eval_args(group)\n gen_parser_from_dataclass(group, GenerationConfig())\n return group\n\n\ndef add_interactive_args(parser):\n group = parser.add_argument_group(\"Interactive\")\n gen_parser_from_dataclass(group, InteractiveConfig())\n\n\ndef add_model_args(parser):\n group = parser.add_argument_group(\"Model configuration\")\n # fmt: off\n\n # Model definitions can be found under fairseq/models/\n #\n # The model architecture can be specified in several ways.\n # In increasing order of priority:\n # 1) model defaults (lowest priority)\n # 2) --arch argument\n # 3) --encoder/decoder-* arguments (highest priority)\n from fairseq.models import ARCH_MODEL_REGISTRY\n group.add_argument('--arch', '-a', metavar='ARCH',\n choices=ARCH_MODEL_REGISTRY.keys(),\n help='model architecture')\n # fmt: on\n return group\n"
] |
[
[
"torch.cuda.device_count"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gabglus/pandas_market_calendars
|
[
"dc1453a240a34f569cfd2b4e8ffd396f82c34b14"
] |
[
"pandas_market_calendars/exchange_calendar_tase.py"
] |
[
"from datetime import time\r\nfrom pandas import Timestamp\r\nfrom pytz import timezone\r\nfrom pandas_market_calendars import MarketCalendar\r\n\r\nTASEClosedDay = [\r\n # 2019\r\n Timestamp('2019-03-21', tz='Asia/Jerusalem'),\r\n Timestamp('2019-04-09', tz='Asia/Jerusalem'),\r\n Timestamp('2019-04-25', tz='Asia/Jerusalem'),\r\n Timestamp('2019-04-26', tz='Asia/Jerusalem'),\r\n Timestamp('2019-05-08', tz='Asia/Jerusalem'),\r\n Timestamp('2019-05-09', tz='Asia/Jerusalem'),\r\n Timestamp('2019-06-09', tz='Asia/Jerusalem'),\r\n Timestamp('2019-08-11', tz='Asia/Jerusalem'),\r\n Timestamp('2019-09-17', tz='Asia/Jerusalem'),\r\n Timestamp('2019-09-29', tz='Asia/Jerusalem'),\r\n Timestamp('2019-09-30', tz='Asia/Jerusalem'),\r\n Timestamp('2019-10-01', tz='Asia/Jerusalem'),\r\n Timestamp('2019-10-08', tz='Asia/Jerusalem'),\r\n Timestamp('2019-10-09', tz='Asia/Jerusalem'),\r\n Timestamp('2019-10-13', tz='Asia/Jerusalem'),\r\n Timestamp('2019-10-14', tz='Asia/Jerusalem'),\r\n Timestamp('2019-10-20', tz='Asia/Jerusalem'),\r\n Timestamp('2019-10-21', tz='Asia/Jerusalem'),\r\n # 2020\r\n Timestamp('2020-03-02', tz='Asia/Jerusalem'),\r\n Timestamp('2020-03-10', tz='Asia/Jerusalem'),\r\n Timestamp('2020-04-08', tz='Asia/Jerusalem'),\r\n Timestamp('2020-04-09', tz='Asia/Jerusalem'),\r\n Timestamp('2020-04-14', tz='Asia/Jerusalem'),\r\n Timestamp('2020-04-15', tz='Asia/Jerusalem'),\r\n Timestamp('2020-04-28', tz='Asia/Jerusalem'),\r\n Timestamp('2020-04-29', tz='Asia/Jerusalem'),\r\n Timestamp('2020-05-28', tz='Asia/Jerusalem'),\r\n Timestamp('2020-05-29', tz='Asia/Jerusalem'),\r\n Timestamp('2020-07-30', tz='Asia/Jerusalem'),\r\n Timestamp('2020-09-20', tz='Asia/Jerusalem'),\r\n Timestamp('2020-09-27', tz='Asia/Jerusalem'),\r\n Timestamp('2020-09-28', tz='Asia/Jerusalem'),\r\n # 2021\r\n Timestamp('2021-02-26', tz='Asia/Jerusalem'),\r\n Timestamp('2021-03-28', tz='Asia/Jerusalem'),\r\n Timestamp('2021-04-02', tz='Asia/Jerusalem'),\r\n Timestamp('2021-04-14', tz='Asia/Jerusalem'),\r\n Timestamp('2021-04-15', tz='Asia/Jerusalem'),\r\n Timestamp('2021-05-16', tz='Asia/Jerusalem'),\r\n Timestamp('2021-05-17', tz='Asia/Jerusalem'),\r\n Timestamp('2021-07-18', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-06', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-07', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-08', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-15', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-16', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-20', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-21', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-27', tz='Asia/Jerusalem'),\r\n Timestamp('2021-09-28', tz='Asia/Jerusalem'),\r\n]\r\n\r\n\r\nclass TASEExchangeCalendar(MarketCalendar):\r\n \"\"\"\r\n Exchange calendar for TASE Stock Exchange\r\n\r\n Note these dates are only checked against 2020 and 2021\r\n https://info.tase.co.il/Eng/about_tase/corporate/Pages/vacation_schedule.aspx\r\n\r\n Opening times for the regular trading of equities (not including closing auction call)\r\n Open Time: 10:00 AM Asia/Jerusalem\r\n Close Time: 3:59 PM Asia/Jerusalem\r\n\r\n Daylight Saving Time in Israel comes into effect on the Friday before the last Sunday in March, and lasts until the last Sunday in October.\r\n During the Daylight Saving time period the clock will be UTC+3, and for the rest of the year UTC+2.\r\n\r\n Regularly-Observed Holidays (not necessarily in order):\r\n - Purim\r\n - Passover_I_Eve\r\n - Passover_I\r\n - Passover_II_Eve\r\n - Passover_II\r\n - Independence_Day\r\n - Yom_HaZikaron\r\n - Shavuot_Eve\r\n - Shavuot\r\n - Tisha_beAv\r\n - Jewish_New_Year_Eve\r\n - Jewish_New_Year_I\r\n - Jewish_New_Year_II\r\n - Yom_Kippur_Eve\r\n - Yom_Kippur\r\n - Sukkoth_Eve\r\n - Sukkoth\r\n - Simchat_Tora_Eve\r\n - Simchat_Tora\r\n \"\"\"\r\n\r\n aliases = ['TASE']\r\n\r\n @property\r\n def name(self):\r\n return \"TASE\"\r\n\r\n @property\r\n def tz(self):\r\n return timezone(\"Asia/Jerusalem\")\r\n\r\n @property\r\n def open_time_default(self):\r\n return time(10, 0, tzinfo=self.tz)\r\n\r\n @property\r\n def close_time_default(self):\r\n return time(15, 59, tzinfo=self.tz)\r\n\r\n @property\r\n def adhoc_holidays(self):\r\n return TASEClosedDay\r\n\r\n @property\r\n def weekmask(self):\r\n return \"Sun Mon Tue Wed Thu\"\r\n"
] |
[
[
"pandas.Timestamp"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
geosmart/spark
|
[
"9c5bcac61ee56fbb271e890cc33f9a983612c5b0"
] |
[
"python/pyspark/pandas/tests/test_ops_on_diff_frames.py"
] |
[
"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom distutils.version import LooseVersion\nfrom itertools import product\nimport unittest\n\nimport pandas as pd\nimport numpy as np\n\nfrom pyspark import pandas as ps\nfrom pyspark.pandas.config import set_option, reset_option\nfrom pyspark.pandas.frame import DataFrame\nfrom pyspark.testing.pandasutils import PandasOnSparkTestCase\nfrom pyspark.testing.sqlutils import SQLTestUtils\nfrom pyspark.pandas.typedef.typehints import (\n extension_dtypes,\n extension_dtypes_available,\n extension_float_dtypes_available,\n extension_object_dtypes_available,\n)\n\n\nclass OpsOnDiffFramesEnabledTest(PandasOnSparkTestCase, SQLTestUtils):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n set_option(\"compute.ops_on_diff_frames\", True)\n\n @classmethod\n def tearDownClass(cls):\n reset_option(\"compute.ops_on_diff_frames\")\n super().tearDownClass()\n\n @property\n def pdf1(self):\n return pd.DataFrame(\n {\"a\": [1, 2, 3, 4, 5, 6, 7, 8, 9], \"b\": [4, 5, 6, 3, 2, 1, 0, 0, 0]},\n index=[0, 1, 3, 5, 6, 8, 9, 10, 11],\n )\n\n @property\n def pdf2(self):\n return pd.DataFrame(\n {\"a\": [9, 8, 7, 6, 5, 4, 3, 2, 1], \"b\": [0, 0, 0, 4, 5, 6, 1, 2, 3]},\n index=list(range(9)),\n )\n\n @property\n def pdf3(self):\n return pd.DataFrame(\n {\"b\": [1, 1, 1, 1, 1, 1, 1, 1, 1], \"c\": [1, 1, 1, 1, 1, 1, 1, 1, 1]},\n index=list(range(9)),\n )\n\n @property\n def pdf4(self):\n return pd.DataFrame(\n {\"e\": [2, 2, 2, 2, 2, 2, 2, 2, 2], \"f\": [2, 2, 2, 2, 2, 2, 2, 2, 2]},\n index=list(range(9)),\n )\n\n @property\n def pdf5(self):\n return pd.DataFrame(\n {\n \"a\": [1, 2, 3, 4, 5, 6, 7, 8, 9],\n \"b\": [4, 5, 6, 3, 2, 1, 0, 0, 0],\n \"c\": [4, 5, 6, 3, 2, 1, 0, 0, 0],\n },\n index=[0, 1, 3, 5, 6, 8, 9, 10, 11],\n ).set_index([\"a\", \"b\"])\n\n @property\n def pdf6(self):\n return pd.DataFrame(\n {\n \"a\": [9, 8, 7, 6, 5, 4, 3, 2, 1],\n \"b\": [0, 0, 0, 4, 5, 6, 1, 2, 3],\n \"c\": [9, 8, 7, 6, 5, 4, 3, 2, 1],\n \"e\": [4, 5, 6, 3, 2, 1, 0, 0, 0],\n },\n index=list(range(9)),\n ).set_index([\"a\", \"b\"])\n\n @property\n def pser1(self):\n midx = pd.MultiIndex(\n [[\"lama\", \"cow\", \"falcon\", \"koala\"], [\"speed\", \"weight\", \"length\", \"power\"]],\n [[0, 3, 1, 1, 1, 2, 2, 2], [0, 2, 0, 3, 2, 0, 1, 3]],\n )\n return pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1], index=midx)\n\n @property\n def pser2(self):\n midx = pd.MultiIndex(\n [[\"lama\", \"cow\", \"falcon\"], [\"speed\", \"weight\", \"length\"]],\n [[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],\n )\n return pd.Series([-45, 200, -1.2, 30, -250, 1.5, 320, 1, -0.3], index=midx)\n\n @property\n def pser3(self):\n midx = pd.MultiIndex(\n [[\"koalas\", \"cow\", \"falcon\"], [\"speed\", \"weight\", \"length\"]],\n [[0, 0, 0, 1, 1, 1, 2, 2, 2], [1, 1, 2, 0, 0, 2, 2, 2, 1]],\n )\n return pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx)\n\n @property\n def psdf1(self):\n return ps.from_pandas(self.pdf1)\n\n @property\n def psdf2(self):\n return ps.from_pandas(self.pdf2)\n\n @property\n def psdf3(self):\n return ps.from_pandas(self.pdf3)\n\n @property\n def psdf4(self):\n return ps.from_pandas(self.pdf4)\n\n @property\n def psdf5(self):\n return ps.from_pandas(self.pdf5)\n\n @property\n def psdf6(self):\n return ps.from_pandas(self.pdf6)\n\n @property\n def psser1(self):\n return ps.from_pandas(self.pser1)\n\n @property\n def psser2(self):\n return ps.from_pandas(self.pser2)\n\n @property\n def psser3(self):\n return ps.from_pandas(self.pser3)\n\n def test_ranges(self):\n self.assert_eq(\n (ps.range(10) + ps.range(10)).sort_index(),\n (\n ps.DataFrame({\"id\": list(range(10))}) + ps.DataFrame({\"id\": list(range(10))})\n ).sort_index(),\n )\n\n def test_no_matched_index(self):\n with self.assertRaisesRegex(ValueError, \"Index names must be exactly matched\"):\n ps.DataFrame({\"a\": [1, 2, 3]}).set_index(\"a\") + ps.DataFrame(\n {\"b\": [1, 2, 3]}\n ).set_index(\"b\")\n\n def test_arithmetic(self):\n self._test_arithmetic_frame(self.pdf1, self.pdf2, check_extension=False)\n self._test_arithmetic_series(self.pser1, self.pser2, check_extension=False)\n\n @unittest.skipIf(not extension_dtypes_available, \"pandas extension dtypes are not available\")\n def test_arithmetic_extension_dtypes(self):\n self._test_arithmetic_frame(\n self.pdf1.astype(\"Int64\"), self.pdf2.astype(\"Int64\"), check_extension=True\n )\n self._test_arithmetic_series(\n self.pser1.astype(int).astype(\"Int64\"),\n self.pser2.astype(int).astype(\"Int64\"),\n check_extension=True,\n )\n\n @unittest.skipIf(\n not extension_float_dtypes_available, \"pandas extension float dtypes are not available\"\n )\n def test_arithmetic_extension_float_dtypes(self):\n self._test_arithmetic_frame(\n self.pdf1.astype(\"Float64\"), self.pdf2.astype(\"Float64\"), check_extension=True\n )\n self._test_arithmetic_series(\n self.pser1.astype(\"Float64\"), self.pser2.astype(\"Float64\"), check_extension=True\n )\n\n def _test_arithmetic_frame(self, pdf1, pdf2, *, check_extension):\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n def assert_eq(actual, expected):\n if LooseVersion(\"1.1\") <= LooseVersion(pd.__version__) < LooseVersion(\"1.2.2\"):\n self.assert_eq(actual, expected, check_exact=not check_extension)\n if check_extension:\n if isinstance(actual, DataFrame):\n for dtype in actual.dtypes:\n self.assertTrue(isinstance(dtype, extension_dtypes))\n else:\n self.assertTrue(isinstance(actual.dtype, extension_dtypes))\n else:\n self.assert_eq(actual, expected)\n\n # Series\n assert_eq((psdf1.a - psdf2.b).sort_index(), (pdf1.a - pdf2.b).sort_index())\n\n assert_eq((psdf1.a * psdf2.a).sort_index(), (pdf1.a * pdf2.a).sort_index())\n\n if check_extension and not extension_float_dtypes_available:\n self.assert_eq(\n (psdf1[\"a\"] / psdf2[\"a\"]).sort_index(), (pdf1[\"a\"] / pdf2[\"a\"]).sort_index()\n )\n else:\n assert_eq((psdf1[\"a\"] / psdf2[\"a\"]).sort_index(), (pdf1[\"a\"] / pdf2[\"a\"]).sort_index())\n\n # DataFrame\n assert_eq((psdf1 + psdf2).sort_index(), (pdf1 + pdf2).sort_index())\n\n # Multi-index columns\n columns = pd.MultiIndex.from_tuples([(\"x\", \"a\"), (\"x\", \"b\")])\n psdf1.columns = columns\n psdf2.columns = columns\n pdf1.columns = columns\n pdf2.columns = columns\n\n # Series\n assert_eq(\n (psdf1[(\"x\", \"a\")] - psdf2[(\"x\", \"b\")]).sort_index(),\n (pdf1[(\"x\", \"a\")] - pdf2[(\"x\", \"b\")]).sort_index(),\n )\n\n assert_eq(\n (psdf1[(\"x\", \"a\")] - psdf2[\"x\"][\"b\"]).sort_index(),\n (pdf1[(\"x\", \"a\")] - pdf2[\"x\"][\"b\"]).sort_index(),\n )\n\n assert_eq(\n (psdf1[\"x\"][\"a\"] - psdf2[(\"x\", \"b\")]).sort_index(),\n (pdf1[\"x\"][\"a\"] - pdf2[(\"x\", \"b\")]).sort_index(),\n )\n\n # DataFrame\n assert_eq((psdf1 + psdf2).sort_index(), (pdf1 + pdf2).sort_index())\n\n def _test_arithmetic_series(self, pser1, pser2, *, check_extension):\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n def assert_eq(actual, expected):\n if LooseVersion(\"1.1\") <= LooseVersion(pd.__version__) < LooseVersion(\"1.2.2\"):\n self.assert_eq(actual, expected, check_exact=not check_extension)\n if check_extension:\n self.assertTrue(isinstance(actual.dtype, extension_dtypes))\n else:\n self.assert_eq(actual, expected)\n\n # MultiIndex Series\n assert_eq((psser1 + psser2).sort_index(), (pser1 + pser2).sort_index())\n\n assert_eq((psser1 - psser2).sort_index(), (pser1 - pser2).sort_index())\n\n assert_eq((psser1 * psser2).sort_index(), (pser1 * pser2).sort_index())\n\n if check_extension and not extension_float_dtypes_available:\n self.assert_eq((psser1 / psser2).sort_index(), (pser1 / pser2).sort_index())\n else:\n assert_eq((psser1 / psser2).sort_index(), (pser1 / pser2).sort_index())\n\n def test_arithmetic_chain(self):\n self._test_arithmetic_chain_frame(self.pdf1, self.pdf2, self.pdf3, check_extension=False)\n self._test_arithmetic_chain_series(\n self.pser1, self.pser2, self.pser3, check_extension=False\n )\n\n @unittest.skipIf(not extension_dtypes_available, \"pandas extension dtypes are not available\")\n def test_arithmetic_chain_extension_dtypes(self):\n self._test_arithmetic_chain_frame(\n self.pdf1.astype(\"Int64\"),\n self.pdf2.astype(\"Int64\"),\n self.pdf3.astype(\"Int64\"),\n check_extension=True,\n )\n self._test_arithmetic_chain_series(\n self.pser1.astype(int).astype(\"Int64\"),\n self.pser2.astype(int).astype(\"Int64\"),\n self.pser3.astype(int).astype(\"Int64\"),\n check_extension=True,\n )\n\n @unittest.skipIf(\n not extension_float_dtypes_available, \"pandas extension float dtypes are not available\"\n )\n def test_arithmetic_chain_extension_float_dtypes(self):\n self._test_arithmetic_chain_frame(\n self.pdf1.astype(\"Float64\"),\n self.pdf2.astype(\"Float64\"),\n self.pdf3.astype(\"Float64\"),\n check_extension=True,\n )\n self._test_arithmetic_chain_series(\n self.pser1.astype(\"Float64\"),\n self.pser2.astype(\"Float64\"),\n self.pser3.astype(\"Float64\"),\n check_extension=True,\n )\n\n def _test_arithmetic_chain_frame(self, pdf1, pdf2, pdf3, *, check_extension):\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n psdf3 = ps.from_pandas(pdf3)\n\n common_columns = set(psdf1.columns).intersection(psdf2.columns).intersection(psdf3.columns)\n\n def assert_eq(actual, expected):\n if LooseVersion(\"1.1\") <= LooseVersion(pd.__version__) < LooseVersion(\"1.2.2\"):\n self.assert_eq(actual, expected, check_exact=not check_extension)\n if check_extension:\n if isinstance(actual, DataFrame):\n for column, dtype in zip(actual.columns, actual.dtypes):\n if column in common_columns:\n self.assertTrue(isinstance(dtype, extension_dtypes))\n else:\n self.assertFalse(isinstance(dtype, extension_dtypes))\n else:\n self.assertTrue(isinstance(actual.dtype, extension_dtypes))\n else:\n self.assert_eq(actual, expected)\n\n # Series\n assert_eq(\n (psdf1.a - psdf2.b - psdf3.c).sort_index(), (pdf1.a - pdf2.b - pdf3.c).sort_index()\n )\n\n assert_eq(\n (psdf1.a * (psdf2.a * psdf3.c)).sort_index(), (pdf1.a * (pdf2.a * pdf3.c)).sort_index()\n )\n\n if check_extension and not extension_float_dtypes_available:\n self.assert_eq(\n (psdf1[\"a\"] / psdf2[\"a\"] / psdf3[\"c\"]).sort_index(),\n (pdf1[\"a\"] / pdf2[\"a\"] / pdf3[\"c\"]).sort_index(),\n )\n else:\n assert_eq(\n (psdf1[\"a\"] / psdf2[\"a\"] / psdf3[\"c\"]).sort_index(),\n (pdf1[\"a\"] / pdf2[\"a\"] / pdf3[\"c\"]).sort_index(),\n )\n\n # DataFrame\n if check_extension and (\n LooseVersion(\"1.0\") <= LooseVersion(pd.__version__) < LooseVersion(\"1.1\")\n ):\n self.assert_eq(\n (psdf1 + psdf2 - psdf3).sort_index(), (pdf1 + pdf2 - pdf3).sort_index(), almost=True\n )\n else:\n assert_eq((psdf1 + psdf2 - psdf3).sort_index(), (pdf1 + pdf2 - pdf3).sort_index())\n\n # Multi-index columns\n columns = pd.MultiIndex.from_tuples([(\"x\", \"a\"), (\"x\", \"b\")])\n psdf1.columns = columns\n psdf2.columns = columns\n pdf1.columns = columns\n pdf2.columns = columns\n columns = pd.MultiIndex.from_tuples([(\"x\", \"b\"), (\"y\", \"c\")])\n psdf3.columns = columns\n pdf3.columns = columns\n\n common_columns = set(psdf1.columns).intersection(psdf2.columns).intersection(psdf3.columns)\n\n # Series\n assert_eq(\n (psdf1[(\"x\", \"a\")] - psdf2[(\"x\", \"b\")] - psdf3[(\"y\", \"c\")]).sort_index(),\n (pdf1[(\"x\", \"a\")] - pdf2[(\"x\", \"b\")] - pdf3[(\"y\", \"c\")]).sort_index(),\n )\n\n assert_eq(\n (psdf1[(\"x\", \"a\")] * (psdf2[(\"x\", \"b\")] * psdf3[(\"y\", \"c\")])).sort_index(),\n (pdf1[(\"x\", \"a\")] * (pdf2[(\"x\", \"b\")] * pdf3[(\"y\", \"c\")])).sort_index(),\n )\n\n # DataFrame\n if check_extension and (\n LooseVersion(\"1.0\") <= LooseVersion(pd.__version__) < LooseVersion(\"1.1\")\n ):\n self.assert_eq(\n (psdf1 + psdf2 - psdf3).sort_index(), (pdf1 + pdf2 - pdf3).sort_index(), almost=True\n )\n else:\n assert_eq((psdf1 + psdf2 - psdf3).sort_index(), (pdf1 + pdf2 - pdf3).sort_index())\n\n def _test_arithmetic_chain_series(self, pser1, pser2, pser3, *, check_extension):\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n psser3 = ps.from_pandas(pser3)\n\n def assert_eq(actual, expected):\n if LooseVersion(\"1.1\") <= LooseVersion(pd.__version__) < LooseVersion(\"1.2.2\"):\n self.assert_eq(actual, expected, check_exact=not check_extension)\n if check_extension:\n self.assertTrue(isinstance(actual.dtype, extension_dtypes))\n else:\n self.assert_eq(actual, expected)\n\n # MultiIndex Series\n assert_eq((psser1 + psser2 - psser3).sort_index(), (pser1 + pser2 - pser3).sort_index())\n\n assert_eq((psser1 * psser2 * psser3).sort_index(), (pser1 * pser2 * pser3).sort_index())\n\n if check_extension and not extension_float_dtypes_available:\n if LooseVersion(pd.__version__) >= LooseVersion(\"1.0\"):\n self.assert_eq(\n (psser1 - psser2 / psser3).sort_index(), (pser1 - pser2 / pser3).sort_index()\n )\n else:\n expected = pd.Series(\n [249.0, np.nan, 0.0, 0.88, np.nan, np.nan, np.nan, np.nan, np.nan, -np.inf]\n + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n index=pd.MultiIndex(\n [\n [\"cow\", \"falcon\", \"koala\", \"koalas\", \"lama\"],\n [\"length\", \"power\", \"speed\", \"weight\"],\n ],\n [\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 3, 3, 3, 4, 4, 4],\n [0, 1, 2, 2, 3, 0, 0, 1, 2, 3, 0, 0, 3, 3, 0, 2, 3],\n ],\n ),\n )\n self.assert_eq((psser1 - psser2 / psser3).sort_index(), expected)\n else:\n assert_eq((psser1 - psser2 / psser3).sort_index(), (pser1 - pser2 / pser3).sort_index())\n\n assert_eq((psser1 + psser2 * psser3).sort_index(), (pser1 + pser2 * pser3).sort_index())\n\n def test_mod(self):\n pser = pd.Series([100, None, -300, None, 500, -700])\n pser_other = pd.Series([-150] * 6)\n psser = ps.from_pandas(pser)\n psser_other = ps.from_pandas(pser_other)\n\n self.assert_eq(psser.mod(psser_other).sort_index(), pser.mod(pser_other))\n self.assert_eq(psser.mod(psser_other).sort_index(), pser.mod(pser_other))\n self.assert_eq(psser.mod(psser_other).sort_index(), pser.mod(pser_other))\n\n def test_rmod(self):\n pser = pd.Series([100, None, -300, None, 500, -700])\n pser_other = pd.Series([-150] * 6)\n psser = ps.from_pandas(pser)\n psser_other = ps.from_pandas(pser_other)\n\n self.assert_eq(psser.rmod(psser_other).sort_index(), pser.rmod(pser_other))\n self.assert_eq(psser.rmod(psser_other).sort_index(), pser.rmod(pser_other))\n self.assert_eq(psser.rmod(psser_other).sort_index(), pser.rmod(pser_other))\n\n def test_getitem_boolean_series(self):\n pdf1 = pd.DataFrame(\n {\"A\": [0, 1, 2, 3, 4], \"B\": [100, 200, 300, 400, 500]}, index=[20, 10, 30, 0, 50]\n )\n pdf2 = pd.DataFrame(\n {\"A\": [0, -1, -2, -3, -4], \"B\": [-100, -200, -300, -400, -500]},\n index=[0, 30, 10, 20, 50],\n )\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1[pdf2.A > -3].sort_index(), psdf1[psdf2.A > -3].sort_index())\n\n self.assert_eq(pdf1.A[pdf2.A > -3].sort_index(), psdf1.A[psdf2.A > -3].sort_index())\n\n self.assert_eq(\n (pdf1.A + 1)[pdf2.A > -3].sort_index(), (psdf1.A + 1)[psdf2.A > -3].sort_index()\n )\n\n def test_loc_getitem_boolean_series(self):\n pdf1 = pd.DataFrame(\n {\"A\": [0, 1, 2, 3, 4], \"B\": [100, 200, 300, 400, 500]}, index=[20, 10, 30, 0, 50]\n )\n pdf2 = pd.DataFrame(\n {\"A\": [0, -1, -2, -3, -4], \"B\": [-100, -200, -300, -400, -500]},\n index=[20, 10, 30, 0, 50],\n )\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1.loc[pdf2.A > -3].sort_index(), psdf1.loc[psdf2.A > -3].sort_index())\n\n self.assert_eq(pdf1.A.loc[pdf2.A > -3].sort_index(), psdf1.A.loc[psdf2.A > -3].sort_index())\n\n self.assert_eq(\n (pdf1.A + 1).loc[pdf2.A > -3].sort_index(), (psdf1.A + 1).loc[psdf2.A > -3].sort_index()\n )\n\n def test_bitwise(self):\n pser1 = pd.Series([True, False, True, False, np.nan, np.nan, True, False, np.nan])\n pser2 = pd.Series([True, False, False, True, True, False, np.nan, np.nan, np.nan])\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n self.assert_eq(pser1 | pser2, (psser1 | psser2).sort_index())\n self.assert_eq(pser1 & pser2, (psser1 & psser2).sort_index())\n\n pser1 = pd.Series([True, False, np.nan], index=list(\"ABC\"))\n pser2 = pd.Series([False, True, np.nan], index=list(\"DEF\"))\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n self.assert_eq(pser1 | pser2, (psser1 | psser2).sort_index())\n self.assert_eq(pser1 & pser2, (psser1 & psser2).sort_index())\n\n @unittest.skipIf(\n not extension_object_dtypes_available, \"pandas extension object dtypes are not available\"\n )\n def test_bitwise_extension_dtype(self):\n def assert_eq(actual, expected):\n if LooseVersion(\"1.1\") <= LooseVersion(pd.__version__) < LooseVersion(\"1.2.2\"):\n self.assert_eq(actual, expected, check_exact=False)\n self.assertTrue(isinstance(actual.dtype, extension_dtypes))\n else:\n self.assert_eq(actual, expected)\n\n pser1 = pd.Series(\n [True, False, True, False, np.nan, np.nan, True, False, np.nan], dtype=\"boolean\"\n )\n pser2 = pd.Series(\n [True, False, False, True, True, False, np.nan, np.nan, np.nan], dtype=\"boolean\"\n )\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n assert_eq((psser1 | psser2).sort_index(), pser1 | pser2)\n assert_eq((psser1 & psser2).sort_index(), pser1 & pser2)\n\n pser1 = pd.Series([True, False, np.nan], index=list(\"ABC\"), dtype=\"boolean\")\n pser2 = pd.Series([False, True, np.nan], index=list(\"DEF\"), dtype=\"boolean\")\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n # a pandas bug?\n # assert_eq((psser1 | psser2).sort_index(), pser1 | pser2)\n # assert_eq((psser1 & psser2).sort_index(), pser1 & pser2)\n assert_eq(\n (psser1 | psser2).sort_index(),\n pd.Series([True, None, None, None, True, None], index=list(\"ABCDEF\"), dtype=\"boolean\"),\n )\n assert_eq(\n (psser1 & psser2).sort_index(),\n pd.Series(\n [None, False, None, False, None, None], index=list(\"ABCDEF\"), dtype=\"boolean\"\n ),\n )\n\n def test_concat_column_axis(self):\n pdf1 = pd.DataFrame({\"A\": [0, 2, 4], \"B\": [1, 3, 5]}, index=[1, 2, 3])\n pdf1.columns.names = [\"AB\"]\n pdf2 = pd.DataFrame({\"C\": [1, 2, 3], \"D\": [4, 5, 6]}, index=[1, 3, 5])\n pdf2.columns.names = [\"CD\"]\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n psdf3 = psdf1.copy()\n psdf4 = psdf2.copy()\n pdf3 = pdf1.copy()\n pdf4 = pdf2.copy()\n\n columns = pd.MultiIndex.from_tuples([(\"X\", \"A\"), (\"X\", \"B\")], names=[\"X\", \"AB\"])\n pdf3.columns = columns\n psdf3.columns = columns\n\n columns = pd.MultiIndex.from_tuples([(\"X\", \"C\"), (\"X\", \"D\")], names=[\"Y\", \"CD\"])\n pdf4.columns = columns\n psdf4.columns = columns\n\n pdf5 = pd.DataFrame({\"A\": [0, 2, 4], \"B\": [1, 3, 5]}, index=[1, 2, 3])\n pdf6 = pd.DataFrame({\"C\": [1, 2, 3]}, index=[1, 3, 5])\n psdf5 = ps.from_pandas(pdf5)\n psdf6 = ps.from_pandas(pdf6)\n\n ignore_indexes = [True, False]\n joins = [\"inner\", \"outer\"]\n\n objs = [\n ([psdf1.A, psdf2.C], [pdf1.A, pdf2.C]),\n # TODO: ([psdf1, psdf2.C], [pdf1, pdf2.C]),\n ([psdf1.A, psdf2], [pdf1.A, pdf2]),\n ([psdf1.A, psdf2.C], [pdf1.A, pdf2.C]),\n ([psdf3[(\"X\", \"A\")], psdf4[(\"X\", \"C\")]], [pdf3[(\"X\", \"A\")], pdf4[(\"X\", \"C\")]]),\n ([psdf3, psdf4[(\"X\", \"C\")]], [pdf3, pdf4[(\"X\", \"C\")]]),\n ([psdf3[(\"X\", \"A\")], psdf4], [pdf3[(\"X\", \"A\")], pdf4]),\n ([psdf3, psdf4], [pdf3, pdf4]),\n ([psdf5, psdf6], [pdf5, pdf6]),\n ([psdf6, psdf5], [pdf6, pdf5]),\n ]\n\n for ignore_index, join in product(ignore_indexes, joins):\n for i, (psdfs, pdfs) in enumerate(objs):\n with self.subTest(ignore_index=ignore_index, join=join, pdfs=pdfs, pair=i):\n actual = ps.concat(psdfs, axis=1, ignore_index=ignore_index, join=join)\n expected = pd.concat(pdfs, axis=1, ignore_index=ignore_index, join=join)\n self.assert_eq(\n repr(actual.sort_values(list(actual.columns)).reset_index(drop=True)),\n repr(expected.sort_values(list(expected.columns)).reset_index(drop=True)),\n )\n\n def test_combine_first(self):\n pser1 = pd.Series({\"falcon\": 330.0, \"eagle\": 160.0})\n pser2 = pd.Series({\"falcon\": 345.0, \"eagle\": 200.0, \"duck\": 30.0})\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n self.assert_eq(\n psser1.combine_first(psser2).sort_index(), pser1.combine_first(pser2).sort_index()\n )\n with self.assertRaisesRegex(\n TypeError, \"`combine_first` only allows `Series` for parameter `other`\"\n ):\n psser1.combine_first(50)\n\n psser1.name = (\"X\", \"A\")\n psser2.name = (\"Y\", \"B\")\n pser1.name = (\"X\", \"A\")\n pser2.name = (\"Y\", \"B\")\n self.assert_eq(\n psser1.combine_first(psser2).sort_index(), pser1.combine_first(pser2).sort_index()\n )\n\n # MultiIndex\n midx1 = pd.MultiIndex(\n [[\"lama\", \"cow\", \"falcon\", \"koala\"], [\"speed\", \"weight\", \"length\", \"power\"]],\n [[0, 3, 1, 1, 1, 2, 2, 2], [0, 2, 0, 3, 2, 0, 1, 3]],\n )\n midx2 = pd.MultiIndex(\n [[\"lama\", \"cow\", \"falcon\"], [\"speed\", \"weight\", \"length\"]],\n [[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],\n )\n pser1 = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1], index=midx1)\n pser2 = pd.Series([-45, 200, -1.2, 30, -250, 1.5, 320, 1, -0.3], index=midx2)\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n self.assert_eq(\n psser1.combine_first(psser2).sort_index(), pser1.combine_first(pser2).sort_index()\n )\n\n # DataFrame\n pdf1 = pd.DataFrame({\"A\": [None, 0], \"B\": [4, None]})\n psdf1 = ps.from_pandas(pdf1)\n pdf2 = pd.DataFrame({\"C\": [3, 3], \"B\": [1, 1]})\n psdf2 = ps.from_pandas(pdf2)\n\n if LooseVersion(pd.__version__) >= LooseVersion(\"1.2.0\"):\n self.assert_eq(pdf1.combine_first(pdf2), psdf1.combine_first(psdf2).sort_index())\n else:\n # pandas < 1.2.0 returns unexpected dtypes,\n # please refer to https://github.com/pandas-dev/pandas/issues/28481 for details\n expected_pdf = pd.DataFrame({\"A\": [None, 0], \"B\": [4.0, 1.0], \"C\": [3, 3]})\n self.assert_eq(expected_pdf, psdf1.combine_first(psdf2).sort_index())\n\n pdf1.columns = pd.MultiIndex.from_tuples([(\"A\", \"willow\"), (\"B\", \"pine\")])\n psdf1 = ps.from_pandas(pdf1)\n pdf2.columns = pd.MultiIndex.from_tuples([(\"C\", \"oak\"), (\"B\", \"pine\")])\n psdf2 = ps.from_pandas(pdf2)\n\n if LooseVersion(pd.__version__) >= LooseVersion(\"1.2.0\"):\n self.assert_eq(pdf1.combine_first(pdf2), psdf1.combine_first(psdf2).sort_index())\n else:\n # pandas < 1.2.0 returns unexpected dtypes,\n # please refer to https://github.com/pandas-dev/pandas/issues/28481 for details\n expected_pdf = pd.DataFrame({\"A\": [None, 0], \"B\": [4.0, 1.0], \"C\": [3, 3]})\n expected_pdf.columns = pd.MultiIndex.from_tuples(\n [(\"A\", \"willow\"), (\"B\", \"pine\"), (\"C\", \"oak\")]\n )\n self.assert_eq(expected_pdf, psdf1.combine_first(psdf2).sort_index())\n\n def test_insert(self):\n #\n # Basic DataFrame\n #\n pdf = pd.DataFrame([1, 2, 3])\n psdf = ps.from_pandas(pdf)\n\n pser = pd.Series([4, 5, 6])\n psser = ps.from_pandas(pser)\n psdf.insert(1, \"y\", psser)\n pdf.insert(1, \"y\", pser)\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n #\n # DataFrame with Index different from inserting Series'\n #\n pdf = pd.DataFrame([1, 2, 3], index=[10, 20, 30])\n psdf = ps.from_pandas(pdf)\n\n pser = pd.Series([4, 5, 6])\n psser = ps.from_pandas(pser)\n psdf.insert(1, \"y\", psser)\n pdf.insert(1, \"y\", pser)\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n #\n # DataFrame with Multi-index columns\n #\n pdf = pd.DataFrame({(\"x\", \"a\"): [1, 2, 3]})\n psdf = ps.from_pandas(pdf)\n\n pser = pd.Series([4, 5, 6])\n psser = ps.from_pandas(pser)\n pdf = pd.DataFrame({(\"x\", \"a\", \"b\"): [1, 2, 3]})\n psdf = ps.from_pandas(pdf)\n psdf.insert(0, \"a\", psser)\n pdf.insert(0, \"a\", pser)\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n psdf.insert(0, (\"b\", \"c\", \"\"), psser)\n pdf.insert(0, (\"b\", \"c\", \"\"), pser)\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_compare(self):\n if LooseVersion(pd.__version__) >= LooseVersion(\"1.1\"):\n pser1 = pd.Series([\"b\", \"c\", np.nan, \"g\", np.nan])\n pser2 = pd.Series([\"a\", \"c\", np.nan, np.nan, \"h\"])\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n self.assert_eq(\n pser1.compare(pser2).sort_index(),\n psser1.compare(psser2).sort_index(),\n )\n\n # `keep_shape=True`\n self.assert_eq(\n pser1.compare(pser2, keep_shape=True).sort_index(),\n psser1.compare(psser2, keep_shape=True).sort_index(),\n )\n # `keep_equal=True`\n self.assert_eq(\n pser1.compare(pser2, keep_equal=True).sort_index(),\n psser1.compare(psser2, keep_equal=True).sort_index(),\n )\n # `keep_shape=True` and `keep_equal=True`\n self.assert_eq(\n pser1.compare(pser2, keep_shape=True, keep_equal=True).sort_index(),\n psser1.compare(psser2, keep_shape=True, keep_equal=True).sort_index(),\n )\n\n # MultiIndex\n pser1.index = pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"z\"), (\"x\", \"k\"), (\"q\", \"l\")]\n )\n pser2.index = pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"z\"), (\"x\", \"k\"), (\"q\", \"l\")]\n )\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n self.assert_eq(\n pser1.compare(pser2).sort_index(),\n psser1.compare(psser2).sort_index(),\n )\n\n # `keep_shape=True` with MultiIndex\n self.assert_eq(\n pser1.compare(pser2, keep_shape=True).sort_index(),\n psser1.compare(psser2, keep_shape=True).sort_index(),\n )\n # `keep_equal=True` with MultiIndex\n self.assert_eq(\n pser1.compare(pser2, keep_equal=True).sort_index(),\n psser1.compare(psser2, keep_equal=True).sort_index(),\n )\n # `keep_shape=True` and `keep_equal=True` with MultiIndex\n self.assert_eq(\n pser1.compare(pser2, keep_shape=True, keep_equal=True).sort_index(),\n psser1.compare(psser2, keep_shape=True, keep_equal=True).sort_index(),\n )\n else:\n psser1 = ps.Series([\"b\", \"c\", np.nan, \"g\", np.nan])\n psser2 = ps.Series([\"a\", \"c\", np.nan, np.nan, \"h\"])\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [\"g\", None], [None, \"h\"]], index=[0, 3, 4], columns=[\"self\", \"other\"]\n )\n self.assert_eq(expected, psser1.compare(psser2).sort_index())\n\n # `keep_shape=True`\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [None, None], [None, None], [\"g\", None], [None, \"h\"]],\n index=[0, 1, 2, 3, 4],\n columns=[\"self\", \"other\"],\n )\n self.assert_eq(\n expected,\n psser1.compare(psser2, keep_shape=True).sort_index(),\n )\n # `keep_equal=True`\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [\"g\", None], [None, \"h\"]], index=[0, 3, 4], columns=[\"self\", \"other\"]\n )\n self.assert_eq(\n expected,\n psser1.compare(psser2, keep_equal=True).sort_index(),\n )\n # `keep_shape=True` and `keep_equal=True`\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [\"c\", \"c\"], [None, None], [\"g\", None], [None, \"h\"]],\n index=[0, 1, 2, 3, 4],\n columns=[\"self\", \"other\"],\n )\n self.assert_eq(\n expected,\n psser1.compare(psser2, keep_shape=True, keep_equal=True).sort_index(),\n )\n\n # MultiIndex\n psser1 = ps.Series(\n [\"b\", \"c\", np.nan, \"g\", np.nan],\n index=pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"z\"), (\"x\", \"k\"), (\"q\", \"l\")]\n ),\n )\n psser2 = ps.Series(\n [\"a\", \"c\", np.nan, np.nan, \"h\"],\n index=pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"z\"), (\"x\", \"k\"), (\"q\", \"l\")]\n ),\n )\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [None, \"h\"], [\"g\", None]],\n index=pd.MultiIndex.from_tuples([(\"a\", \"x\"), (\"q\", \"l\"), (\"x\", \"k\")]),\n columns=[\"self\", \"other\"],\n )\n self.assert_eq(expected, psser1.compare(psser2).sort_index())\n\n # `keep_shape=True`\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [None, None], [None, None], [None, \"h\"], [\"g\", None]],\n index=pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"z\"), (\"q\", \"l\"), (\"x\", \"k\")]\n ),\n columns=[\"self\", \"other\"],\n )\n self.assert_eq(\n expected,\n psser1.compare(psser2, keep_shape=True).sort_index(),\n )\n # `keep_equal=True`\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [None, \"h\"], [\"g\", None]],\n index=pd.MultiIndex.from_tuples([(\"a\", \"x\"), (\"q\", \"l\"), (\"x\", \"k\")]),\n columns=[\"self\", \"other\"],\n )\n self.assert_eq(\n expected,\n psser1.compare(psser2, keep_equal=True).sort_index(),\n )\n # `keep_shape=True` and `keep_equal=True`\n expected = ps.DataFrame(\n [[\"b\", \"a\"], [\"c\", \"c\"], [None, None], [None, \"h\"], [\"g\", None]],\n index=pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"z\"), (\"q\", \"l\"), (\"x\", \"k\")]\n ),\n columns=[\"self\", \"other\"],\n )\n self.assert_eq(\n expected,\n psser1.compare(psser2, keep_shape=True, keep_equal=True).sort_index(),\n )\n\n # Different Index\n with self.assertRaisesRegex(\n ValueError, \"Can only compare identically-labeled Series objects\"\n ):\n psser1 = ps.Series(\n [1, 2, 3, 4, 5],\n index=pd.Index([1, 2, 3, 4, 5]),\n )\n psser2 = ps.Series(\n [2, 2, 3, 4, 1],\n index=pd.Index([5, 4, 3, 2, 1]),\n )\n psser1.compare(psser2)\n # Different MultiIndex\n with self.assertRaisesRegex(\n ValueError, \"Can only compare identically-labeled Series objects\"\n ):\n psser1 = ps.Series(\n [1, 2, 3, 4, 5],\n index=pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"z\"), (\"x\", \"k\"), (\"q\", \"l\")]\n ),\n )\n psser2 = ps.Series(\n [2, 2, 3, 4, 1],\n index=pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\"), (\"c\", \"a\"), (\"x\", \"k\"), (\"q\", \"l\")]\n ),\n )\n psser1.compare(psser2)\n\n def test_different_columns(self):\n psdf1 = self.psdf1\n psdf4 = self.psdf4\n pdf1 = self.pdf1\n pdf4 = self.pdf4\n\n self.assert_eq((psdf1 + psdf4).sort_index(), (pdf1 + pdf4).sort_index(), almost=True)\n\n # Multi-index columns\n columns = pd.MultiIndex.from_tuples([(\"x\", \"a\"), (\"x\", \"b\")])\n psdf1.columns = columns\n pdf1.columns = columns\n columns = pd.MultiIndex.from_tuples([(\"z\", \"e\"), (\"z\", \"f\")])\n psdf4.columns = columns\n pdf4.columns = columns\n\n self.assert_eq((psdf1 + psdf4).sort_index(), (pdf1 + pdf4).sort_index(), almost=True)\n\n def test_assignment_series(self):\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psser = psdf.a\n pser = pdf.a\n psdf[\"a\"] = self.psdf2.a\n pdf[\"a\"] = self.pdf2.a\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n self.assert_eq(psser, pser)\n\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psser = psdf.a\n pser = pdf.a\n psdf[\"a\"] = self.psdf2.b\n pdf[\"a\"] = self.pdf2.b\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n self.assert_eq(psser, pser)\n\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psdf[\"c\"] = self.psdf2.a\n pdf[\"c\"] = self.pdf2.a\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n # Multi-index columns\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n columns = pd.MultiIndex.from_tuples([(\"x\", \"a\"), (\"x\", \"b\")])\n psdf.columns = columns\n pdf.columns = columns\n psdf[(\"y\", \"c\")] = self.psdf2.a\n pdf[(\"y\", \"c\")] = self.pdf2.a\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n pdf = pd.DataFrame({\"a\": [1, 2, 3], \"Koalas\": [0, 1, 2]}).set_index(\"Koalas\", drop=False)\n psdf = ps.from_pandas(pdf)\n\n psdf.index.name = None\n psdf[\"NEW\"] = ps.Series([100, 200, 300])\n\n pdf.index.name = None\n pdf[\"NEW\"] = pd.Series([100, 200, 300])\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_assignment_frame(self):\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psser = psdf.a\n pser = pdf.a\n psdf[[\"a\", \"b\"]] = self.psdf1\n pdf[[\"a\", \"b\"]] = self.pdf1\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n self.assert_eq(psser, pser)\n\n # 'c' does not exist in `psdf`.\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psser = psdf.a\n pser = pdf.a\n psdf[[\"b\", \"c\"]] = self.psdf1\n pdf[[\"b\", \"c\"]] = self.pdf1\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n self.assert_eq(psser, pser)\n\n # 'c' and 'd' do not exist in `psdf`.\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psdf[[\"c\", \"d\"]] = self.psdf1\n pdf[[\"c\", \"d\"]] = self.pdf1\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n # Multi-index columns\n columns = pd.MultiIndex.from_tuples([(\"x\", \"a\"), (\"x\", \"b\")])\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psdf.columns = columns\n pdf.columns = columns\n psdf[[(\"y\", \"c\"), (\"z\", \"d\")]] = self.psdf1\n pdf[[(\"y\", \"c\"), (\"z\", \"d\")]] = self.pdf1\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psdf1 = ps.from_pandas(self.pdf1)\n pdf1 = self.pdf1\n psdf1.columns = columns\n pdf1.columns = columns\n psdf[[\"c\", \"d\"]] = psdf1\n pdf[[\"c\", \"d\"]] = pdf1\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_assignment_series_chain(self):\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psdf[\"a\"] = self.psdf1.a\n pdf[\"a\"] = self.pdf1.a\n\n psdf[\"a\"] = self.psdf2.b\n pdf[\"a\"] = self.pdf2.b\n\n psdf[\"d\"] = self.psdf3.c\n pdf[\"d\"] = self.pdf3.c\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_assignment_frame_chain(self):\n psdf = ps.from_pandas(self.pdf1)\n pdf = self.pdf1\n psdf[[\"a\", \"b\"]] = self.psdf1\n pdf[[\"a\", \"b\"]] = self.pdf1\n\n psdf[[\"e\", \"f\"]] = self.psdf3\n pdf[[\"e\", \"f\"]] = self.pdf3\n\n psdf[[\"b\", \"c\"]] = self.psdf2\n pdf[[\"b\", \"c\"]] = self.pdf2\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_multi_index_arithmetic(self):\n psdf5 = self.psdf5\n psdf6 = self.psdf6\n pdf5 = self.pdf5\n pdf6 = self.pdf6\n\n # Series\n self.assert_eq((psdf5.c - psdf6.e).sort_index(), (pdf5.c - pdf6.e).sort_index())\n\n self.assert_eq((psdf5[\"c\"] / psdf6[\"e\"]).sort_index(), (pdf5[\"c\"] / pdf6[\"e\"]).sort_index())\n\n # DataFrame\n self.assert_eq((psdf5 + psdf6).sort_index(), (pdf5 + pdf6).sort_index(), almost=True)\n\n def test_multi_index_assignment_series(self):\n psdf = ps.from_pandas(self.pdf5)\n pdf = self.pdf5\n psdf[\"x\"] = self.psdf6.e\n pdf[\"x\"] = self.pdf6.e\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n psdf = ps.from_pandas(self.pdf5)\n pdf = self.pdf5\n psdf[\"e\"] = self.psdf6.e\n pdf[\"e\"] = self.pdf6.e\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n psdf = ps.from_pandas(self.pdf5)\n pdf = self.pdf5\n psdf[\"c\"] = self.psdf6.e\n pdf[\"c\"] = self.pdf6.e\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_multi_index_assignment_frame(self):\n psdf = ps.from_pandas(self.pdf5)\n pdf = self.pdf5\n psdf[[\"c\"]] = self.psdf5\n pdf[[\"c\"]] = self.pdf5\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n psdf = ps.from_pandas(self.pdf5)\n pdf = self.pdf5\n psdf[[\"x\"]] = self.psdf5\n pdf[[\"x\"]] = self.pdf5\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n psdf = ps.from_pandas(self.pdf6)\n pdf = self.pdf6\n psdf[[\"x\", \"y\"]] = self.psdf6\n pdf[[\"x\", \"y\"]] = self.pdf6\n\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_frame_loc_setitem(self):\n pdf_orig = pd.DataFrame(\n [[1, 2], [4, 5], [7, 8]],\n index=[\"cobra\", \"viper\", \"sidewinder\"],\n columns=[\"max_speed\", \"shield\"],\n )\n psdf_orig = ps.DataFrame(pdf_orig)\n\n pdf = pdf_orig.copy()\n psdf = psdf_orig.copy()\n pser1 = pdf.max_speed\n pser2 = pdf.shield\n psser1 = psdf.max_speed\n psser2 = psdf.shield\n\n another_psdf = ps.DataFrame(pdf_orig)\n\n psdf.loc[[\"viper\", \"sidewinder\"], [\"shield\"]] = -another_psdf.max_speed\n pdf.loc[[\"viper\", \"sidewinder\"], [\"shield\"]] = -pdf.max_speed\n self.assert_eq(psdf, pdf)\n self.assert_eq(psser1, pser1)\n self.assert_eq(psser2, pser2)\n\n pdf = pdf_orig.copy()\n psdf = psdf_orig.copy()\n pser1 = pdf.max_speed\n pser2 = pdf.shield\n psser1 = psdf.max_speed\n psser2 = psdf.shield\n psdf.loc[another_psdf.max_speed < 5, [\"shield\"]] = -psdf.max_speed\n pdf.loc[pdf.max_speed < 5, [\"shield\"]] = -pdf.max_speed\n self.assert_eq(psdf, pdf)\n self.assert_eq(psser1, pser1)\n self.assert_eq(psser2, pser2)\n\n pdf = pdf_orig.copy()\n psdf = psdf_orig.copy()\n pser1 = pdf.max_speed\n pser2 = pdf.shield\n psser1 = psdf.max_speed\n psser2 = psdf.shield\n psdf.loc[another_psdf.max_speed < 5, [\"shield\"]] = -another_psdf.max_speed\n pdf.loc[pdf.max_speed < 5, [\"shield\"]] = -pdf.max_speed\n self.assert_eq(psdf, pdf)\n self.assert_eq(psser1, pser1)\n self.assert_eq(psser2, pser2)\n\n def test_frame_iloc_setitem(self):\n pdf = pd.DataFrame(\n [[1, 2], [4, 5], [7, 8]],\n index=[\"cobra\", \"viper\", \"sidewinder\"],\n columns=[\"max_speed\", \"shield\"],\n )\n psdf = ps.DataFrame(pdf)\n another_psdf = ps.DataFrame(pdf)\n\n psdf.iloc[[0, 1, 2], 1] = -another_psdf.max_speed\n pdf.iloc[[0, 1, 2], 1] = -pdf.max_speed\n self.assert_eq(psdf, pdf)\n\n with self.assertRaisesRegex(\n ValueError,\n \"shape mismatch\",\n ):\n psdf.iloc[[1, 2], [1]] = -another_psdf.max_speed\n\n psdf.iloc[[0, 1, 2], 1] = 10 * another_psdf.max_speed\n pdf.iloc[[0, 1, 2], 1] = 10 * pdf.max_speed\n self.assert_eq(psdf, pdf)\n\n with self.assertRaisesRegex(ValueError, \"shape mismatch\"):\n psdf.iloc[[0], 1] = 10 * another_psdf.max_speed\n\n def test_series_loc_setitem(self):\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n\n pser_another = pd.Series([1, 2, 3], index=[\"cobra\", \"viper\", \"sidewinder\"])\n psser_another = ps.from_pandas(pser_another)\n\n psser.loc[psser % 2 == 1] = -psser_another\n pser.loc[pser % 2 == 1] = -pser_another\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n psser.loc[psser_another % 2 == 1] = -psser\n pser.loc[pser_another % 2 == 1] = -pser\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n psser.loc[psser_another % 2 == 1] = -psser\n pser.loc[pser_another % 2 == 1] = -pser\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n psser.loc[psser_another % 2 == 1] = -psser_another\n pser.loc[pser_another % 2 == 1] = -pser_another\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n psser.loc[[\"viper\", \"sidewinder\"]] = -psser_another\n pser.loc[[\"viper\", \"sidewinder\"]] = -pser_another\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n psser.loc[psser_another % 2 == 1] = 10\n pser.loc[pser_another % 2 == 1] = 10\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n def test_series_iloc_setitem(self):\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n\n pser1 = pser + 1\n psser1 = psser + 1\n\n pser_another = pd.Series([1, 2, 3], index=[\"cobra\", \"viper\", \"sidewinder\"])\n psser_another = ps.from_pandas(pser_another)\n\n psser.iloc[[0, 1, 2]] = -psser_another\n pser.iloc[[0, 1, 2]] = -pser_another\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n with self.assertRaisesRegex(\n ValueError,\n \"cannot set using a list-like indexer with a different length than the value\",\n ):\n psser.iloc[[1, 2]] = -psser_another\n\n psser.iloc[[0, 1, 2]] = 10 * psser_another\n pser.iloc[[0, 1, 2]] = 10 * pser_another\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n with self.assertRaisesRegex(\n ValueError,\n \"cannot set using a list-like indexer with a different length than the value\",\n ):\n psser.iloc[[0]] = 10 * psser_another\n\n psser1.iloc[[0, 1, 2]] = -psser_another\n pser1.iloc[[0, 1, 2]] = -pser_another\n self.assert_eq(psser1, pser1)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n with self.assertRaisesRegex(\n ValueError,\n \"cannot set using a list-like indexer with a different length than the value\",\n ):\n psser1.iloc[[1, 2]] = -psser_another\n\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]}, index=[\"cobra\", \"viper\", \"sidewinder\"])\n psdf = ps.from_pandas(pdf)\n\n pser = pdf.x\n psery = pdf.y\n psser = psdf.x\n pssery = psdf.y\n\n piloc = pser.iloc\n kiloc = psser.iloc\n\n kiloc[[0, 1, 2]] = -psser_another\n piloc[[0, 1, 2]] = -pser_another\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n with self.assertRaisesRegex(\n ValueError,\n \"cannot set using a list-like indexer with a different length than the value\",\n ):\n kiloc[[1, 2]] = -psser_another\n\n kiloc[[0, 1, 2]] = 10 * psser_another\n piloc[[0, 1, 2]] = 10 * pser_another\n self.assert_eq(psser, pser)\n self.assert_eq(psdf, pdf)\n self.assert_eq(pssery, psery)\n\n with self.assertRaisesRegex(\n ValueError,\n \"cannot set using a list-like indexer with a different length than the value\",\n ):\n kiloc[[0]] = 10 * psser_another\n\n def test_update(self):\n pdf = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [10, 20, 30]})\n psdf = ps.from_pandas(pdf)\n\n pser = pdf.x\n psser = psdf.x\n pser.update(pd.Series([4, 5, 6]))\n psser.update(ps.Series([4, 5, 6]))\n self.assert_eq(psser.sort_index(), pser.sort_index())\n self.assert_eq(psdf.sort_index(), pdf.sort_index())\n\n def test_where(self):\n pdf1 = pd.DataFrame({\"A\": [0, 1, 2, 3, 4], \"B\": [100, 200, 300, 400, 500]})\n pdf2 = pd.DataFrame({\"A\": [0, -1, -2, -3, -4], \"B\": [-100, -200, -300, -400, -500]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1.where(pdf2 > 100), psdf1.where(psdf2 > 100).sort_index())\n\n pdf1 = pd.DataFrame({\"A\": [-1, -2, -3, -4, -5], \"B\": [-100, -200, -300, -400, -500]})\n pdf2 = pd.DataFrame({\"A\": [-10, -20, -30, -40, -50], \"B\": [-5, -4, -3, -2, -1]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1.where(pdf2 < -250), psdf1.where(psdf2 < -250).sort_index())\n\n # multi-index columns\n pdf1 = pd.DataFrame({(\"X\", \"A\"): [0, 1, 2, 3, 4], (\"X\", \"B\"): [100, 200, 300, 400, 500]})\n pdf2 = pd.DataFrame(\n {(\"X\", \"A\"): [0, -1, -2, -3, -4], (\"X\", \"B\"): [-100, -200, -300, -400, -500]}\n )\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1.where(pdf2 > 100), psdf1.where(psdf2 > 100).sort_index())\n\n def test_mask(self):\n pdf1 = pd.DataFrame({\"A\": [0, 1, 2, 3, 4], \"B\": [100, 200, 300, 400, 500]})\n pdf2 = pd.DataFrame({\"A\": [0, -1, -2, -3, -4], \"B\": [-100, -200, -300, -400, -500]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1.mask(pdf2 < 100), psdf1.mask(psdf2 < 100).sort_index())\n\n pdf1 = pd.DataFrame({\"A\": [-1, -2, -3, -4, -5], \"B\": [-100, -200, -300, -400, -500]})\n pdf2 = pd.DataFrame({\"A\": [-10, -20, -30, -40, -50], \"B\": [-5, -4, -3, -2, -1]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1.mask(pdf2 > -250), psdf1.mask(psdf2 > -250).sort_index())\n\n # multi-index columns\n pdf1 = pd.DataFrame({(\"X\", \"A\"): [0, 1, 2, 3, 4], (\"X\", \"B\"): [100, 200, 300, 400, 500]})\n pdf2 = pd.DataFrame(\n {(\"X\", \"A\"): [0, -1, -2, -3, -4], (\"X\", \"B\"): [-100, -200, -300, -400, -500]}\n )\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n self.assert_eq(pdf1.mask(pdf2 < 100), psdf1.mask(psdf2 < 100).sort_index())\n\n def test_multi_index_column_assignment_frame(self):\n pdf = pd.DataFrame({\"a\": [1, 2, 3, 2], \"b\": [4.0, 2.0, 3.0, 1.0]})\n pdf.columns = pd.MultiIndex.from_tuples([(\"a\", \"x\"), (\"a\", \"y\")])\n psdf = ps.DataFrame(pdf)\n\n psdf[\"c\"] = ps.Series([10, 20, 30, 20])\n pdf[\"c\"] = pd.Series([10, 20, 30, 20])\n\n psdf[(\"d\", \"x\")] = ps.Series([100, 200, 300, 200], name=\"1\")\n pdf[(\"d\", \"x\")] = pd.Series([100, 200, 300, 200], name=\"1\")\n\n psdf[(\"d\", \"y\")] = ps.Series([1000, 2000, 3000, 2000], name=(\"1\", \"2\"))\n pdf[(\"d\", \"y\")] = pd.Series([1000, 2000, 3000, 2000], name=(\"1\", \"2\"))\n\n psdf[\"e\"] = ps.Series([10000, 20000, 30000, 20000], name=(\"1\", \"2\", \"3\"))\n pdf[\"e\"] = pd.Series([10000, 20000, 30000, 20000], name=(\"1\", \"2\", \"3\"))\n\n psdf[[(\"f\", \"x\"), (\"f\", \"y\")]] = ps.DataFrame(\n {\"1\": [100000, 200000, 300000, 200000], \"2\": [1000000, 2000000, 3000000, 2000000]}\n )\n pdf[[(\"f\", \"x\"), (\"f\", \"y\")]] = pd.DataFrame(\n {\"1\": [100000, 200000, 300000, 200000], \"2\": [1000000, 2000000, 3000000, 2000000]}\n )\n\n self.assert_eq(repr(psdf.sort_index()), repr(pdf))\n\n with self.assertRaisesRegex(KeyError, \"Key length \\\\(3\\\\) exceeds index depth \\\\(2\\\\)\"):\n psdf[(\"1\", \"2\", \"3\")] = ps.Series([100, 200, 300, 200])\n\n def test_series_dot(self):\n pser = pd.Series([90, 91, 85], index=[2, 4, 1])\n psser = ps.from_pandas(pser)\n pser_other = pd.Series([90, 91, 85], index=[2, 4, 1])\n psser_other = ps.from_pandas(pser_other)\n\n self.assert_eq(psser.dot(psser_other), pser.dot(pser_other))\n\n psser_other = ps.Series([90, 91, 85], index=[1, 2, 4])\n pser_other = pd.Series([90, 91, 85], index=[1, 2, 4])\n\n self.assert_eq(psser.dot(psser_other), pser.dot(pser_other))\n\n # length of index is different\n psser_other = ps.Series([90, 91, 85, 100], index=[2, 4, 1, 0])\n with self.assertRaisesRegex(ValueError, \"matrices are not aligned\"):\n psser.dot(psser_other)\n\n # for MultiIndex\n midx = pd.MultiIndex(\n [[\"lama\", \"cow\", \"falcon\"], [\"speed\", \"weight\", \"length\"]],\n [[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],\n )\n pser = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx)\n psser = ps.from_pandas(pser)\n pser_other = pd.Series([-450, 20, 12, -30, -250, 15, -320, 100, 3], index=midx)\n psser_other = ps.from_pandas(pser_other)\n self.assert_eq(psser.dot(psser_other), pser.dot(pser_other))\n\n pser = pd.Series([0, 1, 2, 3])\n psser = ps.from_pandas(pser)\n\n # DataFrame \"other\" without Index/MultiIndex as columns\n pdf = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]])\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psser.dot(psdf), pser.dot(pdf))\n\n # DataFrame \"other\" with Index as columns\n pdf.columns = pd.Index([\"x\", \"y\"])\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psser.dot(psdf), pser.dot(pdf))\n pdf.columns = pd.Index([\"x\", \"y\"], name=\"cols_name\")\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psser.dot(psdf), pser.dot(pdf))\n\n pdf = pdf.reindex([1, 0, 2, 3])\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psser.dot(psdf), pser.dot(pdf))\n\n # DataFrame \"other\" with MultiIndex as columns\n pdf.columns = pd.MultiIndex.from_tuples([(\"a\", \"x\"), (\"b\", \"y\")])\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psser.dot(psdf), pser.dot(pdf))\n pdf.columns = pd.MultiIndex.from_tuples(\n [(\"a\", \"x\"), (\"b\", \"y\")], names=[\"cols_name1\", \"cols_name2\"]\n )\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psser.dot(psdf), pser.dot(pdf))\n\n psser = ps.DataFrame({\"a\": [1, 2, 3], \"b\": [4, 5, 6]}).b\n pser = psser.to_pandas()\n psdf = ps.DataFrame({\"c\": [7, 8, 9]})\n pdf = psdf.to_pandas()\n self.assert_eq(psser.dot(psdf), pser.dot(pdf))\n\n def test_frame_dot(self):\n pdf = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]])\n psdf = ps.from_pandas(pdf)\n\n pser = pd.Series([1, 1, 2, 1])\n psser = ps.from_pandas(pser)\n self.assert_eq(psdf.dot(psser), pdf.dot(pser))\n\n # Index reorder\n pser = pser.reindex([1, 0, 2, 3])\n psser = ps.from_pandas(pser)\n self.assert_eq(psdf.dot(psser), pdf.dot(pser))\n\n # ser with name\n pser.name = \"ser\"\n psser = ps.from_pandas(pser)\n self.assert_eq(psdf.dot(psser), pdf.dot(pser))\n\n # df with MultiIndex as column (ser with MultiIndex)\n arrays = [[1, 1, 2, 2], [\"red\", \"blue\", \"red\", \"blue\"]]\n pidx = pd.MultiIndex.from_arrays(arrays, names=(\"number\", \"color\"))\n pser = pd.Series([1, 1, 2, 1], index=pidx)\n pdf = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]], columns=pidx)\n psdf = ps.from_pandas(pdf)\n psser = ps.from_pandas(pser)\n self.assert_eq(psdf.dot(psser), pdf.dot(pser))\n\n # df with Index as column (ser with Index)\n pidx = pd.Index([1, 2, 3, 4], name=\"number\")\n pser = pd.Series([1, 1, 2, 1], index=pidx)\n pdf = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]], columns=pidx)\n psdf = ps.from_pandas(pdf)\n psser = ps.from_pandas(pser)\n self.assert_eq(psdf.dot(psser), pdf.dot(pser))\n\n # df with Index\n pdf.index = pd.Index([\"x\", \"y\"], name=\"char\")\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psdf.dot(psser), pdf.dot(pser))\n\n # df with MultiIndex\n pdf.index = pd.MultiIndex.from_arrays([[1, 1], [\"red\", \"blue\"]], names=(\"number\", \"color\"))\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psdf.dot(psser), pdf.dot(pser))\n\n pdf = pd.DataFrame([[1, 2], [3, 4]])\n psdf = ps.from_pandas(pdf)\n self.assert_eq(psdf.dot(psdf[0]), pdf.dot(pdf[0]))\n self.assert_eq(psdf.dot(psdf[0] * 10), pdf.dot(pdf[0] * 10))\n self.assert_eq((psdf + 1).dot(psdf[0] * 10), (pdf + 1).dot(pdf[0] * 10))\n\n def test_to_series_comparison(self):\n psidx1 = ps.Index([1, 2, 3, 4, 5])\n psidx2 = ps.Index([1, 2, 3, 4, 5])\n\n self.assert_eq((psidx1.to_series() == psidx2.to_series()).all(), True)\n\n psidx1.name = \"koalas\"\n psidx2.name = \"koalas\"\n\n self.assert_eq((psidx1.to_series() == psidx2.to_series()).all(), True)\n\n def test_series_repeat(self):\n pser1 = pd.Series([\"a\", \"b\", \"c\"], name=\"a\")\n pser2 = pd.Series([10, 20, 30], name=\"rep\")\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n self.assert_eq(psser1.repeat(psser2).sort_index(), pser1.repeat(pser2).sort_index())\n\n def test_series_ops(self):\n pser1 = pd.Series([1, 2, 3, 4, 5, 6, 7], name=\"x\", index=[11, 12, 13, 14, 15, 16, 17])\n pser2 = pd.Series([1, 2, 3, 4, 5, 6, 7], name=\"x\", index=[11, 12, 13, 14, 15, 16, 17])\n pidx1 = pd.Index([10, 11, 12, 13, 14, 15, 16], name=\"x\")\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n psidx1 = ps.from_pandas(pidx1)\n\n self.assert_eq(\n (psser1 + 1 + 10 * psser2).sort_index(), (pser1 + 1 + 10 * pser2).sort_index()\n )\n self.assert_eq(\n (psser1 + 1 + 10 * psser2.rename()).sort_index(),\n (pser1 + 1 + 10 * pser2.rename()).sort_index(),\n )\n self.assert_eq(\n (psser1.rename() + 1 + 10 * psser2).sort_index(),\n (pser1.rename() + 1 + 10 * pser2).sort_index(),\n )\n self.assert_eq(\n (psser1.rename() + 1 + 10 * psser2.rename()).sort_index(),\n (pser1.rename() + 1 + 10 * pser2.rename()).sort_index(),\n )\n\n self.assert_eq(psser1 + 1 + 10 * psidx1, pser1 + 1 + 10 * pidx1)\n self.assert_eq(psser1.rename() + 1 + 10 * psidx1, pser1.rename() + 1 + 10 * pidx1)\n self.assert_eq(psser1 + 1 + 10 * psidx1.rename(None), pser1 + 1 + 10 * pidx1.rename(None))\n self.assert_eq(\n psser1.rename() + 1 + 10 * psidx1.rename(None),\n pser1.rename() + 1 + 10 * pidx1.rename(None),\n )\n\n self.assert_eq(psidx1 + 1 + 10 * psser1, pidx1 + 1 + 10 * pser1)\n self.assert_eq(psidx1 + 1 + 10 * psser1.rename(), pidx1 + 1 + 10 * pser1.rename())\n self.assert_eq(psidx1.rename(None) + 1 + 10 * psser1, pidx1.rename(None) + 1 + 10 * pser1)\n self.assert_eq(\n psidx1.rename(None) + 1 + 10 * psser1.rename(),\n pidx1.rename(None) + 1 + 10 * pser1.rename(),\n )\n\n pidx2 = pd.Index([11, 12, 13])\n psidx2 = ps.from_pandas(pidx2)\n\n with self.assertRaisesRegex(\n ValueError, \"operands could not be broadcast together with shapes\"\n ):\n psser1 + psidx2\n\n with self.assertRaisesRegex(\n ValueError, \"operands could not be broadcast together with shapes\"\n ):\n psidx2 + psser1\n\n def test_index_ops(self):\n pidx1 = pd.Index([1, 2, 3, 4, 5], name=\"x\")\n pidx2 = pd.Index([6, 7, 8, 9, 10], name=\"x\")\n psidx1 = ps.from_pandas(pidx1)\n psidx2 = ps.from_pandas(pidx2)\n\n self.assert_eq(psidx1 * 10 + psidx2, pidx1 * 10 + pidx2)\n self.assert_eq(psidx1.rename(None) * 10 + psidx2, pidx1.rename(None) * 10 + pidx2)\n\n if LooseVersion(pd.__version__) >= LooseVersion(\"1.0\"):\n self.assert_eq(psidx1 * 10 + psidx2.rename(None), pidx1 * 10 + pidx2.rename(None))\n else:\n self.assert_eq(\n psidx1 * 10 + psidx2.rename(None), (pidx1 * 10 + pidx2.rename(None)).rename(None)\n )\n\n pidx3 = pd.Index([11, 12, 13])\n psidx3 = ps.from_pandas(pidx3)\n\n with self.assertRaisesRegex(\n ValueError, \"operands could not be broadcast together with shapes\"\n ):\n psidx1 + psidx3\n\n pidx1 = pd.Index([1, 2, 3, 4, 5], name=\"a\")\n pidx2 = pd.Index([6, 7, 8, 9, 10], name=\"a\")\n pidx3 = pd.Index([11, 12, 13, 14, 15], name=\"x\")\n psidx1 = ps.from_pandas(pidx1)\n psidx2 = ps.from_pandas(pidx2)\n psidx3 = ps.from_pandas(pidx3)\n\n self.assert_eq(psidx1 * 10 + psidx2, pidx1 * 10 + pidx2)\n\n if LooseVersion(pd.__version__) >= LooseVersion(\"1.0\"):\n self.assert_eq(psidx1 * 10 + psidx3, pidx1 * 10 + pidx3)\n else:\n self.assert_eq(psidx1 * 10 + psidx3, (pidx1 * 10 + pidx3).rename(None))\n\n def test_align(self):\n pdf1 = pd.DataFrame({\"a\": [1, 2, 3], \"b\": [\"a\", \"b\", \"c\"]}, index=[10, 20, 30])\n pdf2 = pd.DataFrame({\"a\": [4, 5, 6], \"c\": [\"d\", \"e\", \"f\"]}, index=[10, 11, 12])\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n for join in [\"outer\", \"inner\", \"left\", \"right\"]:\n for axis in [None, 0]:\n psdf_l, psdf_r = psdf1.align(psdf2, join=join, axis=axis)\n pdf_l, pdf_r = pdf1.align(pdf2, join=join, axis=axis)\n self.assert_eq(psdf_l.sort_index(), pdf_l.sort_index())\n self.assert_eq(psdf_r.sort_index(), pdf_r.sort_index())\n\n pser1 = pd.Series([7, 8, 9], index=[10, 11, 12])\n pser2 = pd.Series([\"g\", \"h\", \"i\"], index=[10, 20, 30])\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n\n for join in [\"outer\", \"inner\", \"left\", \"right\"]:\n psser_l, psser_r = psser1.align(psser2, join=join)\n pser_l, pser_r = pser1.align(pser2, join=join)\n self.assert_eq(psser_l.sort_index(), pser_l.sort_index())\n self.assert_eq(psser_r.sort_index(), pser_r.sort_index())\n\n psdf_l, psser_r = psdf1.align(psser1, join=join, axis=0)\n pdf_l, pser_r = pdf1.align(pser1, join=join, axis=0)\n self.assert_eq(psdf_l.sort_index(), pdf_l.sort_index())\n self.assert_eq(psser_r.sort_index(), pser_r.sort_index())\n\n psser_l, psdf_r = psser1.align(psdf1, join=join)\n pser_l, pdf_r = pser1.align(pdf1, join=join)\n self.assert_eq(psser_l.sort_index(), pser_l.sort_index())\n self.assert_eq(psdf_r.sort_index(), pdf_r.sort_index())\n\n # multi-index columns\n pdf3 = pd.DataFrame(\n {(\"x\", \"a\"): [4, 5, 6], (\"y\", \"c\"): [\"d\", \"e\", \"f\"]}, index=[10, 11, 12]\n )\n psdf3 = ps.from_pandas(pdf3)\n pser3 = pdf3[(\"y\", \"c\")]\n psser3 = psdf3[(\"y\", \"c\")]\n\n for join in [\"outer\", \"inner\", \"left\", \"right\"]:\n psdf_l, psdf_r = psdf1.align(psdf3, join=join, axis=0)\n pdf_l, pdf_r = pdf1.align(pdf3, join=join, axis=0)\n self.assert_eq(psdf_l.sort_index(), pdf_l.sort_index())\n self.assert_eq(psdf_r.sort_index(), pdf_r.sort_index())\n\n psser_l, psser_r = psser1.align(psser3, join=join)\n pser_l, pser_r = pser1.align(pser3, join=join)\n self.assert_eq(psser_l.sort_index(), pser_l.sort_index())\n self.assert_eq(psser_r.sort_index(), pser_r.sort_index())\n\n psdf_l, psser_r = psdf1.align(psser3, join=join, axis=0)\n pdf_l, pser_r = pdf1.align(pser3, join=join, axis=0)\n self.assert_eq(psdf_l.sort_index(), pdf_l.sort_index())\n self.assert_eq(psser_r.sort_index(), pser_r.sort_index())\n\n psser_l, psdf_r = psser3.align(psdf1, join=join)\n pser_l, pdf_r = pser3.align(pdf1, join=join)\n self.assert_eq(psser_l.sort_index(), pser_l.sort_index())\n self.assert_eq(psdf_r.sort_index(), pdf_r.sort_index())\n\n self.assertRaises(ValueError, lambda: psdf1.align(psdf3, axis=None))\n self.assertRaises(ValueError, lambda: psdf1.align(psdf3, axis=1))\n\n def test_pow_and_rpow(self):\n pser = pd.Series([1, 2, np.nan])\n psser = ps.from_pandas(pser)\n pser_other = pd.Series([np.nan, 2, 3])\n psser_other = ps.from_pandas(pser_other)\n\n self.assert_eq(pser.pow(pser_other), psser.pow(psser_other).sort_index())\n self.assert_eq(pser ** pser_other, (psser ** psser_other).sort_index())\n self.assert_eq(pser.rpow(pser_other), psser.rpow(psser_other).sort_index())\n\n def test_shift(self):\n pdf = pd.DataFrame(\n {\n \"Col1\": [10, 20, 15, 30, 45],\n \"Col2\": [13, 23, 18, 33, 48],\n \"Col3\": [17, 27, 22, 37, 52],\n },\n index=np.random.rand(5),\n )\n psdf = ps.from_pandas(pdf)\n\n self.assert_eq(\n pdf.shift().loc[pdf[\"Col1\"] == 20].astype(int), psdf.shift().loc[psdf[\"Col1\"] == 20]\n )\n self.assert_eq(\n pdf[\"Col2\"].shift().loc[pdf[\"Col1\"] == 20].astype(int),\n psdf[\"Col2\"].shift().loc[psdf[\"Col1\"] == 20],\n )\n\n def test_diff(self):\n pdf = pd.DataFrame(\n {\n \"Col1\": [10, 20, 15, 30, 45],\n \"Col2\": [13, 23, 18, 33, 48],\n \"Col3\": [17, 27, 22, 37, 52],\n },\n index=np.random.rand(5),\n )\n psdf = ps.from_pandas(pdf)\n\n self.assert_eq(\n pdf.diff().loc[pdf[\"Col1\"] == 20].astype(int), psdf.diff().loc[psdf[\"Col1\"] == 20]\n )\n self.assert_eq(\n pdf[\"Col2\"].diff().loc[pdf[\"Col1\"] == 20].astype(int),\n psdf[\"Col2\"].diff().loc[psdf[\"Col1\"] == 20],\n )\n\n def test_rank(self):\n pdf = pd.DataFrame(\n {\n \"Col1\": [10, 20, 15, 30, 45],\n \"Col2\": [13, 23, 18, 33, 48],\n \"Col3\": [17, 27, 22, 37, 52],\n },\n index=np.random.rand(5),\n )\n psdf = ps.from_pandas(pdf)\n\n self.assert_eq(pdf.rank().loc[pdf[\"Col1\"] == 20], psdf.rank().loc[psdf[\"Col1\"] == 20])\n self.assert_eq(\n pdf[\"Col2\"].rank().loc[pdf[\"Col1\"] == 20], psdf[\"Col2\"].rank().loc[psdf[\"Col1\"] == 20]\n )\n\n\nclass OpsOnDiffFramesDisabledTest(PandasOnSparkTestCase, SQLTestUtils):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n set_option(\"compute.ops_on_diff_frames\", False)\n\n @classmethod\n def tearDownClass(cls):\n reset_option(\"compute.ops_on_diff_frames\")\n super().tearDownClass()\n\n @property\n def pdf1(self):\n return pd.DataFrame(\n {\"a\": [1, 2, 3, 4, 5, 6, 7, 8, 9], \"b\": [4, 5, 6, 3, 2, 1, 0, 0, 0]},\n index=[0, 1, 3, 5, 6, 8, 9, 9, 9],\n )\n\n @property\n def pdf2(self):\n return pd.DataFrame(\n {\"a\": [9, 8, 7, 6, 5, 4, 3, 2, 1], \"b\": [0, 0, 0, 4, 5, 6, 1, 2, 3]},\n index=list(range(9)),\n )\n\n @property\n def psdf1(self):\n return ps.from_pandas(self.pdf1)\n\n @property\n def psdf2(self):\n return ps.from_pandas(self.pdf2)\n\n def test_arithmetic(self):\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n self.psdf1.a - self.psdf2.b\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n self.psdf1.a - self.psdf2.a\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n self.psdf1[\"a\"] - self.psdf2[\"a\"]\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n self.psdf1 - self.psdf2\n\n def test_assignment(self):\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf = ps.from_pandas(self.pdf1)\n psdf[\"c\"] = self.psdf1.a\n\n def test_frame_loc_setitem(self):\n pdf = pd.DataFrame(\n [[1, 2], [4, 5], [7, 8]],\n index=[\"cobra\", \"viper\", \"sidewinder\"],\n columns=[\"max_speed\", \"shield\"],\n )\n psdf = ps.DataFrame(pdf)\n another_psdf = ps.DataFrame(pdf)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf.loc[[\"viper\", \"sidewinder\"], [\"shield\"]] = another_psdf.max_speed\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf.loc[another_psdf.max_speed < 5, [\"shield\"]] = -psdf.max_speed\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf.loc[another_psdf.max_speed < 5, [\"shield\"]] = -another_psdf.max_speed\n\n def test_frame_iloc_setitem(self):\n pdf = pd.DataFrame(\n [[1, 2], [4, 5], [7, 8]],\n index=[\"cobra\", \"viper\", \"sidewinder\"],\n columns=[\"max_speed\", \"shield\"],\n )\n psdf = ps.DataFrame(pdf)\n another_psdf = ps.DataFrame(pdf)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf.iloc[[1, 2], [1]] = another_psdf.max_speed.iloc[[1, 2]]\n\n def test_series_loc_setitem(self):\n pser = pd.Series([1, 2, 3], index=[\"cobra\", \"viper\", \"sidewinder\"])\n psser = ps.from_pandas(pser)\n\n pser_another = pd.Series([1, 2, 3], index=[\"cobra\", \"viper\", \"sidewinder\"])\n psser_another = ps.from_pandas(pser_another)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser.loc[psser % 2 == 1] = -psser_another\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser.loc[psser_another % 2 == 1] = -psser\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser.loc[psser_another % 2 == 1] = -psser_another\n\n def test_series_iloc_setitem(self):\n pser = pd.Series([1, 2, 3], index=[\"cobra\", \"viper\", \"sidewinder\"])\n psser = ps.from_pandas(pser)\n\n pser_another = pd.Series([1, 2, 3], index=[\"cobra\", \"viper\", \"sidewinder\"])\n psser_another = ps.from_pandas(pser_another)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser.iloc[[1]] = -psser_another.iloc[[1]]\n\n def test_where(self):\n pdf1 = pd.DataFrame({\"A\": [0, 1, 2, 3, 4], \"B\": [100, 200, 300, 400, 500]})\n pdf2 = pd.DataFrame({\"A\": [0, -1, -2, -3, -4], \"B\": [-100, -200, -300, -400, -500]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf1.where(psdf2 > 100)\n\n pdf1 = pd.DataFrame({\"A\": [-1, -2, -3, -4, -5], \"B\": [-100, -200, -300, -400, -500]})\n pdf2 = pd.DataFrame({\"A\": [-10, -20, -30, -40, -50], \"B\": [-5, -4, -3, -2, -1]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf1.where(psdf2 < -250)\n\n def test_mask(self):\n pdf1 = pd.DataFrame({\"A\": [0, 1, 2, 3, 4], \"B\": [100, 200, 300, 400, 500]})\n pdf2 = pd.DataFrame({\"A\": [0, -1, -2, -3, -4], \"B\": [-100, -200, -300, -400, -500]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf1.mask(psdf2 < 100)\n\n pdf1 = pd.DataFrame({\"A\": [-1, -2, -3, -4, -5], \"B\": [-100, -200, -300, -400, -500]})\n pdf2 = pd.DataFrame({\"A\": [-10, -20, -30, -40, -50], \"B\": [-5, -4, -3, -2, -1]})\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf1.mask(psdf2 > -250)\n\n def test_align(self):\n pdf1 = pd.DataFrame({\"a\": [1, 2, 3], \"b\": [\"a\", \"b\", \"c\"]}, index=[10, 20, 30])\n pdf2 = pd.DataFrame({\"a\": [4, 5, 6], \"c\": [\"d\", \"e\", \"f\"]}, index=[10, 11, 12])\n psdf1 = ps.from_pandas(pdf1)\n psdf2 = ps.from_pandas(pdf2)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf1.align(psdf2)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf1.align(psdf2, axis=0)\n\n def test_pow_and_rpow(self):\n pser = pd.Series([1, 2, np.nan])\n psser = ps.from_pandas(pser)\n pser_other = pd.Series([np.nan, 2, 3])\n psser_other = ps.from_pandas(pser_other)\n\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser.pow(psser_other)\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser ** psser_other\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser.rpow(psser_other)\n\n def test_combine_first(self):\n pdf1 = pd.DataFrame({\"A\": [None, 0], \"B\": [4, None]})\n psdf1 = ps.from_pandas(pdf1)\n\n self.assertRaises(TypeError, lambda: psdf1.combine_first(ps.Series([1, 2])))\n\n pser1 = pd.Series({\"falcon\": 330.0, \"eagle\": 160.0})\n pser2 = pd.Series({\"falcon\": 345.0, \"eagle\": 200.0, \"duck\": 30.0})\n psser1 = ps.from_pandas(pser1)\n psser2 = ps.from_pandas(pser2)\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psser1.combine_first(psser2)\n\n pdf1 = pd.DataFrame({\"A\": [None, 0], \"B\": [4, None]})\n psdf1 = ps.from_pandas(pdf1)\n pdf2 = pd.DataFrame({\"C\": [3, 3], \"B\": [1, 1]})\n psdf2 = ps.from_pandas(pdf2)\n with self.assertRaisesRegex(ValueError, \"Cannot combine the series or dataframe\"):\n psdf1.combine_first(psdf2)\n\n\nif __name__ == \"__main__\":\n from pyspark.pandas.tests.test_ops_on_diff_frames import * # noqa: F401\n\n try:\n import xmlrunner # type: ignore[import]\n\n testRunner = xmlrunner.XMLTestRunner(output=\"target/test-reports\", verbosity=2)\n except ImportError:\n testRunner = None\n unittest.main(testRunner=testRunner, verbosity=2)\n"
] |
[
[
"pandas.concat",
"pandas.Series",
"pandas.MultiIndex",
"pandas.MultiIndex.from_tuples",
"pandas.Index",
"pandas.DataFrame",
"pandas.MultiIndex.from_arrays",
"numpy.random.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
GabyRumc/evalutils
|
[
"d77c80d6420980a886302237ca321d09478a3db2"
] |
[
"evalutils/evalutils.py"
] |
[
"import json\nimport logging\nfrom abc import ABC, abstractmethod\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import (\n Any,\n Callable,\n Dict,\n Iterable,\n List,\n Optional,\n Pattern,\n Set,\n Tuple,\n Union,\n)\nfrom warnings import warn\n\nimport SimpleITK\nfrom pandas import DataFrame, Series, concat, merge\n\nfrom .exceptions import ConfigurationError, FileLoaderError, ValidationError\nfrom .io import (\n CSVLoader,\n FileLoader,\n ImageLoader,\n SimpleITKLoader,\n first_int_in_filename_key,\n)\nfrom .scorers import score_detection\nfrom .validators import DataFrameValidator, UniqueImagesValidator\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_INPUT_PATH = Path(\"/input/\")\nDEFAULT_ALGORITHM_OUTPUT_IMAGES_PATH = Path(\"/output/images/\")\nDEFAULT_ALGORITHM_OUTPUT_FILE_PATH = Path(\"/output/results.json\")\nDEFAULT_GROUND_TRUTH_PATH = Path(\"/opt/evaluation/ground-truth/\")\nDEFAULT_EVALUATION_OUTPUT_FILE_PATH = Path(\"/output/metrics.json\")\n\n\nclass Algorithm(ABC):\n def __init__(\n self,\n *,\n index_key: str = \"input_image\",\n file_loaders: Optional[Dict[str, FileLoader]] = None,\n file_filters: Optional[Dict[str, Optional[Pattern[str]]]] = None,\n input_path: Path = DEFAULT_INPUT_PATH,\n output_path: Path = DEFAULT_ALGORITHM_OUTPUT_IMAGES_PATH,\n file_sorter_key: Optional[Callable] = None,\n validators: Optional[Dict[str, Tuple[DataFrameValidator, ...]]] = None,\n output_file: PathLike = DEFAULT_ALGORITHM_OUTPUT_FILE_PATH,\n ):\n \"\"\"\n The base class for all algorithms. Sets the environment and controls\n the flow of the processing once `process` is called.\n\n\n Parameters\n ----------\n index_key\n Fileloader key which must be used for the index.\n Default: `input_image`\n file_loaders\n The loaders that will be used to get all files.\n Default: `evalutils.io.SimpleITKLoader` for `input_image`\n file_filters\n Regular expressions for filtering certain FileLoaders.\n Default: no filtering.\n input_path\n The path in the container where the ground truth will be loaded\n from. Default: `/input`\n output_path\n The path in the container where the output images will be written.\n Default: `/output/images`\n file_sorter_key\n A function that determines how files in the input_path are sorted.\n Default: `None` (alphanumerical)\n validators\n A dictionary containing the validators that will be used on the\n loaded data per file_loader key. Default:\n `evalutils.validators.UniqueImagesValidator` for `input_image`\n output_file\n The path to the location where the results will be written.\n Default: `/output/results.json`\n \"\"\"\n self._index_key = index_key\n self._input_path = input_path\n self._output_path = output_path\n self._file_sorter_key = file_sorter_key\n self._output_file = output_file\n\n self._ground_truth_cases = DataFrame()\n self._predictions_cases = DataFrame()\n\n self._cases: Dict[str, DataFrame] = {}\n\n self._case_results: List[Dict] = []\n\n self._validators: Dict[str, Tuple[DataFrameValidator, ...]] = (\n dict(input_image=(UniqueImagesValidator(),))\n if validators is None\n else validators\n )\n self._file_loaders: Dict[str, FileLoader] = (\n dict(input_image=SimpleITKLoader())\n if file_loaders is None\n else file_loaders\n )\n self._file_filters: Dict[str, Optional[Pattern[str]]] = (\n dict(input_image=None) if file_filters is None else file_filters\n )\n\n super().__init__()\n\n def load(self):\n for key, file_loader in self._file_loaders.items():\n fltr = (\n self._file_filters[key] if key in self._file_filters else None\n )\n self._cases[key] = self._load_cases(\n folder=self._input_path,\n file_loader=file_loader,\n file_filter=fltr,\n )\n\n def _load_cases(\n self,\n *,\n folder: Path,\n file_loader: ImageLoader,\n file_filter: Pattern[str] = None,\n ) -> DataFrame:\n cases = None\n\n for f in sorted(folder.glob(\"**/*\"), key=self._file_sorter_key):\n if file_filter is None or file_filter.match(str(f)):\n try:\n new_cases = file_loader.load(fname=f)\n except FileLoaderError:\n logger.warning(\n f\"Could not load {f.name} using {file_loader}.\"\n )\n else:\n if cases is None:\n cases = new_cases\n else:\n cases += new_cases\n else:\n logger.info(\n f\"Skip loading {f.name} because it doesn't match {file_filter}.\"\n )\n\n if cases is None:\n raise FileLoaderError(\n f\"Could not load any files in {folder} with \" f\"{file_loader}.\"\n )\n\n return DataFrame(cases)\n\n def validate(self):\n \"\"\" Validates each dataframe for each fileloader separately \"\"\"\n file_loaders_keys = [k for k in self._file_loaders.keys()]\n for key in self._validators.keys():\n if key not in file_loaders_keys:\n raise ValueError(\n f\"There is no file_loader associated with: {key}.\\n\"\n f\"Valid file loaders are: {file_loaders_keys}\"\n )\n for key, cases in self._cases.items():\n if key in self._validators:\n self._validate_data_frame(df=cases, file_loader_key=key)\n\n def _validate_data_frame(self, *, df: DataFrame, file_loader_key: str):\n for validator in self._validators[file_loader_key]:\n validator.validate(df=df)\n\n def process(self):\n self.load()\n self.validate()\n self.process_cases()\n self.save()\n\n def process_cases(self, file_loader_key: str = None):\n if file_loader_key is None:\n file_loader_key = self._index_key\n self._case_results = []\n for idx, case in self._cases[file_loader_key].iterrows():\n self._case_results.append(self.process_case(idx=idx, case=case))\n\n @abstractmethod\n def process_case(self, *, idx: int, case: DataFrame) -> Dict:\n raise NotImplementedError()\n\n def save(self):\n with open(str(self._output_file), \"w\") as f:\n json.dump(self._case_results, f)\n\n def _load_input_image(self, *, case) -> Tuple[SimpleITK.Image, Path]:\n input_image_file_path = case[\"path\"]\n\n input_image_file_loader = self._file_loaders[\"input_image\"]\n if not isinstance(input_image_file_loader, ImageLoader):\n raise RuntimeError(\n \"The used FileLoader was not of subclass ImageLoader\"\n )\n\n # Load the image for this case\n input_image = input_image_file_loader.load_image(input_image_file_path)\n\n # Check that it is the expected image\n if input_image_file_loader.hash_image(input_image) != case[\"hash\"]:\n raise RuntimeError(\"Image hashes do not match\")\n\n return input_image, input_image_file_path\n\n @abstractmethod\n def predict(self, *, input_image: SimpleITK.Image) -> Any:\n raise NotImplementedError()\n\n\nclass DetectionAlgorithm(Algorithm):\n def process_case(self, *, idx, case):\n # Load and test the image for this case\n input_image, input_image_file_path = self._load_input_image(case=case)\n\n # Detect and score candidates\n scored_candidates = self.predict(input_image=input_image)\n\n # Write resulting candidates to result.json for this case\n return {\n \"outputs\": [\n dict(type=\"candidates\", data=scored_candidates.to_dict())\n ],\n \"inputs\": [\n dict(type=\"metaio_image\", filename=input_image_file_path.name)\n ],\n \"error_messages\": [],\n }\n\n @abstractmethod\n def predict(self, *, input_image: SimpleITK.Image) -> DataFrame:\n raise NotImplementedError()\n\n @staticmethod\n def _serialize_candidates(\n *,\n candidates: Iterable[Tuple[float, ...]],\n candidate_scores: List[Any],\n ref_image: SimpleITK.Image,\n ) -> List[Dict]:\n data = []\n for coord, score in zip(candidates, candidate_scores):\n world_coords = ref_image.TransformContinuousIndexToPhysicalPoint(\n [c for c in reversed(coord)]\n )\n coord_data = {\n f\"coord{k}\": v for k, v in zip([\"X\", \"Y\", \"Z\"], world_coords)\n }\n coord_data.update({\"score\": score})\n data.append(coord_data)\n return data\n\n\nclass SegmentationAlgorithm(Algorithm):\n def process_case(self, *, idx, case):\n # Load and test the image for this case\n input_image, input_image_file_path = self._load_input_image(case=case)\n\n # Segment nodule candidates\n segmented_nodules = self.predict(input_image=input_image)\n\n # Write resulting segmentation to output location\n segmentation_path = self._output_path / input_image_file_path.name\n if not self._output_path.exists():\n self._output_path.mkdir()\n SimpleITK.WriteImage(segmented_nodules, str(segmentation_path), True)\n\n # Write segmentation file path to result.json for this case\n return {\n \"outputs\": [\n dict(type=\"metaio_image\", filename=segmentation_path.name)\n ],\n \"inputs\": [\n dict(type=\"metaio_image\", filename=input_image_file_path.name)\n ],\n \"error_messages\": [],\n }\n\n @abstractmethod\n def predict(self, *, input_image: SimpleITK.Image) -> SimpleITK.Image:\n raise NotImplementedError()\n\n\nclass ClassificationAlgorithm(Algorithm):\n def process_case(self, *, idx, case):\n # Load and test the image for this case\n input_image, input_image_file_path = self._load_input_image(case=case)\n\n # Classify input_image image\n results = self.predict(input_image=input_image)\n\n # Test classification output\n if not isinstance(results, dict):\n raise ValueError(\"Exepected a dictionary as output\")\n\n # Write resulting classification to result.json for this case\n return {\n \"outputs\": [results],\n \"inputs\": [\n dict(type=\"metaio_image\", filename=input_image_file_path.name)\n ],\n \"error_messages\": [],\n }\n\n @abstractmethod\n def predict(self, *, input_image: SimpleITK.Image) -> Dict:\n raise NotImplementedError()\n\n\nclass BaseEvaluation(ABC):\n def __init__(\n self,\n *,\n ground_truth_path: Path = DEFAULT_GROUND_TRUTH_PATH,\n predictions_path: Path = DEFAULT_INPUT_PATH,\n file_sorter_key: Callable = first_int_in_filename_key,\n file_loader: FileLoader,\n validators: Tuple[DataFrameValidator, ...],\n join_key: str = None,\n aggregates: Set[str] = None,\n output_file: PathLike = DEFAULT_EVALUATION_OUTPUT_FILE_PATH,\n ):\n \"\"\"\n The base class for all evaluations. Sets the environment and controls\n the flow of the evaluation once `evaluate` is called.\n\n\n Parameters\n ----------\n ground_truth_path\n The path in the container where the ground truth will be loaded\n from\n predictions_path\n The path in the container where the submission will be loaded from\n file_sorter_key\n A function that determines how files are sorted and matched\n together\n file_loader\n The loader that will be used to get all files\n validators\n A tuple containing all the validators that will be used on the\n loaded data\n join_key\n The column that will be used to join the predictions and ground\n truth tables\n aggregates\n The set of aggregates that will be calculated by\n `pandas.DataFrame.describe`\n output_file\n The path to the location where the results will be written\n \"\"\"\n if aggregates is None:\n aggregates = {\n \"mean\",\n \"std\",\n \"min\",\n \"max\",\n \"25%\",\n \"50%\",\n \"75%\",\n \"count\",\n \"uniq\",\n \"freq\",\n }\n\n self._ground_truth_path = ground_truth_path\n self._predictions_path = predictions_path\n self._file_sorter_key = file_sorter_key\n self._file_loader = file_loader\n self._validators = validators\n self._join_key = join_key\n self._aggregates = aggregates\n self._output_file = output_file\n\n self._ground_truth_cases = DataFrame()\n self._predictions_cases = DataFrame()\n\n self._cases = DataFrame()\n\n self._case_results = DataFrame()\n self._aggregate_results: Dict[str, Union[float, int, str, None]] = {}\n\n super().__init__()\n\n if isinstance(self._file_loader, CSVLoader) and self._join_key is None:\n raise ConfigurationError(\n f\"You must set a `join_key` when using {self._file_loader}.\"\n )\n\n @property\n def _metrics(self) -> Dict:\n \"\"\" Returns the calculated case and aggregate results \"\"\"\n return {\n \"case\": self._case_results.to_dict(),\n \"aggregates\": self._aggregate_results,\n }\n\n def evaluate(self):\n self.load()\n self.validate()\n self.merge_ground_truth_and_predictions()\n self.cross_validate()\n self.score()\n self.save()\n\n def load(self):\n self._ground_truth_cases = self._load_cases(\n folder=self._ground_truth_path\n )\n self._predictions_cases = self._load_cases(\n folder=self._predictions_path\n )\n\n def _load_cases(self, *, folder: Path) -> DataFrame:\n cases = None\n\n for f in sorted(folder.glob(\"**/*\"), key=self._file_sorter_key):\n try:\n new_cases = self._file_loader.load(fname=f)\n except FileLoaderError:\n logger.warning(\n f\"Could not load {f.name} using {self._file_loader}.\"\n )\n else:\n if cases is None:\n cases = new_cases\n else:\n cases += new_cases\n\n if cases is None:\n raise FileLoaderError(\n f\"Could not load any files in {folder} with \"\n f\"{self._file_loader}.\"\n )\n\n return DataFrame(cases)\n\n def validate(self):\n \"\"\" Validates each dataframe separately \"\"\"\n self._validate_data_frame(df=self._ground_truth_cases)\n self._validate_data_frame(df=self._predictions_cases)\n\n def _validate_data_frame(self, *, df: DataFrame):\n for validator in self._validators:\n validator.validate(df=df)\n\n @abstractmethod\n def merge_ground_truth_and_predictions(self):\n pass\n\n @abstractmethod\n def cross_validate(self):\n \"\"\" Validates both dataframes \"\"\"\n pass\n\n def _raise_missing_predictions_error(self, *, missing=None):\n if missing is not None:\n message = (\n \"Predictions missing: you did not submit predictions for \"\n f\"{missing}. Please try again.\"\n )\n else:\n message = (\n \"Predictions missing: you did not submit enough predictions, \"\n \"please try again.\"\n )\n\n raise ValidationError(message)\n\n def _raise_extra_predictions_error(self, *, extra=None):\n if extra is not None:\n message = (\n \"Too many predictions: we do not have the ground truth data \"\n f\"for {extra}. Please try again.\"\n )\n else:\n message = (\n \"Too many predictions: you submitted too many predictions, \"\n \"please try again.\"\n )\n\n raise ValidationError(message)\n\n @abstractmethod\n def score(self):\n pass\n\n # noinspection PyUnusedLocal\n def score_case(self, *, idx: int, case: DataFrame) -> Dict:\n return {}\n\n def score_aggregates(self) -> Dict:\n aggregate_results = {}\n\n for col in self._case_results.columns:\n aggregate_results[col] = self.aggregate_series(\n series=self._case_results[col]\n )\n\n return aggregate_results\n\n def aggregate_series(self, *, series: Series) -> Dict:\n summary = series.describe()\n valid_keys = [a for a in self._aggregates if a in summary]\n\n series_summary = {}\n\n for k in valid_keys:\n value = summary[k]\n\n # % in keys could cause problems when looking up values later\n key = k.replace(\"%\", \"pc\")\n\n try:\n json.dumps(value)\n except TypeError:\n logger.warning(\n f\"Could not serialize {key}: {value} as json, \"\n f\"so converting {value} to int.\"\n )\n value = int(value)\n\n series_summary[key] = value\n\n return series_summary\n\n def save(self):\n with open(self._output_file, \"w\") as f:\n f.write(json.dumps(self._metrics))\n\n\nclass ClassificationEvaluation(BaseEvaluation):\n \"\"\"\n ClassificationEvaluations have the same number of predictions as the\n number of ground truth cases. These can be things like, what is the\n stage of this case, or segment some things in this case.\n \"\"\"\n\n def merge_ground_truth_and_predictions(self):\n if self._join_key:\n kwargs = {\"on\": self._join_key}\n else:\n kwargs = {\"left_index\": True, \"right_index\": True}\n\n self._cases = merge(\n left=self._ground_truth_cases,\n right=self._predictions_cases,\n indicator=True,\n how=\"outer\",\n suffixes=(\"_ground_truth\", \"_prediction\"),\n **kwargs,\n )\n\n def cross_validate(self):\n missing = [\n p for _, p in self._cases.iterrows() if p[\"_merge\"] == \"left_only\"\n ]\n\n if missing:\n if self._join_key:\n missing = [p[self._join_key] for p in missing]\n self._raise_missing_predictions_error(missing=missing)\n\n extra = [\n p for _, p in self._cases.iterrows() if p[\"_merge\"] == \"right_only\"\n ]\n\n if extra:\n if self._join_key:\n extra = [p[self._join_key] for p in extra]\n self._raise_extra_predictions_error(extra=extra)\n\n def score(self):\n self._case_results = DataFrame()\n for idx, case in self._cases.iterrows():\n self._case_results = self._case_results.append(\n self.score_case(idx=idx, case=case), ignore_index=True\n )\n self._aggregate_results = self.score_aggregates()\n\n\nclass Evaluation(ClassificationEvaluation):\n \"\"\"\n Legacy class, you should use ClassificationEvaluation instead.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n warn(\n (\n \"The Evaluation class is deprecated, \"\n \"please use ClassificationEvaluation instead\"\n ),\n DeprecationWarning,\n )\n super().__init__(*args, **kwargs)\n\n\nclass DetectionEvaluation(BaseEvaluation):\n \"\"\"\n DetectionEvaluations have a different number of predictions from the\n number of ground truth annotations. An example would be detecting lung\n nodules in a CT volume, or malignant cells in a pathology slide.\n \"\"\"\n\n def __init__(self, *args, detection_radius, detection_threshold, **kwargs):\n super().__init__(*args, **kwargs)\n self._detection_radius = detection_radius\n self._detection_threshold = detection_threshold\n\n def merge_ground_truth_and_predictions(self):\n self._cases = concat(\n [self._ground_truth_cases, self._predictions_cases],\n keys=[\"ground_truth\", \"predictions\"],\n )\n\n def cross_validate(self):\n expected_keys = set(self._ground_truth_cases[self._join_key])\n submitted_keys = set(self._predictions_cases[self._join_key])\n\n missing = expected_keys - submitted_keys\n if missing:\n self._raise_missing_predictions_error(missing=missing)\n\n extra = submitted_keys - expected_keys\n if extra:\n self._raise_extra_predictions_error(extra=extra)\n\n def _raise_extra_predictions_error(self, *, extra=None):\n \"\"\" In detection challenges extra predictions are ok \"\"\"\n warn(f\"There are extra predictions for cases: {extra}.\")\n\n def _raise_missing_predictions_error(self, *, missing=None):\n \"\"\" In detection challenges missing predictions are ok \"\"\"\n warn(f\"Could not find predictions for cases: {missing}.\")\n\n def score(self):\n cases = set(self._ground_truth_cases[self._join_key])\n cases |= set(self._predictions_cases[self._join_key])\n\n self._case_results = DataFrame()\n\n for idx, case in enumerate(cases):\n self._case_results = self._case_results.append(\n self.score_case(\n idx=idx,\n case=self._cases.loc[self._cases[self._join_key] == case],\n ),\n ignore_index=True,\n )\n self._aggregate_results = self.score_aggregates()\n\n def score_case(self, *, idx, case):\n score = score_detection(\n ground_truth=self.get_points(case=case, key=\"ground_truth\"),\n predictions=self.get_points(case=case, key=\"predictions\"),\n radius=self._detection_radius,\n )\n\n # Add the case id to the score\n output = score._asdict()\n output.update({self._join_key: case[self._join_key][0]})\n\n return output\n\n def get_points(\n self, *, case, key: str\n ) -> List[Tuple[Union[int, float], Union[int, float]]]:\n raise NotImplementedError\n\n def score_aggregates(self):\n aggregate_results = super().score_aggregates()\n\n totals = self._case_results.sum()\n\n for s in totals.index:\n aggregate_results[s][\"sum\"] = totals[s]\n\n tp = aggregate_results[\"true_positives\"][\"sum\"]\n fp = aggregate_results[\"false_positives\"][\"sum\"]\n fn = aggregate_results[\"false_negatives\"][\"sum\"]\n\n aggregate_results[\"precision\"] = tp / (tp + fp)\n aggregate_results[\"recall\"] = tp / (tp + fn)\n aggregate_results[\"f1_score\"] = 2 * tp / ((2 * tp) + fp + fn)\n\n return aggregate_results\n"
] |
[
[
"pandas.merge",
"pandas.concat",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
BuildJet/mindmeld
|
[
"82b063b21d6012b36ba2a4321edfa56b8c4b8c90"
] |
[
"mindmeld/models/text_models.py"
] |
[
"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis module contains all code required to perform multinomial classification\nof text.\n\"\"\"\nimport logging\nimport operator\nimport random\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.feature_selection import SelectFromModel, SelectPercentile\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import LabelEncoder as SKLabelEncoder\nfrom sklearn.preprocessing import MaxAbsScaler, StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\n\nfrom .helpers import (\n CHAR_NGRAM_FREQ_RSC,\n QUERY_FREQ_RSC,\n WORD_FREQ_RSC,\n WORD_NGRAM_FREQ_RSC,\n register_model,\n)\nfrom .model import EvaluatedExample, Model, StandardModelEvaluation\n\n_NEG_INF = -1e10\n\n# classifier types\nLOG_REG_TYPE = \"logreg\"\nDECISION_TREE_TYPE = \"dtree\"\nRANDOM_FOREST_TYPE = \"rforest\"\nSVM_TYPE = \"svm\"\nSUPER_LEARNER_TYPE = \"super-learner\"\nBASE_MODEL_TYPES = [LOG_REG_TYPE, DECISION_TREE_TYPE, RANDOM_FOREST_TYPE, SVM_TYPE]\n\n# default model scoring type\nACCURACY_SCORING = \"accuracy\"\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TextModel(Model):\n def __init__(self, config):\n super().__init__(config)\n self._class_encoder = SKLabelEncoder()\n self._feat_vectorizer = DictVectorizer()\n self._feat_selector = self._get_feature_selector()\n self._feat_scaler = self._get_feature_scaler()\n self._meta_type = None\n self._meta_feat_vectorizer = DictVectorizer(sparse=False)\n self._base_clfs = {}\n self.cv_loss_ = None\n self.train_acc_ = None\n\n def __getstate__(self):\n \"\"\"Returns the information needed pickle an instance of this class.\n\n By default, pickling removes attributes with names starting with\n underscores. This overrides that behavior.\n \"\"\"\n attributes = self.__dict__.copy()\n attributes[\"_resources\"] = {\n rname: self._resources.get(rname, {})\n for rname in [\n WORD_FREQ_RSC,\n QUERY_FREQ_RSC,\n WORD_NGRAM_FREQ_RSC,\n CHAR_NGRAM_FREQ_RSC,\n ]\n }\n return attributes\n\n def _get_model_constructor(self):\n \"\"\"Returns the class of the actual underlying model\"\"\"\n classifier_type = self.config.model_settings[\"classifier_type\"]\n try:\n return {\n LOG_REG_TYPE: LogisticRegression,\n DECISION_TREE_TYPE: DecisionTreeClassifier,\n RANDOM_FOREST_TYPE: RandomForestClassifier,\n SVM_TYPE: SVC,\n }[classifier_type]\n except KeyError as e:\n msg = \"{}: Classifier type {!r} not recognized\"\n raise ValueError(msg.format(self.__class__.__name__, classifier_type)) from e\n\n def _get_cv_scorer(self, selection_settings):\n \"\"\"\n Returns the scorer to use based on the selection settings and classifier type,\n defaulting to accuracy.\n \"\"\"\n return selection_settings.get(\"scoring\", ACCURACY_SCORING)\n\n def evaluate(self, examples, labels):\n \"\"\"Evaluates a model against the given examples and labels\n\n Args:\n examples: A list of examples to predict\n labels: A list of expected labels\n\n Returns:\n ModelEvaluation: an object containing information about the \\\n evaluation\n \"\"\"\n # TODO: also expose feature weights?\n predictions = self.predict_proba(examples)\n\n # Create a model config object for the current effective config (after param selection)\n config = self._get_effective_config()\n\n evaluations = [\n EvaluatedExample(\n e, labels[i], predictions[i][0], predictions[i][1], config.label_type\n )\n for i, e in enumerate(examples)\n ]\n\n model_eval = StandardModelEvaluation(config, evaluations)\n return model_eval\n\n def fit(self, examples, labels, params=None):\n \"\"\"Trains this model.\n\n This method inspects instance attributes to determine the classifier\n object and cross-validation strategy, and then fits the model to the\n training examples passed in.\n\n Args:\n examples (list): A list of examples.\n labels (list): A parallel list to examples. The gold labels\n for each example.\n params (dict, optional): Parameters to use when training. Parameter\n selection will be bypassed if this is provided\n\n Returns:\n (TextModel): Returns self to match classifier scikit-learn \\\n interfaces.\n \"\"\"\n params = params or self.config.params\n skip_param_selection = params is not None or self.config.param_selection is None\n\n # Shuffle to prevent order effects\n indices = list(range(len(labels)))\n random.shuffle(indices)\n examples = [examples[i] for i in indices]\n labels = [labels[i] for i in indices]\n\n distinct_labels = set(labels)\n if len(set(distinct_labels)) <= 1:\n return self\n\n # Extract features and classes\n y = self._label_encoder.encode(labels)\n X, y, groups = self.get_feature_matrix(examples, y, fit=True)\n\n if skip_param_selection:\n self._clf = self._fit(X, y, params)\n self._current_params = params\n else:\n # run cross validation to select params\n best_clf, best_params = self._fit_cv(X, y, groups)\n self._clf = best_clf\n self._current_params = best_params\n\n return self\n\n def select_params(self, examples, labels, selection_settings=None):\n y = self._label_encoder.encode(labels)\n X, y, groups = self.get_feature_matrix(examples, y, fit=True)\n clf, params = self._fit_cv(X, y, groups, selection_settings)\n self._clf = clf\n return params\n\n def _fit(self, examples, labels, params=None):\n \"\"\"Trains a classifier without cross-validation.\n\n Args:\n examples (numpy.matrix): The feature matrix for a dataset.\n labels (numpy.array): The target output values.\n params (dict): Parameters of the classifier\n\n \"\"\"\n params = self._convert_params(params, labels, is_grid=False)\n model_class = self._get_model_constructor()\n params = self._clean_params(model_class, params)\n return model_class(**params).fit(examples, labels)\n\n def predict(self, examples, dynamic_resource=None):\n X, _, _ = self.get_feature_matrix(examples, dynamic_resource=dynamic_resource)\n y = self._clf.predict(X)\n predictions = self._class_encoder.inverse_transform(y)\n return self._label_encoder.decode(predictions)\n\n def predict_proba(self, examples, dynamic_resource=None):\n X, _, _ = self.get_feature_matrix(examples, dynamic_resource=dynamic_resource)\n return self._predict_proba(X, self._clf.predict_proba)\n\n def predict_log_proba(self, examples, dynamic_resource=None):\n X, _, _ = self.get_feature_matrix(examples, dynamic_resource=dynamic_resource)\n predictions = self._predict_proba(X, self._clf.predict_log_proba)\n\n # JSON can't reliably encode infinity, so replace it with large number\n for row in predictions:\n _, probas = row\n for label, proba in probas.items():\n if proba == -np.Infinity:\n probas[label] = _NEG_INF\n return predictions\n\n def view_extracted_features(self, example, dynamic_resource=None):\n return self._extract_features(\n example, dynamic_resource=dynamic_resource, tokenizer=self.tokenizer\n )\n\n def _get_feature_weight(self, feat_name, label_class):\n \"\"\"Retrieves the feature weight from the coefficient matrix. If there are only two\n classes, the feature vector is actually collapsed into one so we need some logic to\n handle that case.\n\n Args:\n feat_name (str) : The feature name\n label_class (int): The index of the label\n\n Returns:\n (ndarray float): The ndarray with a single float element\n \"\"\"\n if len(self._class_encoder.classes_) == 2 and label_class >= 1:\n return np.array([0.0])\n else:\n return self._clf.coef_[\n label_class, self._feat_vectorizer.vocabulary_[feat_name]\n ]\n\n def inspect(self, example, gold_label=None, dynamic_resource=None):\n \"\"\"This class takes an example and returns a 2D list for every feature with feature\n name, feature value, feature weight and their product for the predicted label. If gold\n label is passed in, we will also include the feature value and weight for the gold\n label and returns the log probability of the difference.\n\n Args:\n example (Query): The query to be predicted\n gold_label (str): The gold label for this string\n dynamic_resource (dict, optional): A dynamic resource to aid NLP inference\n\n Returns:\n (list of lists): A 2D array that includes every feature, their value, weight and \\\n probability\n \"\"\"\n if not isinstance(self._clf, LogisticRegression):\n logging.warning(\n \"Currently inspection is only available for Logistic Regression Model\"\n )\n return []\n\n try:\n gold_class = self._class_encoder.transform([gold_label])\n except ValueError:\n logger.warning(\"Unable to decode label `%s`\", gold_label)\n gold_class = None\n\n pred_label = self.predict([example], dynamic_resource=dynamic_resource)[0]\n pred_class = self._class_encoder.transform([pred_label])\n features = self._extract_features(\n example, dynamic_resource=dynamic_resource, tokenizer=self.tokenizer\n )\n\n logging.info(\"Predicted: %s.\", pred_label)\n\n if gold_class is None:\n columns = [\"Feature\", \"Value\", \"Pred_W({0})\".format(pred_label), \"Pred_P\"]\n else:\n columns = [\n \"Feature\",\n \"Value\",\n \"Pred_W({0})\".format(pred_label),\n \"Pred_P\",\n \"Gold_W({0})\".format(gold_label),\n \"Gold_P\",\n \"Diff\",\n ]\n logging.info(\"Gold: %s.\", gold_label)\n\n inspect_table = [columns]\n\n # Get all active features sorted alphabetically by name\n features = sorted(features.items(), key=operator.itemgetter(0))\n for feature in features:\n feat_name = feature[0]\n feat_value = feature[1]\n\n # Features we haven't seen before won't be in our vectorizer\n # e.g., an exact match feature for a query we've never seen before\n if feat_name not in self._feat_vectorizer.vocabulary_:\n continue\n\n weight = self._get_feature_weight(feat_name, pred_class)\n product = feat_value * weight\n\n if gold_class is None:\n row = [\n feat_name,\n round(feat_value, 4),\n weight.round(4),\n product.round(4),\n \"-\",\n \"-\",\n \"-\",\n ]\n else:\n gold_w = self._get_feature_weight(feat_name, gold_class)\n gold_p = feat_value * gold_w\n diff = gold_p - product\n row = [\n feat_name,\n round(feat_value, 4),\n weight.round(4),\n product.round(4),\n gold_w.round(4),\n gold_p.round(4),\n diff.round(4),\n ]\n\n inspect_table.append(row)\n\n return inspect_table\n\n def _predict_proba(self, X, predictor):\n predictions = []\n for row in predictor(X):\n probabilities = {}\n top_class = None\n for class_index, proba in enumerate(row):\n raw_class = self._class_encoder.inverse_transform([class_index])[0]\n decoded_class = self._label_encoder.decode([raw_class])[0]\n probabilities[decoded_class] = proba\n if proba > probabilities.get(top_class, -1.0):\n top_class = decoded_class\n predictions.append((top_class, probabilities))\n\n return predictions\n\n def get_feature_matrix(self, examples, y=None, fit=False, dynamic_resource=None):\n \"\"\"Transforms a list of examples into a feature matrix.\n\n Args:\n examples (list): The examples.\n\n Returns:\n (tuple): tuple containing:\n\n * (numpy.matrix): The feature matrix.\n * (numpy.array): The group labels for examples.\n \"\"\"\n groups = []\n feats = []\n for idx, example in enumerate(examples):\n feats.append(\n self._extract_features(example, dynamic_resource, self.tokenizer)\n )\n groups.append(idx)\n\n X, y = self._preprocess_data(feats, y, fit=fit)\n return X, y, groups\n\n def _preprocess_data(self, X, y=None, fit=False):\n\n if fit:\n y = self._class_encoder.fit_transform(y)\n X = self._feat_vectorizer.fit_transform(X)\n if self._feat_scaler is not None:\n X = self._feat_scaler.fit_transform(X)\n if self._feat_selector is not None:\n X = self._feat_selector.fit_transform(X, y)\n else:\n X = self._feat_vectorizer.transform(X)\n if self._feat_scaler is not None:\n X = self._feat_scaler.transform(X)\n if self._feat_selector is not None:\n X = self._feat_selector.transform(X)\n\n return X, y\n\n def _convert_params(self, param_grid, y, is_grid=True):\n \"\"\"\n Convert the params from the style given by the config to the style\n passed in to the actual classifier.\n\n Args:\n param_grid (dict): lists of classifier parameter values, keyed by parameter name\n\n Returns:\n (dict): revised param_grid\n \"\"\"\n if \"class_weight\" in param_grid:\n raw_weights = (\n param_grid[\"class_weight\"] if is_grid else [param_grid[\"class_weight\"]]\n )\n weights = [\n {\n k\n if isinstance(k, int)\n else self._class_encoder.transform((k,))[0]: v\n for k, v in cw_dict.items()\n }\n for cw_dict in raw_weights\n ]\n param_grid[\"class_weight\"] = weights if is_grid else weights[0]\n elif \"class_bias\" in param_grid:\n # interpolate between class_bias=0 => class_weight=None\n # and class_bias=1 => class_weight='balanced'\n class_count = np.bincount(y)\n classes = self._class_encoder.classes_\n weights = []\n raw_bias = (\n param_grid[\"class_bias\"] if is_grid else [param_grid[\"class_bias\"]]\n )\n for class_bias in raw_bias:\n # these weights are same as sklearn's class_weight='balanced'\n balanced_w = [(len(y) / len(classes) / c) for c in class_count]\n balanced_tuples = list(zip(list(range(len(classes))), balanced_w))\n\n weights.append(\n {c: (1 - class_bias) + class_bias * w for c, w in balanced_tuples}\n )\n param_grid[\"class_weight\"] = weights if is_grid else weights[0]\n del param_grid[\"class_bias\"]\n\n return param_grid\n\n def _get_feature_selector(self):\n \"\"\"Get a feature selector instance based on the feature_selector model\n parameter\n\n Returns:\n (Object): a feature selector which returns a reduced feature matrix, \\\n given the full feature matrix, X and the class labels, y\n \"\"\"\n if self.config.model_settings is None:\n selector_type = None\n else:\n selector_type = self.config.model_settings.get(\"feature_selector\")\n selector = {\n \"l1\": SelectFromModel(LogisticRegression(penalty=\"l1\", C=1)),\n \"f\": SelectPercentile(),\n }.get(selector_type)\n return selector\n\n def _get_feature_scaler(self):\n \"\"\"Get a feature value scaler based on the model settings\"\"\"\n if self.config.model_settings is None:\n scale_type = None\n else:\n scale_type = self.config.model_settings.get(\"feature_scaler\")\n scaler = {\n \"std-dev\": StandardScaler(with_mean=False),\n \"max-abs\": MaxAbsScaler(),\n }.get(scale_type)\n return scaler\n\n\nregister_model(\"text\", TextModel)\n"
] |
[
[
"sklearn.linear_model.LogisticRegression",
"sklearn.preprocessing.MaxAbsScaler",
"sklearn.preprocessing.LabelEncoder",
"sklearn.feature_selection.SelectPercentile",
"numpy.bincount",
"sklearn.feature_extraction.DictVectorizer",
"sklearn.preprocessing.StandardScaler",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
khurrumsaleem/raven
|
[
"3a158f9ae3851d3eca51b4bd91ea6494e5c0ed89",
"3a158f9ae3851d3eca51b4bd91ea6494e5c0ed89"
] |
[
"ravenframework/Metrics/metrics/SklMetric.py",
"scripts/TestHarness/testers/UnorderedCSVDiffer.py"
] |
[
"# Copyright 2017 Battelle Energy Alliance, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nCreated on August 20 2016\n\n@author: mandd\n\"\"\"\n\n#External Modules------------------------------------------------------------------------------------\nimport numpy as np\nimport ast\n#External Modules End--------------------------------------------------------------------------------\n\n#Internal Modules------------------------------------------------------------------------------------\nfrom ...utils import utils\nfrom .MetricInterface import MetricInterface\nfrom ...utils import InputData, InputTypes\n#Internal Modules End--------------------------------------------------------------------------------\n\nclass SKL(MetricInterface):\n \"\"\"\n Scikit-learn metrics\n \"\"\"\n availMetrics ={}\n\n @classmethod\n def getInputSpecification(cls):\n \"\"\"\n Method to get a reference to a class that specifies the input data for\n class cls.\n @ In, cls, the class for which we are retrieving the specification\n @ Out, inputSpecification, InputData.ParameterInput, class to use for\n specifying input of cls.\n \"\"\"\n inputSpecification = super().getInputSpecification()\n inputSpecification.addSub(InputData.parameterInputFactory(\"metricType\",contentType=InputTypes.StringType),quantity=InputData.Quantity.one)\n inputSpecification.addSub(InputData.parameterInputFactory(\"sample_weight\",contentType=InputTypes.FloatListType),quantity=InputData.Quantity.zero_to_one)\n return inputSpecification\n\n def __init__(self):\n \"\"\"\n Constructor\n @ In, None\n @ Out, None\n \"\"\"\n super().__init__()\n if len(self.availMetrics) == 0:\n import sklearn\n import sklearn.metrics\n # FIXME: median_absolute_error only accepts 1-D numpy array, and if we want to use this metric, it should\n # be handled differently.\n #from sklearn.metrics import median_absolute_error\n\n # regression metrics\n self.availMetrics['regression'] = {}\n self.availMetrics['regression']['explained_variance_score'] = sklearn.metrics.explained_variance_score\n self.availMetrics['regression']['mean_absolute_error'] = sklearn.metrics.mean_absolute_error\n self.availMetrics['regression']['r2_score'] = sklearn.metrics.r2_score\n self.availMetrics['regression']['mean_squared_error'] = sklearn.metrics.mean_squared_error\n # paired distance metrics, no weights\n if int(sklearn.__version__.split(\".\")[1]) > 17:\n self.availMetrics['paired_distance'] = {}\n self.availMetrics['paired_distance']['euclidean'] = sklearn.metrics.pairwise.paired_euclidean_distances\n self.availMetrics['paired_distance']['manhattan'] = sklearn.metrics.pairwise.paired_manhattan_distances\n self.availMetrics['paired_distance']['cosine'] = sklearn.metrics.pairwise.paired_cosine_distances\n # TODO: add more metrics here\n # metric from scipy.spatial.distance, for example mahalanobis, minkowski\n\n # The type of given metric, None or List of two elements, first element should be in availMetrics.keys()\n # and sencond element should be in availMetrics.values()[firstElement].keys()\n self.metricType = None\n # True indicates the metric needs to be able to handle dynamic data\n self._dynamicHandling = True\n\n def handleInput(self, paramInput):\n \"\"\"\n Method that reads the portion of the xml input that belongs to this specialized class\n and initializes internal parameters\n @ In, paramInput, InputData.parameterInput, input specs\n @ Out, None\n \"\"\"\n self.distParams = {}\n for child in paramInput.subparts:\n if child.getName() == \"metricType\":\n self.metricType = list(elem.strip() for elem in child.value.split('|'))\n if len(self.metricType) != 2:\n self.raiseAnError(IOError, \"Metric type: '\", child.value, \"' is not correct, please check the user manual for the correct metric type!\")\n else:\n self.distParams[child.getName()] = child.value\n\n if self.metricType[0] not in self.__class__.availMetrics.keys() or self.metricType[1] not in self.__class__.availMetrics[self.metricType[0]].keys():\n self.raiseAnError(IOError, \"Metric '\", self.name, \"' with metricType '\", self.metricType[0], \"|\", self.metricType[1], \"' is not valid!\")\n\n def run(self, x, y, weights=None, axis=0, **kwargs):\n \"\"\"\n This method computes difference between two points x and y based on given metric\n @ In, x, numpy.ndarray, array containing data of x, if 1D array is provided,\n the array will be reshaped via x.reshape(-1,1) for paired_distance, shape (n_samples, ), if 2D\n array is provided, shape (n_samples, n_outputs)\n @ In, y, numpy.ndarray, array containing data of y, if 1D array is provided,\n the array will be reshaped via y.reshape(-1,1), shape (n_samples, ), if 2D\n array is provided, shape (n_samples, n_outputs)\n @ In, weights, array_like (numpy.array or list), optional, weights associated\n with input, shape (n_samples) if axis = 0, otherwise shape (n_outputs)\n @ In, axis, integer, optional, axis along which a metric is performed, default is 0,\n i.e. the metric will performed along the first dimension (the \"rows\").\n If metric postprocessor is used, the first dimension is the RAVEN_sample_ID,\n and the second dimension is the pivotParameter if HistorySet is provided.\n @ In, kwargs, dict, dictionary of parameters characteristic of each metric\n @ Out, value, numpy.ndarray, metric result, shape (n_outputs) if axis = 0, otherwise\n shape (n_samples), we assume the dimension of input numpy.ndarray is no more than 2.\n \"\"\"\n #######################################################################################\n # The inputs of regression metric, i.e. x, y should have shape (n_samples, n_outputs),\n # and the outputs will have the shape (n_outputs).\n # However, the inputs of paired metric, i.e. x, y should convert the shape to\n # (n_outputs, n_samples), and the outputs will have the shape (n_outputs).\n #######################################################################################\n assert(isinstance(x,np.ndarray)) # NOTE these assertions will not show up for non-debug runs!\n assert(isinstance(y,np.ndarray))\n assert(x.shape == y.shape), \"Input data x, y should have the same shape\"\n if weights is not None and self.metricType[0] == 'regression' and 'sample_weight' not in self.distParams.keys():\n self.distParams['sample_weight'] = weights\n if self.metricType[0] == 'regression':\n self.distParams['multioutput'] = 'raw_values'\n dictTemp = utils.mergeDictionaries(kwargs,self.distParams)\n if self.metricType[0] == 'paired_distance':\n if len(x.shape) == 1:\n x = x.reshape(-1,1)\n y = y.reshape(-1,1)\n else:\n # Transpose is needed, since paired_distance is operated on the 'row'\n x = x.T\n y = y.T\n if axis == 1:\n x = x.T\n y = y.T\n # check the dimension of weights\n assert(x.shape[0] == len(weights)), \"'weights' should have the same length of the first dimension of input data\"\n elif axis != 0:\n self.raiseAnError(IOError, \"Valid axis value should be '0' or '1' for the evaluate method of metric\", self. name, \"value\", axis, \"is provided!\")\n try:\n value = self.__class__.availMetrics[self.metricType[0]][self.metricType[1]](x, y, **dictTemp)\n except TypeError as e:\n self.raiseAWarning('There are some unexpected keyword arguments found in Metric with type \"', self.metricType[1], '\"!')\n self.raiseAnError(TypeError,'Input parameters error:\\n', str(e), '\\n')\n\n return value\n",
"# Copyright 2017 Battelle Energy Alliance, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nThis module implements a unordered csv differ.\n\"\"\"\nfrom __future__ import division, print_function, unicode_literals, absolute_import\nimport sys\nimport os\nimport numpy as np\nimport pandas as pd\n\nfrom Tester import Differ\n\n# get access to math tools from RAVEN\ntry:\n from ravenframework.utils import mathUtils\nexcept ImportError:\n new = os.path.realpath(os.path.join(os.path.realpath(__file__), '..', '..',\n '..', '..'))\n sys.path.append(new)\n from ravenframework.utils import mathUtils\n\nwhoAmI = False # enable to show test dir and out files\ndebug = False # enable to increase printing\n\nclass UnorderedCSVDiffer:\n \"\"\"\n Used for comparing two CSV files without regard for column, row orders\n \"\"\"\n def __init__(self, outFiles, goldFiles, relativeError=1e-10,\n absoluteCheck=False, zeroThreshold=None, ignoreSign=False):\n \"\"\"\n Create an UnorderedCSVDiffer class\n @ In, outFiles, the files to be compared. They will be in testDir + outFiles\n @ In, goldFiles, the files to be compared to the outFiles.\n @ In, relativeError, float, optional, relative error\n @ In, absoluteCheck, bool, optional, if True then check absolute\n differences in the values instead of relative differences\n @ In, zeroThreshold, float, optional, if a number is less equal then\n abs(zeroThreshold), it will be considered 0\n @ In, ignoreSign, bool, optional, if True then the sign will be ignored during the comparison\n @ Out, None.\n \"\"\"\n assert len(outFiles) == len(goldFiles)\n self._out_files = outFiles\n self._gold_files = goldFiles\n self._message = \"\"\n self._same = True\n self._check_absolute_values = absoluteCheck\n self._rel_err = relativeError\n self._zero_threshold = float(zeroThreshold) if zeroThreshold is not None else 0.0\n self._ignore_sign = ignoreSign\n if debug or whoAmI:\n print('out files:', self._out_files)\n print('gold files:', self._gold_files)\n if debug:\n print('err :', self._rel_err)\n print('abs check:', self._check_absolute_values)\n print('zero thr :', self._zero_threshold)\n\n def finalizeMessage(self, same, msg, filename):\n \"\"\"\n Compiles useful messages to print, prepending with file paths.\n @ In, same, bool, True if files are the same\n @ In, msg, list(str), messages that explain differences\n @ In, filename, str, test filename/path\n @ Out, None\n \"\"\"\n if not same:\n self._same = False\n self._message += '\\n'+'*'*20+'\\nDIFF in {}: \\n {}'.format(filename, '\\n '.join(msg))\n\n def find_row(self, row, csv):\n \"\"\"\n Searches for \"row\" in \"csv\"\n @ In, row, pd.Series, row of data\n @ In, csv, pd.Dataframe, dataframe to look in\n @ Out, match, pd.Dataframe or list, matching row of data (or empty list if none found)\n \"\"\"\n if debug:\n print('')\n print('Looking for:\\n', row)\n print('Looking in:\\n', csv)\n match = csv.copy()\n # TODO can I do this as a single search, using binomial on floats +- relErr?\n for idx, val in row.iteritems():\n if debug:\n print(' checking index', idx, 'value', val)\n # Due to relative matches in floats, we may not be sorted with respect to this index.\n ## In an ideal world with perfect matches, we would be. Unfortunately, we have to sort again.\n match = match.sort_values(idx)\n # check type consistency\n ## get a sample from the matching CSV column\n ### TODO could check indices ONCE and re-use instead of checking each time\n matchVal = match[idx].values.item(0) if match[idx].values.shape[0] != 0 else None\n ## find out if match[idx] and/or \"val\" are numbers\n matchIsNumber = mathUtils.isAFloatOrInt(matchVal)\n valIsNumber = mathUtils.isAFloatOrInt(val)\n ## if one is a number and the other is not, consider it a non-match.\n if matchIsNumber != valIsNumber:\n if debug:\n print(' Not same type (number)! lfor: \"{}\" lin: \"{}\"'\n .format(valIsNumber, matchIsNumber))\n return []\n # find index of lowest and highest possible matches\n ## if values are floats, then matches could be as low as val(1-relErr)\n ## and as high as val(1+relErr)\n if matchIsNumber:\n pval = abs(val) if self._ignore_sign else val\n pmatch = abs(match[idx].values) if self._ignore_sign else match[idx].values\n # adjust for negative values\n sign = np.sign(pval)\n lowest = np.searchsorted(pmatch, pval*(1.0-sign*self._rel_err))\n highest = np.searchsorted(pmatch, pval*(1.0+sign*self._rel_err), side='right')-1\n ## if not floats, then check exact matches\n else:\n lowest = np.searchsorted(match[idx].values, val)\n highest = np.searchsorted(match[idx].values, val, side='right')-1\n if debug:\n print(' low/hi match index:', lowest, highest)\n ## if lowest is past end of array, no match found\n if lowest == len(match[idx]):\n if debug:\n print(' Match is past end of sort list!')\n return []\n ## if entry at lowest index doesn't match entry, then it's not to be found\n if not self.matches(match[idx].values[lowest], val, matchIsNumber, self._rel_err):\n if debug:\n print(' Match is not equal to insert point!')\n return []\n ## otherwise, we have some range of matches\n match = match[slice(lowest, highest+1)]\n if debug:\n print(' After searching for {}={}, remaining matches:\\n'.format(idx, val), match)\n return match\n\n def matches(self, aObj, bObj, isNumber, tol):\n \"\"\"\n Determines if two objects match within tolerance.\n @ In, a, object, first object (\"measured\")\n @ In, b, object, second object (\"actual\")\n @ In, isNumber, bool, if True then treat as float with tolerance (else check equivalence)\n @ In, tol, float, tolerance at which to hold match (if float)\n @ Out, matches, bool, True if matching\n \"\"\"\n if not isNumber:\n return aObj == bObj\n if self._ignore_sign:\n aObj = abs(aObj)\n bObj = abs(bObj)\n if self._check_absolute_values:\n return abs(aObj-bObj) < tol\n # otherwise, relative error\n scale = abs(bObj) if bObj != 0 else 1.0\n return abs(aObj-bObj) < scale*tol\n\n def diff(self):\n \"\"\"\n Run the comparison.\n @ In, None\n @ Out, same, bool, if True then files are the same\n @ Out, messages, str, messages to print on fail\n \"\"\"\n # read in files\n for testFilename, goldFilename in zip(self._out_files, self._gold_files):\n # local \"same\" and message list\n same = True\n msg = []\n # load test file\n try:\n testCsv = pd.read_csv(testFilename, sep=',')\n # if file is empty, we can check that's consistent, too\n except pd.errors.EmptyDataError:\n testCsv = None\n # if file doesn't exist, that's another problem\n except IOError:\n msg.append('Test file does not exist!')\n same = False\n # load gold file\n try:\n goldCsv = pd.read_csv(goldFilename, sep=',')\n # if file is empty, we can check that's consistent, too\n except pd.errors.EmptyDataError:\n goldCsv = None\n # if file doesn't exist, that's another problem\n except IOError:\n msg.append('Gold file does not exist!')\n same = False\n # if either file did not exist, clean up and go to next outfile\n if not same:\n self.finalizeMessage(same, msg, testFilename)\n continue\n # at this point, we've loaded both files (even if they're empty), so compare them.\n ## first, cover the case when both files are empty.\n if testCsv is None or goldCsv is None:\n if not (testCsv is None and goldCsv is None):\n same = False\n if testCsv is None:\n msg.append('Test file is empty, but Gold is not!')\n else:\n msg.append('Gold file is empty, but Test is not!')\n # either way, move on to the next file, as no more comparison is needed\n self.finalizeMessage(same, msg, testFilename)\n continue\n ## at this point, both files have data loaded\n ## check columns using symmetric difference\n diffColumns = set(goldCsv.columns)^set(testCsv.columns)\n if len(diffColumns) > 0:\n same = False\n msg.append('Columns are not the same! Different: {}'.format(', '.join(diffColumns)))\n self.finalizeMessage(same, msg, testFilename)\n continue\n ## check index length\n if len(goldCsv.index) != len(testCsv.index):\n same = False\n msg.append(('Different number of entires in Gold ({}) versus'+\n ' Test ({})!').format(len(goldCsv.index), len(testCsv.index)))\n self.finalizeMessage(same, msg, testFilename)\n continue\n ## at this point both CSVs have the same shape, with the same header contents.\n ## align columns\n testCsv = testCsv[goldCsv.columns.tolist()]\n ## set marginal values to zero, fix infinites\n testCsv = self.prep_data_frame(testCsv, self._zero_threshold)\n goldCsv = self.prep_data_frame(goldCsv, self._zero_threshold)\n ## check for matching rows\n for idx in goldCsv.index:\n find = goldCsv.iloc[idx].rename(None)\n match = self.find_row(find, testCsv)\n if len(match) == 0:\n same = False\n msg.append(('Could not find match for row \"{}\" in '+\n 'Gold:\\n{}').format(idx+1, find)) #+1 because of header row\n msg.append('The Test output csv is:')\n msg.append(str(testCsv))\n # stop looking once a mismatch is found\n break\n self.finalizeMessage(same, msg, testFilename)\n return self._same, self._message\n\n def prep_data_frame(self, csv, tol):\n \"\"\"\n Does several prep actions:\n - For any columns that contain numbers, drop near-zero numbers to zero\n - replace infs and nans with symbolic values\n @ In, csv, pd.DataFrame, contents to reduce\n @ In, tol, float, tolerance sufficently near zero\n @ Out, csv, converted dataframe\n \"\"\"\n # use absolute or relative?\n key = {'atol':tol} if self._check_absolute_values else {'rtol':tol}\n # take care of infinites\n csv = csv.replace(np.inf, -sys.float_info.max)\n csv = csv.replace(np.nan, sys.float_info.max)\n for col in csv.columns:\n example = csv[col].values.item(0) if csv[col].values.shape[0] != 0 else None\n # skip columns that aren't numbers TODO might skip float columns with \"None\" early on\n if not mathUtils.isAFloatOrInt(example):\n continue\n # flatten near-zeros\n csv[col].values[np.isclose(csv[col].values, 0, **key)] = 0\n # TODO would like to sort here, but due to relative errors it doesn't do\n # enough good. Instead, sort in findRow.\n return csv\n\nclass UnorderedCSV(Differ):\n \"\"\"\n This is the class to use for handling the parameters block.\n \"\"\"\n\n @staticmethod\n def get_valid_params():\n \"\"\"\n Returns the valid parameters for this class.\n @ In, None\n @ Out, params, _ValidParameters, return the parameters.\n \"\"\"\n params = Differ.get_valid_params()\n params.add_param('rel_err', '', 'Relative Error for csv files')\n params.add_param('zero_threshold', sys.float_info.min*4.0,\n 'it represents the value below which a float is '+\n 'considered zero (XML comparison only)')\n params.add_param('ignore_sign', False, 'if true, then only compare the absolute values')\n params.add_param('check_absolute_value', False, 'if true the values are '+\n 'compared to the tolerance directectly, instead of relatively.')\n return params\n\n def __init__(self, name, params, testDir):\n \"\"\"\n Initializer for the class. Takes a String name and a dictionary params\n @ In, name, string, name of the test.\n @ In, params, dictionary, parameters for the class\n @ In, testDir, string, path to the test.\n @ Out, None.\n \"\"\"\n Differ.__init__(self, name, params, testDir)\n self._zero_threshold = self.specs['zero_threshold']\n self._ignore_sign = bool(self.specs['ignore_sign'])\n if len(self.specs['rel_err']) > 0:\n self._rel_err = float(self.specs['rel_err'])\n else:\n self._rel_err = 1e-10\n self._check_absolute_value = self.specs[\"check_absolute_value\"]\n\n def check_output(self):\n \"\"\"\n Checks that the output matches the gold.\n returns (same, message) where same is true if the\n test passes, or false if the test failes. message should\n gives a human readable explaination of the differences.\n @ In, None\n @ Out, (same, message), same is true if the tests passes.\n \"\"\"\n csvFiles = self._get_test_files()\n goldFiles = self._get_gold_files()\n csvDiff = UnorderedCSVDiffer(csvFiles,\n goldFiles,\n relativeError=self._rel_err,\n zeroThreshold=self._zero_threshold,\n ignoreSign=self._ignore_sign,\n absoluteCheck=self._check_absolute_value)\n return csvDiff.diff()\n"
] |
[
[
"sklearn.__version__.split"
],
[
"numpy.sign",
"pandas.read_csv",
"numpy.searchsorted",
"numpy.isclose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
mmlab-cv/ICIP-2021-2346
|
[
"d208a5b89acfb0405475664bc83d289d5c3eae33",
"d208a5b89acfb0405475664bc83d289d5c3eae33"
] |
[
"topview/results/make_latex_accuracies.py",
"topview/rgb_to_depth/FCRN_pytorch/dataloaders/dataloader.py"
] |
[
"import sys\nsys.path.append('../../')\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pathlib\n\nfrom accuracy import *\nfrom plot import *\n\ndef get_accuracy_for_joints(experiment, needed_acc = 0.1):\n current_file_path = pathlib.Path(__file__).parent.absolute()\n gt_file = f'{current_file_path}/res_files/{experiment}_gt.txt'\n pred_file = f'{current_file_path}/res_files/{experiment}_predictions.txt'\n\n gt = np.loadtxt(gt_file)\n gt = gt.reshape(gt.shape[0], -1, 3)\n\n pred = np.loadtxt(pred_file)\n pred = pred.reshape(pred.shape[0], -1, 3)\n\n dist, acc = compute_dist_acc_wrapper(pred, gt, max_dist=0.3, num=100)\n acc_ind = np.where(dist == needed_acc)\n return acc[:, acc_ind].flatten()\n\ndef create_accuracy_df_for_experiments(needed_acc = 0.1):\n results_acc = []\n for exp in [\"itop_itop_itop\", \"itop_itop_panoptic\", \"itop_both_panoptic\", \"panoptic_panoptic_panoptic\", \"panoptic_panoptic_itop\", \"panoptic_both_itop\", \"both_both_itop\", \"both_both_panoptic\"]:\n exp_acc = get_accuracy_for_joints(exp, needed_acc)\n res_acc = {f\"j{i+1}\": el for i, el in enumerate(exp_acc)}\n \n res_acc = {\n \"experiment\": exp,\n **res_acc,\n }\n\n results_acc.append(res_acc)\n df = pd.DataFrame(results_acc)\n df = df.round(3)\n return df\n\nprint(\"0.1m\")\nprint(create_accuracy_df_for_experiments(0.1).to_latex())\nprint(\"0.2m\")\nprint(create_accuracy_df_for_experiments(0.2).to_latex())",
"import os\nimport os.path\nimport numpy as np\nimport torch.utils.data as data\nimport h5py\nimport dataloaders.transforms as transforms\nimport cv2\n\nIMG_EXTENSIONS = ['.png', ]\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\ndef find_classes(dir):\n classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]\n classes.sort()\n class_to_idx = {classes[i]: i for i in range(len(classes))}\n return classes, class_to_idx\n\n\ndef make_dataset(dir, class_to_idx):\n images = []\n dir = os.path.expanduser(dir)\n subdirectories = os.listdir(dir)\n\n for target in subdirectories:\n d = os.path.join(dir, target)\n\n if not os.path.isdir(d):\n continue\n for root, _, fnames in sorted(os.walk(d)):\n for i, fname in enumerate(sorted(fnames)):\n #if i > 50:\n # continue\n\n if is_image_file(fname) and fname.find('_') > -1:\n path = os.path.join(root, fname)\n item = (path, class_to_idx[target])\n images.append(item)\n\n return images\n\n\ndef h5_loader(path):\n h5f = h5py.File(path, \"r\")\n rgb = np.array(h5f['rgb'])\n rgb = np.transpose(rgb, (1, 2, 0))\n depth = np.array(h5f['depth'])\n return rgb, depth\n\n\ndef substract(a, b):\n return \"\".join(a.rsplit(b))\n\n\ndef panoptic_loader(rgb_path):\n rgb = cv2.imread(rgb_path)\n\n rgb_file_name = rgb_path.split('/')[-1]\n num = rgb_file_name[:8]\n\n depth_path = f\"{substract(rgb_path, rgb_file_name)}/../depth/{num}.png\"\n depth = cv2.imread(depth_path, 0)\n\n return rgb, depth\n\n\n\n# def rgb2grayscale(rgb):\n# return rgb[:,:,0] * 0.2989 + rgb[:,:,1] * 0.587 + rgb[:,:,2] * 0.114\n\nto_tensor = transforms.ToTensor()\n\n\nclass MyDataloader(data.Dataset):\n modality_names = ['rgb', 'rgbd', 'd'] # , 'g', 'gd'\n color_jitter = transforms.ColorJitter(0.4, 0.4, 0.4)\n\n def __init__(self, root, type, sparsifier=None, modality='rgb', loader=panoptic_loader):\n classes, class_to_idx = find_classes(root)\n imgs = make_dataset(root, class_to_idx)\n assert len(imgs) > 0, \"Found 0 images in subfolders of: \" + root + \"\\n\"\n print(\"Found {} images in {} folder.\".format(len(imgs), type))\n self.root = root\n self.imgs = imgs\n self.classes = classes\n self.class_to_idx = class_to_idx\n if type == 'train' or type == 'val':\n self.transform = self.train_transform\n elif type == 'test':\n self.transform = self.val_transform\n else:\n raise (RuntimeError(\"Invalid dataset type: \" + type + \"\\n\"\n \"Supported dataset types are: train, val, test\"))\n self.loader = loader\n self.sparsifier = sparsifier\n\n assert (modality in self.modality_names), \"Invalid modality type: \" + modality + \"\\n\" + \\\n \"Supported dataset types are: \" + ''.join(self.modality_names)\n self.modality = modality\n\n def train_transform(self, rgb, depth):\n raise (RuntimeError(\"train_transform() is not implemented. \"))\n\n def val_transform(rgb, depth):\n raise (RuntimeError(\"val_transform() is not implemented.\"))\n\n def create_sparse_depth(self, rgb, depth):\n if self.sparsifier is None:\n return depth\n else:\n mask_keep = self.sparsifier.dense_to_sparse(rgb, depth)\n sparse_depth = np.zeros(depth.shape)\n sparse_depth[mask_keep] = depth[mask_keep]\n return sparse_depth\n\n def create_rgbd(self, rgb, depth):\n sparse_depth = self.create_sparse_depth(rgb, depth)\n rgbd = np.append(rgb, np.expand_dims(sparse_depth, axis=2), axis=2)\n return rgbd\n\n def __getraw__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (rgb, depth) the raw data.\n \"\"\"\n path, target = self.imgs[index]\n rgb, depth = self.loader(path)\n return rgb, depth\n\n def __getitem__(self, index):\n rgb, depth = self.__getraw__(index)\n if self.transform is not None:\n rgb_np, depth_np = self.transform(rgb, depth)\n else:\n raise (RuntimeError(\"transform not defined\"))\n\n if self.modality == 'rgb':\n input_np = rgb_np\n elif self.modality == 'rgbd':\n input_np = self.create_rgbd(rgb_np, depth_np)\n elif self.modality == 'd':\n input_np = self.create_sparse_depth(rgb_np, depth_np)\n\n input_tensor = to_tensor(input_np)\n while input_tensor.dim() < 3:\n input_tensor = input_tensor.unsqueeze(0)\n depth_tensor = to_tensor(depth_np)\n depth_tensor = depth_tensor.unsqueeze(0)\n\n return input_tensor, depth_tensor\n\n def __len__(self):\n return len(self.imgs)\n"
] |
[
[
"numpy.where",
"numpy.loadtxt",
"pandas.DataFrame"
],
[
"numpy.expand_dims",
"numpy.array",
"numpy.zeros",
"numpy.transpose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yejh90093/Py.finance
|
[
"e5c660970d4bb890cbf401d288d70829d3e6c966"
] |
[
"Tw.finance.py"
] |
[
"import os\n\nimport numpy\nimport requests\nimport datetime\nimport time\nimport math\nimport pandas as pd\nimport functions\nimport xlwt\nimport numpy as np\nfrom tqdm import tqdm\nimport gspread\nfrom gspread_dataframe import set_with_dataframe\nfrom oauth2client.service_account import ServiceAccountCredentials\n\ndebug_mode = False\nsave_local_file = False\njump_phase_two = False\nstart_index = 800\n\ncurrentDate = datetime.datetime.utcnow()\ndateStr = currentDate.strftime(\"%Y-%m-%d\") if not debug_mode else \"Debug-\" + currentDate.strftime(\"%Y-%m-%d\")\n\nscope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('tw-finance-f09c6b5d4a8c.json', scope)\ngc = gspread.authorize(credentials)\nsh = gc.open('Tw-finance')\n\ntry:\n if debug_mode:\n try:\n ws = sh.worksheet(dateStr)\n sh.del_worksheet(ws)\n print(\"Delete exist sheet: \" + dateStr)\n except:\n print(\"Create new sheet: \" + dateStr)\n\n ws = sh.add_worksheet(title=dateStr, rows='1000', cols='12')\nexcept Exception as e:\n print(e)\n print(\"Cannot add worksheet. Please check if the sheet already exist.\")\n exit(1)\n\n\npbar = tqdm(total=972)\nnow = datetime.datetime.now()\ndayStart = str(int(time.time()))\ndayEnd = str(int(time.time()) - 8640000)\nmonthEnd = str(int(time.time()) - 686400000)\n\nall = functions.readAll()\n\nresultDic = {}\nidArr = []\ntempArr = []\nnameArr = []\ndayWilliamsRArr = []\ndayRSIArr = []\nmonthRSIArr = []\nmonthMTMArr = []\nmonthDMIArr_plus = []\nmonthDMIArr_minus = []\nprocess = 0\n\n# print(all.keys())\n\nfor value in all.values:\n pbar.update(1)\n\n if debug_mode and pbar.n < start_index:\n continue\n\n tempArr.append(value[0])\n nameArr.append(value[1])\n\n responseDay = functions.getFinanceData(value[0], dayStart, dayEnd, \"1d\")\n try:\n dataArrayDay = functions.dataTextToArray(responseDay.text)\n except:\n sh.del_worksheet(ws)\n print()\n print(\"ERROR: dataTextToArray responseDay. Invalid cookie.\")\n break #exit(1)\n\n arrWilliamsR = functions.arrayWilliamsR(dataArrayDay, 50)\n arrRSI = functions.arrayRSI(dataArrayDay, 60)\n\n dayWilliamsR = arrWilliamsR[len(arrWilliamsR) - 1][9]\n dayRSI = arrRSI[len(arrRSI) - 1][7]\n\n dayWilliamsRArr.append(dayWilliamsR)\n dayRSIArr.append(dayRSI)\n\n responseMonth = functions.getFinanceData(value[0], dayStart, monthEnd, \"1mo\")\n\n try:\n dataArrayMonth = functions.dataTextToArray(responseMonth.text)\n except:\n sh.del_worksheet(ws)\n print()\n print(\"ERROR: dataTextToArray responseMonth. Invalid cookie.\")\n break #exit(1)\n\n arrSize = len(dataArrayMonth)\n if arrSize >= 2:\n if dataArrayMonth[arrSize - 1][2] < dataArrayMonth[arrSize - 2][2]:\n dataArrayMonth[arrSize - 1][2] = dataArrayMonth[arrSize - 2][2]\n if dataArrayMonth[arrSize - 1][3] > dataArrayMonth[arrSize - 2][3]:\n dataArrayMonth[arrSize - 1][3] = dataArrayMonth[arrSize - 2][3]\n\n dataArrayMonth = np.delete(dataArrayMonth, len(dataArrayMonth) - 2, axis=0)\n\n # print (responseMonth.text)\n # print (dataArrayMonth)\n\n arrRSIMonth = functions.arrayRSI(dataArrayMonth, 4)\n arrDMIMonth = functions.arrayDMI(dataArrayMonth, 1)\n arrMTMMonth = functions.arrayMTM(dataArrayMonth, 3, 2)\n if len(arrRSIMonth) <= 1:\n monthRSI = None\n else:\n monthRSI = arrRSIMonth[len(arrRSIMonth) - 1][7]\n\n if len(arrDMIMonth) <= 1:\n monthDMI = None\n else:\n monthDMI_plus = arrDMIMonth[len(arrDMIMonth) - 1][7]\n monthDMI_minus = arrDMIMonth[len(arrDMIMonth) - 1][8]\n\n if len(arrMTMMonth) <= 1:\n monthMTM = None\n else:\n monthMTM = arrMTMMonth[len(arrMTMMonth) - 1][9]\n\n monthRSIArr.append(monthRSI)\n monthMTMArr.append(monthMTM)\n monthDMIArr_plus.append(monthDMI_plus)\n monthDMIArr_minus.append(monthDMI_minus)\n\n process = process + 1\n\n if debug_mode and process > 30:\n break\n\nresultDic['monthRSI'] = monthRSIArr\nresultDic['monthMTM'] = monthMTMArr\nresultDic['monthDMI_plus'] = monthDMIArr_plus\nresultDic['monthDMI_minus'] = monthDMIArr_minus\nresultDic['dayRSI'] = dayRSIArr\nresultDic['dayWilliamsR'] = dayWilliamsRArr\nresultDic[all.keys()[1]] = nameArr\nresultDic[all.keys()[0]] = tempArr\n\nresultDF = pd.DataFrame(resultDic)\npbar.close()\n# print (resultDF)\n\n\nresultDF = resultDF.reindex(\n columns=['證券代號', '證券名稱', 'dayWilliamsR', 'dayRSI', 'monthRSI', 'monthDMI_plus', 'monthDMI_minus', 'monthMTM'])\naccordDic = resultDF[resultDF.monthRSI > 77]\naccordDic = accordDic[accordDic.dayRSI > 57]\naccordDic = accordDic[accordDic.dayWilliamsR < 20]\n\n# print(accordDic)\n\nif save_local_file:\n resultDF.to_excel('all_results_last.xls', sheet_name=dateStr)\n functions.append_df_to_excel('log_results.xlsx', accordDic, sheet_name=dateStr, index=False)\n\nset_with_dataframe(ws, accordDic, row=1, col=1, include_index=True, include_column_header=True)\n# print(accordDic)\n\nlistMACDWeekDiff = []\nlistMACDWeekDirection = []\n\npbar_MACD = tqdm(total=len(accordDic))\n\n\nfor index, row in accordDic.iterrows():\n # print(index, row['證券代號'], row['證券名稱'])\n responseWeek = functions.getFinanceData(row['證券代號'], dayStart, monthEnd, \"1mo\")\n\n try:\n dataArrayWeek = functions.dataTextToArray(responseWeek.text)\n except:\n # sh.del_worksheet(ws)\n print()\n print(\"ERROR: dataTextToArray responseMonth. Invalid cookie.\")\n exit(1)\n\n arrMACDWeek = functions.arrayMACD(dataArrayWeek, 12, 26, 9)\n if len(arrMACDWeek)>0:\n #print(arrMACDWeek[len(arrMACDWeek)-1])\n listMACDWeekDiff.append(arrMACDWeek[len(arrMACDWeek)-1][9])\n listMACDWeekDirection.append(arrMACDWeek[len(arrMACDWeek)-1][10])\n pbar_MACD.update(1)\n\naccordDic['MACD_Diff'] = list(pd.Series(listMACDWeekDiff))\naccordDic['MACD_Direction'] = list(pd.Series(listMACDWeekDirection))\n\n#print(accordDic)\nset_with_dataframe(ws, accordDic, row=1, col=1, include_index=True, include_column_header=True)\n\npbar_MACD.close()\n"
] |
[
[
"pandas.Series",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
ggzhang0071/Self-Supervised-Embedding-Fusion-Transformer
|
[
"91ad5276bf9a796b93a9f8f2200ce75747725fed"
] |
[
"validate.py"
] |
[
"#!/usr/bin/env python3 -u\n# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the LICENSE file in\n# the root directory of this source tree. An additional grant of patent rights\n# can be found in the PATENTS file in the same directory.\n\nimport torch\n\nfrom fairseq import checkpoint_utils, options, progress_bar, utils\n\n\ndef main(args, override_args=None):\n utils.import_user_module(args)\n\n use_fp16 = args.fp16\n use_cuda = torch.cuda.is_available() and not args.cpu\n\n \n\n if override_args is not None:\n overrides = vars(override_args)\n overrides.update(eval(getattr(override_args, 'model_overrides', '{}')))\n else:\n overrides = None\n\n # Load ensemble\n print('| loading model(s) from {}'.format(args.path))\n models, model_args, task = checkpoint_utils.load_model_ensemble_and_task(\n [args.path],\n arg_overrides=overrides,\n )\n model = models[0]\n\n \n\n # Move models to GPU\n for model in models:\n if use_fp16:\n model.half()\n if use_cuda:\n model.cuda()\n\n # Print args\n print(model_args)\n\n # Build criterion\n criterion = task.build_criterion(model_args)\n criterion.eval()\n\n # Load valid dataset (we load training data below, based on the latest checkpoint)\n for subset in args.valid_subset.split(','):\n try:\n task.load_dataset(subset, combine=False, epoch=0)\n dataset = task.dataset(subset)\n except KeyError:\n raise Exception('Cannot find dataset: ' + subset)\n\n # Initialize data iterator\n itr = task.get_batch_iterator(\n dataset=dataset,\n max_tokens=args.max_tokens,\n max_sentences=args.max_sentences,\n max_positions=utils.resolve_max_positions(\n task.max_positions(),\n *[m.max_positions() for m in models],\n ),\n ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test,\n required_batch_size_multiple=args.required_batch_size_multiple,\n seed=args.seed,\n num_workers=args.num_workers,\n ).next_epoch_itr(shuffle=False)\n progress = progress_bar.build_progress_bar(\n args, itr,\n prefix='valid on \\'{}\\' subset'.format(subset),\n no_progress_bar='simple'\n )\n\n log_outputs = []\n for i, sample in enumerate(progress):\n sample = utils.move_to_cuda(sample) if use_cuda else sample\n _loss, _sample_size, log_output = task.valid_step(sample, model, criterion)\n \n progress.log(log_output, step=i)\n log_outputs.append(log_output)\n\n log_output = task.aggregate_logging_outputs(log_outputs, criterion)\n\n progress.print(log_output, tag=subset, step=i)\n\n\ndef cli_main():\n parser = options.get_validation_parser()\n args = options.parse_args_and_arch(parser)\n\n # only override args that are explicitly given on the command line\n override_parser = options.get_validation_parser()\n override_args = options.parse_args_and_arch(override_parser, suppress_defaults=True)\n\n main(args, override_args)\n\n\nif __name__ == '__main__':\n cli_main()\n"
] |
[
[
"torch.cuda.is_available"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dmorrill10/research2018
|
[
"3604e3fb774f6d882e41cc217ceb85038d3775e5",
"3604e3fb774f6d882e41cc217ceb85038d3775e5"
] |
[
"research2018/test/tabular_cfr_test.py",
"research2018/test/mnist_test.py"
] |
[
"import tensorflow as tf\ntf.compat.v1.enable_eager_execution()\nfrom research2018.tabular_cfr import TabularCfr, TabularCfrCurrent\n\n\nclass TabularCfrTest(tf.test.TestCase):\n def setUp(self):\n tf.random.set_seed(42)\n\n def test_zeros(self):\n num_info_sets = 2\n num_actions = 3\n patient = TabularCfr.zeros(num_info_sets, num_actions)\n self.assertAllClose(\n tf.fill([num_info_sets, num_actions], 1.0 / num_actions),\n patient.cur())\n self.assertAllClose(\n tf.fill([num_info_sets, num_actions], 1.0 / num_actions),\n patient.avg())\n self.assertAllClose(\n tf.fill([num_info_sets, num_actions], 1.0 / num_actions),\n patient.policy())\n\n def test_update(self):\n num_info_sets = 2\n num_actions = 3\n patient = TabularCfr(\n TabularCfrCurrent(\n tf.random.normal(shape=[num_info_sets, num_actions])),\n tf.zeros([num_info_sets, num_actions]))\n\n initial_cur = tf.constant([[0.50621, 0., 0.49379],\n [0.333333, 0.333333, 0.333333]])\n self.assertAllClose(initial_cur, patient.cur())\n self.assertAllClose(\n tf.fill([num_info_sets, num_actions], 1.0 / num_actions),\n patient.avg())\n self.assertAllClose(\n tf.fill([num_info_sets, num_actions], 1.0 / num_actions),\n patient.policy())\n\n def env(policy):\n return tf.random.normal(\n shape=[num_info_sets, num_actions]) * policy\n\n patient.update(env)\n\n next_cur = tf.constant([[0.39514, 0., 0.60486],\n [0.333333, 0.333333, 0.333333]])\n self.assertAllClose(next_cur, patient.cur())\n self.assertAllClose(initial_cur, patient.avg())\n self.assertAllClose(initial_cur, patient.policy())\n\n patient.update(env)\n\n next_next_cur = [[0., 0., 1.], [0.333333, 0.333333, 0.333333]]\n self.assertAllClose(next_next_cur, patient.cur())\n self.assertAllClose((initial_cur + next_cur) / 2.0, patient.avg())\n self.assertAllClose((initial_cur + next_cur) / 2.0, patient.policy())\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"import tensorflow as tf\nfrom research2018 import mnist\n\n\nclass MnistTest(tf.test.TestCase):\n def test_new_training_dataset_and_normalizer(self):\n for constant_reward in [None, 0.5]:\n mnist.new_training_dataset_and_normalizer(constant_reward)\n\n def test_subtract_mean_scale_to_zero_one_data_normalizer(self):\n data, normalizer = mnist.new_training_dataset_and_normalizer()\n normalized_x = normalizer(data.x)\n self.assertAlmostEqual(0.0, tf.reduce_mean(normalized_x).numpy())\n self.assertLessEqual(tf.reduce_max(tf.abs(normalized_x)).numpy(), 1.0)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.fill",
"tensorflow.constant",
"tensorflow.zeros",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.test.main",
"tensorflow.random.normal",
"tensorflow.random.set_seed"
],
[
"tensorflow.test.main",
"tensorflow.abs",
"tensorflow.reduce_mean"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.4",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.2",
"1.2",
"2.10"
]
}
] |
feynfan13/transtory
|
[
"4dd48033fdcd95b4a0dbc19f5b26d15b4b533979"
] |
[
"transtory/shanghaimetro/publicdata.py"
] |
[
"import os\nimport pandas as pd\n\nfrom transtory.common import singleton\nfrom .configs import get_configs, ShmSysConfigs\n\n\nclass ShmPublicData(object):\n \"\"\"Public data, including\n -- Lines\n -- Stations\n -- Trains\n \"\"\"\n train_json_name = 'trains.json'\n\n def __init__(self):\n self.train_vs_type = None\n\n @staticmethod\n def _get_train_sn_from_line_and_seq(line, seq, gen=None):\n if gen is None:\n return '{:s}{:03d}'.format(line, seq)\n else:\n return '{:s}{:03d}-{:02d}'.format(line, seq, gen)\n\n def _add_train_and_type_in_sn_range(self, line, train_type: str, sn_range, gen=None):\n seq_list = range(sn_range[0], sn_range[1] + 1)\n for seq in seq_list:\n self.train_line_type_list[0].append(self._get_train_sn_from_line_and_seq(line, seq, gen))\n self.train_line_type_list[1].append(line)\n self.train_line_type_list[2].append(train_type)\n\n def get_train_vs_type_table(self):\n if self.train_vs_type is None:\n self.train_vs_type = self._make_train_vs_type_table()\n return self.train_vs_type\n\n def _load_train_table_from_json(self):\n configs: ShmSysConfigs = get_configs()\n json_path = os.sep.join([configs.publicdata_folder, self.train_json_name])\n\n def _make_train_vs_type_table(self):\n self.train_line_type_list = [[], [], []]\n # Line 01\n self._add_train_and_type_in_sn_range('01', \"01A01-01\", (1, 1))\n self._add_train_and_type_in_sn_range('01', \"01A01-02\", (2, 2))\n self._add_train_and_type_in_sn_range('01', \"01A01-01\", (3, 10))\n self._add_train_and_type_in_sn_range('01', \"01A03\", (11, 13))\n self._add_train_and_type_in_sn_range('01', \"01A01-01\", (14, 14))\n self._add_train_and_type_in_sn_range('01', \"01A03\", (15, 16))\n self._add_train_and_type_in_sn_range('01', \"01A02-02\", (17, 17))\n self._add_train_and_type_in_sn_range('01', \"01A02-01\", (18, 25))\n self._add_train_and_type_in_sn_range('01', \"01A04-01\", (26, 29))\n self._add_train_and_type_in_sn_range('01', \"01A04-02\", (30, 37))\n self._add_train_and_type_in_sn_range('01', \"01A05\", (40, 55))\n self._add_train_and_type_in_sn_range('01', \"01A06\", (56, 66))\n self._add_train_and_type_in_sn_range('01', \"01A06\", (67, 86))\n # Line 02\n self._add_train_and_type_in_sn_range('02', '02A01', (1, 16))\n self._add_train_and_type_in_sn_range('02', '02A02', (33, 53))\n self._add_train_and_type_in_sn_range('02', '02A03', (54, 69))\n self._add_train_and_type_in_sn_range('02', '02A04-01', (70, 85), 1)\n self._add_train_and_type_in_sn_range('02', '02A04', (70, 85))\n self._add_train_and_type_in_sn_range('02', '02A05', (86, 116))\n # Line 03\n self._add_train_and_type_in_sn_range('03', \"03A01\", (1, 28))\n self._add_train_and_type_in_sn_range('03', \"03A02&04A02\", (29, 36))\n # Train 37-49 is borrowed from Line 04 and patched to 03xxx\n # We use 04xxx when registering the respective trips\n # Line 04\n self._add_train_and_type_in_sn_range('04', \"04A01\", (1, 2)) # Siemens\n self._add_train_and_type_in_sn_range('04', \"04A01\", (3, 28)) # 南车株洲\n self._add_train_and_type_in_sn_range('04', \"03A02&04A02\", (29, 29)) # 中车长春\n self._add_train_and_type_in_sn_range('04', \"03A02&04A02\", (30, 36)) # Alstom上海\n self._add_train_and_type_in_sn_range('04', \"03A02&04A02\", (37, 49)) # Alstom上海\n self._add_train_and_type_in_sn_range('04', \"03A02&04A02\", (50, 55)) # Alstom上海\n # Line 05\n self._add_train_and_type_in_sn_range('05', \"05C01\", (1, 13))\n self._add_train_and_type_in_sn_range('05', \"05C01\", (15, 18))\n self._add_train_and_type_in_sn_range('05', \"05C02\", (19, 51))\n # Line 06\n self._add_train_and_type_in_sn_range('06', \"06C01\", (1, 3))\n self._add_train_and_type_in_sn_range('06', \"06C01\", (5, 13))\n self._add_train_and_type_in_sn_range('06', \"06C01\", (15, 23))\n self._add_train_and_type_in_sn_range('06', \"06C02\", (25, 33))\n self._add_train_and_type_in_sn_range('06', \"06C02\", (35, 36))\n self._add_train_and_type_in_sn_range('06', \"06C03\", (37, 43))\n self._add_train_and_type_in_sn_range('06', \"06C03\", (45, 53))\n self._add_train_and_type_in_sn_range('06', \"06C03\", (55, 56))\n self._add_train_and_type_in_sn_range('06', \"06C04\", (57, 82))\n # Line 07\n self._add_train_and_type_in_sn_range('07', \"07A01\", (1, 42))\n self._add_train_and_type_in_sn_range('07', \"07A02\", (43, 72))\n self._add_train_and_type_in_sn_range('07', \"07A03\", (73, 79))\n # Line 08\n self._add_train_and_type_in_sn_range('08', \"08C01\", (1, 28))\n self._add_train_and_type_in_sn_range('08', \"08C02\", (29, 45))\n self._add_train_and_type_in_sn_range('08', \"08C03\", (46, 66))\n self._add_train_and_type_in_sn_range('08', \"08C04\", (67, 90))\n # Line 09\n self._add_train_and_type_in_sn_range('09', \"09A01\", (1, 10))\n self._add_train_and_type_in_sn_range('09', \"09A02\", (11, 51))\n self._add_train_and_type_in_sn_range('09', \"09A03\", (53, 88))\n self._add_train_and_type_in_sn_range('09', \"09A04\", (89, 105))\n # Line 10\n self._add_train_and_type_in_sn_range('10', \"10A01\", (1, 41))\n self._add_train_and_type_in_sn_range('10', \"10A02\", (42, 67))\n # Line 11\n self._add_train_and_type_in_sn_range('11', \"11A01\", (1, 66))\n self._add_train_and_type_in_sn_range('11', \"11A02\", (67, 72))\n self._add_train_and_type_in_sn_range('11', \"11A03\", (73, 82))\n # Line 12\n self._add_train_and_type_in_sn_range('12', \"12A01\", (1, 41))\n self._add_train_and_type_in_sn_range('12', \"12A02\", (42, 56))\n self._add_train_and_type_in_sn_range('12', \"12A03\", (57, 75))\n # Line 13\n self._add_train_and_type_in_sn_range('13', \"13A01\", (1, 24))\n self._add_train_and_type_in_sn_range('13', \"13A02\", (25, 62))\n # Line 14\n self._add_train_and_type_in_sn_range('14', \"14A01\", (1, 49))\n # Line 15\n self._add_train_and_type_in_sn_range('15', \"15A01\", (1, 54))\n # Line 16\n self._add_train_and_type_in_sn_range('16', \"16A01\", (1, 46))\n self._add_train_and_type_in_sn_range('16', \"16A02\", (47, 61))\n # Line 17\n self._add_train_and_type_in_sn_range('17', \"17A01\", (1, 5))\n self._add_train_and_type_in_sn_range('17', \"17A01\", (6, 28))\n # Line 18\n self._add_train_and_type_in_sn_range('18', \"18A01\", (1, 50))\n # Line T01\n self._add_train_and_type_in_sn_range('T01', 'APM300', (1, 11))\n\n train_vs_type_df = pd.DataFrame.from_dict(data={'train': self.train_line_type_list[0],\n 'line': self.train_line_type_list[1],\n 'type': self.train_line_type_list[2]})\n train_vs_type_df.index = train_vs_type_df['train']\n return train_vs_type_df\n\n\nget_public_data = singleton(ShmPublicData)\n\n\nclass ShmPublicDataApp(object):\n instance = None\n\n def __init__(self):\n self.public_data: ShmPublicData = get_public_data()\n\n @classmethod\n def get_instance(cls):\n if cls.instance is None:\n cls.instance = ShmPublicDataApp()\n return cls.instance\n\n def get_type_of_train(self, train_sn):\n query_table = self.public_data.get_train_vs_type_table()\n # Include the case of updated trains\n if '-' in train_sn:\n train_sn = train_sn.split('-')[0]\n return query_table.loc[train_sn, 'type']\n\n def get_train_type_list(self):\n train_table = self.public_data.get_train_vs_type_table()\n train_type_list = train_table.groupby(by='type')['train'].count()\n return train_type_list\n\n def get_train_df(self):\n return self.public_data.train_vs_type\n\n def get_line_list(self):\n train_table = self.public_data.get_train_vs_type_table()\n line_list = train_table['line'].unique()\n return line_list\n\n def get_trains_of_line(self, line_str):\n train_df = self.public_data.get_train_vs_type_table()\n return train_df[train_df['line'] == int(line_str)]\n\n @staticmethod\n def get_train_sn(line: str, seq: int):\n \"\"\"Get train sn from line and number in line\n Before 2017-12, number takes two digits, such as 0101.\n Currently, with expanding rolling stocks and lines, number can be\n -- for main lines, 2-digit line number + 3-digit train sequence number, such as 01001.\n -- for minor lines, 3-alphadigit line number + 3-digit train sequence number, such as T01001.\n \"\"\"\n # return \"{:2d}{:2d}\".format(line, number)\n return '{:s}{:3d}'.format(line, seq)\n\n @staticmethod\n def get_line_and_seq_from_train_sn(train_sn):\n if train_sn[0].isalpha(): # minor lines, such as APM\n sep_loc = 3\n else: # main lines, such as Line 1\n sep_loc = 2\n return train_sn[0:sep_loc], int(train_sn[sep_loc:])\n\n\nget_public_data_app = singleton(ShmPublicDataApp)\n"
] |
[
[
"pandas.DataFrame.from_dict"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
colincsl/pyKinectTools
|
[
"a84bb5b7ff9dd613576415932865c2ad435520b3"
] |
[
"pyKinectTools/utils/AlignCameras.py"
] |
[
"''' Use this file to hand register multiple depth cameras with the 3D visualizer\n\nProcedure:\n1) Modify the scrip below for your files\n2) After adding points, click the mayavi button in the window and add Transformation to the scene. Drag the second points to the transformation.\n3) Manually match the two scenes\n4) Click red button \"Start/Stop Script Recording\". Transform a tiny bit so that you see the transformation matrix\n5) Write down/save the transformation matrix\n'''\n\nfrom pyKinectTools.utils.DepthUtils import *\nfrom scipy.misc import imread\nfrom mayavi import mlab\nfrom mayavi.api import Engine\nimport cPickle as pickle\n\n\n''' ---- Transforms ---\nICUDec2012 data:\n#3->2:\ttransform_data.transform.matrix.__setstate__({'elements': [0.9553782053802112, -0.09691967661345026, 0.27903236545178867, -392.81878278215254, 0.09283849668727677, 0.9952919671849423, 0.02783726980083738, 231.6724797545669, -0.2804166511056782, -0.0006901755293638524, 0.9598781305147085, -118.84124965680712, 0.0, 0.0, 0.0, 1.0]})\n#1->2:\ttransform_data2.transform.matrix.__setstate__({'elements': [-0.8531195226064485, -0.08215320378328564, 0.5152066878990207, 761.2299809410998, 0.3177589268248827, 0.7014041249433673, 0.6380137286418792, 1427.5420972165339, -0.4137829679564377, 0.7080134918351199, -0.5722766383564786, -3399.696025885259, 0.0, 0.0, 0.0, 1.0]})\n\nOffice 23Feb2013\ntop->bottom view\n#1->2 [0.9955555989899513, 0.03914715069837748, 0.08565366257179756, 240.34720254711863,\n\t\t-0.08535684788048972, 0.7593599156829527, 0.6450478485925556, 1305.7428154935583,\n\t\t-0.039790172651939335, -0.6494921239292868, 0.759326493093817, -237.20556423494145,\n\t\t0.0, 0.0, 0.0, 1.0]})\n '''\n\n'''\nICUDec2012\nbase_dir1 = '/media/Data/ICU_Dec2012/ICU_Dec2012_r40_c1/depth/356/14/1/'\nbase_dir23 = '/media/Data/ICU_Dec2012/ICU_Dec2012_r40_c2/depth/356/14/0/'\n\ndepthFile1 = base_dir1+'device_1/'+'depth_356_14_1_55_00_95.png'\ndepthFile2 = base_dir23+'device_1/'+'depth_356_14_0_10_01_44.png'\ndepthFile3 = base_dir23+'device_2/'+'depth_356_14_0_10_00_48.png'\n'''\n\n'''\n# Office_25Feb2013\nbase_dir = '/Users/colin/Data/Office_25Feb2013/depth/56/17/31/'\ndepthFile1 = base_dir+'device_1/'+'depth_56_17_31_0_00_506677.png'\ndepthFile2 = base_dir+'device_2/'+'depth_56_17_31_0_00_510469.png'\n'''\n'''\n# CIRL_28Feb2013\nbase_dir = '/Users/colin/Data/CIRL_28Feb2013/depth/59/13/42/'\ndepthFile1 = base_dir+'device_1/'+'depth_59_13_42_0_00_364016.png'\ndepthFile2 = base_dir+'device_2/'+'depth_59_13_42_0_00_645072.png'\n\nresult:\nT = np.array([[0.857551855717905, 0.11935353392976167, 0.5003594195108932, -1053.586999301418],\n\t\t\t[0.1430128492517155, 0.8790419590510106, -0.45478847740098743, 1081.8626448851123],\n\t\t\t[-0.4941175363248235, 0.4615625289885183, 0.736754974282534, 1295.7083313896273],\n\t\t\t[0.0, 0.0, 0.0, 1.0]])\n'''\n\n'''\n# JHU CIRL pod\nbase_dir = '/Users/colin/Data/JHU_RGBD_Pose/CIRL_P1/depth/100/11/15/'\ndepthFile1 = base_dir+'device_1/'+'depth_100_11_15_59_13_725918.png'\ndepthFile2 = base_dir+'device_2/'+'depth_100_11_15_59_13_395133.png'\n\nresult:\nT = np.array([[0.857551855717905, 0.11935353392976167, 0.5003594195108932, -1053.586999301418],\n\t\t\t[0.1430128492517155, 0.8790419590510106, -0.45478847740098743, 1081.8626448851123],\n\t\t\t[-0.4941175363248235, 0.4615625289885183, 0.736754974282534, 1295.7083313896273],\n\t\t\t[0.0, 0.0, 0.0, 1.0]])\n'''\n\n\n\n''' --------------------Main setup-------------------------------- '''\n\ndepthIm1 = imread(depthFile1)\ndepthIm2 = imread(depthFile2)\npts1 = depthIm2XYZ(depthIm1).astype(np.int)\npts2 = depthIm2XYZ(depthIm2).astype(np.int)\n\nengine = Engine()\nengine.start()\n\nfigure = mlab.figure(1, bgcolor=(0,0,0), fgcolor=(1,1,1))\nmlab.clf()\nfigure.scene.disable_render = True\n\ninterval = 40 # Don't show all points (otherwise it's slow!)\npts = np.array([x for x in pts1 if x[2] > -93500])\npts = np.vstack([[0,0,1], pts])\nptsViz1 = mlab.points3d(pts[::interval,0], pts[::interval,1], pts[::interval,2], 2.-(np.minimum(pts[::interval,2], 5000)/float((-pts[:,2]).max()))/1000., scale_factor=30., colormap='summer')\npts = np.array([x for x in pts2 if x[2] > -93500])\npts = np.vstack([[0,0,1], pts])\nptsViz1 = mlab.points3d(pts[::interval,0], pts[::interval,1], pts[::interval,2], 2.-(np.minimum(pts[::interval,2], 5000)/float((-pts[:,2]).max()))/1000., scale_factor=30., colormap='Blues')\n\n\n# Copy description and transform here as 4x4 matrix\n# e.g.\nfilename = 'Registration.dat'\ndescription = \"JHU CIRL Pod Bottom (good) cam to top (bad) cam\"\nT = np.array([[0.857551855717905, 0.11935353392976167, 0.5003594195108932, -1053.586999301418],\n\t\t\t\t[0.1430128492517155, 0.8790419590510106, -0.45478847740098743, 1081.8626448851123],\n\t\t\t\t[-0.4941175363248235, 0.4615625289885183, 0.736754974282534, 1295.7083313896273],\n\t\t\t\t[0.0, 0.0, 0.0, 1.0]])\n# save\npickle.dump({'description':description, 'transform':T}, open(filename, 'w'))\n\n\n\n''' --------------------------------------------------------- '''\n''' ------------------- Fine Tuning ------------------------- '''\n''' --------------------------------------------------------- '''\nfrom mayavi.filters.transform_data import TransformData\n\ndepthIm1 = imread(depthFile1)\ndepthIm2 = imread(depthFile2)\ndepthIm3 = imread(depthFile3)\n\n''' Put all in the frame of 2 '''\n\npts1 = depthIm2XYZ(depthIm1)#.astype(np.int)\npts2 = depthIm2XYZ(depthIm2)#.astype(np.int)\npts3 = depthIm2XYZ(depthIm3).astype(np.int)\n\np1 = depthIm2PosIm(depthIm1)\np2 = depthIm2PosIm(depthIm2)\np3 = depthIm2PosIm(depthIm3)\n\n'''3DViz'''\n\nengine = Engine()\nengine.start()\n\nfigure = mlab.figure(1, bgcolor=(0,0,0), fgcolor=(1,1,1))\nmlab.clf()\nfigure.scene.disable_render = True\n\ninterval = 15\n\n'''2'''\npts = np.array([x for x in pts2 if x[2] > -93500])\nptsViz1 = mlab.points3d(pts[::interval,0], pts[::interval,1], pts[::interval,2], 2.-(np.minimum(pts[::interval,2], 5000)/float((-pts[:,2]).max()))/1000., scale_factor=10., colormap='Blues')\n'''3'''\npts = np.array([x for x in pts3 if x[2] > -93500])\nptsViz2 = mlab.points3d(pts[::interval,0], pts[::interval,1], pts[::interval,2], 2.-(np.minimum(pts[::interval,2], 5000)/float((-pts[:,2]).max()))/1000., scale_factor=10., colormap='PuOr')\n\ntransform_data = TransformData()\nengine.add_filter(transform_data, engine.scenes[0].children[1])\ntransform_data.children = [engine.scenes[0].children[1].children[0]]\n# engine.scenes[0].children[1].children[0]=[]\n\ntransform_data.transform.matrix.__setstate__({'elements': [0.9553782053802112, -0.09691967661345026, 0.27903236545178867, -392.81878278215254, 0.09283849668727677, 0.9952919671849423, 0.02783726980083738, 231.6724797545669, -0.2804166511056782, -0.0006901755293638524, 0.9598781305147085, -118.84124965680712, 0.0, 0.0, 0.0, 1.0]})\ntransform_data.widget.set_transform(transform_data.transform)\ntransform_data.filter.update()\ntransform_data.widget.enabled = False\n\n'''1'''\npts = np.array([x for x in pts1 if x[2] > -93500])\nptsViz1 = mlab.points3d(pts[::interval,0], pts[::interval,1], pts[::interval,2], 2.-(np.minimum(pts[::interval,2], 5000)/float((-pts[:,2]).max()))/1000., scale_factor=10., colormap='summer')\nmlab.view(azimuth=0, elevation=0, distance=3000., focalpoint=(0,0,0), figure=figure)#, reset_roll=False)\nfigure.scene.disable_render = False\n\ntransform_data2 = TransformData()\nengine.add_filter(transform_data2, engine.scenes[0].children[2])\ntransform_data2.children = [engine.scenes[0].children[2].children[0]]\n# engine.scenes[0].children[2].children[0]=[]\n\n\ntransform_data2.transform.matrix.__setstate__({'elements': [-0.8531195226064485, -0.08215320378328564, 0.5152066878990207, 761.2299809410998, 0.3177589268248827, 0.7014041249433673, 0.6380137286418792, 1427.5420972165339, -0.4137829679564377, 0.7080134918351199, -0.5722766383564786, -3399.696025885259, 0.0, 0.0, 0.0, 1.0]})\ntransform_data2.widget.set_transform(transform_data1.transform)\ntransform_data2.filter.update()\ntransform_data2.widget.enabled = False\n\n\n'''\nmlab.view(azimuth=0, elevation=0, distance=3000., focalpoint=(0,0,0), figure=figure)#, reset_roll=False)\n\n'''\n"
] |
[
[
"scipy.misc.imread"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"1.0",
"0.19",
"0.18",
"1.2",
"0.12",
"0.10",
"0.17",
"0.16"
],
"tensorflow": []
}
] |
mhwasil/pointcloud_classification
|
[
"c4dd36db556087cc90dca16e31958adfd3641482"
] |
[
"models/pointcnn.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, '../../utils/pointcnn'))\n\nimport math\nimport pointfly as pf\nimport tensorflow as tf\n\n\ndef xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, with_X_transformation, depth_multiplier,\n sorting_method=None, with_global=False):\n _, indices_dilated = pf.knn_indices_general(qrs, pts, K * D, True)\n indices = indices_dilated[:, :, ::D, :]\n\n if sorting_method is not None:\n indices = pf.sort_points(pts, indices, sorting_method)\n\n nn_pts = tf.gather_nd(pts, indices, name=tag + 'nn_pts') # (N, P, K, 3)\n nn_pts_center = tf.expand_dims(qrs, axis=2, name=tag + 'nn_pts_center') # (N, P, 1, 3)\n nn_pts_local = tf.subtract(nn_pts, nn_pts_center, name=tag + 'nn_pts_local') # (N, P, K, 3)\n\n # Prepare features to be transformed\n nn_fts_from_pts_0 = pf.dense(nn_pts_local, C_pts_fts, tag + 'nn_fts_from_pts_0', is_training)\n nn_fts_from_pts = pf.dense(nn_fts_from_pts_0, C_pts_fts, tag + 'nn_fts_from_pts', is_training)\n if fts is None:\n nn_fts_input = nn_fts_from_pts\n else:\n nn_fts_from_prev = tf.gather_nd(fts, indices, name=tag + 'nn_fts_from_prev')\n nn_fts_input = tf.concat([nn_fts_from_pts, nn_fts_from_prev], axis=-1, name=tag + 'nn_fts_input')\n\n if with_X_transformation:\n ######################## X-transformation #########################\n X_0 = pf.conv2d(nn_pts_local, K * K, tag + 'X_0', is_training, (1, K))\n X_0_KK = tf.reshape(X_0, (N, P, K, K), name=tag + 'X_0_KK')\n X_1 = pf.depthwise_conv2d(X_0_KK, K, tag + 'X_1', is_training, (1, K))\n X_1_KK = tf.reshape(X_1, (N, P, K, K), name=tag + 'X_1_KK')\n X_2 = pf.depthwise_conv2d(X_1_KK, K, tag + 'X_2', is_training, (1, K), activation=None)\n X_2_KK = tf.reshape(X_2, (N, P, K, K), name=tag + 'X_2_KK')\n fts_X = tf.matmul(X_2_KK, nn_fts_input, name=tag + 'fts_X')\n ###################################################################\n else:\n fts_X = nn_fts_input\n\n fts_conv = pf.separable_conv2d(fts_X, C, tag + 'fts_conv', is_training, (1, K), depth_multiplier=depth_multiplier)\n fts_conv_3d = tf.squeeze(fts_conv, axis=2, name=tag + 'fts_conv_3d')\n\n if with_global:\n fts_global_0 = pf.dense(qrs, C // 4, tag + 'fts_global_0', is_training)\n fts_global = pf.dense(fts_global_0, C // 4, tag + 'fts_global', is_training)\n return tf.concat([fts_global, fts_conv_3d], axis=-1, name=tag + 'fts_conv_3d_with_global')\n else:\n return fts_conv_3d\n\n\nclass PointCNN:\n def __init__(self, points, features, is_training, setting):\n xconv_params = setting.xconv_params\n fc_params = setting.fc_params\n with_X_transformation = setting.with_X_transformation\n sorting_method = setting.sorting_method\n N = tf.shape(points)[0]\n\n if setting.sampling == 'fps':\n from sampling import tf_sampling\n\n self.layer_pts = [points]\n if features is None:\n self.layer_fts = [features]\n else:\n features = tf.reshape(features, (N, -1, setting.data_dim - 3), name='features_reshape')\n C_fts = xconv_params[0]['C'] // 2\n features_hd = pf.dense(features, C_fts, 'features_hd', is_training)\n self.layer_fts = [features_hd]\n\n for layer_idx, layer_param in enumerate(xconv_params):\n tag = 'xconv_' + str(layer_idx + 1) + '_'\n K = layer_param['K']\n D = layer_param['D']\n P = layer_param['P']\n C = layer_param['C']\n links = layer_param['links']\n if setting.sampling != 'random' and links:\n print('Error: flexible links are supported only when random sampling is used!')\n exit()\n\n # get k-nearest points\n pts = self.layer_pts[-1]\n fts = self.layer_fts[-1]\n if P == -1 or (layer_idx > 0 and P == xconv_params[layer_idx - 1]['P']):\n qrs = self.layer_pts[-1]\n else:\n if setting.sampling == 'fps':\n fps_indices = tf_sampling.farthest_point_sample(P, pts)\n batch_indices = tf.tile(tf.reshape(tf.range(N), (-1, 1, 1)), (1, P, 1))\n indices = tf.concat([batch_indices, tf.expand_dims(fps_indices,-1)], axis=-1)\n qrs = tf.gather_nd(pts, indices, name= tag + 'qrs') # (N, P, 3)\n elif setting.sampling == 'ids':\n indices = pf.inverse_density_sampling(pts, K, P)\n qrs = tf.gather_nd(pts, indices)\n elif setting.sampling == 'random':\n qrs = tf.slice(pts, (0, 0, 0), (-1, P, -1), name=tag + 'qrs') # (N, P, 3)\n else:\n print('Unknown sampling method!')\n exit()\n self.layer_pts.append(qrs)\n\n if layer_idx == 0:\n C_pts_fts = C // 2 if fts is None else C // 4\n depth_multiplier = 4\n else:\n C_prev = xconv_params[layer_idx - 1]['C']\n C_pts_fts = C_prev // 4\n depth_multiplier = math.ceil(C / C_prev)\n with_global = (setting.with_global and layer_idx == len(xconv_params) - 1)\n fts_xconv = xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, with_X_transformation,\n depth_multiplier, sorting_method, with_global)\n fts_list = []\n for link in links:\n fts_from_link = self.layer_fts[link]\n if fts_from_link is not None:\n fts_slice = tf.slice(fts_from_link, (0, 0, 0), (-1, P, -1), name=tag + 'fts_slice_' + str(-link))\n fts_list.append(fts_slice)\n if fts_list:\n fts_list.append(fts_xconv)\n self.layer_fts.append(tf.concat(fts_list, axis=-1, name=tag + 'fts_list_concat'))\n else:\n self.layer_fts.append(fts_xconv)\n\n if hasattr(setting, 'xdconv_params'):\n for layer_idx, layer_param in enumerate(setting.xdconv_params):\n tag = 'xdconv_' + str(layer_idx + 1) + '_'\n K = layer_param['K']\n D = layer_param['D']\n pts_layer_idx = layer_param['pts_layer_idx']\n qrs_layer_idx = layer_param['qrs_layer_idx']\n\n pts = self.layer_pts[pts_layer_idx + 1]\n fts = self.layer_fts[pts_layer_idx + 1] if layer_idx == 0 else self.layer_fts[-1]\n qrs = self.layer_pts[qrs_layer_idx + 1]\n fts_qrs = self.layer_fts[qrs_layer_idx + 1]\n P = xconv_params[qrs_layer_idx]['P']\n C = xconv_params[qrs_layer_idx]['C']\n C_prev = xconv_params[pts_layer_idx]['C']\n C_pts_fts = C_prev // 4\n depth_multiplier = 1\n fts_xdconv = xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, with_X_transformation,\n depth_multiplier, sorting_method)\n fts_concat = tf.concat([fts_xdconv, fts_qrs], axis=-1, name=tag + 'fts_concat')\n fts_fuse = pf.dense(fts_concat, C, tag + 'fts_fuse', is_training)\n self.layer_pts.append(qrs)\n self.layer_fts.append(fts_fuse)\n\n self.fc_layers = [self.layer_fts[-1]]\n for layer_idx, layer_param in enumerate(fc_params):\n C = layer_param['C']\n dropout_rate = layer_param['dropout_rate']\n fc = pf.dense(self.fc_layers[-1], C, 'fc{:d}'.format(layer_idx), is_training)\n fc_drop = tf.layers.dropout(fc, dropout_rate, training=is_training, name='fc{:d}_drop'.format(layer_idx))\n self.fc_layers.append(fc_drop)\n\nclass PointCNN_SEG:\n def __init__(self, points, features, is_training, setting):\n xconv_params = setting.xconv_params\n fc_params_classification = setting.fc_params_classification\n fc_params_segmentation = setting.fc_params_segmentation\n with_X_transformation = setting.with_X_transformation\n sorting_method = setting.sorting_method\n N = tf.shape(points)[0]\n\n if setting.sampling == 'fps':\n from sampling import tf_sampling\n\n self.layer_pts = [points]\n if features is None:\n self.layer_fts = [features]\n else:\n features = tf.reshape(features, (N, -1, setting.data_dim - 3), name='features_reshape')\n C_fts = xconv_params[0]['C'] // 2\n features_hd = pf.dense(features, C_fts, 'features_hd', is_training)\n self.layer_fts = [features_hd]\n\n for layer_idx, layer_param in enumerate(xconv_params):\n tag = 'xconv_' + str(layer_idx + 1) + '_'\n K = layer_param['K']\n D = layer_param['D']\n P = layer_param['P']\n C = layer_param['C']\n links = layer_param['links']\n if setting.sampling != 'random' and links:\n print('Error: flexible links are supported only when random sampling is used!')\n exit()\n\n # get k-nearest points\n pts = self.layer_pts[-1]\n fts = self.layer_fts[-1]\n if P == -1 or (layer_idx > 0 and P == xconv_params[layer_idx - 1]['P']):\n qrs = self.layer_pts[-1]\n else:\n if setting.sampling == 'fps':\n fps_indices = tf_sampling.farthest_point_sample(P, pts)\n batch_indices = tf.tile(tf.reshape(tf.range(N), (-1, 1, 1)), (1, P, 1))\n indices = tf.concat([batch_indices, tf.expand_dims(fps_indices,-1)], axis=-1)\n qrs = tf.gather_nd(pts, indices, name= tag + 'qrs') # (N, P, 3)\n elif setting.sampling == 'ids':\n indices = pf.inverse_density_sampling(pts, K, P)\n qrs = tf.gather_nd(pts, indices)\n elif setting.sampling == 'random':\n qrs = tf.slice(pts, (0, 0, 0), (-1, P, -1), name=tag + 'qrs') # (N, P, 3)\n else:\n print('Unknown sampling method!')\n exit()\n self.layer_pts.append(qrs)\n\n if layer_idx == 0:\n C_pts_fts = C // 2 if fts is None else C // 4\n depth_multiplier = 4\n else:\n C_prev = xconv_params[layer_idx - 1]['C']\n C_pts_fts = C_prev // 4\n depth_multiplier = math.ceil(C / C_prev)\n with_global = (setting.with_global and layer_idx == len(xconv_params) - 1)\n fts_xconv = xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, with_X_transformation,\n depth_multiplier, sorting_method, with_global)\n fts_list = []\n for link in links:\n fts_from_link = self.layer_fts[link]\n if fts_from_link is not None:\n fts_slice = tf.slice(fts_from_link, (0, 0, 0), (-1, P, -1), name=tag + 'fts_slice_' + str(-link))\n fts_list.append(fts_slice)\n if fts_list:\n fts_list.append(fts_xconv)\n self.layer_fts.append(tf.concat(fts_list, axis=-1, name=tag + 'fts_list_concat'))\n else:\n self.layer_fts.append(fts_xconv)\n\n #######Classification Branch\n self.fc_layers_classification = [self.layer_fts[-1]]\n for layer_idx, layer_param in enumerate(fc_params_classification):\n C = layer_param['C']\n dropout_rate = layer_param['dropout_rate']\n fc = pf.dense(self.fc_layers_classification[-1], C, 'fc_class_{:d}'.format(layer_idx), is_training)\n fc_drop = tf.layers.dropout(fc, dropout_rate, training=is_training, name='fc_class_{:d}_drop'.format(layer_idx))\n self.fc_layers_classification.append(fc_drop) \n \n\n #######Segmentation Branch\n if hasattr(setting, 'xdconv_params'):\n for layer_idx, layer_param in enumerate(setting.xdconv_params):\n tag = 'xdconv_' + str(layer_idx + 1) + '_'\n K = layer_param['K']\n D = layer_param['D']\n pts_layer_idx = layer_param['pts_layer_idx']\n qrs_layer_idx = layer_param['qrs_layer_idx']\n\n pts = self.layer_pts[pts_layer_idx + 1]\n fts = self.layer_fts[pts_layer_idx + 1] if layer_idx == 0 else self.layer_fts[-1]\n qrs = self.layer_pts[qrs_layer_idx + 1]\n fts_qrs = self.layer_fts[qrs_layer_idx + 1]\n P = xconv_params[qrs_layer_idx]['P']\n C = xconv_params[qrs_layer_idx]['C']\n C_prev = xconv_params[pts_layer_idx]['C']\n C_pts_fts = C_prev // 4\n depth_multiplier = 1\n fts_xdconv = xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, with_X_transformation,\n depth_multiplier, sorting_method)\n fts_concat = tf.concat([fts_xdconv, fts_qrs], axis=-1, name=tag + 'fts_concat')\n fts_fuse = pf.dense(fts_concat, C, tag + 'fts_fuse', is_training)\n self.layer_pts.append(qrs)\n self.layer_fts.append(fts_fuse)\n\n self.fc_layers_segmentation = [self.layer_fts[-1]]\n for layer_idx, layer_param in enumerate(fc_params_segmentation):\n C = layer_param['C']\n dropout_rate = layer_param['dropout_rate']\n fc = pf.dense(self.fc_layers_segmentation[-1], C, 'fc_seg_{:d}'.format(layer_idx), is_training)\n fc_drop = tf.layers.dropout(fc, dropout_rate, training=is_training, name='fc_seg_{:d}_drop'.format(layer_idx))\n self.fc_layers_segmentation.append(fc_drop)"
] |
[
[
"tensorflow.matmul",
"tensorflow.concat",
"tensorflow.gather_nd",
"tensorflow.range",
"tensorflow.shape",
"tensorflow.slice",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.squeeze",
"tensorflow.subtract"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"1.0",
"1.2"
]
}
] |
zhengxxn/adaptive-knn-mt
|
[
"338ec0ddf02ed80b5cd4cbae922ad0ebe93e8339",
"d81142405076a4d322985936316cfff9d2460273"
] |
[
"experimental_generate.py",
"fairseq/data/dictionary.py"
] |
[
"#!/usr/bin/env python3 -u\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"\"\"\nTranslate pre-processed data with a trained model.\n\"\"\"\n\nimport ast\nimport logging\nimport math\nimport os\nimport sys\nfrom itertools import chain\n\nimport numpy as np\nimport torch\nfrom fairseq import checkpoint_utils, options, scoring, tasks, utils\nfrom fairseq.logging import progress_bar\nfrom fairseq.logging.meters import StopwatchMeter, TimeMeter\n\n\ndef main(args):\n assert args.path is not None, \"--path required for generation!\"\n assert (\n not args.sampling or args.nbest == args.beam\n ), \"--sampling requires --nbest to be equal to --beam\"\n assert (\n args.replace_unk is None or args.dataset_impl == \"raw\"\n ), \"--replace-unk requires a raw text dataset (--dataset-impl=raw)\"\n\n if args.results_path is not None:\n os.makedirs(args.results_path, exist_ok=True)\n output_path = os.path.join(\n args.results_path, \"generate-{}.txt\".format(args.gen_subset)\n )\n with open(output_path, \"w\", buffering=1, encoding=\"utf-8\") as h:\n return _main(args, h)\n else:\n return _main(args, sys.stdout)\n\n\ndef get_symbols_to_strip_from_output(generator):\n if hasattr(generator, \"symbols_to_strip_from_output\"):\n return generator.symbols_to_strip_from_output\n else:\n return {generator.eos}\n\n\ndef _main(args, output_file):\n logging.basicConfig(\n format=\"%(asctime)s | %(levelname)s | %(name)s | %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n level=os.environ.get(\"LOGLEVEL\", \"INFO\").upper(),\n stream=output_file,\n )\n logger = logging.getLogger(\"fairseq_cli.generate\")\n\n utils.import_user_module(args)\n\n if args.max_tokens is None and args.batch_size is None:\n args.max_tokens = 12000\n logger.info(args)\n\n # Fix seed for stochastic decoding\n if args.seed is not None and not args.no_seed_provided:\n np.random.seed(args.seed)\n utils.set_torch_seed(args.seed)\n\n use_cuda = torch.cuda.is_available() and not args.cpu\n\n # Load dataset splits\n task = tasks.setup_task(args)\n task.load_dataset(args.gen_subset)\n\n # Set dictionaries\n try:\n src_dict = getattr(task, \"source_dictionary\", None)\n except NotImplementedError:\n src_dict = None\n tgt_dict = task.target_dictionary\n\n print('---------')\n overrides = ast.literal_eval(args.model_overrides)\n print('---------', overrides)\n\n # Load ensemble\n logger.info(\"loading model(s) from {}\".format(args.path))\n models, _model_args = checkpoint_utils.load_model_ensemble(\n utils.split_paths(args.path),\n arg_overrides=overrides,\n task=task,\n suffix=getattr(args, \"checkpoint_suffix\", \"\"),\n strict=(args.checkpoint_shard_count == 1),\n num_shards=args.checkpoint_shard_count,\n )\n print(_model_args)\n\n if args.lm_path is not None:\n overrides[\"data\"] = args.data\n\n try:\n lms, _ = checkpoint_utils.load_model_ensemble(\n [args.lm_path],\n arg_overrides=overrides,\n task=None,\n )\n except:\n logger.warning(\n f\"Failed to load language model! Please make sure that the language model dict is the same \"\n f\"as target dict and is located in the data dir ({args.data})\"\n )\n raise\n\n assert len(lms) == 1\n else:\n lms = [None]\n\n # Optimize ensemble for generation\n for model in chain(models, lms):\n if model is None:\n continue\n if args.fp16:\n model.half()\n if use_cuda and not args.pipeline_model_parallel:\n model.cuda()\n model.prepare_for_inference_(args)\n\n # Load alignment dictionary for unknown word replacement\n # (None if no unknown word replacement, empty if no path to align dictionary)\n align_dict = utils.load_align_dict(args.replace_unk)\n\n # Load dataset (possibly sharded)\n itr = task.get_batch_iterator(\n dataset=task.dataset(args.gen_subset),\n max_tokens=args.max_tokens,\n max_sentences=args.batch_size,\n max_positions=utils.resolve_max_positions(\n task.max_positions(), *[model.max_positions() for model in models]\n ),\n ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test,\n required_batch_size_multiple=args.required_batch_size_multiple,\n num_shards=args.num_shards,\n shard_id=args.shard_id,\n num_workers=args.num_workers,\n data_buffer_size=args.data_buffer_size,\n ).next_epoch_itr(shuffle=False)\n progress = progress_bar.progress_bar(\n itr,\n log_format=args.log_format,\n log_interval=args.log_interval,\n default_log_format=(\"tqdm\" if not args.no_progress_bar else \"none\"),\n )\n\n # Initialize generator\n gen_timer = StopwatchMeter()\n\n extra_gen_cls_kwargs = {\"lm_model\": lms[0], \"lm_weight\": args.lm_weight, \"knn_record_distance\": args.knn_record_distance,\n \"knn_record_index\": args.knn_record_index, \"knn_record_lambda\": args.knn_record_lambda,\n \"knn_record_label_counts\": args.knn_record_label_counts}\n generator = task.build_generator(\n models, args, extra_gen_cls_kwargs=extra_gen_cls_kwargs\n )\n\n # Handle tokenization and BPE\n tokenizer = task.build_tokenizer(args)\n bpe = task.build_bpe(args)\n\n def decode_fn(x):\n if bpe is not None:\n x = bpe.decode(x)\n if tokenizer is not None:\n x = tokenizer.decode(x)\n return x\n\n scorer = scoring.build_scorer(args, tgt_dict)\n\n num_sentences = 0\n has_target = True\n wps_meter = TimeMeter()\n for sample in progress:\n sample = utils.move_to_cuda(sample) if use_cuda else sample\n if \"net_input\" not in sample:\n continue\n\n prefix_tokens = None\n if args.prefix_size > 0:\n prefix_tokens = sample[\"target\"][:, : args.prefix_size]\n\n constraints = None\n if \"constraints\" in sample:\n constraints = sample[\"constraints\"]\n\n gen_timer.start()\n hypos = task.inference_step(\n generator,\n models,\n sample,\n prefix_tokens=prefix_tokens,\n constraints=constraints,\n )\n num_generated_tokens = sum(len(h[0][\"tokens\"]) for h in hypos)\n gen_timer.stop(num_generated_tokens)\n\n for i, sample_id in enumerate(sample[\"id\"].tolist()):\n has_target = sample[\"target\"] is not None\n\n # Remove padding\n if \"src_tokens\" in sample[\"net_input\"]:\n src_tokens = utils.strip_pad(\n sample[\"net_input\"][\"src_tokens\"][i, :], tgt_dict.pad()\n )\n else:\n src_tokens = None\n\n target_tokens = None\n if has_target:\n target_tokens = (\n utils.strip_pad(sample[\"target\"][i, :], tgt_dict.pad()).int().cpu()\n )\n\n # Either retrieve the original sentences or regenerate them from tokens.\n if align_dict is not None:\n src_str = task.dataset(args.gen_subset).src.get_original_text(sample_id)\n target_str = task.dataset(args.gen_subset).tgt.get_original_text(\n sample_id\n )\n else:\n if src_dict is not None:\n src_str = src_dict.string(src_tokens, args.remove_bpe)\n else:\n src_str = \"\"\n if has_target:\n target_str = tgt_dict.string(\n target_tokens,\n args.remove_bpe,\n escape_unk=True,\n extra_symbols_to_ignore=get_symbols_to_strip_from_output(\n generator\n ),\n )\n\n src_str = decode_fn(src_str)\n if has_target:\n target_str = decode_fn(target_str)\n\n if not args.quiet:\n if src_dict is not None:\n print(\"S-{}\\t{}\".format(sample_id, src_str), file=output_file)\n if has_target:\n print(\"T-{}\\t{}\".format(sample_id, target_str), file=output_file)\n\n # Process top predictions\n for j, hypo in enumerate(hypos[i][: args.nbest]):\n hypo_tokens, hypo_str, alignment = utils.post_process_prediction(\n hypo_tokens=hypo[\"tokens\"].int().cpu(),\n src_str=src_str,\n alignment=hypo[\"alignment\"],\n align_dict=align_dict,\n tgt_dict=tgt_dict,\n remove_bpe=args.remove_bpe,\n extra_symbols_to_ignore=get_symbols_to_strip_from_output(generator),\n )\n detok_hypo_str = decode_fn(hypo_str)\n if not args.quiet:\n score = hypo[\"score\"] / math.log(2) # convert to base 2\n # original hypothesis (after tokenization and BPE)\n print(\n \"H-{}\\t{}\\t{}\".format(sample_id, score, hypo_str),\n file=output_file,\n )\n # detokenized hypothesis\n print(\n \"D-{}\\t{}\\t{}\".format(sample_id, score, detok_hypo_str),\n file=output_file,\n )\n print(\n \"P-{}\\t{}\".format(\n sample_id,\n \" \".join(\n map(\n lambda x: \"{:.4f}\".format(x),\n # convert from base e to base 2\n hypo[\"positional_scores\"]\n .div_(math.log(2))\n .tolist(),\n )\n ),\n ),\n file=output_file,\n )\n\n if args.knn_record_distance:\n min_distance = hypo[\"knn_distance\"][0].tolist()\n avg_distance = torch.mean(hypo[\"knn_distance\"], dim=0).tolist()\n print(\"M-{}\\t{}\".format(sample_id, \" \".join([str(int(elem)) for elem in min_distance])), file=output_file)\n print(\"A-{}\\t{}\".format(sample_id, \" \".join([str(int(elem)) for elem in avg_distance])), file=output_file)\n\n if args.knn_record_label_counts:\n print(\"N-{}\\t{}\".format(sample_id, \" \".\n join([str(elem) for elem in hypo[\"knn_label_counts\"].squeeze(0).tolist()])),\n file=output_file)\n\n if args.knn_record_lambda:\n print(\"L-{}\\t{}\".format(sample_id, \" \".\n join([str(round(elem, 2)) for elem in hypo[\"knn_lambda\"].squeeze(0).tolist()])),\n file=output_file)\n\n if args.print_alignment:\n print(\n \"A-{}\\t{}\".format(\n sample_id,\n \" \".join(\n [\n \"{}-{}\".format(src_idx, tgt_idx)\n for src_idx, tgt_idx in alignment\n ]\n ),\n ),\n file=output_file,\n )\n\n if args.print_step:\n print(\n \"I-{}\\t{}\".format(sample_id, hypo[\"steps\"]),\n file=output_file,\n )\n\n if getattr(args, \"retain_iter_history\", False):\n for step, h in enumerate(hypo[\"history\"]):\n _, h_str, _ = utils.post_process_prediction(\n hypo_tokens=h[\"tokens\"].int().cpu(),\n src_str=src_str,\n alignment=None,\n align_dict=None,\n tgt_dict=tgt_dict,\n remove_bpe=None,\n )\n print(\n \"E-{}_{}\\t{}\".format(sample_id, step, h_str),\n file=output_file,\n )\n\n # Score only the top hypothesis\n if has_target and j == 0:\n if align_dict is not None or args.remove_bpe is not None:\n # Convert back to tokens for evaluation with unk replacement and/or without BPE\n target_tokens = tgt_dict.encode_line(\n target_str, add_if_not_exist=True\n )\n hypo_tokens = tgt_dict.encode_line(\n detok_hypo_str, add_if_not_exist=True\n )\n if hasattr(scorer, \"add_string\"):\n scorer.add_string(target_str, detok_hypo_str)\n else:\n scorer.add(target_tokens, hypo_tokens)\n\n wps_meter.update(num_generated_tokens)\n progress.log({\"wps\": round(wps_meter.avg)})\n num_sentences += (\n sample[\"nsentences\"] if \"nsentences\" in sample else sample[\"id\"].numel()\n )\n\n logger.info(\"NOTE: hypothesis and token scores are output in base 2\")\n logger.info(\n \"Translated {} sentences ({} tokens) in {:.1f}s ({:.2f} sentences/s, {:.2f} tokens/s)\".format(\n num_sentences,\n gen_timer.n,\n gen_timer.sum,\n num_sentences / gen_timer.sum,\n 1.0 / gen_timer.avg,\n )\n )\n if has_target:\n if args.bpe and not args.sacrebleu:\n if args.remove_bpe:\n logger.warning(\n \"BLEU score is being computed by splitting detokenized string on spaces, this is probably not what you want. Use --sacrebleu for standard 13a BLEU tokenization\"\n )\n else:\n logger.warning(\n \"If you are using BPE on the target side, the BLEU score is computed on BPE tokens, not on proper words. Use --sacrebleu for standard 13a BLEU tokenization\"\n )\n # use print to be consistent with other main outputs: S-, H-, T-, D- and so on\n print(\n \"Generate {} with beam={}: {}\".format(\n args.gen_subset, args.beam, scorer.result_string()\n ),\n file=output_file,\n )\n\n return scorer\n\n\ndef cli_main():\n parser = options.get_experimental_generation_parser()\n args = options.parse_args_and_arch(parser)\n main(args)\n\n\nif __name__ == \"__main__\":\n cli_main()\n",
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nfrom collections import Counter\nfrom multiprocessing import Pool\n\nimport torch\nfrom fairseq import utils\nfrom fairseq.binarizer import safe_readline\nfrom fairseq.data import data_utils\nfrom fairseq.file_io import PathManager\nfrom fairseq.tokenizer import tokenize_line\n\n\nclass Dictionary(object):\n \"\"\"A mapping from symbols to consecutive integers\"\"\"\n\n def __init__(\n self,\n *, # begin keyword-only arguments\n bos=\"<s>\",\n pad=\"<pad>\",\n eos=\"</s>\",\n unk=\"<unk>\",\n extra_special_symbols=None,\n ):\n self.bos_word, self.unk_word, self.pad_word, self.eos_word = bos, unk, pad, eos\n self.symbols = []\n self.count = []\n self.indices = {}\n self.bos_index = self.add_symbol(bos)\n self.pad_index = self.add_symbol(pad)\n self.eos_index = self.add_symbol(eos)\n self.unk_index = self.add_symbol(unk)\n if extra_special_symbols:\n for s in extra_special_symbols:\n self.add_symbol(s)\n self.nspecial = len(self.symbols)\n\n def __eq__(self, other):\n return self.indices == other.indices\n\n def __getitem__(self, idx):\n if idx < len(self.symbols):\n return self.symbols[idx]\n return self.unk_word\n\n def __len__(self):\n \"\"\"Returns the number of symbols in the dictionary\"\"\"\n return len(self.symbols)\n\n def __contains__(self, sym):\n return sym in self.indices\n\n def index(self, sym):\n \"\"\"Returns the index of the specified symbol\"\"\"\n assert isinstance(sym, str)\n if sym in self.indices:\n return self.indices[sym]\n return self.unk_index\n\n def string(\n self,\n tensor,\n bpe_symbol=None,\n escape_unk=False,\n extra_symbols_to_ignore=None,\n unk_string=None,\n return_list=False,\n ):\n \"\"\"Helper for converting a tensor of token indices to a string.\n\n Can optionally remove BPE symbols or escape <unk> words.\n \"\"\"\n if torch.is_tensor(tensor) and tensor.dim() == 2:\n if return_list:\n return [self.string(t, bpe_symbol, escape_unk, extra_symbols_to_ignore) for t in tensor]\n else:\n return \"\\n\".join(\n self.string(t, bpe_symbol, escape_unk, extra_symbols_to_ignore)\n for t in tensor\n )\n\n extra_symbols_to_ignore = set(extra_symbols_to_ignore or [])\n extra_symbols_to_ignore.add(self.eos())\n\n def token_string(i):\n if i == self.unk():\n if unk_string is not None:\n return unk_string\n else:\n return self.unk_string(escape_unk)\n else:\n return self[i]\n\n if hasattr(self, \"bos_index\"):\n extra_symbols_to_ignore.add(self.bos())\n\n sent = \" \".join(\n token_string(i)\n for i in tensor\n if utils.item(i) not in extra_symbols_to_ignore\n )\n\n return data_utils.post_process(sent, bpe_symbol)\n\n def unk_string(self, escape=False):\n \"\"\"Return unknown string, optionally escaped as: <<unk>>\"\"\"\n if escape:\n return \"<{}>\".format(self.unk_word)\n else:\n return self.unk_word\n\n def add_symbol(self, word, n=1, overwrite=False):\n \"\"\"Adds a word to the dictionary\"\"\"\n if word in self.indices and not overwrite:\n idx = self.indices[word]\n self.count[idx] = self.count[idx] + n\n return idx\n else:\n idx = len(self.symbols)\n self.indices[word] = idx\n self.symbols.append(word)\n self.count.append(n)\n return idx\n\n def update(self, new_dict):\n \"\"\"Updates counts from new dictionary.\"\"\"\n for word in new_dict.symbols:\n idx2 = new_dict.indices[word]\n if word in self.indices:\n idx = self.indices[word]\n self.count[idx] = self.count[idx] + new_dict.count[idx2]\n else:\n idx = len(self.symbols)\n self.indices[word] = idx\n self.symbols.append(word)\n self.count.append(new_dict.count[idx2])\n\n def finalize(self, threshold=-1, nwords=-1, padding_factor=8):\n \"\"\"Sort symbols by frequency in descending order, ignoring special ones.\n\n Args:\n - threshold defines the minimum word count\n - nwords defines the total number of words in the final dictionary,\n including special symbols\n - padding_factor can be used to pad the dictionary size to be a\n multiple of 8, which is important on some hardware (e.g., Nvidia\n Tensor Cores).\n \"\"\"\n if nwords <= 0:\n nwords = len(self)\n\n new_indices = dict(zip(self.symbols[: self.nspecial], range(self.nspecial)))\n new_symbols = self.symbols[: self.nspecial]\n new_count = self.count[: self.nspecial]\n\n c = Counter(\n dict(\n sorted(zip(self.symbols[self.nspecial :], self.count[self.nspecial :]))\n )\n )\n for symbol, count in c.most_common(nwords - self.nspecial):\n if count >= threshold:\n new_indices[symbol] = len(new_symbols)\n new_symbols.append(symbol)\n new_count.append(count)\n else:\n break\n\n assert len(new_symbols) == len(new_indices)\n\n self.count = list(new_count)\n self.symbols = list(new_symbols)\n self.indices = new_indices\n\n self.pad_to_multiple_(padding_factor)\n\n def pad_to_multiple_(self, padding_factor):\n \"\"\"Pad Dictionary size to be a multiple of *padding_factor*.\"\"\"\n if padding_factor > 1:\n i = 0\n while len(self) % padding_factor != 0:\n symbol = \"madeupword{:04d}\".format(i)\n self.add_symbol(symbol, n=0)\n i += 1\n\n def bos(self):\n \"\"\"Helper to get index of beginning-of-sentence symbol\"\"\"\n return self.bos_index\n\n def pad(self):\n \"\"\"Helper to get index of pad symbol\"\"\"\n return self.pad_index\n\n def eos(self):\n \"\"\"Helper to get index of end-of-sentence symbol\"\"\"\n return self.eos_index\n\n def unk(self):\n \"\"\"Helper to get index of unk symbol\"\"\"\n return self.unk_index\n\n @classmethod\n def load(cls, f):\n \"\"\"Loads the dictionary from a text file with the format:\n\n ```\n <symbol0> <count0>\n <symbol1> <count1>\n ...\n ```\n \"\"\"\n d = cls()\n d.add_from_file(f)\n return d\n\n def add_from_file(self, f):\n \"\"\"\n Loads a pre-existing dictionary from a text file and adds its symbols\n to this instance.\n \"\"\"\n if isinstance(f, str):\n try:\n with open(PathManager.get_local_path(f), \"r\", encoding=\"utf-8\") as fd:\n self.add_from_file(fd)\n except FileNotFoundError as fnfe:\n raise fnfe\n except UnicodeError:\n raise Exception(\n \"Incorrect encoding detected in {}, please \"\n \"rebuild the dataset\".format(f)\n )\n return\n\n lines = f.readlines()\n indices_start_line = self._load_meta(lines)\n\n for line in lines[indices_start_line:]:\n try:\n line, field = line.rstrip().rsplit(\" \", 1)\n if field == \"#fairseq:overwrite\":\n overwrite = True\n line, field = line.rsplit(\" \", 1)\n else:\n overwrite = False\n count = int(field)\n word = line\n if word in self and not overwrite:\n raise RuntimeError(\n \"Duplicate word found when loading Dictionary: '{}'. \"\n \"Duplicate words can overwrite earlier ones by adding the \"\n \"#fairseq:overwrite flag at the end of the corresponding row \"\n \"in the dictionary file. If using the Camembert model, please \"\n \"download an updated copy of the model file.\".format(word)\n )\n self.add_symbol(word, n=count, overwrite=overwrite)\n except ValueError:\n raise ValueError(\n \"Incorrect dictionary format, expected '<token> <cnt> [flags]'\"\n )\n\n def _save(self, f, kv_iterator):\n if isinstance(f, str):\n PathManager.mkdirs(os.path.dirname(f))\n with PathManager.open(f, \"w\", encoding=\"utf-8\") as fd:\n return self.save(fd)\n for k, v in kv_iterator:\n print(\"{} {}\".format(k, v), file=f)\n\n def _get_meta(self):\n return [], []\n\n def _load_meta(self, lines):\n return 0\n\n def save(self, f):\n \"\"\"Stores dictionary into a text file\"\"\"\n ex_keys, ex_vals = self._get_meta()\n self._save(\n f,\n zip(\n ex_keys + self.symbols[self.nspecial :],\n ex_vals + self.count[self.nspecial :],\n ),\n )\n\n def dummy_sentence(self, length):\n t = torch.Tensor(length).uniform_(self.nspecial + 1, len(self)).long()\n t[-1] = self.eos()\n return t\n\n def encode_line(\n self,\n line,\n line_tokenizer=tokenize_line,\n add_if_not_exist=True,\n consumer=None,\n append_eos=True,\n reverse_order=False,\n ):\n words = line_tokenizer(line)\n if reverse_order:\n words = list(reversed(words))\n nwords = len(words)\n ids = torch.IntTensor(nwords + 1 if append_eos else nwords)\n\n for i, word in enumerate(words):\n if add_if_not_exist:\n idx = self.add_symbol(word)\n else:\n idx = self.index(word)\n if consumer is not None:\n consumer(word, idx)\n ids[i] = idx\n if append_eos:\n ids[nwords] = self.eos_index\n return ids\n\n @staticmethod\n def _add_file_to_dictionary_single_worker(\n filename, tokenize, eos_word, worker_id=0, num_workers=1\n ):\n counter = Counter()\n with open(PathManager.get_local_path(filename), \"r\", encoding=\"utf-8\") as f:\n size = os.fstat(f.fileno()).st_size\n chunk_size = size // num_workers\n offset = worker_id * chunk_size\n end = offset + chunk_size\n f.seek(offset)\n if offset > 0:\n safe_readline(f) # drop first incomplete line\n line = f.readline()\n while line:\n for word in tokenize(line):\n counter.update([word])\n counter.update([eos_word])\n if f.tell() > end:\n break\n line = f.readline()\n return counter\n\n @staticmethod\n def add_file_to_dictionary(filename, dict, tokenize, num_workers):\n def merge_result(counter):\n for w, c in sorted(counter.items()):\n dict.add_symbol(w, c)\n\n if num_workers > 1:\n pool = Pool(processes=num_workers)\n results = []\n for worker_id in range(num_workers):\n results.append(\n pool.apply_async(\n Dictionary._add_file_to_dictionary_single_worker,\n (filename, tokenize, dict.eos_word, worker_id, num_workers),\n )\n )\n pool.close()\n pool.join()\n for r in results:\n merge_result(r.get())\n else:\n merge_result(\n Dictionary._add_file_to_dictionary_single_worker(\n filename, tokenize, dict.eos_word\n )\n )\n\n\nclass TruncatedDictionary(object):\n def __init__(self, wrapped_dict, length):\n self.__class__ = type(\n wrapped_dict.__class__.__name__,\n (self.__class__, wrapped_dict.__class__),\n {},\n )\n self.__dict__ = wrapped_dict.__dict__\n self.wrapped_dict = wrapped_dict\n self.length = min(len(self.wrapped_dict), length)\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, i):\n if i < self.length:\n return self.wrapped_dict[i]\n return self.wrapped_dict.unk()\n"
] |
[
[
"torch.mean",
"torch.cuda.is_available",
"numpy.random.seed"
],
[
"torch.is_tensor",
"torch.Tensor",
"torch.IntTensor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ajsanjoaquin/pytorch-YOLOv4
|
[
"dbc10cdc43668f29647ea2019ec13c4109d590c1"
] |
[
"tool/darknet2pytorch.py"
] |
[
"import torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom tool.region_loss import RegionLoss\nfrom tool.yolo_layer import YoloLayer\nfrom tool.config import *\nfrom tool.torch_utils import *\n\n\nclass Mish(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n x = x * (torch.tanh(torch.nn.functional.softplus(x)))\n return x\n\n\nclass MaxPoolDark(nn.Module):\n def __init__(self, size=2, stride=1):\n super(MaxPoolDark, self).__init__()\n self.size = size\n self.stride = stride\n\n def forward(self, x):\n '''\n darknet output_size = (input_size + p - k) / s +1\n p : padding = k - 1\n k : size\n s : stride\n torch output_size = (input_size + 2*p -k) / s +1\n p : padding = k//2\n '''\n p = self.size // 2\n if ((x.shape[2] - 1) // self.stride) != ((x.shape[2] + 2 * p - self.size) // self.stride):\n padding1 = (self.size - 1) // 2\n padding2 = padding1 + 1\n else:\n padding1 = (self.size - 1) // 2\n padding2 = padding1\n if ((x.shape[3] - 1) // self.stride) != ((x.shape[3] + 2 * p - self.size) // self.stride):\n padding3 = (self.size - 1) // 2\n padding4 = padding3 + 1\n else:\n padding3 = (self.size - 1) // 2\n padding4 = padding3\n x = F.max_pool2d(F.pad(x, (padding3, padding4, padding1, padding2), mode='replicate'),\n self.size, stride=self.stride)\n return x\n\n\nclass Upsample_expand(nn.Module):\n def __init__(self, stride=2):\n super(Upsample_expand, self).__init__()\n self.stride = stride\n\n def forward(self, x):\n assert (x.data.dim() == 4)\n \n x = x.view(x.size(0), x.size(1), x.size(2), 1, x.size(3), 1).\\\n expand(x.size(0), x.size(1), x.size(2), self.stride, x.size(3), self.stride).contiguous().\\\n view(x.size(0), x.size(1), x.size(2) * self.stride, x.size(3) * self.stride)\n\n return x\n\n\nclass Upsample_interpolate(nn.Module):\n def __init__(self, stride):\n super(Upsample_interpolate, self).__init__()\n self.stride = stride\n\n def forward(self, x):\n assert (x.data.dim() == 4)\n\n out = F.interpolate(x, size=(x.size(2) * self.stride, x.size(3) * self.stride), mode='nearest')\n return out\n\n\nclass Reorg(nn.Module):\n def __init__(self, stride=2):\n super(Reorg, self).__init__()\n self.stride = stride\n\n def forward(self, x):\n stride = self.stride\n assert (x.data.dim() == 4)\n B = x.data.size(0)\n C = x.data.size(1)\n H = x.data.size(2)\n W = x.data.size(3)\n assert (H % stride == 0)\n assert (W % stride == 0)\n ws = stride\n hs = stride\n x = x.view(B, C, H / hs, hs, W / ws, ws).transpose(3, 4).contiguous()\n x = x.view(B, C, H / hs * W / ws, hs * ws).transpose(2, 3).contiguous()\n x = x.view(B, C, hs * ws, H / hs, W / ws).transpose(1, 2).contiguous()\n x = x.view(B, hs * ws * C, H / hs, W / ws)\n return x\n\n\nclass GlobalAvgPool2d(nn.Module):\n def __init__(self):\n super(GlobalAvgPool2d, self).__init__()\n\n def forward(self, x):\n N = x.data.size(0)\n C = x.data.size(1)\n H = x.data.size(2)\n W = x.data.size(3)\n x = F.avg_pool2d(x, (H, W))\n x = x.view(N, C)\n return x\n\n\n# for route, shortcut and sam\nclass EmptyModule(nn.Module):\n def __init__(self):\n super(EmptyModule, self).__init__()\n\n def forward(self, x):\n return x\n\n\n# support route shortcut and reorg\nclass Darknet(nn.Module):\n def __init__(self, cfgfile, inference=False):\n super(Darknet, self).__init__()\n self.inference = inference\n self.training = not self.inference\n\n self.blocks = parse_cfg(cfgfile)\n self.width = int(self.blocks[0]['width'])\n self.height = int(self.blocks[0]['height'])\n\n self.models = self.create_network(self.blocks) # merge conv, bn,leaky\n self.loss = self.models[len(self.models) - 1]\n\n if self.blocks[(len(self.blocks) - 1)]['type'] == 'region':\n self.anchors = self.loss.anchors\n self.num_anchors = self.loss.num_anchors\n self.anchor_step = self.loss.anchor_step\n self.num_classes = self.loss.num_classes\n\n self.header = torch.IntTensor([0, 0, 0, 0])\n self.seen = 0\n\n def forward(self, x):\n ind = -2\n self.loss = None\n outputs = dict()\n out_boxes = []\n for block in self.blocks:\n ind = ind + 1\n # if ind > 0:\n # return x\n\n if block['type'] == 'net':\n continue\n elif block['type'] in ['convolutional', 'maxpool', 'reorg', 'upsample', 'avgpool', 'softmax', 'connected']:\n x = self.models[ind](x)\n outputs[ind] = x\n elif block['type'] == 'route':\n layers = block['layers'].split(',')\n layers = [int(i) if int(i) > 0 else int(i) + ind for i in layers]\n if len(layers) == 1:\n if 'groups' not in block.keys() or int(block['groups']) == 1:\n x = outputs[layers[0]]\n outputs[ind] = x\n else:\n groups = int(block['groups'])\n group_id = int(block['group_id'])\n _, b, _, _ = outputs[layers[0]].shape\n x = outputs[layers[0]][:, b // groups * group_id:b // groups * (group_id + 1)]\n outputs[ind] = x\n elif len(layers) == 2:\n x1 = outputs[layers[0]]\n x2 = outputs[layers[1]]\n x = torch.cat((x1, x2), 1)\n outputs[ind] = x\n elif len(layers) == 4:\n x1 = outputs[layers[0]]\n x2 = outputs[layers[1]]\n x3 = outputs[layers[2]]\n x4 = outputs[layers[3]]\n x = torch.cat((x1, x2, x3, x4), 1)\n outputs[ind] = x\n else:\n print(\"rounte number > 2 ,is {}\".format(len(layers)))\n\n elif block['type'] == 'shortcut':\n from_layer = int(block['from'])\n activation = block['activation']\n from_layer = from_layer if from_layer > 0 else from_layer + ind\n x1 = outputs[from_layer]\n x2 = outputs[ind - 1]\n x = x1 + x2\n if activation == 'leaky':\n x = F.leaky_relu(x, 0.1, inplace=True)\n elif activation == 'relu':\n x = F.relu(x, inplace=True)\n outputs[ind] = x\n elif block['type'] == 'sam':\n from_layer = int(block['from'])\n from_layer = from_layer if from_layer > 0 else from_layer + ind\n x1 = outputs[from_layer]\n x2 = outputs[ind - 1]\n x = x1 * x2\n outputs[ind] = x\n elif block['type'] == 'region':\n continue\n if self.loss:\n self.loss = self.loss + self.models[ind](x)\n else:\n self.loss = self.models[ind](x)\n outputs[ind] = None\n elif block['type'] == 'yolo':\n # if self.training:\n # pass\n # else:\n # boxes = self.models[ind](x)\n # out_boxes.append(boxes)\n boxes = self.models[ind](x)\n out_boxes.append(boxes)\n elif block['type'] == 'cost':\n continue\n else:\n print('unknown type %s' % (block['type']))\n\n if self.training:\n return out_boxes\n else:\n return get_region_boxes(out_boxes)\n\n def print_network(self):\n print_cfg(self.blocks)\n\n def create_network(self, blocks):\n models = nn.ModuleList()\n\n prev_filters = 3\n out_filters = []\n prev_stride = 1\n out_strides = []\n conv_id = 0\n for block in blocks:\n if block['type'] == 'net':\n prev_filters = int(block['channels'])\n continue\n elif block['type'] == 'convolutional':\n conv_id = conv_id + 1\n batch_normalize = int(block['batch_normalize'])\n filters = int(block['filters'])\n kernel_size = int(block['size'])\n stride = int(block['stride'])\n is_pad = int(block['pad'])\n pad = (kernel_size - 1) // 2 if is_pad else 0\n activation = block['activation']\n model = nn.Sequential()\n if batch_normalize:\n model.add_module('conv{0}'.format(conv_id),\n nn.Conv2d(prev_filters, filters, kernel_size, stride, pad, bias=False))\n model.add_module('bn{0}'.format(conv_id), nn.BatchNorm2d(filters))\n # model.add_module('bn{0}'.format(conv_id), BN2d(filters))\n else:\n model.add_module('conv{0}'.format(conv_id),\n nn.Conv2d(prev_filters, filters, kernel_size, stride, pad))\n if activation == 'leaky':\n model.add_module('leaky{0}'.format(conv_id), nn.LeakyReLU(0.1, inplace=True))\n elif activation == 'relu':\n model.add_module('relu{0}'.format(conv_id), nn.ReLU(inplace=True))\n elif activation == 'mish':\n model.add_module('mish{0}'.format(conv_id), Mish())\n elif activation == 'linear':\n pass\n elif activation == 'logistic':\n model.add_module('sigmoid{0}'.format(conv_id), nn.Sigmoid())\n else:\n print(\"No convolutional activation named {}\".format(activation))\n\n prev_filters = filters\n out_filters.append(prev_filters)\n prev_stride = stride * prev_stride\n out_strides.append(prev_stride)\n models.append(model)\n elif block['type'] == 'maxpool':\n pool_size = int(block['size'])\n stride = int(block['stride'])\n if stride == 1 and pool_size % 2:\n # You can use Maxpooldark instead, here is convenient to convert onnx.\n # Example: [maxpool] size=3 stride=1\n model = nn.MaxPool2d(kernel_size=pool_size, stride=stride, padding=pool_size // 2)\n elif stride == pool_size:\n # You can use Maxpooldark instead, here is convenient to convert onnx.\n # Example: [maxpool] size=2 stride=2\n model = nn.MaxPool2d(kernel_size=pool_size, stride=stride, padding=0)\n else:\n model = MaxPoolDark(pool_size, stride)\n out_filters.append(prev_filters)\n prev_stride = stride * prev_stride\n out_strides.append(prev_stride)\n models.append(model)\n elif block['type'] == 'avgpool':\n model = GlobalAvgPool2d()\n out_filters.append(prev_filters)\n models.append(model)\n elif block['type'] == 'softmax':\n model = nn.Softmax()\n out_strides.append(prev_stride)\n out_filters.append(prev_filters)\n models.append(model)\n elif block['type'] == 'cost':\n if block['_type'] == 'sse':\n model = nn.MSELoss(reduction='mean')\n elif block['_type'] == 'L1':\n model = nn.L1Loss(reduction='mean')\n elif block['_type'] == 'smooth':\n model = nn.SmoothL1Loss(reduction='mean')\n out_filters.append(1)\n out_strides.append(prev_stride)\n models.append(model)\n elif block['type'] == 'reorg':\n stride = int(block['stride'])\n prev_filters = stride * stride * prev_filters\n out_filters.append(prev_filters)\n prev_stride = prev_stride * stride\n out_strides.append(prev_stride)\n models.append(Reorg(stride))\n elif block['type'] == 'upsample':\n stride = int(block['stride'])\n out_filters.append(prev_filters)\n prev_stride = prev_stride // stride\n out_strides.append(prev_stride)\n\n models.append(Upsample_expand(stride))\n # models.append(Upsample_interpolate(stride))\n\n elif block['type'] == 'route':\n layers = block['layers'].split(',')\n ind = len(models)\n layers = [int(i) if int(i) > 0 else int(i) + ind for i in layers]\n if len(layers) == 1:\n if 'groups' not in block.keys() or int(block['groups']) == 1:\n prev_filters = out_filters[layers[0]]\n prev_stride = out_strides[layers[0]]\n else:\n prev_filters = out_filters[layers[0]] // int(block['groups'])\n prev_stride = out_strides[layers[0]] // int(block['groups'])\n elif len(layers) == 2:\n assert (layers[0] == ind - 1 or layers[1] == ind - 1)\n prev_filters = out_filters[layers[0]] + out_filters[layers[1]]\n prev_stride = out_strides[layers[0]]\n elif len(layers) == 4:\n assert (layers[0] == ind - 1)\n prev_filters = out_filters[layers[0]] + out_filters[layers[1]] + out_filters[layers[2]] + \\\n out_filters[layers[3]]\n prev_stride = out_strides[layers[0]]\n else:\n print(\"route error!!!\")\n\n out_filters.append(prev_filters)\n out_strides.append(prev_stride)\n models.append(EmptyModule())\n elif block['type'] == 'shortcut':\n ind = len(models)\n prev_filters = out_filters[ind - 1]\n out_filters.append(prev_filters)\n prev_stride = out_strides[ind - 1]\n out_strides.append(prev_stride)\n models.append(EmptyModule())\n elif block['type'] == 'sam':\n ind = len(models)\n prev_filters = out_filters[ind - 1]\n out_filters.append(prev_filters)\n prev_stride = out_strides[ind - 1]\n out_strides.append(prev_stride)\n models.append(EmptyModule())\n elif block['type'] == 'connected':\n filters = int(block['output'])\n if block['activation'] == 'linear':\n model = nn.Linear(prev_filters, filters)\n elif block['activation'] == 'leaky':\n model = nn.Sequential(\n nn.Linear(prev_filters, filters),\n nn.LeakyReLU(0.1, inplace=True))\n elif block['activation'] == 'relu':\n model = nn.Sequential(\n nn.Linear(prev_filters, filters),\n nn.ReLU(inplace=True))\n prev_filters = filters\n out_filters.append(prev_filters)\n out_strides.append(prev_stride)\n models.append(model)\n elif block['type'] == 'region':\n loss = RegionLoss()\n anchors = block['anchors'].split(',')\n loss.anchors = [float(i) for i in anchors]\n loss.num_classes = int(block['classes'])\n loss.num_anchors = int(block['num'])\n loss.anchor_step = len(loss.anchors) // loss.num_anchors\n loss.object_scale = float(block['object_scale'])\n loss.noobject_scale = float(block['noobject_scale'])\n loss.class_scale = float(block['class_scale'])\n loss.coord_scale = float(block['coord_scale'])\n out_filters.append(prev_filters)\n out_strides.append(prev_stride)\n models.append(loss)\n elif block['type'] == 'yolo':\n yolo_layer = YoloLayer()\n anchors = block['anchors'].split(',')\n anchor_mask = block['mask'].split(',')\n yolo_layer.anchor_mask = [int(i) for i in anchor_mask]\n yolo_layer.anchors = [float(i) for i in anchors]\n yolo_layer.num_classes = int(block['classes'])\n self.num_classes = yolo_layer.num_classes\n yolo_layer.num_anchors = int(block['num'])\n yolo_layer.anchor_step = len(yolo_layer.anchors) // yolo_layer.num_anchors\n yolo_layer.stride = prev_stride\n yolo_layer.scale_x_y = float(block['scale_x_y'])\n # yolo_layer.object_scale = float(block['object_scale'])\n # yolo_layer.noobject_scale = float(block['noobject_scale'])\n # yolo_layer.class_scale = float(block['class_scale'])\n # yolo_layer.coord_scale = float(block['coord_scale'])\n out_filters.append(prev_filters)\n out_strides.append(prev_stride)\n models.append(yolo_layer)\n else:\n print('unknown type %s' % (block['type']))\n\n return models\n\n def load_weights(self, weightfile):\n fp = open(weightfile, 'rb')\n header = np.fromfile(fp, count=5, dtype=np.int32)\n self.header = torch.from_numpy(header)\n self.seen = self.header[3]\n buf = np.fromfile(fp, dtype=np.float32)\n fp.close()\n\n start = 0\n ind = -2\n for block in self.blocks:\n if start >= buf.size:\n break\n ind = ind + 1\n if block['type'] == 'net':\n continue\n elif block['type'] == 'convolutional':\n model = self.models[ind]\n batch_normalize = int(block['batch_normalize'])\n if batch_normalize:\n start = load_conv_bn(buf, start, model[0], model[1])\n else:\n start = load_conv(buf, start, model[0])\n elif block['type'] == 'connected':\n model = self.models[ind]\n if block['activation'] != 'linear':\n start = load_fc(buf, start, model[0])\n else:\n start = load_fc(buf, start, model)\n elif block['type'] == 'maxpool':\n pass\n elif block['type'] == 'reorg':\n pass\n elif block['type'] == 'upsample':\n pass\n elif block['type'] == 'route':\n pass\n elif block['type'] == 'shortcut':\n pass\n elif block['type'] == 'sam':\n pass\n elif block['type'] == 'region':\n pass\n elif block['type'] == 'yolo':\n pass\n elif block['type'] == 'avgpool':\n pass\n elif block['type'] == 'softmax':\n pass\n elif block['type'] == 'cost':\n pass\n else:\n print('unknown type %s' % (block['type']))\n\n # def save_weights(self, outfile, cutoff=0):\n # if cutoff <= 0:\n # cutoff = len(self.blocks) - 1\n #\n # fp = open(outfile, 'wb')\n # self.header[3] = self.seen\n # header = self.header\n # header.numpy().tofile(fp)\n #\n # ind = -1\n # for blockId in range(1, cutoff + 1):\n # ind = ind + 1\n # block = self.blocks[blockId]\n # if block['type'] == 'convolutional':\n # model = self.models[ind]\n # batch_normalize = int(block['batch_normalize'])\n # if batch_normalize:\n # save_conv_bn(fp, model[0], model[1])\n # else:\n # save_conv(fp, model[0])\n # elif block['type'] == 'connected':\n # model = self.models[ind]\n # if block['activation'] != 'linear':\n # save_fc(fc, model)\n # else:\n # save_fc(fc, model[0])\n # elif block['type'] == 'maxpool':\n # pass\n # elif block['type'] == 'reorg':\n # pass\n # elif block['type'] == 'upsample':\n # pass\n # elif block['type'] == 'route':\n # pass\n # elif block['type'] == 'shortcut':\n # pass\n # elif block['type'] == 'sam':\n # pass\n # elif block['type'] == 'region':\n # pass\n # elif block['type'] == 'yolo':\n # pass\n # elif block['type'] == 'avgpool':\n # pass\n # elif block['type'] == 'softmax':\n # pass\n # elif block['type'] == 'cost':\n # pass\n # else:\n # print('unknown type %s' % (block['type']))\n # fp.close()\n"
] |
[
[
"torch.nn.SmoothL1Loss",
"torch.nn.Sequential",
"torch.nn.Softmax",
"numpy.fromfile",
"torch.nn.functional.avg_pool2d",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.Sigmoid",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.LeakyReLU",
"torch.nn.functional.leaky_relu",
"torch.nn.BatchNorm2d",
"torch.nn.L1Loss",
"torch.nn.ReLU",
"torch.nn.MSELoss",
"torch.nn.functional.pad"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
OstapFerensovych/ODrive
|
[
"918240fe3323d7040d5b1f71f899afb78da1fe6a"
] |
[
"tools/odrive/utils.py"
] |
[
"from __future__ import print_function\n\nimport sys\nimport time\nimport threading\nimport platform\nimport subprocess\nimport os\nimport numpy as np\nfrom fibre.utils import Event\nimport odrive.enums\nfrom odrive.enums import *\n\ntry:\n if platform.system() == 'Windows':\n import win32console\n import colorama\n colorama.init()\nexcept ImportError:\n print(\"Could not init terminal features.\")\n print(\"Refer to install instructions at http://docs.odriverobotics.com/#downloading-and-installing-tools\")\n sys.stdout.flush()\n pass\n\nif sys.version_info < (3, 0):\n input = raw_input\n\n_VT100Colors = {\n 'green': '\\x1b[92;1m',\n 'cyan': '\\x1b[96;1m',\n 'yellow': '\\x1b[93;1m',\n 'red': '\\x1b[91;1m',\n 'default': '\\x1b[0m'\n}\n\ndef calculate_thermistor_coeffs(degree, Rload, R_25, Beta, Tmin, Tmax, plot = False):\n T_25 = 25 + 273.15 #Kelvin\n temps = np.linspace(Tmin, Tmax, 1000)\n tempsK = temps + 273.15\n\n # https://en.wikipedia.org/wiki/Thermistor#B_or_%CE%B2_parameter_equation\n r_inf = R_25 * np.exp(-Beta/T_25)\n R_temps = r_inf * np.exp(Beta/tempsK)\n V = Rload / (Rload + R_temps)\n\n fit = np.polyfit(V, temps, degree)\n p1 = np.poly1d(fit)\n fit_temps = p1(V)\n\n if plot:\n import matplotlib.pyplot as plt\n print(fit)\n plt.plot(V, temps, label='actual')\n plt.plot(V, fit_temps, label='fit')\n plt.xlabel('normalized voltage')\n plt.ylabel('Temp [C]')\n plt.legend(loc=0)\n plt.show()\n\n return p1\n\nclass OperationAbortedException(Exception):\n pass\n\ndef set_motor_thermistor_coeffs(axis, Rload, R_25, Beta, Tmin, TMax):\n coeffs = calculate_thermistor_coeffs(3, Rload, R_25, Beta, Tmin, TMax)\n axis.motor.motor_thermistor.config.poly_coefficient_0 = float(coeffs[3])\n axis.motor.motor_thermistor.config.poly_coefficient_1 = float(coeffs[2])\n axis.motor.motor_thermistor.config.poly_coefficient_2 = float(coeffs[1])\n axis.motor.motor_thermistor.config.poly_coefficient_3 = float(coeffs[0])\n\ndef dump_errors(odrv, clear=False, printfunc = print):\n axes = [(name, axis) for name, axis in odrv._remote_attributes.items() if 'axis' in name]\n axes.sort()\n\n def dump_errors_for_module(indent, name, obj, path, errorcodes):\n prefix = indent + name.strip('0123456789') + \": \"\n for elem in path.split('.'):\n if not hasattr(obj, elem):\n printfunc(prefix + _VT100Colors['yellow'] + \"not found\" + _VT100Colors['default'])\n return\n parent = obj\n obj = getattr(obj, elem)\n if obj != 0:\n printfunc(indent + name + \": \" + _VT100Colors['red'] + \"Error(s):\" + _VT100Colors['default'])\n for bit in range(64):\n if obj & (1 << bit) != 0:\n printfunc(indent + \" \" + errorcodes.get((1 << bit), 'UNKNOWN ERROR: 0x{:08X}'.format(1 << bit)))\n if clear:\n setattr(parent, elem, 0)\n else:\n printfunc(indent + name + \": \" + _VT100Colors['green'] + \"no error\" + _VT100Colors['default'])\n\n system_error_codes = {v: k for k, v in odrive.enums.__dict__ .items() if k.startswith(\"ODRIVE_ERROR_\")}\n dump_errors_for_module(\"\", \"system\", odrv, 'error', system_error_codes)\n\n for name, axis in axes:\n printfunc(name)\n\n # Flatten axis and submodules\n # (name, obj, path, errorcode)\n module_decode_map = [\n ('axis', axis, 'error', {v: k for k, v in odrive.enums.__dict__ .items() if k.startswith(\"AXIS_ERROR_\")}),\n ('motor', axis, 'motor.error', {v: k for k, v in odrive.enums.__dict__ .items() if k.startswith(\"MOTOR_ERROR_\")}),\n ('sensorless_estimator', axis, 'sensorless_estimator.error', {v: k for k, v in odrive.enums.__dict__ .items() if k.startswith(\"SENSORLESS_ESTIMATOR_ERROR\")}),\n ('encoder', axis, 'encoder.error', {v: k for k, v in odrive.enums.__dict__ .items() if k.startswith(\"ENCODER_ERROR_\")}),\n ('controller', axis, 'controller.error', {v: k for k, v in odrive.enums.__dict__ .items() if k.startswith(\"CONTROLLER_ERROR_\")}),\n ]\n\n for name, obj, path, errorcodes in module_decode_map:\n dump_errors_for_module(\" \", name, obj, path, errorcodes)\n\ndef oscilloscope_dump(odrv, num_vals, filename='oscilloscope.csv'):\n with open(filename, 'w') as f:\n for x in range(num_vals):\n f.write(str(odrv.oscilloscope.get_val(x)))\n f.write('\\n')\n\ndata_rate = 200\nplot_rate = 10\nnum_samples = 500\ndef start_liveplotter(get_var_callback):\n \"\"\"\n Starts a liveplotter.\n The variable that is plotted is retrieved from get_var_callback.\n This function returns immediately and the liveplotter quits when\n the user closes it.\n \"\"\"\n\n import matplotlib.pyplot as plt\n\n cancellation_token = Event()\n\n global vals\n vals = []\n def fetch_data():\n global vals\n while not cancellation_token.is_set():\n try:\n data = get_var_callback()\n except Exception as ex:\n print(str(ex))\n time.sleep(1)\n continue\n vals.append(data)\n if len(vals) > num_samples:\n vals = vals[-num_samples:]\n time.sleep(1/data_rate)\n\n # TODO: use animation for better UI performance, see:\n # https://matplotlib.org/examples/animation/simple_anim.html\n def plot_data():\n global vals\n\n plt.ion()\n\n # Make sure the script terminates when the user closes the plotter\n def closed(evt):\n cancellation_token.set()\n fig = plt.figure()\n fig.canvas.mpl_connect('close_event', closed)\n\n while not cancellation_token.is_set():\n plt.clf()\n plt.plot(vals)\n plt.legend(list(range(len(vals))))\n fig.canvas.draw()\n fig.canvas.start_event_loop(1/plot_rate)\n\n fetch_t = threading.Thread(target=fetch_data)\n fetch_t.daemon = True\n fetch_t.start()\n \n plot_t = threading.Thread(target=plot_data)\n plot_t.daemon = True\n plot_t.start()\n\n return cancellation_token;\n #plot_data()\n\n\nclass BulkCapture:\n '''\n Asynchronously captures a bulk set of data when instance is created.\n\n get_var_callback: a function that returns the data you want to collect (see the example below)\n data_rate: Rate in hz\n length: Length of time to capture in seconds\n\n Example Usage:\n capture = BulkCapture(lambda :[odrv0.axis0.encoder.pos_estimate, odrv0.axis0.controller.pos_setpoint])\n # Do stuff while capturing (like sending position commands)\n capture.event.wait() # When you're done doing stuff, wait for the capture to be completed.\n print(capture.data) # Do stuff with the data\n capture.plot_data() # Helper method to plot the data\n '''\n\n def __init__(self,\n get_var_callback,\n data_rate=500.0,\n duration=2.0):\n from threading import Event, Thread\n import numpy as np\n\n self.get_var_callback = get_var_callback\n self.event = Event()\n def loop():\n vals = []\n start_time = time.monotonic()\n period = 1.0 / data_rate\n while time.monotonic() - start_time < duration:\n try:\n data = get_var_callback()\n except Exception as ex:\n print(str(ex))\n print(\"Waiting 1 second before next data point\")\n time.sleep(1)\n continue\n relative_time = time.monotonic() - start_time\n vals.append([relative_time] + data)\n time.sleep(period - (relative_time % period)) # this ensures consistently timed samples\n self.data = np.array(vals) # A lock is not really necessary due to the event\n print(\"Capture complete\")\n achieved_data_rate = len(self.data) / self.data[-1, 0]\n if achieved_data_rate < (data_rate * 0.9):\n print(\"Achieved average data rate: {}Hz\".format(achieved_data_rate))\n print(\"If this rate is significantly lower than what you specified, consider lowering it below the achieved value for more consistent sampling.\")\n self.event.set() # tell the main thread that the bulk capture is complete\n Thread(target=loop, daemon=True).start()\n \n def plot(self):\n import matplotlib.pyplot as plt\n import inspect\n from textwrap import wrap\n plt.plot(self.data[:,0], self.data[:,1:])\n plt.xlabel(\"Time (seconds)\")\n title = (str(inspect.getsource(self.get_var_callback))\n .strip(\"['\\\\n']\")\n .split(\" = \")[1])\n plt.title(\"\\n\".join(wrap(title, 60)))\n plt.legend(range(self.data.shape[1]-1))\n plt.show()\n\n\ndef step_and_plot( axis,\n step_size=100.0,\n settle_time=0.5,\n data_rate=500.0,\n ctrl_mode=CONTROL_MODE_POSITION_CONTROL):\n \n if ctrl_mode is CONTROL_MODE_POSITION_CONTROL:\n get_var_callback = lambda :[axis.encoder.pos_estimate, axis.controller.pos_setpoint]\n initial_setpoint = axis.encoder.pos_estimate\n def set_setpoint(setpoint):\n axis.controller.pos_setpoint = setpoint\n elif ctrl_mode is CONTROL_MODE_VELOCITY_CONTROL:\n get_var_callback = lambda :[axis.encoder.vel_estimate, axis.controller.vel_setpoint]\n initial_setpoint = 0\n def set_setpoint(setpoint):\n axis.controller.vel_setpoint = setpoint\n else:\n print(\"Invalid control mode\")\n return\n \n initial_settle_time = 0.5\n initial_control_mode = axis.controller.config.control_mode # Set it back afterwards\n print(initial_control_mode)\n axis.controller.config.control_mode = ctrl_mode\n axis.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL\n \n capture = BulkCapture(get_var_callback,\n data_rate=data_rate,\n duration=initial_settle_time + settle_time)\n\n set_setpoint(initial_setpoint)\n time.sleep(initial_settle_time)\n set_setpoint(initial_setpoint + step_size) # relative/incremental movement\n\n capture.event.wait() # wait for Bulk Capture to be complete\n\n axis.requested_state = AXIS_STATE_IDLE\n axis.controller.config.control_mode = initial_control_mode\n capture.plot()\n\n\ndef print_drv_regs(name, motor):\n \"\"\"\n Dumps the current gate driver regisers for the specified motor\n \"\"\"\n fault = motor.gate_driver.drv_fault\n status_reg_1 = motor.gate_driver.status_reg_1\n status_reg_2 = motor.gate_driver.status_reg_2\n ctrl_reg_1 = motor.gate_driver.ctrl_reg_1\n ctrl_reg_2 = motor.gate_driver.ctrl_reg_2\n print(name + \": \" + str(fault))\n print(\"DRV Fault Code: \" + str(fault))\n print(\"Status Reg 1: \" + str(status_reg_1) + \" (\" + format(status_reg_1, '#010b') + \")\")\n print(\"Status Reg 2: \" + str(status_reg_2) + \" (\" + format(status_reg_2, '#010b') + \")\")\n print(\"Control Reg 1: \" + str(ctrl_reg_1) + \" (\" + format(ctrl_reg_1, '#013b') + \")\")\n print(\"Control Reg 2: \" + str(ctrl_reg_2) + \" (\" + format(ctrl_reg_2, '#09b') + \")\")\n\ndef show_oscilloscope(odrv):\n size = 18000\n values = []\n for i in range(size):\n values.append(odrv.oscilloscope.get_val(i))\n\n import matplotlib.pyplot as plt\n plt.plot(values)\n plt.show()\n\ndef rate_test(device):\n \"\"\"\n Tests how many integers per second can be transmitted\n \"\"\"\n\n # import matplotlib.pyplot as plt\n # plt.ion()\n\n print(\"reading 10000 values...\")\n numFrames = 10000\n vals = []\n for _ in range(numFrames):\n vals.append(device.axis0.loop_counter)\n\n loopsPerFrame = (vals[-1] - vals[0])/numFrames\n loopsPerSec = (168000000/(6*3500))\n FramePerSec = loopsPerSec/loopsPerFrame\n print(\"Frames per second: \" + str(FramePerSec))\n\n # plt.plot(vals)\n # plt.show(block=True)\n\ndef usb_burn_in_test(get_var_callback, cancellation_token):\n \"\"\"\n Starts background threads that read a values form the USB device in a spin-loop\n \"\"\"\n\n def fetch_data():\n global vals\n i = 0\n while not cancellation_token.is_set():\n try:\n get_var_callback()\n i += 1\n except Exception as ex:\n print(str(ex))\n time.sleep(1)\n i = 0\n continue\n if i % 1000 == 0:\n print(\"read {} values\".format(i))\n threading.Thread(target=fetch_data, daemon=True).start()\n\ndef yes_no_prompt(question, default=None):\n if default is None:\n question += \" [y/n] \"\n elif default == True:\n question += \" [Y/n] \"\n elif default == False:\n question += \" [y/N] \"\n\n while True:\n print(question, end='')\n\n choice = input().lower()\n if choice in {'yes', 'y'}:\n return True\n elif choice in {'no', 'n'}:\n return False\n elif choice == '' and default is not None:\n return default\n\ndef dump_interrupts(odrv):\n interrupts = [\n (-12, \"MemoryManagement_IRQn\"),\n (-11, \"BusFault_IRQn\"),\n (-10, \"UsageFault_IRQn\"),\n (-5, \"SVCall_IRQn\"),\n (-4, \"DebugMonitor_IRQn\"),\n (-2, \"PendSV_IRQn\"),\n (-1, \"SysTick_IRQn\"),\n (0, \"WWDG_IRQn\"),\n (1, \"PVD_IRQn\"),\n (2, \"TAMP_STAMP_IRQn\"),\n (3, \"RTC_WKUP_IRQn\"),\n (4, \"FLASH_IRQn\"),\n (5, \"RCC_IRQn\"),\n (6, \"EXTI0_IRQn\"),\n (7, \"EXTI1_IRQn\"),\n (8, \"EXTI2_IRQn\"),\n (9, \"EXTI3_IRQn\"),\n (10, \"EXTI4_IRQn\"),\n (11, \"DMA1_Stream0_IRQn\"),\n (12, \"DMA1_Stream1_IRQn\"),\n (13, \"DMA1_Stream2_IRQn\"),\n (14, \"DMA1_Stream3_IRQn\"),\n (15, \"DMA1_Stream4_IRQn\"),\n (16, \"DMA1_Stream5_IRQn\"),\n (17, \"DMA1_Stream6_IRQn\"),\n (18, \"ADC_IRQn\"),\n (19, \"CAN1_TX_IRQn\"),\n (20, \"CAN1_RX0_IRQn\"),\n (21, \"CAN1_RX1_IRQn\"),\n (22, \"CAN1_SCE_IRQn\"),\n (23, \"EXTI9_5_IRQn\"),\n (24, \"TIM1_BRK_TIM9_IRQn\"),\n (25, \"TIM1_UP_TIM10_IRQn\"),\n (26, \"TIM1_TRG_COM_TIM11_IRQn\"),\n (27, \"TIM1_CC_IRQn\"),\n (28, \"TIM2_IRQn\"),\n (29, \"TIM3_IRQn\"),\n (30, \"TIM4_IRQn\"),\n (31, \"I2C1_EV_IRQn\"),\n (32, \"I2C1_ER_IRQn\"),\n (33, \"I2C2_EV_IRQn\"),\n (34, \"I2C2_ER_IRQn\"),\n (35, \"SPI1_IRQn\"),\n (36, \"SPI2_IRQn\"),\n (37, \"USART1_IRQn\"),\n (38, \"USART2_IRQn\"),\n (39, \"USART3_IRQn\"),\n (40, \"EXTI15_10_IRQn\"),\n (41, \"RTC_Alarm_IRQn\"),\n (42, \"OTG_FS_WKUP_IRQn\"),\n (43, \"TIM8_BRK_TIM12_IRQn\"),\n (44, \"TIM8_UP_TIM13_IRQn\"),\n (45, \"TIM8_TRG_COM_TIM14_IRQn\"),\n (46, \"TIM8_CC_IRQn\"),\n (47, \"DMA1_Stream7_IRQn\"),\n (48, \"FMC_IRQn\"),\n (49, \"SDMMC1_IRQn\"),\n (50, \"TIM5_IRQn\"),\n (51, \"SPI3_IRQn\"),\n (52, \"UART4_IRQn\"),\n (53, \"UART5_IRQn\"),\n (54, \"TIM6_DAC_IRQn\"),\n (55, \"TIM7_IRQn\"),\n (56, \"DMA2_Stream0_IRQn\"),\n (57, \"DMA2_Stream1_IRQn\"),\n (58, \"DMA2_Stream2_IRQn\"),\n (59, \"DMA2_Stream3_IRQn\"),\n (60, \"DMA2_Stream4_IRQn\"),\n (61, \"ETH_IRQn\"),\n (62, \"ETH_WKUP_IRQn\"),\n (63, \"CAN2_TX_IRQn\"),\n (64, \"CAN2_RX0_IRQn\"),\n (65, \"CAN2_RX1_IRQn\"),\n (66, \"CAN2_SCE_IRQn\"),\n (67, \"OTG_FS_IRQn\"),\n (68, \"DMA2_Stream5_IRQn\"),\n (69, \"DMA2_Stream6_IRQn\"),\n (70, \"DMA2_Stream7_IRQn\"),\n (71, \"USART6_IRQn\"),\n (72, \"I2C3_EV_IRQn\"),\n (73, \"I2C3_ER_IRQn\"),\n (74, \"OTG_HS_EP1_OUT_IRQn\"),\n (75, \"OTG_HS_EP1_IN_IRQn\"),\n (76, \"OTG_HS_WKUP_IRQn\"),\n (77, \"OTG_HS_IRQn\"),\n # gap\n (80, \"RNG_IRQn\"),\n (81, \"FPU_IRQn\"),\n (82, \"UART7_IRQn\"),\n (83, \"UART8_IRQn\"),\n (84, \"SPI4_IRQn\"),\n (85, \"SPI5_IRQn\"),\n # gap\n (87, \"SAI1_IRQn\"),\n # gap\n (91, \"SAI2_IRQn\"),\n (92, \"QUADSPI_IRQn\"),\n (93, \"LPTIM1_IRQn\"),\n # gap\n (103, \"SDMMC2_IRQn\")\n ]\n\n print(\"| # | Name | Prio | En | Count |\")\n print(\"|-----|-------------------------|------|----|---------|\")\n for irqn, irq_name in interrupts:\n status = odrv.get_interrupt_status(irqn)\n if (status != 0):\n print(\"| {} | {} | {} | {} | {} |\".format(\n str(irqn).rjust(3),\n irq_name.ljust(23),\n str(status & 0xff).rjust(4),\n \" *\" if (status & 0x80000000) else \" \",\n str((status >> 8) & 0x7fffff).rjust(7)))\n\ndef dump_threads(odrv):\n prefixes = [\"max_stack_usage_\", \"stack_size_\", \"prio_\"]\n keys = [k[len(prefix):] for k in dir(odrv.system_stats) for prefix in prefixes if k.startswith(prefix)]\n good_keys = set([k for k in set(keys) if keys.count(k) == len(prefixes)])\n if len(good_keys) > len(set(keys)):\n print(\"Warning: incomplete thread information for threads {}\".format(set(keys) - good_keys))\n\n print(\"| Name | Stack Size [B] | Max Ever Stack Usage [B] | Prio |\")\n print(\"|---------|----------------|--------------------------|------|\")\n for k in sorted(good_keys):\n sz = getattr(odrv.system_stats, \"stack_size_\" + k)\n use = getattr(odrv.system_stats, \"max_stack_usage_\" + k)\n print(\"| {} | {} | {} | {} |\".format(\n k.ljust(7),\n str(sz).rjust(14),\n \"{} ({:.1f}%)\".format(use, use / sz * 100).rjust(24),\n str(getattr(odrv.system_stats, \"prio_\" + k)).rjust(4)\n ))\n\n\ndef dump_dma(odrv):\n if odrv.hw_version_major == 3:\n dma_functions = [[\n # https://www.st.com/content/ccc/resource/technical/document/reference_manual/3d/6d/5a/66/b4/99/40/d4/DM00031020.pdf/files/DM00031020.pdf/jcr:content/translations/en.DM00031020.pdf Table 42\n [\"SPI3_RX\", \"-\", \"SPI3_RX\", \"SPI2_RX\", \"SPI2_TX\", \"SPI3_TX\", \"-\", \"SPI3_TX\"],\n [\"I2C1_RX\", \"-\", \"TIM7_UP\", \"-\", \"TIM7_UP\", \"I2C1_RX\", \"I2C1_TX\", \"I2C1_TX\"],\n [\"TIM4_CH1\", \"-\", \"I2S3_EXT_RX\", \"TIM4_CH2\", \"I2S2_EXT_TX\", \"I2S3_EXT_TX\", \"TIM4_UP\", \"TIM4_CH3\"],\n [\"I2S3_EXT_RX\", \"TIM2_UP/TIM2_CH3\", \"I2C3_RX\", \"I2S2_EXT_RX\", \"I2C3_TX\", \"TIM2_CH1\", \"TIM2_CH2/TIM2_CH4\", \"TIM2_UP/TIM2_CH4\"],\n [\"UART5_RX\", \"USART3_RX\", \"UART4_RX\", \"USART3_TX\", \"UART4_TX\", \"USART2_RX\", \"USART2_TX\", \"UART5_TX\"],\n [\"UART8_TX\", \"UART7_TX\", \"TIM3_CH4/TIM3_UP\", \"UART7_RX\", \"TIM3_CH1/TIM3_TRIG\", \"TIM3_CH2\", \"UART8_RX\", \"TIM3_CH3\"],\n [\"TIM5_CH3/TIM5_UP\", \"TIM5_CH4/TIM5_TRIG\", \"TIM5_CH1\", \"TIM5_CH4/TIM5_TRIG\", \"TIM5_CH2\", \"-\", \"TIM5_UP\", \"-\"],\n [\"-\", \"TIM6_UP\", \"I2C2_RX\", \"I2C2_RX\", \"USART3_TX\", \"DAC1\", \"DAC2\", \"I2C2_TX\"],\n ], [\n # https://www.st.com/content/ccc/resource/technical/document/reference_manual/3d/6d/5a/66/b4/99/40/d4/DM00031020.pdf/files/DM00031020.pdf/jcr:content/translations/en.DM00031020.pdf Table 43\n [\"ADC1\", \"SAI1_A\", \"TIM8_CH1/TIM8_CH2/TIM8_CH3\", \"SAI1_A\", \"ADC1\", \"SAI1_B\", \"TIM1_CH1/TIM1_CH2/TIM1_CH3\", \"-\"],\n [\"-\", \"DCMI\", \"ADC2\", \"ADC2\", \"SAI1_B\", \"SPI6_TX\", \"SPI6_RX\", \"DCMI\"],\n [\"ADC3\", \"ADC3\", \"-\", \"SPI5_RX\", \"SPI5_TX\", \"CRYP_OUT\", \"CRYP_IN\", \"HASH_IN\"],\n [\"SPI1_RX\", \"-\", \"SPI1_RX\", \"SPI1_TX\", \"-\", \"SPI1_TX\", \"-\", \"-\"],\n [\"SPI4_RX\", \"SPI4_TX\", \"USART1_RX\", \"SDIO\", \"-\", \"USART1_RX\", \"SDIO\", \"USART1_TX\"],\n [\"-\", \"USART6_RX\", \"USART6_RX\", \"SPI4_RX\", \"SPI4_TX\", \"-\", \"USART6_TX\", \"USART6_TX\"],\n [\"TIM1_TRIG\", \"TIM1_CH1\", \"TIM1_CH2\", \"TIM1_CH1\", \"TIM1_CH4/TIM1_TRIG/TIM1_COM\", \"TIM1_UP\", \"TIM1_CH3\", \"-\"],\n [\"-\", \"TIM8_UP\", \"TIM8_CH1\", \"TIM8_CH2\", \"TIM8_CH3\", \"SPI5_RX\", \"SPI5_TX\", \"TIM8_CH4/TIM8_TRIG/TIM8_COM\"],\n ]]\n elif odrv.hw_version_major == 4:\n dma_functions = [[\n # https://www.st.com/resource/en/reference_manual/dm00305990-stm32f72xxx-and-stm32f73xxx-advanced-armbased-32bit-mcus-stmicroelectronics.pdf Table 26\n [\"SPI3_RX\", \"-\", \"SPI3_RX\", \"SPI2_RX\", \"SPI2_TX\", \"SPI3_TX\", \"-\", \"SPI3_TX\"],\n [\"I2C1_RX\", \"I2C3_RX\", \"TIM7_UP\", \"-\", \"TIM7_UP\", \"I2C1_RX\", \"I2C1_TX\", \"I2C1_TX\"],\n [\"TIM4_CH1\", \"-\", \"-\", \"TIM4_CH2\", \"-\", \"-\", \"TIM4_UP\", \"TIM4_CH3\"],\n [\"-\", \"TIM2_UP/TIM2_CH3\", \"I2C3_RX\", \"-\", \"I2C3_TX\", \"TIM2_CH1\", \"TIM2_CH2/TIM2_CH4\", \"TIM2_UP/TIM2_CH4\"],\n [\"UART5_RX\", \"USART3_RX\", \"UART4_RX\", \"USART3_TX\", \"UART4_TX\", \"USART2_RX\", \"USART2_TX\", \"UART5_TX\"],\n [\"UART8_TX\", \"UART7_TX\", \"TIM3_CH4/TIM3_UP\", \"UART7_RX\", \"TIM3_CH1/TIM3_TRIG\", \"TIM3_CH2\", \"UART8_RX\", \"TIM3_CH3\"],\n [\"TIM5_CH3/TIM5_UP\", \"TIM5_CH4/TIM5_TRIG\", \"TIM5_CH1\", \"TIM5_CH4/TIM5_TRIG\", \"TIM5_CH2\", \"-\", \"TIM5_UP\", \"-\"],\n [\"-\", \"TIM6_UP\", \"I2C2_RX\", \"I2C2_RX\", \"USART3_TX\", \"DAC1\", \"DAC2\", \"I2C2_TX\"],\n ], [\n # https://www.st.com/resource/en/reference_manual/dm00305990-stm32f72xxx-and-stm32f73xxx-advanced-armbased-32bit-mcus-stmicroelectronics.pdf Table 27\n [\"ADC1\", \"SAI1_A\", \"TIM8_CH1/TIM8_CH2/TIM8_CH3\", \"SAI1_A\", \"ADC1\", \"SAI1_B\", \"TIM1_CH1/TIM1_CH2/TIM1_CH3\", \"SAI2_B\"],\n [\"-\", \"-\", \"ADC2\", \"ADC2\", \"SAI1_B\", \"-\", \"-\", \"-\"],\n [\"ADC3\", \"ADC3\", \"-\", \"SPI5_RX\", \"SPI5_TX\", \"AES_OUT\", \"AES_IN\", \"-\"],\n [\"SPI1_RX\", \"-\", \"SPI1_RX\", \"SPI1_TX\", \"SAI2_A\", \"SPI1_TX\", \"SAI2_B\", \"QUADSPI\"],\n [\"SPI4_RX\", \"SPI4_TX\", \"USART1_RX\", \"SDMMC1\", \"-\", \"USART1_RX\", \"SDMMC1\", \"USART1_TX\"],\n [\"-\", \"USART6_RX\", \"USART6_RX\", \"SPI4_RX\", \"SPI4_TX\", \"-\", \"USART6_TX\", \"USART6_TX\"],\n [\"TIM1_TRIG\", \"TIM1_CH1\", \"TIM1_CH2\", \"TIM1_CH1\", \"TIM1_CH4/TIM1_TRIG/TIM1_COM\", \"TIM1_UP\", \"TIM1_CH3\", \"-\"],\n [\"-\", \"TIM8_UP\", \"TIM8_CH1\", \"TIM8_CH2\", \"TIM8_CH3\", \"SPI5_RX\", \"SPI5_TX\", \"TIM8_CH4/TIM8_TRIG/TIM8_COM\"],\n None,\n None,\n None,\n [\"SDMMC2\", \"-\", \"-\", \"-\", \"-\", \"SDMMC2\", \"-\", \"-\"],\n ]]\n\n print(\"| Name | Prio | Channel | Configured |\")\n print(\"|--------------|------|----------------------------------|------------|\")\n for stream_num in range(16):\n status = odrv.get_dma_status(stream_num)\n if (status != 0):\n channel = (status >> 2) & 0x7\n ch_name = dma_functions[stream_num >> 3][channel][stream_num & 0x7]\n print(\"| DMA{}_Stream{} | {} | {} {} | {} |\".format(\n (stream_num >> 3) + 1,\n (stream_num & 0x7),\n (status & 0x3),\n channel,\n (\"(\" + ch_name + \")\").ljust(30),\n \"*\" if (status & 0x80000000) else \" \"))\n\ndef dump_timing(odrv, n_samples=100, path='/tmp/timings.png'):\n import matplotlib.pyplot as plt\n import re\n \n timings = []\n \n for attr in dir(odrv.task_times):\n if not attr.startswith('_'):\n timings.append((attr, getattr(odrv.task_times, attr), [], [])) # (name, obj, start_times, lengths)\n for k in dir(odrv):\n if re.match(r'axis[0-9]+', k):\n for attr in dir(getattr(odrv, k).task_times):\n if not attr.startswith('_'):\n timings.append((k + '.' + attr, getattr(getattr(odrv, k).task_times, attr), [], [])) # (name, obj, start_times, lengths)\n\n # Take a couple of samples\n print(\"sampling...\")\n for i in range(n_samples):\n odrv.task_timers_armed = True # Trigger sample and wait for it to finish\n while odrv.task_timers_armed: pass\n for name, obj, start_times, lengths in timings:\n start_times.append(obj.start_time)\n lengths.append(obj.length)\n print(\"done\")\n\n # sort by start time\n timings = sorted(timings, key = lambda x: np.mean(x[2]))\n\n plt.rcParams['figure.figsize'] = 21, 9\n plt.figure()\n plt.grid(True)\n plt.barh(\n [-i for i in range(len(timings))], # y positions\n [np.mean(lengths) for name, obj, start_times, lengths in timings], # lengths\n left = [np.mean(start_times) for name, obj, start_times, lengths in timings], # starts\n xerr = (\n [np.std(lengths) for name, obj, start_times, lengths in timings], # error bars to the left side\n [(min(obj.max_length, 20100) - np.mean(lengths)) for name, obj, start_times, lengths in timings], # error bars to the right side - TODO: remove artificial min()\n ),\n tick_label = [name for name, obj, start_times, lengths in timings], # labels\n )\n plt.savefig(path, bbox_inches='tight')\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.polyfit",
"numpy.poly1d",
"numpy.linspace",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.clf",
"numpy.mean",
"numpy.std",
"matplotlib.pyplot.grid",
"numpy.exp",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
delcacho/DataSciencePlatform
|
[
"c19ac4c1aba54bafc0fed05cc534bb447ab3b631"
] |
[
"model/test.py"
] |
[
"import warnings\nwarnings.filterwarnings(\"ignore\")\nfrom seldon_core.seldon_client import SeldonClient\nimport pandas as pd\n\ndata = pd.read_csv(\"wine-quality.csv\")\ndata.head()\n\nx_0 = data.drop([\"quality\"], axis=1).values[:1]\nbatch = x_0\n\nsc = SeldonClient( \\\n deployment_name=\"mlflow-ab-test\",\n namespace = \"default\",\n gateway_endpoint=\"api.bayescluster.com\",\n transport=\"rest\",\n debug = True \\\n)\n\ncolnames = data.columns.tolist()\ncolnames.remove(\"quality\")\n\nfor i in range(1,2000):\n r = sc.predict(data=batch, names=colnames, payload_type = \"ndarray\")\n print(r)\n\nassert(r.success==True)\n\n\n#r = sc.explain(data=batch, predictor=\"quality\")\n#print(r)\n"
] |
[
[
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
jason9075/ithome_tensorflow_series
|
[
"e8f92de2a73a88e7b03a9ac58ece4c4a604f066e",
"e8f92de2a73a88e7b03a9ac58ece4c4a604f066e"
] |
[
"14/record_dataset.py",
"11/debug_dropout.py"
] |
[
"import cv2\nimport tensorflow as tf\n\nTFRECORD_PATH = '../tfrecord/member.tfrecord'\n\n\ndef main():\n data_set = tf.data.TFRecordDataset(TFRECORD_PATH)\n data_set = data_set.map(parse_function)\n data_set = data_set.shuffle(buffer_size=9)\n data_set = data_set.batch(3)\n iterator = data_set.make_initializable_iterator()\n next_element = iterator.get_next()\n\n with tf.Session() as sess:\n sess.run(iterator.initializer)\n\n results, imgs = sess.run(next_element)\n\n print('names: {}'.format(results['member/name']))\n print('ages: {}'.format(results['member/age']))\n print('heights: {}'.format(results['member/height']))\n print('prefer_prods: {}'.format(results['member/prefer_prods']))\n\n for img in imgs:\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n cv2.imshow('img', img)\n cv2.waitKey(-1)\n\n\ndef parse_function(example_proto):\n features = {'member/name': tf.io.FixedLenFeature([], tf.string),\n 'member/encoded': tf.io.FixedLenFeature([], tf.string),\n 'member/age': tf.io.FixedLenFeature([], tf.int64),\n 'member/height': tf.io.VarLenFeature(tf.float32),\n 'member/prefer_prods': tf.io.VarLenFeature(tf.int64)}\n features = tf.io.parse_single_example(example_proto, features)\n images = tf.image.decode_png(features['member/encoded'], channels=3)\n # 注意png原本有4個channel,但執行到下面的處理會出錯,所以前一行先降成3個channel。\n images = tf.image.random_brightness(images, 0.1)\n images = tf.image.random_saturation(images, 0.7, 1.3)\n images = tf.image.random_contrast(images, 0.6, 1.5)\n images = tf.image.random_flip_left_right(images)\n\n return features, images\n\n\nif __name__ == '__main__':\n main()\n",
"import cv2\nimport tensorflow as tf\nfrom tensorflow.python.platform import gfile\nimport numpy as np\n\nMODEL_PB = '../pb/bn_dropout_model.pb'\n\n\ndef main():\n graph = tf.get_default_graph()\n\n graph_def = graph.as_graph_def()\n with gfile.FastGFile(MODEL_PB, 'rb') as f:\n graph_def.ParseFromString(f.read())\n tf.import_graph_def(graph_def, name='')\n\n input_node = graph.get_tensor_by_name(\n \"input_node:0\")\n training_node = graph.get_tensor_by_name(\n \"training:0\")\n\n debug_node = graph.get_tensor_by_name(\n \"dropout/cond/Merge:0\")\n\n with tf.Session() as sess:\n image = cv2.imread('../05/ithome.jpg')\n image = np.expand_dims(image, 0)\n\n result = sess.run(debug_node, feed_dict={input_node: image, training_node: True})\n print(f'training true:\\n{result[0, 22:28, 22:28, 0]}')\n\n result = sess.run(debug_node, feed_dict={input_node: image, training_node: False})\n print(f'training false:\\n{result[0, 22:28, 22:28, 0]}')\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"tensorflow.image.random_brightness",
"tensorflow.image.random_contrast",
"tensorflow.image.random_flip_left_right",
"tensorflow.data.TFRecordDataset",
"tensorflow.image.decode_png",
"tensorflow.io.parse_single_example",
"tensorflow.image.random_saturation",
"tensorflow.io.FixedLenFeature",
"tensorflow.io.VarLenFeature",
"tensorflow.Session"
],
[
"tensorflow.get_default_graph",
"tensorflow.import_graph_def",
"numpy.expand_dims",
"tensorflow.Session",
"tensorflow.python.platform.gfile.FastGFile"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
ogrenenmakine/censusEnumerators
|
[
"e63b5f888a0aaefa69dbc0413d567b1643c5c503"
] |
[
"source/NACDVOCDetection.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nimport os\nimport logging\nimport numpy as np\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\nimport mxnet as mx\nfrom source.base import VisionDataset\n\n\nclass NACDDetection(VisionDataset):\n \"\"\"Pascal VOC detection Dataset.\n Parameters\n ----------\n root : str, default '~/mxnet/datasets/voc'\n Path to folder storing the dataset.\n splits : list of tuples, default ((2007, 'trainval'), (2012, 'trainval'))\n List of combinations of (year, name)\n For years, candidates can be: 2007, 2012.\n For names, candidates can be: 'train', 'val', 'trainval', 'test'.\n transform : callable, defaut None\n A function that takes data and label and transforms them. Refer to\n :doc:`./transforms` for examples.\n A transform function for object detection should take label into consideration,\n because any geometric modification will require label to be modified.\n index_map : dict, default None\n In default, the 20 classes are mapped into indices from 0 to 19. We can\n customize it by providing a str to int dict specifying how to map class\n names to indicies. Use by advanced users only, when you want to swap the orders\n of class labels.\n preload_label : bool, default True\n If True, then parse and load all labels into memory during\n initialization. It often accelerate speed but require more memory\n usage. Typical preloaded labels took tens of MB. You only need to disable it\n when your dataset is extreamly large.\n \"\"\"\n CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car',\n 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',\n 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor', 'negative', 'cluster')\n\n def __init__(self, root=os.path.join('~', '.mxnet', 'datasets', 'voc'),\n splits=((2007, 'trainval'), (2012, 'trainval')),\n transform=None, index_map=None, preload_label=True):\n super(NACDDetection, self).__init__(root)\n self._im_shapes = {}\n self._root = os.path.expanduser(root)\n self._transform = transform\n self._splits = splits\n self._items = self._load_items(splits)\n self._anno_path = os.path.join('{}', 'Annotations', '{}.xml')\n self._image_path = os.path.join('{}', 'JPEGImages', '{}.jpg')\n self.index_map = index_map or dict(zip(self.classes, range(self.num_class)))\n self._label_cache = self._preload_labels() if preload_label else None\n\n def __str__(self):\n detail = ','.join([str(s[0]) + s[1] for s in self._splits])\n return self.__class__.__name__ + '(' + detail + ')'\n\n @property\n def classes(self):\n \"\"\"Category names.\"\"\"\n return type(self).CLASSES\n\n def __len__(self):\n return len(self._items)\n\n def __getitem__(self, idx):\n img_id = self._items[idx]\n img_path = self._image_path.format(*img_id)\n label = self._label_cache[idx] if self._label_cache else self._load_label(idx)\n img = mx.image.imread(img_path, 1)\n if self._transform is not None:\n return self._transform(img, label)\n return img, label\n\n def _load_items(self, splits):\n \"\"\"Load individual image indices from splits.\"\"\"\n ids = []\n for year, name in splits:\n root = os.path.join(self._root, 'VOC' + str(year))\n lf = os.path.join(root, 'ImageSets', 'Main', name + '.txt')\n with open(lf, 'r') as f:\n ids += [(root, line.strip()) for line in f.readlines()]\n return ids\n\n def _load_label(self, idx):\n \"\"\"Parse xml file and return labels.\"\"\"\n img_id = self._items[idx]\n anno_path = self._anno_path.format(*img_id)\n root = ET.parse(anno_path).getroot()\n size = root.find('size')\n width = float(size.find('width').text)\n height = float(size.find('height').text)\n if idx not in self._im_shapes:\n # store the shapes for later usage\n self._im_shapes[idx] = (width, height)\n label = []\n for obj in root.iter('object'):\n difficult = 0\n cls_name = obj.find('name').text.strip().lower()\n cls_id = self.index_map[cls_name]\n xml_box = obj.find('bndbox')\n xmin = (float(xml_box.find('xmin').text) - 1)\n ymin = (float(xml_box.find('ymin').text) - 1)\n xmax = (float(xml_box.find('xmax').text) - 1)\n ymax = (float(xml_box.find('ymax').text) - 1)\n try:\n self._validate_label(xmin, ymin, xmax, ymax, width, height)\n except AssertionError as e:\n raise RuntimeError(\"Invalid label at {}, {}\".format(anno_path, e))\n label.append([xmin, ymin, xmax, ymax, cls_id, difficult])\n return np.array(label)\n\n def _validate_label(self, xmin, ymin, xmax, ymax, width, height):\n \"\"\"Validate labels.\"\"\"\n assert xmin >= -1 and xmin < width, (\n \"xmin must in [0, {}), given {}\".format(width, xmin))\n assert ymin >= -1 and ymin < height, (\n \"ymin must in [0, {}), given {}\".format(height, ymin))\n assert xmax > xmin and xmax <= width + 1, (\n \"xmax must in (xmin, {}], given {}\".format(width, xmax))\n assert ymax > ymin and ymax <= height + 1, (\n \"ymax must in (ymin, {}], given {}\".format(height, ymax))\n\n def _preload_labels(self):\n \"\"\"Preload all labels into memory.\"\"\"\n logging.debug(\"Preloading %s labels into memory...\", str(self))\n return [self._load_label(idx) for idx in range(len(self))]\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SeriousDim/gr09
|
[
"db23a064c422c146ade39c81bb287ee958038731"
] |
[
"old_filter.py"
] |
[
"from PIL import Image\nimport numpy as np\nimg = Image.open(\"img2.jpg\")\narr = np.array(img)\na = len(arr)\na1 = len(arr[1])\ni = 0\nwhile i < a - 11:\n j = 0\n while j < a1 - 11:\n s = 0\n for n in range(i, i + 10):\n for n1 in range(j, j + 10):\n n1 = arr[n][n1][0]\n n2 = arr[n][n1][1]\n n3 = arr[n][n1][2]\n M = n1 + n2 + n3\n s += M\n s = int(s // 100)\n for n in range(i, i + 10):\n for n1 in range(j, j + 10):\n arr[n][n1][0] = int(s // 50) * 50\n arr[n][n1][1] = int(s // 50) * 50\n arr[n][n1][2] = int(s // 50) * 50\n j = j + 10\n i = i + 10\nres = Image.fromarray(arr)\nres.save('res.jpg')\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LiYangCom1994/companylair
|
[
"e8d085e3357b08f178b089c4a52e5dc2f9eb103f"
] |
[
"wd/wdapp/timeseries_analysis.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import learning_curve\n\nfrom sklearn.metrics import fbeta_score, make_scorer\n\nfrom sklearn.metrics import r2_score, mean_squared_error, make_scorer\nfrom sklearn.grid_search import GridSearchCV\ndef plot_learning_curve(clf, title):\n train_sizes, train_scores, test_scores = learning_curve(clf, \n X, \n Y, \n cv=10, \n n_jobs=-1, \n train_sizes=np.linspace(.1, 1., 10), \n verbose=0)\n\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n\n plt.figure()\n plt.title(title)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n\n # Plot the average training and test score lines at each training set size\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"b\", label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"r\", label=\"Test score\")\n\n # Plot the std deviation as a transparent range at each training set size\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color=\"b\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color=\"r\")\n plt.legend(loc=\"best\")\ndef encode(x):\n if (x.dtype is np.dtype('O') and x.name != 'sales') or x.name == 'date':\n return x.astype('category').cat.codes\n\n return x\n\ndf_tmp = df_tmp.apply(encode)\n\nx_col = df_tmp.columns.values[df_tmp.columns.values != 'sales']\n\nX = df_tmp[x_col].values\nY = df_tmp['sales'].values\n\ndisplay(X)\ndisplay(Y) \n\ndsr = DecisionTreeRegressor(random_state = 0, min_samples_split = 15, max_depth = 10)\n\nscores = cross_val_score(dsr, X, Y, cv = 15)\ndisplay(scores)\nprint(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\n\nrfr = RandomForestRegressor(n_estimators = 10)\n\nscores = cross_val_score(rfr, X, Y, cv = 10)\ndisplay(scores)\nprint(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\ndsr.fit(X, Y)\npre_y_by_dsr = dsr.predict(X)\n\nrfr.fit(X, Y)\npre_y_by_rfr = rfr.predict(X)\nf = pd.DataFrame(index=df_tmp.index)\ndf['month'] = list(map(lambda x: x.month, df_tmp.index.date))\n\ndf['pred_by_decision_tree_regressor'] = pre_y_by_dsr\ndf['pred_by_random_forest_regressor'] = pre_y_by_rfr\n\ndf['country'] = df_tmp['country']\ndf['actual'] = Y\n\nm = df.groupby(['country', 'date'])['pred_by_decision_tree_regressor', 'pred_by_random_forest_regressor', 'actual'].mean()\nv = df.groupby(['country', 'date'])['pred_by_decision_tree_regressor', 'pred_by_random_forest_regressor', 'actual'].var()\n\nfig, axes = plt.subplots(len(countries), 2, figsize=(20, 25)) \nfor i in range(3):\n m.xs(i).plot(title = countries[i] + \" (Mean)\", ax = axes[i, 0])\n v.xs(i).plot(title = countries[i] + \" (Variance)\", ax = axes[i, 1])\n\n \nplt.legend(loc='best')\n\n\n\nplot_learning_curve(dsr, \"Decision_Tree_Regressor\")\nplot_learning_curve(rfr, \"Random_Forest_Regressor\")"
] |
[
[
"sklearn.ensemble.RandomForestRegressor",
"matplotlib.pyplot.legend",
"sklearn.tree.DecisionTreeRegressor",
"sklearn.model_selection.cross_val_score",
"matplotlib.pyplot.title",
"numpy.linspace",
"pandas.DataFrame",
"numpy.dtype",
"matplotlib.pyplot.plot",
"numpy.std",
"matplotlib.pyplot.ylabel",
"numpy.mean",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Pangoraw/PaDiM
|
[
"76f757fd51c46abda1ced5a26c2865c6d91a8cca",
"76f757fd51c46abda1ced5a26c2865c6d91a8cca"
] |
[
"padim/utils/utils.py",
"examples/semmacape.py"
] |
[
"\"\"\"\nUtils module\n\nThe code from this file comes from:\n * https://github.com/taikiinoue45/PaDiM\n\"\"\"\nfrom typing import List\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nfrom numpy import ndarray as NDArray\nfrom skimage import measure\nfrom sklearn.metrics import auc, roc_auc_score, roc_curve\nfrom tqdm import tqdm\n\nimport torch\nfrom torch import Tensor\nimport torch.nn.functional as F\n\n\ndef embeddings_concat(x0: Tensor, x1: Tensor) -> Tensor:\n b0, c0, h0, w0 = x0.size()\n _, c1, h1, w1 = x1.size()\n s = h0 // h1\n x0 = F.unfold(x0, kernel_size=(s, s), dilation=(1, 1), stride=(s, s))\n x0 = x0.view(b0, c0, -1, h1, w1)\n z = torch.zeros(b0, c0 + c1, x0.size(2), h1, w1).to(x0.device)\n for i in range(x0.size(2)):\n z[:, :, i, :, :] = torch.cat((x0[:, :, i, :, :], x1), 1)\n z = z.view(b0, -1, h1 * w1)\n z = F.fold(z, kernel_size=(s, s), output_size=(h0, w0), stride=(s, s))\n return z\n\n\ndef mean_smoothing(amaps: Tensor, kernel_size: int = 21) -> Tensor:\n mean_kernel = torch.ones(1, 1, kernel_size, kernel_size) / kernel_size ** 2\n mean_kernel = mean_kernel.to(amaps.device)\n return F.conv2d(amaps, mean_kernel, padding=kernel_size // 2, groups=1)\n\n\ndef compute_roc_score(amaps: NDArray, y_trues: NDArray, stems: List[str]) -> float:\n\n num_data = len(stems)\n y_scores = amaps.reshape(num_data, -1).max(axis=1)\n fprs, tprs, thresholds = roc_curve(y_trues, y_scores, pos_label=1, drop_intermediate=False)\n\n # Save roc_curve.csv\n keys = [f\"threshold_{i}\" for i in range(len(thresholds))]\n roc_df = pd.DataFrame({\"key\": keys, \"fpr\": fprs, \"tpr\": tprs, \"threshold\": thresholds})\n roc_df.to_csv(\"roc_curve.csv\", index=False)\n\n # Update test_dataset.csv\n # pred_csv = pd.merge(\n # pd.DataFrame({\"stem\": stems, \"y_score\": y_scores, \"y_true\": y_trues}),\n # pd.read_csv(\"test_dataset.csv\"),\n # on=\"stem\",\n # )\n # for i, th in enumerate(thresholds):\n # pred_csv[f\"threshold_{i}\"] = pred_csv[\"y_score\"].apply(lambda x: 1 if x >= th else 0)\n # pred_csv.to_csv(\"test_dataset.csv\", index=False)\n\n print(\"np.unique\", np.unique(y_trues))\n\n return roc_auc_score(y_trues, y_scores)\n\n\ndef compute_pro_score(amaps: NDArray, masks: NDArray) -> float:\n\n df = pd.DataFrame([], columns=[\"pro\", \"fpr\", \"threshold\"])\n binary_amaps = np.zeros_like(amaps, dtype=np.bool)\n\n max_step = 200\n min_th = amaps.min()\n max_th = amaps.max()\n delta = (max_th - min_th) / max_step\n\n for th in tqdm(np.arange(min_th, max_th, delta), desc=\"compute pro\"):\n binary_amaps[amaps <= th] = 0\n binary_amaps[amaps > th] = 1\n\n pros = []\n for binary_amap, mask in zip(binary_amaps, masks):\n for region in measure.regionprops(measure.label(mask)):\n axes0_ids = region.coords[:, 0]\n axes1_ids = region.coords[:, 1]\n TP_pixels = binary_amap[axes0_ids, axes1_ids].sum()\n pros.append(TP_pixels / region.area)\n\n inverse_masks = 1 - masks\n FP_pixels = np.logical_and(inverse_masks, binary_amaps).sum()\n fpr = FP_pixels / inverse_masks.sum()\n\n df = df.append({\"pro\": mean(pros), \"fpr\": fpr, \"threshold\": th}, ignore_index=True)\n\n df.to_csv(\"pro_curve.csv\", index=False)\n return auc(df[\"fpr\"], df[\"pro\"])\n\n\ndef draw_roc_and_pro_curve(roc_score: float, pro_score: float) -> None:\n\n grid = ImageGrid(\n fig=plt.figure(figsize=(8, 8)),\n rect=111,\n nrows_ncols=(1, 1),\n axes_pad=0.15,\n share_all=True,\n cbar_location=\"right\",\n cbar_mode=\"single\",\n cbar_size=\"5%\",\n cbar_pad=0.15,\n )\n\n roc_df = pd.read_csv(\"roc_curve.csv\")\n fpr = roc_df[\"fpr\"]\n tpr = roc_df[\"tpr\"]\n th = roc_df[\"threshold\"]\n v_min = th.min()\n grid[0].plot(fpr, tpr, color=\"k\", label=f\"ROC Score: {round(roc_score, 3):.3f}\", zorder=1)\n im = grid[0].scatter(fpr, tpr, s=8, c=th, cmap=\"jet\", vmin=v_min, vmax=1, zorder=2)\n grid[0].set_xlim(-0.05, 1.05)\n grid[0].set_ylim(-0.05, 1.05)\n grid[0].set_xticks(np.arange(0, 1.1, 0.1))\n grid[0].set_yticks(np.arange(0, 1.1, 0.1))\n grid[0].tick_params(axis=\"both\", labelsize=14)\n grid[0].set_xlabel(\"FPR: FP / (TN + FP)\", fontsize=24)\n grid[0].set_ylabel(\"TPR: TP / (TP + FN)\", fontsize=24)\n grid[0].xaxis.set_label_coords(0.5, -0.1)\n grid[0].yaxis.set_label_coords(-0.1, 0.5)\n grid[0].legend(fontsize=24)\n grid[0].grid(which=\"both\", linestyle=\"dotted\", linewidth=1)\n cb = plt.colorbar(im, cax=grid.cbar_axes[0])\n cb.ax.tick_params(labelsize=\"large\")\n plt.savefig(\"roc_curve.png\")\n plt.close()\n\n grid = ImageGrid(\n fig=plt.figure(figsize=(8, 8)),\n rect=111,\n nrows_ncols=(1, 1),\n axes_pad=0.15,\n share_all=True,\n cbar_location=\"right\",\n cbar_mode=\"single\",\n cbar_size=\"5%\",\n cbar_pad=0.15,\n )\n\n pro_df = pd.read_csv(\"pro_curve.csv\")\n fpr = pro_df[\"fpr\"]\n pro = pro_df[\"pro\"]\n th = pro_df[\"threshold\"]\n grid[0].plot(fpr, pro, color=\"k\", label=f\"PRO Score: {round(pro_score, 3):.3f}\", zorder=1)\n im = grid[0].scatter(fpr, pro, s=8, c=th, cmap=\"jet\", vmin=v_min, vmax=1, zorder=2)\n grid[0].set_xlim(-0.05, 1.05)\n grid[0].set_ylim(-0.05, 1.05)\n grid[0].set_xticks(np.arange(0, 1.1, 0.1))\n grid[0].set_yticks(np.arange(0, 1.1, 0.1))\n grid[0].tick_params(axis=\"both\", labelsize=14)\n grid[0].set_xlabel(\"FPR: FP / (TN + FP)\", fontsize=24)\n grid[0].set_ylabel(\"PRO: Per-Region Overlap\", fontsize=24)\n grid[0].xaxis.set_label_coords(0.5, -0.1)\n grid[0].yaxis.set_label_coords(-0.1, 0.5)\n grid[0].legend(fontsize=24)\n grid[0].grid(which=\"both\", linestyle=\"dotted\", linewidth=1)\n cb = plt.colorbar(im, cax=grid.cbar_axes[0])\n cb.ax.tick_params(labelsize=\"large\")\n plt.savefig(\"pro_curve.png\")\n plt.close()\n\n\ndef savegif(imgs: NDArray, amaps: NDArray, masks: NDArray, stems: List[str]) -> None:\n\n os.mkdir(\"results\")\n pbar = tqdm(enumerate(zip(stems, imgs, masks, amaps)), desc=\"savefig\")\n for i, (stem, img, mask, amap) in pbar:\n\n # How to get two subplots to share the same y-axis with a single colorbar\n # https://stackoverflow.com/a/38940369\n grid = ImageGrid(\n fig=plt.figure(figsize=(12, 4)),\n rect=111,\n nrows_ncols=(1, 3),\n axes_pad=0.15,\n share_all=True,\n cbar_location=\"right\",\n cbar_mode=\"single\",\n cbar_size=\"5%\",\n cbar_pad=0.15,\n )\n\n img = denormalize(img)\n\n grid[0].imshow(img)\n grid[0].tick_params(labelbottom=False, labelleft=False, bottom=False, left=False)\n grid[0].set_title(\"Input Image\", fontsize=24)\n\n grid[1].imshow(img)\n grid[1].imshow(mask, alpha=0.3, cmap=\"Reds\")\n grid[1].tick_params(labelbottom=False, labelleft=False, bottom=False, left=False)\n grid[1].set_title(\"Ground Truth\", fontsize=24)\n\n grid[2].imshow(img)\n im = grid[2].imshow(amap, alpha=0.3, cmap=\"jet\", vmin=0, vmax=1)\n grid[2].tick_params(labelbottom=False, labelleft=False, bottom=False, left=False)\n grid[2].cax.toggle_label(True)\n grid[2].set_title(\"Anomaly Map\", fontsize=24)\n\n plt.colorbar(im, cax=grid.cbar_axes[0])\n plt.savefig(f\"results/{stem}.png\", bbox_inches=\"tight\")\n plt.close()\n\n # NOTE(inoue): The gif files converted by PIL or imageio were low-quality.\n # So, I used the conversion command (ImageMagick) instead.\n subprocess.run(\"convert -delay 100 -loop 0 results/*.png result.gif\", shell=True)\n\n\ndef denormalize(img: NDArray) -> NDArray:\n\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n img = (img * std + mean) * 255.0\n return img.astype(np.uint8)\n",
"import os\nimport pickle\n\nimport torch\nfrom tqdm import tqdm\nimport pandas as pd\nfrom PIL import Image\nfrom torchvision import transforms\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import DataLoader, Dataset\n\nfrom padim import PaDiM, PaDiMShared\nfrom padim.datasets import LimitedDataset\n\n\nclass TrainingDataset(Dataset):\n def __init__(self, data_dir, img_transforms):\n self.data_dir = data_dir\n self.data_frame = pd.read_csv(\"./empty_ranking.csv\", index_col=0)\n self.transforms = img_transforms\n\n def __getitem__(self, index):\n if index % 2 == 0:\n direction = -1\n else:\n direction = 1\n index = direction * index // 2\n\n img_path = self.data_dir + self.data_frame.iloc[index][0]\n img = Image.open(img_path)\n img = self.transforms(img)\n\n return img, 1\n\n def __len__(self):\n length, _ = self.data_frame.shape\n return length\n\n\ndef train(cfg):\n LIMIT = cfg.train_limit\n PARAMS_PATH = cfg.params_path\n SHARED = cfg.shared\n size = tuple(map(int, cfg.size.split(\"x\")))\n\n if SHARED:\n Model = PaDiMShared\n else:\n Model = PaDiM\n\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n padim = Model(device=device, backbone=\"wide_resnet50\", size=size)\n img_transforms = transforms.Compose([\n transforms.ToTensor(),\n transforms.Resize(size),\n transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]\n ),\n ])\n if \"semmacape\" in cfg.train_folder:\n training_dataset = TrainingDataset(\n data_dir=cfg.train_folder,\n img_transforms=img_transforms,\n )\n else:\n training_dataset = ImageFolder(root=cfg.train_folder, transform=img_transforms)\n\n n_cpus = int(os.getenv(\"SLURM_CPUS_PER_TASK\", 12))\n dataloader = DataLoader(\n batch_size=32,\n num_workers=n_cpus,\n dataset=LimitedDataset(limit=LIMIT, dataset=training_dataset),\n )\n\n for batch in tqdm(dataloader):\n if isinstance(batch, tuple) or isinstance(batch, list):\n batch = batch[0]\n padim.train_one_batch(batch)\n\n print(\">> Saving params\")\n params = padim.get_residuals()\n with open(PARAMS_PATH, 'wb') as f:\n pickle.dump(params, f)\n print(f\">> Params saved at {PARAMS_PATH}\")\n\n return padim\n"
] |
[
[
"sklearn.metrics.roc_auc_score",
"torch.cat",
"pandas.DataFrame",
"numpy.zeros_like",
"pandas.read_csv",
"torch.ones",
"numpy.unique",
"numpy.arange",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"torch.nn.functional.conv2d",
"sklearn.metrics.roc_curve",
"matplotlib.pyplot.savefig",
"sklearn.metrics.auc",
"numpy.logical_and",
"numpy.array",
"torch.nn.functional.fold",
"matplotlib.pyplot.colorbar",
"torch.nn.functional.unfold"
],
[
"pandas.read_csv",
"torch.cuda.is_available"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
zmlabe/predictGMSTrate
|
[
"2bde4a106de1988d772f15a52d283d23bb7128f4",
"2bde4a106de1988d772f15a52d283d23bb7128f4",
"2bde4a106de1988d772f15a52d283d23bb7128f4",
"2bde4a106de1988d772f15a52d283d23bb7128f4",
"2bde4a106de1988d772f15a52d283d23bb7128f4"
] |
[
"Scripts/read_HadCRUT.py",
"Scripts/read_ERA5_monthlyBE.py",
"Scripts/LRP_v1.py",
"Scripts/plot_MSFigure_2.py",
"Dark_Scripts/calc_Hiatus_v3.py"
] |
[
"\"\"\"\nFunction reads in monthly data from HadCRUTv4\n \nNotes\n-----\n Author : Zachary Labe\n Date : 10 January 2022\n \nUsage\n-----\n [1] read_HadCRUT(directory,sliceperiod,sliceyear,\n sliceshape,addclimo,slicenan)\n\"\"\"\n\ndef read_HadCRUT(directory,sliceperiod,sliceyear,sliceshape,addclimo,slicenan):\n \"\"\"\n Function reads monthly data from HadCRUT\n \n Parameters\n ----------\n directory : string\n path for data\n sliceperiod : string\n how to average time component of data\n sliceyear : string\n how to slice number of years for data\n sliceshape : string\n shape of output array\n addclimo : binary\n True or false to add climatology\n slicenan : string or float\n Set missing values\n \n Returns\n -------\n lat : 1d numpy array\n latitudes\n lon : 1d numpy array\n longitudes\n var : 3d numpy array or 4d numpy array \n [time,lat,lon] or [year,month,lat,lon]\n \n Usage\n -----\n lat,lon,var = read_HadCRUT(directory,sliceperiod,sliceyear,\n sliceshape,addclimo,slicenan)\n \"\"\"\n print('\\n>>>>>>>>>> STARTING read_HadCRUT function!')\n \n ### Import modules\n import numpy as np\n from netCDF4 import Dataset\n import warnings\n import calc_Utilities as UT\n warnings.simplefilter(action='ignore', category=FutureWarning)\n warnings.simplefilter(action='ignore', category=RuntimeWarning)\n \n ###########################################################################\n ### Parameters\n time = np.arange(1850,2020+1,1)\n monthslice = sliceyear.shape[0]*12\n mon = 12\n \n ###########################################################################\n ### Read in data\n filename = 'T2M_HadCRUT_1850-2020.nc'\n data = Dataset(directory + filename,'r')\n lat1 = data.variables['latitude'][:]\n lon1 = data.variables['longitude'][:]\n anom = data.variables['T2M'][:,:,:]\n data.close()\n \n print('Years of output =',sliceyear.min(),'to',sliceyear.max())\n ###########################################################################\n ### Reshape data into [year,month,lat,lon]\n datamon = np.reshape(anom,(anom.shape[0]//mon,mon,\n lat1.shape[0],lon1.shape[0]))\n \n ###########################################################################\n ### Return absolute temperature (1961-1990 baseline)\n if addclimo == True:\n filename = 'CLIM_HadCRUT_1880-2020.n'\n datac = Dataset(directory + filename,'r')\n clim = datac['CLIM'][:,:,:]\n datac.close()\n \n ### Add [anomaly+climatology]\n tempmon = datamon + clim\n print('Completed: calculated absolute temperature!')\n else:\n tempmon = datamon\n print('Completed: calculated anomalies!')\n \n ###########################################################################\n ### Slice over months (currently = [yr,mn,lat,lon])\n ### Shape of output array\n if sliceperiod == 'annual':\n temptime = np.nanmean(tempmon,axis=1)\n if sliceshape == 1:\n tempshape = temptime.ravel()\n elif sliceshape == 3:\n tempshape = temptime\n print('Shape of output = ', tempshape.shape,[[tempshape.ndim]])\n print('Completed: ANNUAL MEAN!')\n print('Completed: ANNUAL MEAN!')\n elif sliceperiod == 'DJF':\n tempshape = UT.calcDecJanFeb(tempmon,lat1,lon1,'surface',1)\n print('Shape of output = ', tempshape.shape,[[tempshape.ndim]])\n print('Completed: DJF MEAN!')\n elif sliceperiod == 'JJA':\n temptime = np.nanmean(tempmon[:,5:8,:,:],axis=1)\n if sliceshape == 1:\n tempshape = temptime.ravel()\n elif sliceshape == 3:\n tempshape = temptime\n print('Shape of output = ', tempshape.shape,[[tempshape.ndim]])\n print('Completed: JJA MEAN!')\n elif sliceperiod == 'none':\n temptime = tempmon\n if sliceshape == 1:\n tempshape = tempshape.ravel()\n elif sliceshape == 3:\n tempshape = np.reshape(temptime,(temptime.shape[0]*temptime.shape[1],\n temptime.shape[2],temptime.shape[3]))\n elif sliceshape == 4:\n tempshape = tempmon\n print('Shape of output =', tempshape.shape, [[tempshape.ndim]])\n print('Completed: ALL MONTHS!')\n \n ###########################################################################\n ### Change missing values\n if slicenan == 'nan':\n tempshape[np.where(np.isnan(tempshape))] = np.nan\n print('Completed: missing values are =',slicenan)\n else:\n tempshape[np.where(np.isnan(tempshape))] = slicenan\n \n print('>>>>>>>>>> ENDING read_HadCRUT function!')\n return lat1,lon1,tempshape\n\n### Test functions - do not use!\n# import numpy as np\n# import matplotlib.pyplot as plt\n# directory = '/Users/zlabe/Data/HadCRUT/'\n# sliceperiod = 'DJF'\n# sliceyear = np.arange(1850,2020+1,1)\n# sliceshape = 3\n# slicenan = 'nan'\n# addclimo = True\n# lat,lon,var = read_HadCRUT(directory,sliceperiod,sliceyear,sliceshape,addclimo,slicenan)",
"\"\"\"\nFunction reads in monthly data from ERA5-BE\n \nNotes\n-----\n Author : Zachary Labe\n Date : 15 July 2020\n \nUsage\n-----\n [1] read_ERA5_monthlyBE(variq,directory,sliceperiod,sliceyear,\n sliceshape,addclimo,slicenan)\n\"\"\"\n\ndef read_ERA5_monthlyBE(variq,directory,sliceperiod,sliceyear,sliceshape,addclimo,slicenan):\n \"\"\"\n Function reads monthly data from ERA5\n \n Parameters\n ----------\n variq : string\n variable to retrieve\n directory : string\n path for data\n sliceperiod : string\n how to average time component of data\n sliceyear : string\n how to slice number of years for data\n sliceshape : string\n shape of output array\n addclimo : binary\n True or false to add climatology\n slicenan : string or float\n Set missing values\n \n Returns\n -------\n lat : 1d numpy array\n latitudes\n lon : 1d numpy array\n longitudes\n var : 3d numpy array or 4d numpy array \n [time,lat,lon] or [year,month,lat,lon]\n \n Usage\n -----\n lat,lon,var = read_ERA5_monthlyBE(variq,directory,sliceperiod,sliceyear,\n sliceshape,addclimo,slicenan)\n \"\"\"\n print('\\n>>>>>>>>>> STARTING read_ERA5_monthlyBE (Back Extension) function!')\n \n ### Import modules\n import numpy as np\n from netCDF4 import Dataset\n import warnings\n import calc_Utilities as UT\n from calendar import monthrange\n warnings.simplefilter(action='ignore', category=FutureWarning)\n warnings.simplefilter(action='ignore', category=RuntimeWarning)\n \n ###########################################################################\n ### Parameters\n time = np.arange(1950,2020+1,1)\n monthslice = sliceyear.shape[0]*12\n mon = 12\n \n ###########################################################################\n ### Read in data\n filename = 'monthly/%s_1950-2020.nc' % variq\n data = Dataset(directory + filename,'r')\n lat1 = data.variables['latitude'][:]\n lon1 = data.variables['longitude'][:]\n var = data.variables['%s' % variq][:,:,:]\n data.close()\n \n print('Years of output =',sliceyear.min(),'to',sliceyear.max())\n ###########################################################################\n ### Reshape data into [year,month,lat,lon]\n datamon = np.reshape(var,(var.shape[0]//mon,mon,\n lat1.shape[0],lon1.shape[0]))\n \n ###########################################################################\n ### Return absolute temperature (1981-2010 baseline)\n if addclimo == True:\n varmon = datamon\n print('Completed: calculated absolute variable!')\n else:\n yearbasemin = 1981\n yearbasemax = 2010\n yearq = np.where((time >= yearbasemin) & (time<=yearbasemax))[0]\n varmon = datamon - np.nanmean(datamon[yearq,:,:,:],axis=0)\n print('Completed: calculated anomalies!')\n \n ###########################################################################\n ### Slice over months (currently = [yr,mn,lat,lon])\n ### Shape of output array\n if sliceperiod == 'annual':\n vartime = np.nanmean(varmon,axis=1)\n if sliceshape == 1:\n varshape = vartime.ravel()\n elif sliceshape == 3:\n varshape = vartime\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: ANNUAL MEAN!')\n elif sliceperiod == 'DJF':\n varshape = UT.calcDecJanFeb(varmon,lat1,lon1,'surface',1)\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: DJF MEAN!')\n elif sliceperiod == 'JJA':\n vartime = np.nanmean(varmon[:,5:8,:,:],axis=1)\n if sliceshape == 1:\n varshape = vartime.ravel()\n elif sliceshape == 3:\n varshape = vartime\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: JJA MEAN!')\n elif sliceperiod == 'JFM':\n vartime = np.nanmean(varmon[:,0:3,:,:],axis=1)\n if sliceshape == 1:\n varshape = vartime.ravel()\n elif sliceshape == 3:\n varshape = vartime\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: JFM MEAN!')\n elif sliceperiod == 'AMJ':\n vartime = np.nanmean(varmon[:,3:6,:,:],axis=1)\n if sliceshape == 1:\n varshape = vartime.ravel()\n elif sliceshape == 3:\n varshape = vartime\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: AMJ MEAN!')\n elif sliceperiod == 'JAS':\n vartime = np.nanmean(varmon[:,6:9,:,:],axis=1)\n if sliceshape == 1:\n varshape = vartime.ravel()\n elif sliceshape == 3:\n varshape = vartime\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: JAS MEAN!')\n elif sliceperiod == 'SON':\n vartime = np.nanmean(varmon[:,8:11,:,:],axis=1)\n if sliceshape == 1:\n varshape = vartime.ravel()\n elif sliceshape == 3:\n varshape = vartime\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: SON MEAN!')\n elif sliceperiod == 'OND':\n vartime = np.nanmean(varmon[:,9:,:,:],axis=1)\n if sliceshape == 1:\n varshape = vartime.ravel()\n elif sliceshape == 3:\n varshape = vartime\n print('Shape of output = ', varshape.shape,[[varshape.ndim]])\n print('Completed: OND MEAN!')\n elif sliceperiod == 'none':\n vartime = varmon\n if sliceshape == 1:\n varshape = varshape.ravel()\n elif sliceshape == 3:\n varshape = np.reshape(vartime,(vartime.shape[0]*vartime.shape[1],\n vartime.shape[2],vartime.shape[3]))\n elif sliceshape == 4:\n varshape = varmon\n print('Shape of output =', varshape.shape, [[varshape.ndim]])\n print('Completed: ALL MONTHS!')\n \n ###########################################################################\n ### Change missing values\n if slicenan == 'nan':\n varshape[np.where(np.isnan(varshape))] = np.nan\n print('Completed: missing values are =',slicenan)\n else:\n varshape[np.where(np.isnan(varshape))] = slicenan\n \n ###########################################################################\n ### Change units\n if variq == 'SLP':\n varshape = varshape/100 # Pa to hPa\n print('Completed: Changed units (Pa to hPa)!')\n elif any([variq=='T2M',variq=='SST']):\n varshape = varshape - 273.15 # K to C\n print('Completed: Changed units (K to C)!')\n elif variq == 'P':\n varshape = varshape*1000 # m/day to mm/day\n ### \"Average Monthly Rate of Precipitation\"\n print('*** CURRENT UNITS ---> [[ mm/day ]]! ***')\n \n print('>>>>>>>>>> ENDING read_ERA5_monthlyBE (Back Extension) function!')\n return lat1,lon1,varshape\n\n# ### Test functions - do not use!\n# import numpy as np\n# import matplotlib.pyplot as plt\n# import calc_Utilities as UT\n# variq = 'T2M'\n# directory = '/Users/zlabe/Data/ERA5/'\n# sliceperiod = 'annual'\n# sliceyear = np.arange(1950,2020+1,1)\n# sliceshape = 3\n# slicenan = 'nan'\n# addclimo = True\n# lat,lon,var = read_ERA5_monthlyBE(variq,directory,sliceperiod,\n# sliceyear,sliceshape,addclimo,\n# slicenan)\n# lon2,lat2 = np.meshgrid(lon,lat)\n# ave = UT.calc_weightedAve(var,lat2)",
"\"\"\"\nFirst version of ANN to test new ML model - accompanying LRP script\n\nNotes : Need to use older TF1.15 environment with innvestigate\n\nAuthor : Zachary M. Labe\nDate : 25 August 2021\nVersion : 1 (mostly for testing)\n\"\"\"\n\n### Import packages\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\nfrom mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid\nimport palettable.cubehelix as cm\nimport cmocean as cmocean\nimport calc_Utilities as UT\nimport calc_dataFunctions as df\nimport calc_Stats as dSS\nimport calc_LRPclass as LRP\nimport innvestigate\nfrom sklearn.metrics import accuracy_score\nimport keras.backend as Back\nfrom keras.layers import Dense, Activation, Dropout\nfrom keras import regularizers,optimizers,metrics,initializers\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\n\n\n### Plotting defaults \nplt.rc('text',usetex=True)\nplt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']})\n\n###############################################################################\n###############################################################################\n###############################################################################\n### Original model\ndef loadmodel(Xtrain,Xtest,Ytrain,Ytest,hidden,random_network_seed,random_segment_seed,n_epochs,batch_size,lr_here,ridgePenalty,actFun,input_shape,output_shape,vari_predict):\n ### Directory of saved models\n dirname = '/Users/zlabe/Documents/Research/GmstTrendPrediction/SavedModels/'\n \n print('----ANN Training: learning rate = '+str(lr_here)+'; activation = '+actFun+'; batch = '+str(batch_size) + '----')\n Back.clear_session()\n model = Sequential()\n\n ### Input layer\n model.add(Dense(hidden[0],input_shape=(input_shape,),\n activation=actFun))\n\n ### Initialize other layers\n for layer in hidden[1:]:\n model.add(Dense(layer,activation=actFun))\n \n print('\\nTHIS IS AN ANN!\\n')\n\n #### Initialize output layer\n model.add(Dense(output_shape,activation=None))\n\n ### Add softmax layer at the end\n model.add(Activation('softmax'))\n \n ### Add weights from compiled model\n savename = 'ANNv2_'+vari_predict[0]+'_hiatus_' + actFun + '_L2_'+ str(ridgePenalty)+ '_LR_' + str(lr_here)+ '_Batch'+ str(batch_size)+ '_Iters' + str(n_epochs) + '_' + str(len(hidden)) + 'x' + str(hidden[0]) + '_SegSeed' + str(random_segment_seed) + '_NetSeed'+ str(random_network_seed) \n if(rm_ensemble_mean==True):\n savename = savename + '_EnsembleMeanRemoved' \n \n modelwrite = dirname + savename + '.h5'\n model.load_weights(modelwrite)\n \n return model\n\n### Hyperparamters for files of the ANN model\nrm_ensemble_mean = True\n\nif rm_ensemble_mean == False:\n variq = 'T2M'\n vari_predict = ['OHC100']\n fac = 0.8\n random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True))\n random_network_seed = 87750\n hidden = [20,20]\n n_epochs = 500\n batch_size = 128\n lr_here = 0.001\n ridgePenalty = 0.05\n actFun = 'relu'\n fractWeight = 0.5\n yearsall = np.arange(1990,2099+1,1)\nelif rm_ensemble_mean == True:\n variq = 'T2M'\n vari_predict = ['OHC100']\n fac = 0.7\n random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True))\n random_network_seed = 87750\n hidden = [30,30]\n n_epochs = 500\n batch_size = 128\n lr_here = 0.001\n ridgePenalty = 0.5\n actFun = 'relu'\n fractWeight = 0.5\n yearsall = np.arange(1990,2099+1,1)\nelse:\n print(ValueError('SOMETHING IS WRONG WITH DATA PROCESSING!'))\n sys.exit()\n \n### Read in data\ndirectorymodel = '/Users/zlabe/Documents/Research/GmstTrendPrediction/SavedModels/'\nsavename = 'ANNv2_'+vari_predict[0]+'_hiatus_' + actFun + '_L2_'+ str(ridgePenalty)+ '_LR_' + str(lr_here)+ '_Batch'+ str(batch_size)+ '_Iters' + str(n_epochs) + '_' + str(len(hidden)) + 'x' + str(hidden[0]) + '_SegSeed' + str(random_segment_seed) + '_NetSeed'+ str(random_network_seed) \nif(rm_ensemble_mean==True):\n savename = savename + '_EnsembleMeanRemoved' \n\norigdata = np.load(directorymodel + savename + '.npz')\nXtrain = origdata['Xtrain']\nYtrain = origdata['Ytrain']\nXtest = origdata['Xtest']\nYtest = origdata['Ytest']\nXobsS = origdata['XobsS']\nlats = origdata['lats']\nlons = origdata['lons']\nyearsall = np.arange(1990,2100+1,1)\n\n### Standardize\nXtrainS,XtestS,stdVals = dSS.standardize_data(Xtrain,Xtest)\nXmean, Xstd = stdVals \n\n### ANN model paramaters\ninput_shape=np.shape(Xtrain)[1]\noutput_shape=np.shape(Ytrain)[1]\n\n### Load model \nmodel = loadmodel(Xtrain,Xtest,Ytrain,Ytest,hidden,random_network_seed,random_segment_seed,n_epochs,batch_size,lr_here,ridgePenalty,actFun,input_shape,output_shape,vari_predict)\n\n##############################################################################\n##############################################################################\n##############################################################################\n### Calculate LRP\nbiasBool = False\nnum_of_class = 2\nannType = 'class'\nlrpRule = 'z'\nnormLRP = True\nnumLats = lats.shape[0]\nnumLons = lons.shape[0]\nnumDim = 3\n\nlrpall = LRP.calc_LRPModel(model,np.append(XtrainS,XtestS,axis=0),\n np.append(Ytrain,Ytest,axis=0),\n biasBool,annType,num_of_class,\n yearsall,lrpRule,normLRP,\n numLats,numLons,numDim)\nmeanlrp = np.nanmean(lrpall,axis=0)\nfig=plt.figure()\nplt.contourf(meanlrp,300,cmap=cmocean.cm.thermal)\n\n### For training data only\nlrptrain = LRP.calc_LRPModel(model,XtrainS,Ytrain,biasBool,\n annType,num_of_class,\n yearsall,lrpRule,normLRP,\n numLats,numLons,numDim)\n\n### For training data only\nlrptest = LRP.calc_LRPModel(model,XtestS,Ytest,biasBool,\n annType,num_of_class,\n yearsall,lrpRule,normLRP,\n numLats,numLons,numDim)\n\n### For observations data only\nlrpobservations = LRP.calc_LRPObs(model,XobsS,biasBool,annType,\n num_of_class,yearsall,lrpRule,\n normLRP,numLats,numLons,numDim)\n\n##############################################################################\n##############################################################################\n##############################################################################\ndef netcdfLRP(lats,lons,var,directory,typemodel,saveData):\n print('\\n>>> Using netcdfLRP function!')\n \n from netCDF4 import Dataset\n import numpy as np\n \n name = 'LRPMap' + typemodel + '_' + saveData + '.nc'\n filename = directory + name\n ncfile = Dataset(filename,'w',format='NETCDF4')\n ncfile.description = 'LRP maps for using selected seed' \n \n ### Dimensions\n ncfile.createDimension('years',var.shape[0])\n ncfile.createDimension('lat',var.shape[1])\n ncfile.createDimension('lon',var.shape[2])\n \n ### Variables\n years = ncfile.createVariable('years','f4',('years'))\n latitude = ncfile.createVariable('lat','f4',('lat'))\n longitude = ncfile.createVariable('lon','f4',('lon'))\n varns = ncfile.createVariable('LRP','f4',('years','lat','lon'))\n \n ### Units\n varns.units = 'unitless relevance'\n ncfile.title = 'LRP relevance'\n ncfile.instituion = 'Colorado State University'\n ncfile.references = 'Barnes et al. [2020]'\n \n ### Data\n years[:] = np.arange(var.shape[0])\n latitude[:] = lats\n longitude[:] = lons\n varns[:] = var\n \n ncfile.close()\n print('*Completed: Created netCDF4 File!')\n\ndirectoryoutput = '/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/'\nnetcdfLRP(lats,lons,lrpall,directoryoutput,'AllData',savename)\nnetcdfLRP(lats,lons,lrptrain,directoryoutput,'Training',savename)\nnetcdfLRP(lats,lons,lrptest,directoryoutput,'Testing',savename)\nnetcdfLRP(lats,lons,lrpobservations,directoryoutput,'Obs',savename)\n",
"\"\"\"\nMake figure of predictions of testing data for paper\n\nAuthor : Zachary M. Labe\nDate : 6 October 2021\nVersion : 2 \n\"\"\"\n\n### Import packages\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n### Plotting defaults \nplt.rc('text',usetex=True)\nplt.rc('font',**{'family':'sans-serif','sans-serif':['Avant Garde']})\n\n### Hyperparamters for files of the ANN model\nrm_ensemble_mean = True\nens1 = np.arange(1,10+1,1)\nens2 = np.arange(21,50+1,1)\nens = np.append(ens1,ens2)\n\nif rm_ensemble_mean == False:\n vari_predict = ['OHC100']\n fac = 0.7\n random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True))\n random_network_seed = 87750\n hidden = [20,20]\n n_epochs = 500\n batch_size = 128\n lr_here = 0.001\n ridgePenalty = 0.05\n actFun = 'relu'\n fractWeight = 0.5\n yearsall = np.arange(1990,2090+1,1)\nelif rm_ensemble_mean == True:\n vari_predict = ['OHC100']\n fac = 0.7\n random_segment_seed = int(np.genfromtxt('/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/SelectedSegmentSeed.txt',unpack=True))\n random_network_seed = 87750\n hidden = [30,30]\n n_epochs = 500\n batch_size = 128\n lr_here = 0.001\n ridgePenalty = 0.5\n actFun = 'relu'\n fractWeight = 0.5\n yearsall = np.arange(1990,2090+1,1)\nelse:\n print(ValueError('SOMETHING IS WRONG WITH DATA PROCESSING!'))\n sys.exit()\n\n### Naming conventions for files\ndirectorymodel = '/Users/zlabe/Documents/Research/GmstTrendPrediction/SavedModels/'\nsavename = 'ANNv2_'+vari_predict[0]+'_hiatus_' + actFun + '_L2_'+ str(ridgePenalty)+ '_LR_' + str(lr_here)+ '_Batch'+ str(batch_size)+ '_Iters' + str(n_epochs) + '_' + str(len(hidden)) + 'x' + str(hidden[0]) + '_SegSeed' + str(random_segment_seed) + '_NetSeed'+ str(random_network_seed) \nif(rm_ensemble_mean==True):\n savename = savename + '_EnsembleMeanRemoved' \n \n### Directories to save files\ndirectorydata = '/Users/zlabe/Documents/Research/GmstTrendPrediction/Data/'\ndirectoryfigure = '/Users/zlabe/Desktop/GmstTrendPrediction/MS-Figures_v1/'\n\n###############################################################################\n###############################################################################\n###############################################################################\n### Read in data for testing predictions and actual hiatuses\ntestindices = np.genfromtxt(directorydata + 'testingEnsIndices_' + savename + '.txt').astype(int)\nactual_test = np.genfromtxt(directorydata + 'testingTrueLabels_' + savename + '.txt')\npredict_test = np.genfromtxt(directorydata + 'testingPredictedLabels_' + savename+ '.txt')\npredict_testconf = np.genfromtxt(directorydata + 'testingPredictedConfidence_' + savename+ '.txt')[:,1]\n\n### Reshape arrays for [ensemble,year]\nact_re = np.swapaxes(actual_test.reshape(testindices.shape[0],1,yearsall.shape[0]),0,1).squeeze()\npre_re = np.swapaxes(predict_test.reshape(testindices.shape[0],1,yearsall.shape[0]),0,1).squeeze()\npre_reconf = np.swapaxes(predict_testconf.reshape(testindices.shape[0],1,yearsall.shape[0]),0,1).squeeze()\n\n###############################################################################\n###############################################################################\n###############################################################################\n### Count hiatuses in testing\nuniquetest,counttest = np.unique(predict_test,return_counts=True)\nactual_uniquetest,actual_counttest = np.unique(actual_test,return_counts=True)\n\n###############################################################################\n###############################################################################\n###############################################################################\n### Create arrays for plotting\ndef adjust_spines(ax, spines):\n for loc, spine in ax.spines.items():\n if loc in spines:\n spine.set_position(('outward', 5))\n else:\n spine.set_color('none') \n if 'left' in spines:\n ax.yaxis.set_ticks_position('left')\n else:\n ax.yaxis.set_ticks([])\n\n if 'bottom' in spines:\n ax.xaxis.set_ticks_position('bottom')\n else:\n ax.xaxis.set_ticks([]) \n\nlength = np.arange(yearsall.shape[0])\n\nfor i in range(testindices.shape[0]):\n act_re[i,np.where(act_re[i] == 1)] = i+1\n pre_re[i,np.where(pre_re[i] == 1)] = i+1\nact_re[np.where(act_re == 0)] = np.nan\npre_re[np.where(pre_re == 0)] = np.nan\n\nfig = plt.figure()\nax = plt.subplot(111)\nadjust_spines(ax, ['left', 'bottom'])\nax.spines['top'].set_color('none')\nax.spines['right'].set_color('none')\nax.spines['left'].set_color('none')\nax.spines['bottom'].set_color('dimgrey')\nax.spines['left'].set_linewidth(2)\nax.spines['bottom'].set_linewidth(2)\nax.tick_params('both',length=4,width=2,which='major',color='dimgrey')\nax.tick_params(axis='y',which='both',length=0)\nax.yaxis.grid(zorder=1,color='dimgrey',alpha=0.35,clip_on=False)\n\nfor i in range(testindices.shape[0]):\n plt.scatter(yearsall,act_re[i],s=50,color='darkgrey',clip_on=False,zorder=2,\n edgecolor='k',linewidth=0.1,label='Actual Slowdowns')\n for yr in range(pre_re.shape[1]):\n if act_re[i,yr] == pre_re[i,yr]:\n cc = 'deepskyblue'\n label = 'Correct Predictions'\n elif act_re[i,yr] != pre_re[i,yr]:\n cc = 'crimson'\n label = 'Wrong Predictions'\n else:\n print(ValueError('SOMETHING MIGHT BE WRONG!'))\n sys.exit()\n plt.scatter(yearsall[yr],pre_re[i,yr],s=20,color=cc,clip_on=False,\n zorder=3,edgecolor='k',linewidth=0.1,label=label)\n if i == 0:\n if yr == 3:\n leg = plt.legend(shadow=False,fontsize=10,loc='upper center',\n bbox_to_anchor=(0.5,1.175),\n fancybox=True,ncol=3,frameon=False,\n handlelength=0)\n \nplt.xticks(np.arange(1990,2101,10),map(str,np.arange(1990,2101,10)),size=7)\nplt.yticks(np.arange(1,testindices.shape[0]+1,1),map(str,ens[testindices]),size=7)\nplt.xlim([1990,2090]) \nplt.ylim([1,testindices.shape[0]])\nplt.xlabel(r'\\textbf{Years}')\nplt.ylabel(r'\\textbf{Ensemble Member \\#}')\n\nplt.savefig(directoryfigure + 'Figure_2.png',dpi=600)\n\n\n",
"\"\"\"\nFunctions calculate hiatus and acceleration definitions\n \nNotes\n-----\n Author : Zachary Labe\n Date : 1 September 2021\n \nUsage\n-----\n [1] calc_thresholdOfTrend(data,trendlength,years,AGWstart,typeOfTrend)\n [2] calc_HiatusAcc(data,trendlength,years,AGWstart,SLOPEthresh,typeOfTrend)\n [3] combineEvents(hiatus,accel,typeOfData)\n\"\"\"\ndef calc_thresholdOfTrend(data,trendlength,years,AGWstart,typeOfTrend): \n \"\"\"\n Function calculates threshold for trend analysis of hiatus or acceleration\n\n Parameters\n ----------\n data : n-d numpy array\n data from selected data set\n trendlength : integer\n length of trend periods to calculate\n years : 1d array\n Original years of input data\n AGWstart : integer\n Start of data to calculate trends over\n typeOfTrend : string\n hiatus or accel\n \n Returns\n -------\n SLOPEthresh : float \n float of the actual trend for hiatus or acceleration\n obsdiff : float\n PERCENT difference compared to mean decadal trencds and \n the hiatus/acceleration\n\n Usage\n -----\n SLOPEthresh,obsdiff = calc_thresholdOfTrend(data,trendlength,years,AGWstart,typeOfTrend)\n \"\"\"\n print('\\n>>>>>>>>>> Using calc_thresholdOfTrend function!')\n \n ### Import modules\n import numpy as np\n import sys\n \n if data.ndim == 1: \n ### Pick start of forced climate change\n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ### Calculate trend periods\n yearstrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n datatrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n for hi in range(len(yearsnew)-(trendlength-1)):\n yearstrend[hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrend[hi,:] = data[hi:hi+trendlength]\n\n ### Calculate trend lines \n linetrend = np.empty((len(yearsnew)-trendlength+1,2))\n for hi in range(len(yearsnew)-trendlength+1):\n linetrend[hi,:] = np.polyfit(yearstrend[hi],datatrend[hi],1)\n \n ### Slopes\n slope = linetrend[:,0]\n stdslope = np.nanstd(slope)\n meantrend = np.nanmean(slope)\n \n print('\\n**%s** is %s years long!' % (typeOfTrend,trendlength))\n print('-- Number of years is',yearsnew.shape[0],'and number of trends is',slope.shape[0],'--')\n \n if typeOfTrend == 'hiatus':\n SLOPEthresh = meantrend - (1*stdslope)\n obsdiff = SLOPEthresh/meantrend\n elif typeOfTrend == 'accel':\n SLOPEthresh = meantrend + (1*stdslope)\n obsdiff = SLOPEthresh/meantrend\n \n elif data.ndim == 2:\n ### Pick start of forced climate change\n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[:,yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ensmean = np.nanmean(data,axis=0)\n yearstrendens = np.empty((len(yearsnew)-trendlength+1,trendlength))\n datatrendens = np.empty((len(yearsnew)-trendlength+1,trendlength))\n for hi in range(len(yearsnew)-(trendlength-1)):\n yearstrendens[hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrendens[hi,:] = ensmean[hi:hi+trendlength]\n\n ### Calculate trend lines \n linetrendens = np.empty((len(yearsnew)-trendlength+1,2))\n for hi in range(len(yearsnew)-trendlength+1):\n linetrendens[hi,:] = np.polyfit(yearstrendens[hi],datatrendens[hi],1)\n \n ### Slopes\n slopeens = linetrendens[:,0]\n stdslopeens = np.nanstd(slopeens)\n meantrendens = np.nanmean(slopeens) \n SLOPEthresh = slopeens\n obsdiff = np.nan\n \n else:\n print(ValueError('WRONG DIMENSIONS OF OBS!'))\n sys.exit()\n \n print('>>>>>>>>>> Ending calc_thresholdOfTrend function!')\n return SLOPEthresh,obsdiff\n\ndef calc_HiatusAcc(data,trendlength,years,AGWstart,SLOPEthresh,typeOfTrend,diffBase):\n \"\"\"\n Function calculates actual trend analysis of hiatus or acceleration in \n observations and climate model data\n\n Parameters\n ----------\n data : n-d numpy array\n data from selected data set\n trendlength : integer\n length of trend periods to calculate\n years : 1d array\n Original years of input data\n AGWstart : integer\n Start of data to calculate trends over\n SLOPEthresh : float\n float of the actual trend for hiatus or acceleration\n typeOfTrend : string\n hiatus or accel\n diffBase : float\n percent difference from mean trend trends and obs hiatus/acceleration events\n \n Returns\n -------\n yearstrend : 2-d array\n years calculated for each individual trend line\n linetrend : 2-d array\n slopes and intercepts for each trend line\n indexslopeNegative : n-d array\n index of hiatus or acceleration events\n classes : n-day array\n array of binary numbers for yes event or no event\n \n Usage\n -----\n yearstrend,linetrend,indexslopeNegative,classes = calc_HiatusAcc(data,trendlength,years,AGWstart,SLOPEthresh,typeOfTrend,diffBase)\n \"\"\"\n print('\\n>>>>>>>>>> Using calc_HiatusAcc function!')\n \n ### Import modules\n import numpy as np\n import sys\n \n hiatusSLOPE = SLOPEthresh\n \n if data.ndim == 1: \n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ### Calculate trend periods\n yearstrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n datatrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n for hi in range(len(yearsnew)-(trendlength-1)):\n yearstrend[hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrend[hi,:] = data[hi:hi+trendlength]\n\n ### Calculate trend lines \n linetrend = np.empty((len(yearsnew)-trendlength+1,2))\n for hi in range(len(yearsnew)-trendlength+1): \n linetrend[hi,:] = np.polyfit(yearstrend[hi],datatrend[hi],1)\n \n ### Count number of hiatus or acceleration periods\n slope = linetrend[:,0] \n if typeOfTrend == 'hiatus':\n indexslopeNegative = np.where((slope[:] <= hiatusSLOPE))[0]\n elif typeOfTrend == 'accel':\n indexslopeNegative = np.where((slope[:] > hiatusSLOPE))[0]\n else:\n print(ValueError('--- WRONG TYPE OF EVENT! ---'))\n sys.exit()\n print('INDEX OF **%s**---->' % typeOfTrend,indexslopeNegative)\n \n ### Calculate classes\n classes = np.zeros((len(yearsnew)))\n classes[indexslopeNegative] = 1\n \n elif data.ndim == 2:\n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[:,yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ens = len(data)\n \n ### Calculate trend periods\n yearstrend = np.empty((ens,len(yearsnew)-trendlength+1,trendlength))\n datatrend = np.empty((ens,len(yearsnew)-trendlength+1,trendlength))\n for e in range(ens):\n for hi in range(len(yearsnew)-trendlength+1):\n yearstrend[e,hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrend[e,hi,:] = data[e,hi:hi+trendlength] \n \n ### Calculate trend lines\n linetrend = np.empty((ens,len(yearsnew)-trendlength+1,2))\n for e in range(ens):\n for hi in range(len(yearsnew)-trendlength+1):\n linetrend[e,hi,:] = np.polyfit(yearstrend[e,hi],datatrend[e,hi],1)\n \n ### Count number of hiatus periods\n slope = linetrend[:,:,0]\n\n if typeOfTrend == 'hiatus':\n indexslopeNegative = []\n for e in range(ens):\n hiatusSLOPEq = hiatusSLOPE*diffBase\n indexslopeNegativeyr = []\n for yr in range(hiatusSLOPEq.shape[0]):\n if slope[e,yr] <= hiatusSLOPEq[yr]:\n indexslopeNegativeyr.append(yr)\n indexslopeNegative.append(indexslopeNegativeyr)\n elif typeOfTrend == 'accel':\n indexslopeNegative = []\n for e in range(ens):\n hiatusSLOPEq = hiatusSLOPE*diffBase\n indexslopeNegativeyr = []\n for yr in range(hiatusSLOPEq.shape[0]):\n if slope[e,yr] > hiatusSLOPEq[yr]:\n indexslopeNegativeyr.append(yr)\n indexslopeNegative.append(indexslopeNegativeyr)\n else:\n print(ValueError('--- WRONG TYPE OF EVENT! ---'))\n sys.exit()\n \n ### Calculate classes\n classes = np.zeros((data.shape))\n for e in range(ens):\n classes[e,indexslopeNegative[e]] = 1\n \n print('\\n>>>>>>>>>> Ending calc_HiatusAcc function!') \n return yearstrend,linetrend,indexslopeNegative,classes\n\ndef combineEvents(hiatus,accel,typeOfData):\n \"\"\"\n Function calculates actual trend analysis of hiatus or acceleration in \n observations and climate model data\n\n Parameters\n ----------\n hiatus : n-d array\n binary array of hiatus events for all years in data\n accel : n-d array\n binary array of acceleration events for all years in data\n typeOfTrend : string\n hiatus or accel\n \n Returns\n -------\n classEVENTs : n-dy array\n array of classes for both hiatus and acceleration events (0,1,2)\n\n Usage\n -----\n classEVENTs = combineEvents(hiatus,accel,typeOfData)\n \"\"\"\n print('\\n>>>>>>>>>> Using combineEvents function!')\n \n ### Import modules\n import numpy as np\n import sys\n \n if typeOfData == 'obs':\n zerosAll = np.zeros((hiatus.shape))\n \n whereH = np.where((hiatus == 1.))[0]\n whereA = np.where((accel == 1.))[0]\n zerosAll[whereH] = 1.\n zerosAll[whereA] = 2.\n classEVENTs = zerosAll\n print(typeOfData)\n elif typeOfData == 'model':\n ens = len(hiatus)\n classEVENTs = np.empty((hiatus.shape))\n for e in range(ens):\n zerosAll = np.zeros((hiatus[e].shape))\n \n whereH = np.where((hiatus[e] == 1.))[0]\n whereA = np.where((accel[e] == 1.))[0]\n zerosAll[whereH] = 1.\n zerosAll[whereA] = 2.\n classEVENTs[e,:] = zerosAll\n print(typeOfData)\n else:\n print(ValueError('WRONG TYPE OF DATA SET!'))\n sys.exit()\n \n print('>>>>>>>>>> Ending combineEvents function!')\n return classEVENTs"
] |
[
[
"numpy.reshape",
"numpy.arange",
"numpy.isnan",
"numpy.nanmean"
],
[
"numpy.reshape",
"numpy.arange",
"numpy.isnan",
"numpy.nanmean",
"numpy.where"
],
[
"matplotlib.pyplot.contourf",
"numpy.arange",
"matplotlib.pyplot.rc",
"numpy.genfromtxt",
"numpy.append",
"numpy.shape",
"numpy.nanmean",
"numpy.load",
"matplotlib.pyplot.figure"
],
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.scatter",
"numpy.unique",
"numpy.arange",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.savefig",
"numpy.genfromtxt",
"numpy.append",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.where",
"matplotlib.pyplot.figure"
],
[
"numpy.polyfit",
"numpy.arange",
"numpy.empty",
"numpy.nanmean",
"numpy.nanstd",
"numpy.where",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lrast/gpytorch
|
[
"2e0bbc9f59e4b4b54780c3e55db784c3d2c9a5bf",
"2e0bbc9f59e4b4b54780c3e55db784c3d2c9a5bf",
"2e0bbc9f59e4b4b54780c3e55db784c3d2c9a5bf",
"2e0bbc9f59e4b4b54780c3e55db784c3d2c9a5bf"
] |
[
"test/lazy/test_chol_lazy_tensor.py",
"test/kernels/test_cosine_kernel.py",
"gpytorch/lazy/root_lazy_tensor.py",
"gpytorch/priors/lkj_prior.py"
] |
[
"#!/usr/bin/env python3\n\nimport unittest\n\nimport torch\n\nfrom gpytorch.lazy import CholLazyTensor, TriangularLazyTensor\nfrom gpytorch.test.lazy_tensor_test_case import LazyTensorTestCase\n\n\nclass TestCholLazyTensor(LazyTensorTestCase, unittest.TestCase):\n seed = 0\n should_test_sample = True\n should_call_cg = False\n should_call_lanczos = False\n\n def create_lazy_tensor(self):\n chol = torch.tensor(\n [[3, 0, 0, 0, 0], [-1, 2, 0, 0, 0], [1, 4, 1, 0, 0], [0, 2, 3, 2, 0], [-4, -2, 1, 3, 4]],\n dtype=torch.float,\n requires_grad=True,\n )\n return CholLazyTensor(TriangularLazyTensor(chol))\n\n def evaluate_lazy_tensor(self, lazy_tensor):\n chol = lazy_tensor.root.evaluate()\n return chol.matmul(chol.transpose(-1, -2))\n\n\nclass TestCholLazyTensorBatch(TestCholLazyTensor):\n seed = 0\n\n def create_lazy_tensor(self):\n chol = torch.tensor(\n [\n [[3, 0, 0, 0, 0], [-1, 2, 0, 0, 0], [1, 4, 1, 0, 0], [0, 2, 3, 2, 0], [-4, -2, 1, 3, 4]],\n [[2, 0, 0, 0, 0], [3, 1, 0, 0, 0], [-2, 3, 2, 0, 0], [-2, 1, -1, 3, 0], [-4, -4, 5, 2, 3]],\n ],\n dtype=torch.float,\n )\n chol.add_(torch.eye(5).unsqueeze(0))\n chol.requires_grad_(True)\n return CholLazyTensor(TriangularLazyTensor(chol))\n\n\nclass TestCholLazyTensorMultiBatch(TestCholLazyTensor):\n seed = 0\n # Because these LTs are large, we'll skil the big tests\n should_test_sample = False\n skip_slq_tests = True\n\n def create_lazy_tensor(self):\n chol = torch.tensor(\n [\n [[3, 0, 0, 0, 0], [-1, 2, 0, 0, 0], [1, 4, 1, 0, 0], [0, 2, 3, 2, 0], [-4, -2, 1, 3, 4]],\n [[2, 0, 0, 0, 0], [3, 1, 0, 0, 0], [-2, 3, 2, 0, 0], [-2, 1, -1, 3, 0], [-4, -4, 5, 2, 3]],\n ],\n dtype=torch.float,\n )\n chol = chol.repeat(3, 1, 1, 1)\n chol[1].mul_(2)\n chol[2].mul_(0.5)\n chol.add_(torch.eye(5).unsqueeze_(0).unsqueeze_(0))\n chol.requires_grad_(True)\n return CholLazyTensor(TriangularLazyTensor(chol))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"#!/usr/bin/env python3\n\nimport math\nimport unittest\n\nimport torch\n\nfrom gpytorch.kernels import CosineKernel\n\n\nclass TestCosineKernel(unittest.TestCase):\n def test_computes_periodic_function(self):\n a = torch.tensor([[4, 1], [2, 2], [8, 0]], dtype=torch.float)\n b = torch.tensor([[0, 0], [2, 1], [1, 0]], dtype=torch.float)\n period = 1\n kernel = CosineKernel().initialize(period_length=period)\n kernel.eval()\n\n actual = torch.zeros(3, 3)\n for i in range(3):\n for j in range(3):\n actual[i, j] = torch.cos(math.pi * ((a[i] - b[j]) / period).norm(2, dim=-1))\n\n res = kernel(a, b).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # diag\n res = kernel(a, b).diag()\n actual = actual.diag()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims\n actual = torch.zeros(2, 3, 3)\n for i in range(3):\n for j in range(3):\n for l in range(2):\n actual[l, i, j] = torch.cos(math.pi * ((a[i, l] - b[j, l]) / period))\n res = kernel(a, b, last_dim_is_batch=True).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims + diag\n res = kernel(a, b, last_dim_is_batch=True).diag()\n actual = torch.cat([actual[i].diag().unsqueeze(0) for i in range(actual.size(0))])\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n def test_batch(self):\n a = torch.tensor([[4, 2, 8], [1, 2, 3]], dtype=torch.float).view(2, 3, 1)\n b = torch.tensor([[0, 2, 1], [-1, 2, 0]], dtype=torch.float).view(2, 3, 1)\n period = torch.tensor(1, dtype=torch.float).view(1, 1, 1)\n kernel = CosineKernel().initialize(period_length=period)\n kernel.eval()\n\n actual = torch.zeros(2, 3, 3)\n for k in range(2):\n for i in range(3):\n for j in range(3):\n actual[k, i, j] = torch.cos(math.pi * ((a[k, i] - b[k, j]) / period))\n\n res = kernel(a, b).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n def test_batch_separate(self):\n a = torch.tensor([[[4, 1], [2, 2], [8, 0]], [[2, 5], [6, 1], [0, 1]]], dtype=torch.float)\n b = torch.tensor([[[0, 0], [2, 1], [1, 0]], [[1, 1], [2, 3], [1, 0]]], dtype=torch.float)\n period = torch.tensor([1, 2], dtype=torch.float).view(2, 1, 1)\n kernel = CosineKernel(batch_shape=torch.Size([2])).initialize(period_length=period)\n kernel.eval()\n\n actual = torch.zeros(2, 3, 3)\n for k in range(2):\n for i in range(3):\n for j in range(3):\n actual[k, i, j] = torch.cos(math.pi * ((a[k, i] - b[k, j]) / period[k]).norm(2, dim=-1))\n\n res = kernel(a, b).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # diag\n res = kernel(a, b).diag()\n actual = torch.cat([actual[i].diag().unsqueeze(0) for i in range(actual.size(0))])\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims\n actual = torch.zeros(2, 2, 3, 3)\n for k in range(2):\n for i in range(3):\n for j in range(3):\n for l in range(2):\n actual[k, l, i, j] = torch.cos(math.pi * ((a[k, i, l] - b[k, j, l]) / period[k]))\n res = kernel(a, b, last_dim_is_batch=True).evaluate()\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n # batch_dims + diag\n res = kernel(a, b, last_dim_is_batch=True).diag()\n actual = actual.diagonal(dim1=-2, dim2=-1)\n self.assertLess(torch.norm(res - actual), 1e-5)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"#!/usr/bin/env python3\n\nimport torch\n\nfrom ..utils.broadcasting import _pad_with_singletons\nfrom ..utils.getitem import _equal_indices, _noop_index\nfrom ..utils.memoize import cached\nfrom .lazy_tensor import LazyTensor\nfrom .matmul_lazy_tensor import MatmulLazyTensor\nfrom .non_lazy_tensor import NonLazyTensor, lazify\n\n\nclass RootLazyTensor(LazyTensor):\n def __init__(self, root):\n root = lazify(root)\n super().__init__(root)\n self.root = root\n\n def _expand_batch(self, batch_shape):\n if len(batch_shape) == 0:\n return self\n return self.__class__(self.root._expand_batch(batch_shape))\n\n def _get_indices(self, row_index, col_index, *batch_indices):\n row_index = row_index.unsqueeze(-1)\n col_index = col_index.unsqueeze(-1)\n batch_indices = tuple(batch_index.unsqueeze(-1) for batch_index in batch_indices)\n inner_index = torch.arange(0, self.root.size(-1), device=self.device)\n inner_index = _pad_with_singletons(inner_index, row_index.dim() - 1, 0)\n\n left_tensor = self.root._get_indices(row_index, inner_index, *batch_indices)\n if torch.equal(row_index, col_index):\n res = left_tensor.pow(2).sum(-1)\n else:\n right_tensor = self.root._get_indices(col_index, inner_index, *batch_indices)\n res = (left_tensor * right_tensor).sum(-1)\n return res\n\n def _getitem(self, row_index, col_index, *batch_indices):\n # Make sure we're not generating more memory with our \"efficient\" method\n if torch.is_tensor(row_index) and torch.is_tensor(col_index):\n num_indices = row_index.numel()\n if num_indices > self.matrix_shape.numel():\n return lazify(self.evaluate())._getitem(row_index, col_index, *batch_indices)\n\n left_tensor = self.root._getitem(row_index, _noop_index, *batch_indices)\n if _equal_indices(row_index, col_index):\n res = self.__class__(left_tensor)\n else:\n right_tensor = self.root._getitem(col_index, _noop_index, *batch_indices)\n res = MatmulLazyTensor(left_tensor, right_tensor.transpose(-1, -2))\n\n return res\n\n def _matmul(self, rhs):\n return self.root._matmul(self.root._t_matmul(rhs))\n\n def _mul_constant(self, constant):\n if constant > 0:\n res = self.__class__(self.root._mul_constant(constant.sqrt()))\n else:\n res = super()._mul_constant(constant)\n return res\n\n def _t_matmul(self, rhs):\n # Matrix is symmetric\n return self._matmul(rhs)\n\n def root_decomposition(self):\n return self\n\n def _root_decomposition(self):\n return self.root\n\n def _root_decomposition_size(self):\n return self.root.size(-1)\n\n def _size(self):\n return torch.Size((*self.root.batch_shape, self.root.size(-2), self.root.size(-2)))\n\n def _transpose_nonbatch(self):\n return self\n\n def diag(self):\n if isinstance(self.root, NonLazyTensor):\n return (self.root.tensor ** 2).sum(-1)\n else:\n return super().diag()\n\n @cached\n def evaluate(self):\n eval_root = self.root.evaluate()\n return torch.matmul(eval_root, eval_root.transpose(-1, -2))\n",
"#!/usr/bin/env python3\n\nimport math\nfrom numbers import Number\n\nimport torch\nfrom torch.distributions import constraints\nfrom torch.nn import Module as TModule\n\nfrom ..utils.cholesky import psd_safe_cholesky\nfrom .prior import Prior\n\n\nclass LKJPrior(Prior):\n r\"\"\"LKJ prior over n x n (positive definite) correlation matrices\n\n .. math:\n\n \\begin{equation*}\n pdf(\\Sigma) ~ |\\Sigma| ^ (\\eta - 1)\n \\end{equation*}\n\n where :math:`\\eta > 0` is a shape parameter.\n\n Reference: Bayesian Data Analysis, 3rd ed., Gelman et al., p. 576\n \"\"\"\n\n arg_constraints = {\"n\": constraints.positive_integer, \"eta\": constraints.positive}\n # TODO: move correlation matrix validation upstream into pytorch\n support = constraints.positive_definite\n _validate_args = True\n\n def __init__(self, n, eta, validate_args=False):\n TModule.__init__(self)\n if not isinstance(n, int) or n < 1:\n raise ValueError(\"n must be a positive integer\")\n if isinstance(eta, Number):\n eta = torch.tensor(float(eta))\n self.n = torch.tensor(n, dtype=torch.long, device=eta.device)\n batch_shape = eta.shape\n event_shape = torch.Size([n, n])\n # Normalization constant(s)\n i = torch.arange(n, dtype=eta.dtype, device=eta.device)\n C = (((2 * eta.view(-1, 1) - 2 + i) * i).sum(1) * math.log(2)).view_as(eta)\n C += n * torch.sum(2 * torch.lgamma(i / 2 + 1) - torch.lgamma(i + 2))\n # need to assign values before registering as buffers to make argument validation work\n self.eta = eta\n self.C = C\n super(LKJPrior, self).__init__(batch_shape, event_shape, validate_args=validate_args)\n # now need to delete to be able to register buffer\n del self.eta, self.C\n self.register_buffer(\"eta\", eta)\n self.register_buffer(\"C\", C)\n\n def log_prob(self, X):\n if any(s != self.n for s in X.shape[-2:]):\n raise ValueError(\"Correlation matrix is not of size n={}\".format(self.n.item()))\n if not _is_valid_correlation_matrix(X):\n raise ValueError(\"Input is not a valid correlation matrix\")\n log_diag_sum = psd_safe_cholesky(X, upper=True).diagonal(dim1=-2, dim2=-1).log().sum(-1)\n return self.C + (self.eta - 1) * 2 * log_diag_sum\n\n\nclass LKJCholeskyFactorPrior(LKJPrior):\n r\"\"\"LKJ prior over n x n (positive definite) Cholesky-decomposed\n correlation matrices\n\n .. math:\n\n \\begin{equation*}\n pdf(\\Sigma) ~ |\\Sigma| ^ (\\eta - 1)\n \\end{equation*}\n\n where :math:`\\eta > 0` is a shape parameter and n is the dimension of the\n correlation matrix.\n\n LKJCholeskyFactorPrior is different from LKJPrior in that it accepts the\n Cholesky factor of the correlation matrix to compute probabilities.\n \"\"\"\n\n support = constraints.lower_cholesky\n\n def log_prob(self, X):\n if any(s != self.n for s in X.shape[-2:]):\n raise ValueError(\"Cholesky factor is not of size n={}\".format(self.n.item()))\n if not _is_valid_correlation_matrix_cholesky_factor(X):\n raise ValueError(\"Input is not a Cholesky factor of a valid correlation matrix\")\n log_diag_sum = torch.diagonal(X, dim1=-2, dim2=-1).log().sum(-1)\n return self.C + (self.eta - 1) * 2 * log_diag_sum\n\n\nclass LKJCovariancePrior(LKJPrior):\n \"\"\"LKJCovariancePrior combines an LKJ prior over the correlation matrix\n and a user-specified prior over marginal standard deviations to return a\n prior over the full covariance matrix.\n\n Usage: LKJCovariancePrior(n, eta, sd_prior), where\n n is a positive integer, the size of the covariance matrix,\n eta is a positive shape parameter for the LKJPrior over correlations, and\n sd_prior is a scalar Prior over nonnegative numbers, which is used for\n each of the n marginal standard deviations on the covariance matrix.\n \"\"\"\n\n def __init__(self, n, eta, sd_prior, validate_args=False):\n if not isinstance(sd_prior, Prior):\n raise ValueError(\"sd_prior must be an instance of Prior\")\n if not isinstance(n, int):\n raise ValueError(\"n must be an integer\")\n if sd_prior.event_shape not in {torch.Size([1]), torch.Size([n])}:\n raise ValueError(\"sd_prior must have event_shape 1 or n\")\n correlation_prior = LKJPrior(n=n, eta=eta, validate_args=validate_args)\n if sd_prior.batch_shape != correlation_prior.batch_shape:\n raise ValueError(\"sd_prior must have same batch_shape as eta\")\n TModule.__init__(self)\n super(LKJPrior, self).__init__(\n correlation_prior.batch_shape, correlation_prior.event_shape, validate_args=False\n )\n self.correlation_prior = correlation_prior\n self.sd_prior = sd_prior\n\n def log_prob(self, X):\n marginal_var = torch.diagonal(X, dim1=-2, dim2=-1)\n if not torch.all(marginal_var >= 0):\n raise ValueError(\"Variance(s) cannot be negative\")\n marginal_sd = marginal_var.sqrt()\n sd_diag_mat = _batch_form_diag(1 / marginal_sd)\n correlations = torch.matmul(torch.matmul(sd_diag_mat, X), sd_diag_mat)\n log_prob_corr = self.correlation_prior.log_prob(correlations)\n log_prob_sd = self.sd_prior.log_prob(marginal_sd)\n return log_prob_corr + log_prob_sd\n\n\ndef _batch_form_diag(tsr):\n \"\"\"Form diagonal matrices in batch mode.\"\"\"\n eye = torch.eye(tsr.shape[-1], dtype=tsr.dtype, device=tsr.device)\n M = tsr.unsqueeze(-1).expand(tsr.shape + tsr.shape[-1:])\n return eye * M\n\n\ndef _is_valid_correlation_matrix(Sigma, tol=1e-6):\n \"\"\"Check if supplied matrix is a valid correlation matrix\n\n A matrix is a valid correlation matrix if it is positive semidefinite, and\n if all diagonal elements are equal to 1.\n\n Args:\n Sigma: A n x n correlation matrix, or a batch of b correlation matrices\n with shape b x n x n\n tol: The tolerance with which to check unit value of the diagonal elements\n\n Returns:\n True if Sigma is a valid correlation matrix, False otherwise (in batch\n mode, all matrices in the batch need to be valid correlation matrices)\n\n \"\"\"\n evals, _ = torch.symeig(Sigma, eigenvectors=False)\n if not torch.all(evals >= -tol):\n return False\n return all(torch.all(torch.abs(S.diag() - 1) < tol) for S in Sigma.view(-1, *Sigma.shape[-2:]))\n\n\ndef _is_valid_correlation_matrix_cholesky_factor(L, tol=1e-6):\n \"\"\"Check if supplied matrix is a Cholesky factor of a valid correlation matrix\n\n A matrix is a Cholesky fator of a valid correlation matrix if it is lower\n triangular, has positive diagonal, and unit row-sum\n\n Args:\n L: A n x n lower-triangular matrix, or a batch of b lower-triangular\n matrices with shape b x n x n\n tol: The tolerance with which to check positivity of the diagonal and\n unit-sum of the rows\n\n Returns:\n True if L is a Cholesky factor of a valid correlation matrix, False\n otherwise (in batch mode, all matrices in the batch need to be\n Cholesky factors of valid correlation matrices)\n\n \"\"\"\n unit_row_length = torch.all((torch.norm(L, dim=-1) - 1).abs() < tol)\n return unit_row_length and torch.all(constraints.lower_cholesky.check(L))\n"
] |
[
[
"torch.eye",
"torch.tensor"
],
[
"torch.Size",
"torch.norm",
"torch.zeros",
"torch.tensor",
"torch.cos"
],
[
"torch.is_tensor",
"torch.equal"
],
[
"torch.all",
"torch.Size",
"torch.diagonal",
"torch.norm",
"torch.nn.Module.__init__",
"torch.eye",
"torch.tensor",
"torch.matmul",
"torch.distributions.constraints.lower_cholesky.check",
"torch.symeig",
"torch.arange",
"torch.lgamma"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Ottawa-Autonomous-Vehicle-Group/learning-to-drive-in-5-minutes
|
[
"fb82bc77593605711289e03f95dcfb6d3ea9e6c3"
] |
[
"algos/custom_ppo2.py"
] |
[
"import time\nfrom collections import deque\n\nimport gym\nimport numpy as np\nfrom stable_baselines import logger, PPO2\nfrom stable_baselines.a2c.utils import total_episode_reward_logger\nfrom stable_baselines.common import explained_variance, TensorboardWriter\nfrom stable_baselines.common.runners import AbstractEnvRunner\nfrom stable_baselines.ppo2.ppo2 import get_schedule_fn, safe_mean, swap_and_flatten\n\n\nclass PPO2WithVAE(PPO2):\n \"\"\"\n Custom PPO2 version.\n\n Notable changes:\n - optimization is done after each episode and not after n steps\n \"\"\"\n def learn(self, total_timesteps, callback=None, log_interval=1, tb_log_name=\"PPO2\"):\n # Transform to callable if needed\n self.learning_rate = get_schedule_fn(self.learning_rate)\n self.cliprange = get_schedule_fn(self.cliprange)\n\n with TensorboardWriter(self.graph, self.tensorboard_log, tb_log_name) as writer:\n self._setup_learn()\n\n runner = Runner(env=self.env, model=self, n_steps=self.n_steps, gamma=self.gamma, lam=self.lam)\n self.episode_reward = np.zeros((self.n_envs,))\n\n ep_info_buf = deque(maxlen=100)\n t_first_start = time.time()\n n_timesteps = 0\n # nupdates = total_timesteps // self.n_batch\n for timestep in range(1, total_timesteps + 1):\n assert self.n_batch % self.nminibatches == 0\n batch_size = self.n_batch // self.nminibatches\n t_start = time.time()\n frac = 1.0 - timestep / total_timesteps\n lr_now = self.learning_rate(frac)\n cliprangenow = self.cliprange(frac)\n # true_reward is the reward without discount\n obs, returns, masks, actions, values, neglogpacs, states, ep_infos, true_reward = runner.run()\n n_timesteps += len(obs)\n ep_info_buf.extend(ep_infos)\n mb_loss_vals = []\n if states is None: # nonrecurrent version\n inds = np.arange(self.n_batch)\n for epoch_num in range(self.noptepochs):\n np.random.shuffle(inds)\n for start in range(0, self.n_batch, batch_size):\n # timestep = ((update * self.noptepochs * self.n_batch + epoch_num * self.n_batch + start) //\n # batch_size)\n end = start + batch_size\n mbinds = inds[start:end]\n slices = (arr[mbinds] for arr in (obs, returns, masks, actions, values, neglogpacs))\n mb_loss_vals.append(self._train_step(lr_now, cliprangenow, *slices, writer=writer,\n update=n_timesteps))\n else: # recurrent version\n assert self.n_envs % self.nminibatches == 0\n env_indices = np.arange(self.n_envs)\n flat_indices = np.arange(self.n_envs * self.n_steps).reshape(self.n_envs, self.n_steps)\n envs_per_batch = batch_size // self.n_steps\n for epoch_num in range(self.noptepochs):\n np.random.shuffle(env_indices)\n for stan_timestepsrt in range(0, self.n_envs, envs_per_batch):\n # timestep = ((update * self.noptepochs * self.n_envs + epoch_num * self.n_envs + start) //\n # envs_per_batch)\n end = start + envs_per_batch\n mb_env_inds = env_indices[start:end]\n mb_flat_inds = flat_indices[mb_env_inds].ravel()\n slices = (arr[mb_flat_inds] for arr in (obs, returns, masks, actions, values, neglogpacs))\n mb_states = states[mb_env_inds]\n mb_loss_vals.append(self._train_step(lr_now, cliprangenow, *slices, update=n_timesteps,\n writer=writer, states=mb_states))\n\n loss_vals = np.mean(mb_loss_vals, axis=0)\n t_now = time.time()\n fps = int(self.n_batch / (t_now - t_start))\n\n if writer is not None:\n self.episode_reward = total_episode_reward_logger(self.episode_reward,\n true_reward.reshape((self.n_envs, self.n_steps)),\n masks.reshape((self.n_envs, self.n_steps)),\n writer, n_timesteps)\n\n if self.verbose >= 1 and (timestep % log_interval == 0 or timestep == 1):\n explained_var = explained_variance(values, returns)\n logger.logkv(\"total_timesteps\", n_timesteps)\n logger.logkv(\"fps\", fps)\n logger.logkv(\"explained_variance\", float(explained_var))\n logger.logkv('ep_rewmean', safe_mean([ep_info['r'] for ep_info in ep_info_buf]))\n logger.logkv('eplenmean', safe_mean([ep_info['l'] for ep_info in ep_info_buf]))\n logger.logkv('time_elapsed', t_start - t_first_start)\n for (loss_val, loss_name) in zip(loss_vals, self.loss_names):\n logger.logkv(loss_name, loss_val)\n logger.dumpkvs()\n\n if callback is not None:\n # Only stop training if return value is False, not when it is None. This is for backwards\n # compatibility with callbacks that have no return statement.\n if callback(locals(), globals()) is False:\n break\n if n_timesteps > total_timesteps:\n break\n\n return self\n\n\nclass Runner(AbstractEnvRunner):\n def __init__(self, *, env, model, n_steps, gamma, lam):\n \"\"\"\n A runner to learn the policy of an environment for a model\n\n :param env: (Gym environment) The environment to learn from\n :param model: (Model) The model to learn\n :param n_steps: (int) The number of steps to run for each environment\n :param gamma: (float) Discount factor\n :param lam: (float) Factor for trade-off of bias vs variance for Generalized Advantage Estimator\n \"\"\"\n super().__init__(env=env, model=model, n_steps=n_steps)\n self.lam = lam\n self.gamma = gamma\n\n def run(self):\n \"\"\"\n Run a learning step of the model\n\n :return:\n - observations: (np.ndarray) the observations\n - rewards: (np.ndarray) the rewards\n - masks: (numpy bool) whether an episode is over or not\n - actions: (np.ndarray) the actions\n - values: (np.ndarray) the value function output\n - negative log probabilities: (np.ndarray)\n - states: (np.ndarray) the internal states of the recurrent policies\n - infos: (dict) the extra information of the model\n \"\"\"\n # mb stands for minibatch\n mb_obs, mb_rewards, mb_actions, mb_values, mb_dones, mb_neglogpacs = [], [], [], [], [], []\n mb_states = self.states\n ep_infos = []\n while True:\n actions, values, self.states, neglogpacs = self.model.step(self.obs, self.states, self.dones)\n mb_obs.append(self.obs.copy())\n mb_actions.append(actions)\n mb_values.append(values)\n mb_neglogpacs.append(neglogpacs)\n mb_dones.append(self.dones)\n clipped_actions = actions\n # Clip the actions to avoid out of bound error\n if isinstance(self.env.action_space, gym.spaces.Box):\n clipped_actions = np.clip(actions, self.env.action_space.low, self.env.action_space.high)\n self.obs[:], rewards, self.dones, infos = self.env.step(clipped_actions)\n for info in infos:\n maybe_ep_info = info.get('episode')\n if maybe_ep_info is not None:\n ep_infos.append(maybe_ep_info)\n mb_rewards.append(rewards)\n if self.dones:\n print(\"Episode finished. Reward: {:.2f} {} Steps\".format(np.sum(mb_rewards), len(mb_rewards)))\n if len(mb_rewards) >= self.n_steps:\n break\n\n # batch of steps to batch of rollouts\n mb_obs = np.asarray(mb_obs, dtype=self.obs.dtype)\n mb_rewards = np.asarray(mb_rewards, dtype=np.float32)\n mb_actions = np.asarray(mb_actions)\n mb_values = np.asarray(mb_values, dtype=np.float32)\n mb_neglogpacs = np.asarray(mb_neglogpacs, dtype=np.float32)\n mb_dones = np.asarray(mb_dones, dtype=np.bool)\n last_values = self.model.value(self.obs, self.states, self.dones)\n # discount/bootstrap off value fn\n mb_advs = np.zeros_like(mb_rewards)\n true_reward = np.copy(mb_rewards)\n last_gae_lam = 0\n for step in reversed(range(self.n_steps)):\n if step == self.n_steps - 1:\n nextnonterminal = 1.0 - self.dones\n nextvalues = last_values\n else:\n nextnonterminal = 1.0 - mb_dones[step + 1]\n nextvalues = mb_values[step + 1]\n delta = mb_rewards[step] + self.gamma * nextvalues * nextnonterminal - mb_values[step]\n mb_advs[step] = last_gae_lam = delta + self.gamma * self.lam * nextnonterminal * last_gae_lam\n mb_returns = mb_advs + mb_values\n\n mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs, true_reward = \\\n map(swap_and_flatten, (mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs, true_reward))\n\n return mb_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs, mb_states, ep_infos, true_reward\n"
] |
[
[
"numpy.clip",
"numpy.asarray",
"numpy.arange",
"numpy.random.shuffle",
"numpy.copy",
"numpy.zeros_like",
"numpy.mean",
"numpy.zeros",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ARSadri/RobustGaussianFittingLibrary
|
[
"e8f273f0fb363f3092628ff295758d45595b1f19"
] |
[
"RobustGaussianFittingLibrary/cWrapper.py"
] |
[
"\"\"\"\n------------------------------------------------------\nThis file is part of RobustGaussianFittingLibrary,\na free library WITHOUT ANY WARRANTY\nCopyright: 2017-2020 LaTrobe University Melbourne,\n 2019-2020 Deutsches Elektronen-Synchrotron\n------------------------------------------------------\n\"\"\"\n\n\"\"\" A ctypes wrapper for the Robust Gaussian Fitting Library C file\nNothing to look for in this file, its just a wrapper\n\"\"\"\nimport numpy as np\nimport ctypes\nimport os\nimport fnmatch\n\ndir_path = os.path.dirname(os.path.realpath(__file__)) + os.path.sep + '..' + os.path.sep\nfileNameTemplate = 'RGFLib*.so'\nflist = fnmatch.filter(os.listdir(dir_path + os.path.sep), fileNameTemplate)\nif(len(flist)==0):\t#for those who use make\n\tdir_path = os.path.dirname(os.path.realpath(__file__))\n\tfileNameTemplate = 'RGFLib*.so'\n\tflist = fnmatch.filter(os.listdir(dir_path + os.path.sep), fileNameTemplate)\n\t\nRGFCLib = ctypes.cdll.LoadLibrary(dir_path + os.path.sep + flist[0])\n\n'''\nvoid islandRemoval(unsigned char* inMask, unsigned char* labelMap, \n\t\t\t\t\t unsigned int X, unsigned int Y, \n\t\t\t\t\t unsigned int islandSizeThreshold)\n'''\nRGFCLib.islandRemoval.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_uint8, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_uint8, flags='C_CONTIGUOUS'),\n ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32]\n \n'''\nvoid indexCheck(float* inTensor, float* targetLoc, unsigned int X, unsigned int Y, unsigned int Z)\n'''\nRGFCLib.indexCheck.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_int, ctypes.c_int, ctypes.c_float]\n\n'''\nfloat MSSE(float *error, unsigned int vecLen, float MSSE_LAMBDA, unsigned int k, float minimumResidual)\n'''\nRGFCLib.MSSE.restype = ctypes.c_float\nRGFCLib.MSSE.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint, ctypes.c_float, ctypes.c_uint, ctypes.c_float ]\n\n'''\nfloat MSSEWeighted(float* error, float* weights, unsigned int vecLen, \n float MSSE_LAMBDA, unsigned int k, float minimumResidual)\n'''\nRGFCLib.MSSEWeighted.restype = ctypes.c_float\nRGFCLib.MSSEWeighted.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint, ctypes.c_float, ctypes.c_uint, ctypes.c_float ]\n\n'''\nvoid fitValue(float* inVec,\n\t\t\t float* inWeights,\n\t\t\t float* modelParams,\n\t\t\t float theta,\n\t\t\t unsigned int inN,\n float topkPerc,\n\t\t\t float botkPerc,\n float MSSE_LAMBDA,\n\t\t\t unsigned char optIters,\n float minimumResidual,\n\t\t\t unsigned int downSampledSize);\n'''\nRGFCLib.fitValue.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_float, \n ctypes.c_int, \n ctypes.c_float, \n ctypes.c_float, \n ctypes.c_float, \n ctypes.c_uint8, \n ctypes.c_float, \n ctypes.c_int]\n\n'''\nvoid fitValue2Skewed(float* inVec,\n\t\t\t float* inWeights,\n\t\t\t float* modelParams,\n\t\t\t float theta,\n\t\t\t unsigned int inN,\n\t\t\t\t\t float topkPerc,\n\t\t\t float botkPerc,\n float MSSE_LAMBDA,\n\t\t\t unsigned char optIters,\n float minimumResidual,\n\t\t\t unsigned int downSampledSize);\n''' \nRGFCLib.fitValue2Skewed.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_float, \n ctypes.c_int,\n ctypes.c_float, \n ctypes.c_float, \n ctypes.c_float, \n ctypes.c_uint8, \n ctypes.c_float, \n ctypes.c_int]\n\n\n'''\nvoid medianOfFits(float *vec, float *weights, \n float *modelParams, float theta, unsigned int N,\n float topkMin, float topkMax, unsigned int numSamples, float samplePerc,\n float MSSE_LAMBDA, unsigned char optIters, float minimumResidual) \n'''\nRGFCLib.medianOfFits.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_float, ctypes.c_uint32, \n ctypes.c_float, ctypes.c_float, ctypes.c_uint32, ctypes.c_float, \n ctypes.c_float, ctypes.c_uint8, ctypes.c_float] \n\n'''\nvoid RobustAlgebraicLineFitting(float* x, float* y, float* mP, unsigned int N,\n\t\t\t\t\t\t\t float topKthPerc, float bottomKthPerc, float MSSE_LAMBDA)\n''' \nRGFCLib.RobustAlgebraicLineFitting.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float]\n\n\n'''\nvoid RobustAlgebraicLineFittingTensor(float *inTensorX, float *inTensorY, \n float *modelParamsMap, unsigned int N,\n unsigned int X, unsigned int Y, \n float topKthPerc, float bottomKthPerc, float MSSE_LAMBDA)\n'''\nRGFCLib.RobustAlgebraicLineFittingTensor.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint, ctypes.c_uint, ctypes.c_uint,\n ctypes.c_float, ctypes.c_float, ctypes.c_float] \n \n'''\nvoid fitValueTensor(float* inTensor, float* inWeights, float* modelParamsMap,\n\t\t\t\t\tunsigned int N, unsigned int X, unsigned int Y,\n\t\t\t\t\tfloat topkPerc, float botkPerc, float MSSE_LAMBDA,\n\t\t\t\t\tunsigned char optIters, float minimumResidual,\n\t\t\t\t\tunsigned int downSampledSize);\n'''\nRGFCLib.fitValueTensor.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32,\n ctypes.c_float, ctypes.c_float, ctypes.c_float, \n ctypes.c_uint8, ctypes.c_float, ctypes.c_uint32]\n\n'''\nvoid RobustAlgebraicPlaneFitting(float* x, float* y, float* z, float* mP, float* mP_Init,\n\t\t\t\t\t\t\tunsigned int N, float topkPerc, float botkPerc,\n\t\t\t\t\t\t\tfloat MSSE_LAMBDA, unsigned char stretch2CornersOpt, \n\t\t\t\t\t\t\tfloat minimumResidual, unsigned char optIters)\n'''\nRGFCLib.RobustAlgebraicPlaneFitting.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_int, ctypes.c_float, ctypes.c_float, \n ctypes.c_float, ctypes.c_uint8, ctypes.c_float, ctypes.c_uint8]\n \n'''\nvoid RSGImage(float* inImage, unsigned char* inMask, float *modelParamsMap,\n\t\t\t\tunsigned int winX, unsigned int winY,\n\t\t\t\tunsigned int X, unsigned int Y,\n\t\t\t\tfloat topkPerc, float botkPerc,\n\t\t\t\tfloat MSSE_LAMBDA, unsigned char stretch2CornersOpt,\n\t\t\t\tunsigned char numModelParams, unsigned char optIters,\n float minimumResidual)\n''' \nRGFCLib.RSGImage.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_uint8, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint32, ctypes.c_uint32, \n ctypes.c_uint32, ctypes.c_uint32, \n ctypes.c_float, ctypes.c_float, \n ctypes.c_float, ctypes.c_uint8, \n ctypes.c_uint8, ctypes.c_uint8, ctypes.c_float]\n \n'''\nvoid RSGImage_by_Image_Tensor(float* inImage_Tensor, unsigned char* inMask_Tensor,\n\t\t\t\t\t\tfloat *model_mean, float *model_std,\n\t\t\t\t\t\tunsigned int winX, unsigned int winY,\n\t\t\t\t\t\tunsigned int N, unsigned int X, unsigned int Y,\n\t\t\t\t\t\tfloat topkPerc, float botkPerc,\n\t\t\t\t\t\tfloat MSSE_LAMBDA, unsigned char stretch2CornersOpt,\n\t\t\t\t\t\tunsigned char numModelParams, unsigned char optIters,\n float minimumResidual)\n'''\nRGFCLib.RSGImage_by_Image_Tensor.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_uint8, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint32, ctypes.c_uint32, \n ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32,\n ctypes.c_float, ctypes.c_float, \n ctypes.c_float, ctypes.c_uint8, \n ctypes.c_uint8, ctypes.c_uint8, ctypes.c_float]\n\n'''\nvoid fitBackgroundRadially(float* inImage, unsigned char* inMask,\n float* modelParamsMap, float* vecMP,\n unsigned int minRes,\n unsigned int maxRes,\n unsigned int shellWidth,\n unsigned int stride,\n unsigned int X_Cent,\n unsigned int Y_Cent,\n unsigned char includeCenter,\n unsigned int finiteSampleBias,\n unsigned int X, unsigned int Y,\n float topkPerc, float botkPerc,\n float MSSE_LAMBDA,\n unsigned char optIters,\n float minimumResidual);\n'''\n\nRGFCLib.fitBackgroundRadially.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_uint8, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, \n ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32,\n ctypes.c_uint8, ctypes.c_uint32, \n ctypes.c_uint32, ctypes.c_uint32, \n ctypes.c_float, ctypes.c_float, \n ctypes.c_float, ctypes.c_uint8, ctypes.c_float]\n\n'''\nvoid fitBackgroundCylindrically(float* inTensor,\n\t\t\t\t\t\t\t\tunsigned char* inMask,\n float* modelParamsMap,\n\t\t\t\t\t\t\t\tfloat* vecMP,\n unsigned int minRes,\n unsigned int maxRes,\n unsigned int shellWidth,\n unsigned char includeCenter,\n unsigned int finiteSampleBias,\n\t\t\t\t\t\t\t\tunsigned int N,\n unsigned int X,\n\t\t\t\t\t\t\t\tunsigned int Y,\n float topkPerc,\n\t\t\t\t\t\t\t\tfloat botkPerc,\n float MSSE_LAMBDA,\n unsigned char optIters,\n\t\t\t\t\t\t float minimumResidual)\n'''\nRGFCLib.fitBackgroundCylindrically.argtypes = [\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_uint8, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n np.ctypeslib.ndpointer(ctypes.c_float, flags='C_CONTIGUOUS'),\n ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, \n ctypes.c_uint8, ctypes.c_uint32, \n ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, \n ctypes.c_float, ctypes.c_float, \n ctypes.c_float, ctypes.c_uint8, ctypes.c_float]\n"
] |
[
[
"numpy.ctypeslib.ndpointer"
]
] |
[
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
whywhs/Detection_and_Recognition_in_Remote_Sensing_Image
|
[
"201c7450ad45d203b59d8345fb6fad903fad8748"
] |
[
"faster_rcnn/core/loader.py"
] |
[
"# --------------------------------------------------------\n# Deformable Convolutional Networks\n# Copyright (c) 2016 by Contributors\n# Copyright (c) 2017 Microsoft\n# Licensed under The Apache-2.0 License [see LICENSE for details]\n# Modified by Yuwen Xiong\n# --------------------------------------------------------\n\nimport numpy as np\nimport mxnet as mx\nfrom mxnet.executor_manager import _split_input_slice\n\nfrom config.config import config\nfrom utils.image import tensor_vstack\nfrom rpn.rpn import get_rpn_testbatch, get_rpn_batch, assign_anchor, get_rpn_batch_quadrangle, assign_quadrangle_anchor, get_rpn_quadrangle_testbatch\nfrom rcnn import get_rcnn_testbatch, get_rcnn_batch\n\n\nclass TestLoader(mx.io.DataIter):\n def __init__(self, roidb, config, batch_size=1, shuffle=False,\n has_rpn=False):\n super(TestLoader, self).__init__()\n\n # save parameters as properties\n self.cfg = config\n self.roidb = roidb\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.has_rpn = has_rpn\n\n # infer properties from roidb\n self.size = len(self.roidb)\n self.index = np.arange(self.size)\n\n # decide data and label names (only for training)\n if has_rpn:\n self.data_name = ['data', 'im_info']\n else:\n self.data_name = ['data', 'rois']\n self.label_name = None\n\n # status variable for synchronization between get_data and get_label\n self.cur = 0\n self.data = None\n self.label = []\n self.im_info = None\n\n # get first batch to fill in provide_data and provide_label\n self.reset()\n self.get_batch()\n\n @property\n def provide_data(self):\n return [[(k, v.shape) for k, v in zip(self.data_name, idata)] for idata in self.data]\n\n @property\n def provide_label(self):\n return [None for _ in range(len(self.data))]\n\n @property\n def provide_data_single(self):\n return [(k, v.shape) for k, v in zip(self.data_name, self.data[0])]\n\n @property\n def provide_label_single(self):\n return None\n\n def reset(self):\n self.cur = 0\n if self.shuffle:\n np.random.shuffle(self.index)\n\n def iter_next(self):\n return self.cur < self.size\n\n def next(self):\n if self.iter_next():\n self.get_batch()\n self.cur += self.batch_size\n return self.im_info, mx.io.DataBatch(data=self.data, label=self.label,\n pad=self.getpad(), index=self.getindex(),\n provide_data=self.provide_data, provide_label=self.provide_label)\n else:\n raise StopIteration\n\n def getindex(self):\n return self.cur / self.batch_size\n\n def getpad(self):\n if self.cur + self.batch_size > self.size:\n return self.cur + self.batch_size - self.size\n else:\n return 0\n\n def get_batch(self):\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n if self.has_rpn:\n data, label, im_info = get_rpn_testbatch(roidb, self.cfg)\n else:\n data, label, im_info = get_rcnn_testbatch(roidb, self.cfg)\n self.data = [[mx.nd.array(idata[name]) for name in self.data_name] for idata in data]\n self.im_info = im_info\n\n def get_batch_individual(self):\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n if self.has_rpn:\n data, label, im_info = get_rpn_testbatch(roidb, self.cfg)\n else:\n data, label, im_info = get_rcnn_testbatch(roidb, self.cfg)\n self.data = [mx.nd.array(data[name]) for name in self.data_name]\n self.im_info = im_info\n\n\nclass QuadrangleTestLoader(mx.io.DataIter):\n def __init__(self, roidb, config, batch_size=1, shuffle=False,\n has_rpn=False):\n super(QuadrangleTestLoader, self).__init__()\n\n # save parameters as properties\n self.cfg = config\n self.roidb = roidb\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.has_rpn = has_rpn\n\n # infer properties from roidb\n self.size = len(self.roidb)\n self.index = np.arange(self.size)\n\n # decide data and label names (only for training)\n if has_rpn:\n self.data_name = ['data', 'im_info']\n else:\n self.data_name = ['data', 'rois']\n self.label_name = None\n\n # status variable for synchronization between get_data and get_label\n self.cur = 0\n self.data = None\n self.label = []\n self.im_info = None\n\n # get first batch to fill in provide_data and provide_label\n # self.reset()\n self.get_batch()\n\n @property\n def provide_data(self):\n return [[(k, v.shape) for k, v in zip(self.data_name, idata)] for idata in self.data]\n\n @property\n def provide_label(self):\n return [None for _ in range(len(self.data))]\n\n @property\n def provide_data_single(self):\n return [(k, v.shape) for k, v in zip(self.data_name, self.data[0])]\n\n @property\n def provide_label_single(self):\n return None\n\n def reset(self):\n self.cur = 0\n if self.shuffle:\n np.random.shuffle(self.index)\n\n def iter_next(self):\n return self.cur < self.size\n\n def next(self):\n if self.iter_next():\n self.get_batch()\n self.cur += self.batch_size\n return self.im_info, mx.io.DataBatch(data=self.data, label=self.label,\n pad=self.getpad(), index=self.getindex(),\n provide_data=self.provide_data, provide_label=self.provide_label)\n else:\n raise StopIteration\n\n def getindex(self):\n return self.cur / self.batch_size\n\n def getpad(self):\n if self.cur + self.batch_size > self.size:\n return self.cur + self.batch_size - self.size\n else:\n return 0\n\n def get_batch(self):\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n if self.has_rpn:\n data, label, im_info = get_rpn_quadrangle_testbatch(roidb, self.cfg)\n else:\n data, label, im_info = get_rcnn_testbatch(roidb, self.cfg)\n self.data = [[mx.nd.array(idata[name]) for name in self.data_name] for idata in data]\n self.im_info = im_info\n\n def get_batch_individual(self):\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n if self.has_rpn:\n data, label, im_info = get_rpn_quadrangle_testbatch(roidb, self.cfg)\n else:\n data, label, im_info = get_rcnn_testbatch(roidb, self.cfg)\n self.data = [mx.nd.array(data[name]) for name in self.data_name]\n self.im_info = im_info\n\n\nclass ROIIter(mx.io.DataIter):\n def __init__(self, roidb, config, batch_size=2, shuffle=False, ctx=None, work_load_list=None, aspect_grouping=False):\n \"\"\"\n This Iter will provide roi data to Fast R-CNN network\n :param roidb: must be preprocessed\n :param batch_size: must divide BATCH_SIZE(128)\n :param shuffle: bool\n :param ctx: list of contexts\n :param work_load_list: list of work load\n :param aspect_grouping: group images with similar aspects\n :return: ROIIter\n \"\"\"\n super(ROIIter, self).__init__()\n\n # save parameters as properties\n self.roidb = roidb\n self.cfg = config\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.ctx = ctx\n if self.ctx is None:\n self.ctx = [mx.cpu()]\n self.work_load_list = work_load_list\n self.aspect_grouping = aspect_grouping\n\n # infer properties from roidb\n self.size = len(roidb)\n self.index = np.arange(self.size)\n\n # decide data and label names (only for training)\n self.data_name = ['data', 'rois']\n self.label_name = ['label', 'bbox_target', 'bbox_weight']\n\n # status variable for synchronization between get_data and get_label\n self.cur = 0\n self.batch = None\n self.data = None\n self.label = None\n\n # get first batch to fill in provide_data and provide_label\n self.reset()\n self.get_batch_individual()\n\n @property\n def provide_data(self):\n return [[(k, v.shape) for k, v in zip(self.data_name, self.data[i])] for i in xrange(len(self.data))]\n\n @property\n def provide_label(self):\n return [[(k, v.shape) for k, v in zip(self.label_name, self.label[i])] for i in xrange(len(self.data))]\n\n @property\n def provide_data_single(self):\n return [(k, v.shape) for k, v in zip(self.data_name, self.data[0])]\n\n @property\n def provide_label_single(self):\n return [(k, v.shape) for k, v in zip(self.label_name, self.label[0])]\n\n def reset(self):\n self.cur = 0\n if self.shuffle:\n if self.aspect_grouping:\n widths = np.array([r['width'] for r in self.roidb])\n heights = np.array([r['height'] for r in self.roidb])\n horz = (widths >= heights)\n vert = np.logical_not(horz)\n horz_inds = np.where(horz)[0]\n vert_inds = np.where(vert)[0]\n inds = np.hstack((np.random.permutation(horz_inds), np.random.permutation(vert_inds)))\n extra = inds.shape[0] % self.batch_size\n inds_ = np.reshape(inds[:-extra], (-1, self.batch_size))\n row_perm = np.random.permutation(np.arange(inds_.shape[0]))\n inds[:-extra] = np.reshape(inds_[row_perm, :], (-1,))\n self.index = inds\n else:\n np.random.shuffle(self.index)\n\n def iter_next(self):\n return self.cur + self.batch_size <= self.size\n\n def next(self):\n if self.iter_next():\n self.get_batch_individual()\n self.cur += self.batch_size\n return mx.io.DataBatch(data=self.data, label=self.label,\n pad=self.getpad(), index=self.getindex(),\n provide_data=self.provide_data, provide_label=self.provide_label)\n else:\n raise StopIteration\n\n def getindex(self):\n return self.cur / self.batch_size\n\n def getpad(self):\n if self.cur + self.batch_size > self.size:\n return self.cur + self.batch_size - self.size\n else:\n return 0\n\n def get_batch(self):\n # slice roidb\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n\n # decide multi device slices\n work_load_list = self.work_load_list\n ctx = self.ctx\n if work_load_list is None:\n work_load_list = [1] * len(ctx)\n assert isinstance(work_load_list, list) and len(work_load_list) == len(ctx), \\\n \"Invalid settings for work load. \"\n slices = _split_input_slice(self.batch_size, work_load_list)\n\n # get each device\n data_list = []\n label_list = []\n for islice in slices:\n iroidb = [roidb[i] for i in range(islice.start, islice.stop)]\n data, label = get_rcnn_batch(iroidb, self.cfg)\n data_list.append(data)\n label_list.append(label)\n\n all_data = dict()\n for key in data_list[0].keys():\n all_data[key] = tensor_vstack([batch[key] for batch in data_list])\n\n all_label = dict()\n for key in label_list[0].keys():\n all_label[key] = tensor_vstack([batch[key] for batch in label_list])\n\n self.data = [mx.nd.array(all_data[name]) for name in self.data_name]\n self.label = [mx.nd.array(all_label[name]) for name in self.label_name]\n\n def get_batch_individual(self):\n # slice roidb\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n\n # decide multi device slices\n work_load_list = self.work_load_list\n ctx = self.ctx\n if work_load_list is None:\n work_load_list = [1] * len(ctx)\n assert isinstance(work_load_list, list) and len(work_load_list) == len(ctx), \\\n \"Invalid settings for work load. \"\n slices = _split_input_slice(self.batch_size, work_load_list)\n\n rst = []\n for idx, islice in enumerate(slices):\n iroidb = [roidb[i] for i in range(islice.start, islice.stop)]\n rst.append(self.parfetch(iroidb))\n\n all_data = [_['data'] for _ in rst]\n all_label = [_['label'] for _ in rst]\n self.data = [[mx.nd.array(data[key]) for key in self.data_name] for data in all_data]\n self.label = [[mx.nd.array(label[key]) for key in self.label_name] for label in all_label]\n\n def parfetch(self, iroidb):\n data, label = get_rcnn_batch(iroidb, self.cfg)\n return {'data': data, 'label': label}\n\n\nclass AnchorLoader(mx.io.DataIter):\n\n def __init__(self, feat_sym, roidb, cfg, batch_size=1, shuffle=False, ctx=None, work_load_list=None,\n feat_stride=16, anchor_scales=(8, 16, 32), anchor_ratios=(0.5, 1, 2), allowed_border=0,\n aspect_grouping=False):\n \"\"\"\n This Iter will provide roi data to Fast R-CNN network\n :param feat_sym: to infer shape of assign_output\n :param roidb: must be preprocessed\n :param batch_size: must divide BATCH_SIZE(128)\n :param shuffle: bool\n :param ctx: list of contexts\n :param work_load_list: list of work load\n :param aspect_grouping: group images with similar aspects\n :return: AnchorLoader\n \"\"\"\n super(AnchorLoader, self).__init__()\n\n # save parameters as properties\n self.feat_sym = feat_sym\n self.roidb = roidb\n self.cfg = cfg\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.ctx = ctx\n if self.ctx is None:\n self.ctx = [mx.cpu()]\n self.work_load_list = work_load_list\n self.feat_stride = feat_stride\n self.anchor_scales = anchor_scales\n self.anchor_ratios = anchor_ratios\n self.allowed_border = allowed_border\n self.aspect_grouping = aspect_grouping\n\n # infer properties from roidb\n self.size = len(roidb)\n self.index = np.arange(self.size)\n\n # decide data and label names\n if config.TRAIN.END2END:\n self.data_name = ['data', 'im_info', 'gt_boxes']\n else:\n self.data_name = ['data']\n self.label_name = ['label', 'bbox_target', 'bbox_weight']\n\n # status variable for synchronization between get_data and get_label\n self.cur = 0\n self.batch = None\n self.data = None\n self.label = None\n\n # get first batch to fill in provide_data and provide_label\n self.reset()\n self.get_batch_individual()\n\n @property\n def provide_data(self):\n return [[(k, v.shape) for k, v in zip(self.data_name, self.data[i])] for i in xrange(len(self.data))]\n\n @property\n def provide_label(self):\n return [[(k, v.shape) for k, v in zip(self.label_name, self.label[i])] for i in xrange(len(self.data))]\n\n @property\n def provide_data_single(self):\n return [(k, v.shape) for k, v in zip(self.data_name, self.data[0])]\n\n @property\n def provide_label_single(self):\n return [(k, v.shape) for k, v in zip(self.label_name, self.label[0])]\n\n def reset(self):\n self.cur = 0\n if self.shuffle:\n if self.aspect_grouping:\n widths = np.array([r['width'] for r in self.roidb])\n heights = np.array([r['height'] for r in self.roidb])\n horz = (widths >= heights)\n vert = np.logical_not(horz)\n horz_inds = np.where(horz)[0]\n vert_inds = np.where(vert)[0]\n inds = np.hstack((np.random.permutation(horz_inds), np.random.permutation(vert_inds)))\n extra = inds.shape[0] % self.batch_size\n inds_ = np.reshape(inds[:-extra], (-1, self.batch_size))\n row_perm = np.random.permutation(np.arange(inds_.shape[0]))\n inds[:-extra] = np.reshape(inds_[row_perm, :], (-1,))\n self.index = inds\n else:\n np.random.shuffle(self.index)\n\n def iter_next(self):\n return self.cur + self.batch_size <= self.size\n\n def next(self):\n if self.iter_next():\n self.get_batch_individual()\n self.cur += self.batch_size\n return mx.io.DataBatch(data=self.data, label=self.label,\n pad=self.getpad(), index=self.getindex(),\n provide_data=self.provide_data, provide_label=self.provide_label)\n else:\n raise StopIteration\n\n def getindex(self):\n return self.cur / self.batch_size\n\n def getpad(self):\n if self.cur + self.batch_size > self.size:\n return self.cur + self.batch_size - self.size\n else:\n return 0\n\n def infer_shape(self, max_data_shape=None, max_label_shape=None):\n \"\"\" Return maximum data and label shape for single gpu \"\"\"\n if max_data_shape is None:\n max_data_shape = []\n if max_label_shape is None:\n max_label_shape = []\n max_shapes = dict(max_data_shape + max_label_shape)\n input_batch_size = max_shapes['data'][0]\n im_info = [[max_shapes['data'][2], max_shapes['data'][3], 1.0]]\n _, feat_shape, _ = self.feat_sym.infer_shape(**max_shapes)\n label = assign_anchor(feat_shape[0], np.zeros((0, 5)), im_info, self.cfg,\n self.feat_stride, self.anchor_scales, self.anchor_ratios, self.allowed_border)\n label = [label[k] for k in self.label_name]\n label_shape = [(k, tuple([input_batch_size] + list(v.shape[1:]))) for k, v in zip(self.label_name, label)]\n return max_data_shape, label_shape\n\n def get_batch(self):\n # slice roidb\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n\n # decide multi device slice\n work_load_list = self.work_load_list\n ctx = self.ctx\n if work_load_list is None:\n work_load_list = [1] * len(ctx)\n assert isinstance(work_load_list, list) and len(work_load_list) == len(ctx), \\\n \"Invalid settings for work load. \"\n slices = _split_input_slice(self.batch_size, work_load_list)\n\n # get testing data for multigpu\n data_list = []\n label_list = []\n for islice in slices:\n iroidb = [roidb[i] for i in range(islice.start, islice.stop)]\n data, label = get_rpn_batch(iroidb, self.cfg)\n data_list.append(data)\n label_list.append(label)\n\n # pad data first and then assign anchor (read label)\n data_tensor = tensor_vstack([batch['data'] for batch in data_list])\n for data, data_pad in zip(data_list, data_tensor):\n data['data'] = data_pad[np.newaxis, :]\n\n new_label_list = []\n for data, label in zip(data_list, label_list):\n # infer label shape\n data_shape = {k: v.shape for k, v in data.items()}\n del data_shape['im_info']\n _, feat_shape, _ = self.feat_sym.infer_shape(**data_shape)\n feat_shape = [int(i) for i in feat_shape[0]]\n\n # add gt_boxes to data for e2e\n data['gt_boxes'] = label['gt_boxes'][np.newaxis, :, :]\n\n # assign anchor for label\n label = assign_anchor(feat_shape, label['gt_boxes'], data['im_info'], self.cfg,\n self.feat_stride, self.anchor_scales,\n self.anchor_ratios, self.allowed_border)\n new_label_list.append(label)\n\n all_data = dict()\n for key in self.data_name:\n all_data[key] = tensor_vstack([batch[key] for batch in data_list])\n\n all_label = dict()\n for key in self.label_name:\n pad = -1 if key == 'label' else 0\n all_label[key] = tensor_vstack([batch[key] for batch in new_label_list], pad=pad)\n\n self.data = [mx.nd.array(all_data[key]) for key in self.data_name]\n self.label = [mx.nd.array(all_label[key]) for key in self.label_name]\n\n def get_batch_individual(self):\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n # decide multi device slice\n work_load_list = self.work_load_list\n ctx = self.ctx\n if work_load_list is None:\n work_load_list = [1] * len(ctx)\n assert isinstance(work_load_list, list) and len(work_load_list) == len(ctx), \\\n \"Invalid settings for work load. \"\n slices = _split_input_slice(self.batch_size, work_load_list)\n rst = []\n for idx, islice in enumerate(slices):\n iroidb = [roidb[i] for i in range(islice.start, islice.stop)]\n rst.append(self.parfetch(iroidb))\n all_data = [_['data'] for _ in rst]\n all_label = [_['label'] for _ in rst]\n self.data = [[mx.nd.array(data[key]) for key in self.data_name] for data in all_data]\n self.label = [[mx.nd.array(label[key]) for key in self.label_name] for label in all_label]\n\n def parfetch(self, iroidb):\n # get testing data for multigpu\n data, label = get_rpn_batch(iroidb, self.cfg)\n data_shape = {k: v.shape for k, v in data.items()}\n del data_shape['im_info']\n _, feat_shape, _ = self.feat_sym.infer_shape(**data_shape)\n feat_shape = [int(i) for i in feat_shape[0]]\n\n # add gt_boxes to data for e2e\n data['gt_boxes'] = label['gt_boxes'][np.newaxis, :, :]\n\n # assign anchor for label\n label = assign_anchor(feat_shape, label['gt_boxes'], data['im_info'], self.cfg,\n self.feat_stride, self.anchor_scales,\n self.anchor_ratios, self.allowed_border)\n return {'data': data, 'label': label}\n\n# TODO test this dataloader for quadrangle\nclass QuadrangleAnchorLoader(mx.io.DataIter):\n def __init__(self, feat_sym, roidb, cfg, batch_size=1, shuffle=False, ctx=None, work_load_list=None,\n feat_stride=16, anchor_scales=(8, 16, 32), anchor_ratios=(0.5, 1, 2), allowed_border=0,\n aspect_grouping=False):\n \"\"\"\n This Iter will provide roi data to Fast R-CNN network\n :param feat_sym: to infer shape of assign_output\n :param roidb: must be preprocessed\n :param batch_size: must divide BATCH_SIZE(128)\n :param shuffle: bool\n :param ctx: list of contexts\n :param work_load_list: list of work load\n :param aspect_grouping: group images with similar aspects\n :return: AnchorLoader\n \"\"\"\n super(QuadrangleAnchorLoader, self).__init__()\n\n # save parameters as properties\n self.feat_sym = feat_sym\n self.roidb = roidb\n self.cfg = cfg\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.ctx = ctx\n if self.ctx is None:\n self.ctx = [mx.cpu()]\n self.work_load_list = work_load_list\n self.feat_stride = feat_stride\n self.anchor_scales = anchor_scales\n self.anchor_ratios = anchor_ratios\n self.allowed_border = allowed_border\n self.aspect_grouping = aspect_grouping\n\n # infer properties from roidb\n self.size = len(roidb)\n self.index = np.arange(self.size)\n\n # decide data and label names\n if config.TRAIN.END2END:\n self.data_name = ['data', 'im_info', 'gt_boxes']\n else:\n self.data_name = ['data']\n self.label_name = ['label', 'bbox_target', 'bbox_weight']\n\n # status variable for synchronization between get_data and get_label\n self.cur = 0\n self.batch = None\n self.data = None\n self.label = None\n\n # get first batch to fill in provide_data and provide_label\n self.reset()\n self.get_batch_individual()\n\n @property\n def provide_data(self):\n return [[(k, v.shape) for k, v in zip(self.data_name, self.data[i])] for i in xrange(len(self.data))]\n\n @property\n def provide_label(self):\n return [[(k, v.shape) for k, v in zip(self.label_name, self.label[i])] for i in xrange(len(self.data))]\n\n @property\n def provide_data_single(self):\n return [(k, v.shape) for k, v in zip(self.data_name, self.data[0])]\n\n @property\n def provide_label_single(self):\n return [(k, v.shape) for k, v in zip(self.label_name, self.label[0])]\n\n def reset(self):\n self.cur = 0\n if self.shuffle:\n if self.aspect_grouping:\n widths = np.array([r['width'] for r in self.roidb])\n heights = np.array([r['height'] for r in self.roidb])\n horz = (widths >= heights)\n vert = np.logical_not(horz)\n horz_inds = np.where(horz)[0]\n vert_inds = np.where(vert)[0]\n inds = np.hstack((np.random.permutation(horz_inds), np.random.permutation(vert_inds)))\n extra = inds.shape[0] % self.batch_size\n inds_ = np.reshape(inds[:-extra], (-1, self.batch_size))\n row_perm = np.random.permutation(np.arange(inds_.shape[0]))\n inds[:-extra] = np.reshape(inds_[row_perm, :], (-1,))\n self.index = inds\n else:\n np.random.shuffle(self.index)\n\n def iter_next(self):\n return self.cur + self.batch_size <= self.size\n\n def next(self):\n if self.iter_next():\n self.get_batch_individual()\n self.cur += self.batch_size\n return mx.io.DataBatch(data=self.data, label=self.label,\n pad=self.getpad(), index=self.getindex(),\n provide_data=self.provide_data, provide_label=self.provide_label)\n else:\n raise StopIteration\n\n def getindex(self):\n return self.cur / self.batch_size\n\n def getpad(self):\n if self.cur + self.batch_size > self.size:\n return self.cur + self.batch_size - self.size\n else:\n return 0\n\n def infer_shape(self, max_data_shape=None, max_label_shape=None):\n \"\"\" Return maximum data and label shape for single gpu \"\"\"\n if max_data_shape is None:\n max_data_shape = []\n if max_label_shape is None:\n max_label_shape = []\n max_shapes = dict(max_data_shape + max_label_shape)\n input_batch_size = max_shapes['data'][0]\n # change the shape of im_info\n im_info = [[max_shapes['data'][2], max_shapes['data'][3], 1.0]]\n\n feat_shape_list = []\n for i in range(len(self.feat_stride)):\n _, feat_shape, _ = self.feat_sym[i].infer_shape(**max_shapes)\n feat_shape = [int(i) for i in feat_shape[0]]\n feat_shape_list.append(feat_shape)\n\n label = assign_quadrangle_anchor(feat_shape_list, np.zeros((0, 9)), im_info, self.cfg,\n self.feat_stride, self.anchor_scales, self.anchor_ratios, self.allowed_border)\n label = [label[k] for k in self.label_name]\n label_shape = [(k, tuple([input_batch_size] + list(v.shape[1:]))) for k, v in zip(self.label_name, label)]\n return max_data_shape, label_shape\n\n def get_batch(self):\n # slice roidb\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n\n # decide multi device slice\n work_load_list = self.work_load_list\n ctx = self.ctx\n if work_load_list is None:\n work_load_list = [1] * len(ctx)\n assert isinstance(work_load_list, list) and len(work_load_list) == len(ctx), \\\n \"Invalid settings for work load. \"\n slices = _split_input_slice(self.batch_size, work_load_list)\n\n # get testing data for multigpu\n data_list = []\n label_list = []\n for islice in slices:\n iroidb = [roidb[i] for i in range(islice.start, islice.stop)]\n data, label = get_rpn_batch_quadrangle(iroidb, self.cfg)\n data_list.append(data)\n label_list.append(label)\n\n # pad data first and then assign anchor (read label)\n data_tensor = tensor_vstack([batch['data'] for batch in data_list])\n for data, data_pad in zip(data_list, data_tensor):\n data['data'] = data_pad[np.newaxis, :]\n\n new_label_list = []\n for data, label in zip(data_list, label_list):\n # infer label shape\n data_shape = {k: v.shape for k, v in data.items()}\n del data_shape['im_info']\n _, feat_shape, _ = self.feat_sym.infer_shape(**data_shape)\n feat_shape = [int(i) for i in feat_shape[0]]\n\n # add gt_boxes to data for e2e\n data['gt_boxes'] = label['gt_boxes'][np.newaxis, :, :]\n\n # assign quadrangle anchor for label\n label = assign_quadrangle_anchor(feat_shape, label['gt_boxes'], data['im_info'], self.cfg,\n self.feat_stride, self.anchor_scales,\n self.anchor_ratios, self.allowed_border)\n new_label_list.append(label)\n\n all_data = dict()\n for key in self.data_name:\n all_data[key] = tensor_vstack([batch[key] for batch in data_list])\n\n all_label = dict()\n for key in self.label_name:\n pad = -1 if key == 'label' else 0\n all_label[key] = tensor_vstack([batch[key] for batch in new_label_list], pad=pad)\n\n self.data = [mx.nd.array(all_data[key]) for key in self.data_name]\n self.label = [mx.nd.array(all_label[key]) for key in self.label_name]\n\n def get_batch_individual(self):\n cur_from = self.cur\n cur_to = min(cur_from + self.batch_size, self.size)\n roidb = [self.roidb[self.index[i]] for i in range(cur_from, cur_to)]\n # decide multi device slice\n work_load_list = self.work_load_list\n ctx = self.ctx\n if work_load_list is None:\n work_load_list = [1] * len(ctx)\n assert isinstance(work_load_list, list) and len(work_load_list) == len(ctx), \\\n \"Invalid settings for work load. \"\n slices = _split_input_slice(self.batch_size, work_load_list)\n rst = []\n for idx, islice in enumerate(slices):\n iroidb = [roidb[i] for i in range(islice.start, islice.stop)]\n rst.append(self.parfetch(iroidb))\n all_data = [_['data'] for _ in rst]\n all_label = [_['label'] for _ in rst]\n self.data = [[mx.nd.array(data[key]) for key in self.data_name] for data in all_data]\n self.label = [[mx.nd.array(label[key]) for key in self.label_name] for label in all_label]\n\n def parfetch(self, iroidb):\n # get testing data for multigpu\n data, label = get_rpn_batch_quadrangle(iroidb, self.cfg)\n # print data\n # print label\n data_shape = {k: v.shape for k, v in data.items()}\n del data_shape['im_info']\n\n feat_shape_list = []\n for s in range(len(self.feat_stride)):\n _, feat_shape, _ = self.feat_sym[s].infer_shape(**data_shape)\n feat_shape = [int(i) for i in feat_shape[0]]\n feat_shape_list.append(feat_shape)\n\n\n # add gt_boxes to data for e2e\n data['gt_boxes'] = label['gt_boxes'][np.newaxis, :, :]\n\n # assign anchor for label\n label = assign_quadrangle_anchor(feat_shape_list, label['gt_boxes'], data['im_info'], self.cfg,\n self.feat_stride, self.anchor_scales,\n self.anchor_ratios, self.allowed_border)\n return {'data': data, 'label': label}\n\n"
] |
[
[
"numpy.logical_not",
"numpy.reshape",
"numpy.arange",
"numpy.random.shuffle",
"numpy.random.permutation",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dcherian/cf-xarray
|
[
"a5aa1d601f9c37ef47b4cd6026a65b57b727c043"
] |
[
"cf_xarray/helpers.py"
] |
[
"from typing import Optional, Sequence\n\nimport numpy as np\nimport xarray as xr\nfrom xarray import DataArray\n\n\ndef bounds_to_vertices(\n bounds: DataArray,\n bounds_dim: str,\n core_dims=None,\n order: Optional[str] = \"counterclockwise\",\n) -> DataArray:\n \"\"\"\n Convert bounds variable to vertices. There 2 covered cases:\n - 1D coordinates, with bounds of shape (N, 2),\n converted to vertices of shape (N+1,)\n - 2D coordinates, with bounds of shape (N, M, 4).\n converted to vertices of shape (N+1, M+1).\n\n Parameters\n ----------\n bounds : DataArray\n The bounds to convert.\n bounds_dim : str\n The name of the bounds dimension of `bounds` (the one of length 2 or 4).\n order : {'counterclockwise', 'clockwise', None}\n Valid for 2D coordinates only (i.e. bounds of shape (..., N, M, 4), ignored otherwise.\n Order the bounds are given in, assuming that ax0-ax1-upward is a right handed\n coordinate system, where ax0 and ax1 are the two first dimensions of `bounds`.\n If None, the counterclockwise version is computed and then verified. If the\n check fails the clockwise version is returned. See Notes for more details.\n core_dims : list, optional\n List of core dimensions for apply_ufunc. This must not include bounds_dims.\n The shape of (*core_dims, bounds_dim) must be (N, 2) or (N, M, 4).\n\n Returns\n -------\n DataArray\n Either of shape (N+1,) or (N+1, M+1). New vertex dimensions are named\n from the intial dimension and suffix \"_vertices\".\n\n Notes\n -----\n Getting the correct axes \"order\" is tricky. There are no real standards for\n dimension names or even axes order, even though the CF conventions mentions the\n ax0-ax1-upward (counterclockwise bounds) as being the default. Moreover, xarray can\n tranpose data without raising any warning or error, which make attributes\n unreliable.\n\n Please refer to the CF conventions document : http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#cell-boundaries.\n \"\"\"\n\n if core_dims is None:\n core_dims = [dim for dim in bounds.dims if dim != bounds_dim]\n\n output_sizes = {f\"{dim}_vertices\": bounds.sizes[dim] + 1 for dim in core_dims}\n output_core_dims = list(output_sizes.keys())\n\n n_core_dims = len(core_dims)\n nbounds = bounds[bounds_dim].size\n\n if not (n_core_dims == 2 and nbounds == 4) and not (\n n_core_dims == 1 and nbounds == 2\n ):\n raise ValueError(\n f\"Bounds format not understood. Got {bounds.dims} with shape {bounds.shape}.\"\n )\n\n return xr.apply_ufunc(\n _bounds_helper,\n bounds,\n input_core_dims=[core_dims + [bounds_dim]],\n dask=\"parallelized\",\n kwargs={\"n_core_dims\": n_core_dims, \"nbounds\": nbounds, \"order\": order},\n output_core_dims=[output_core_dims],\n dask_gufunc_kwargs=dict(output_sizes=output_sizes),\n output_dtypes=[bounds.dtype],\n )\n\n\ndef _bounds_helper(values, n_core_dims, nbounds, order):\n if n_core_dims == 2 and nbounds == 4:\n # Vertices case (2D lat/lon)\n if order in [\"counterclockwise\", None]:\n # Names assume we are drawing axis 1 upward et axis 2 rightward.\n bot_left = values[..., :, :, 0]\n bot_right = values[..., :, -1:, 1]\n top_right = values[..., -1:, -1:, 2]\n top_left = values[..., -1:, :, 3]\n vertex_vals = np.block([[bot_left, bot_right], [top_left, top_right]])\n if order is None: # We verify if the ccw version works.\n calc_bnds = np.moveaxis(vertices_to_bounds(vertex_vals).values, 0, -1)\n order = \"counterclockwise\" if np.all(calc_bnds == values) else \"clockwise\"\n if order == \"clockwise\":\n bot_left = values[..., :, :, 0]\n top_left = values[..., -1:, :, 1]\n top_right = values[..., -1:, -1:, 2]\n bot_right = values[..., :, -1:, 3]\n # Our asumption was wrong, axis 1 is rightward and axis 2 is upward\n vertex_vals = np.block([[bot_left, bot_right], [top_left, top_right]])\n elif n_core_dims == 1 and nbounds == 2:\n # Middle points case (1D lat/lon)\n vertex_vals = np.concatenate((values[..., :, 0], values[..., -1:, 1]), axis=-1)\n\n return vertex_vals\n\n\ndef vertices_to_bounds(\n vertices: DataArray, out_dims: Sequence[str] = (\"bounds\", \"x\", \"y\")\n) -> DataArray:\n \"\"\"\n Convert vertices to CF-compliant bounds. There 2 covered cases:\n - 1D coordinates, with vertices of shape (N+1,),\n converted to bounds of shape (N, 2)\n - 2D coordinates, with vertices of shape (N+1, M+1).\n converted to bounds of shape (N, M, 4).\n\n Parameters\n ----------\n bounds : DataArray\n The bounds to convert. Must be of shape (N, 2) or (N, M, 4).\n out_dims : Sequence[str],\n The name of the dimension in the output. The first is the 'bounds'\n dimension and the following are the coordinate dimensions.\n Returns\n -------\n DataArray\n \"\"\"\n if vertices.ndim == 1:\n bnd_vals = np.stack((vertices[:-1], vertices[1:]), axis=0)\n elif vertices.ndim == 2:\n bnd_vals = np.stack(\n (\n vertices[:-1, :-1],\n vertices[:-1, 1:],\n vertices[1:, 1:],\n vertices[1:, :-1],\n ),\n axis=0,\n )\n else:\n raise ValueError(\n f\"vertices format not understood. Got {vertices.dims} with shape {vertices.shape}.\"\n )\n return xr.DataArray(bnd_vals, dims=out_dims[: vertices.ndim + 1])\n"
] |
[
[
"numpy.concatenate",
"numpy.all",
"numpy.block",
"numpy.stack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Cho0joy/botty
|
[
"ed9c22b78a527443b46fdc3070cb128f32501e2e"
] |
[
"src/shop/drognan.py"
] |
[
"import datetime\nimport os\nimport time\nimport math\nimport random\nfrom typing import Dict, Tuple, Union, List, Callable\n\nimport keyboard\nimport numpy as np\n\nfrom screen import Screen\nfrom config import Config\nfrom logger import Logger\nfrom npc_manager import NpcManager, Npc\nfrom template_finder import TemplateFinder\nfrom utils.custom_mouse import mouse\nfrom utils.misc import wait\n\n\ndef exit(run_obj):\n run_time = str(datetime.timedelta(seconds=round(time.time() - run_obj.start_time)))\n Logger.info(\"Exiting shopping mall...\")\n print(\n \"STATS \\truns \\t\\ttime \\titems_evaluated \\titems_bought\\n\"\n f\"\\t{run_obj.run_count} \\t\\t{run_time}\"\n f\"\\t\\t{run_obj.items_evaluated} \\t\\t\\t{run_obj.items_bought}\"\n )\n os._exit(0)\n\n\nclass DrognanShopper:\n \"\"\"\n Shop at Drognan for Items.\n Currently supported: Hammerdin scepters\n\n In order to start the shopping bot:\n 1.) Run this this file in Python.\n 2.) Be ingame in Lut Golein (Act 2 town)\n 3.) Stand close to Drognan and the town exit (must be top right layout)\n 4.) While being ingame, press resume_key (default F11) to start the shopping, and exit_key (default F12) to stop it.\n \"\"\"\n\n def __init__(self, config: Config):\n self._config = config\n\n # Set look_for variables to False if you dont like your personal shopper to look for these\n # Obviously something need to be set to True, or your shopper will be very confused\n self.look_for_scepters = self._config.shop[\"shop_hammerdin_scepters\"]\n self.speed_factor = 1.0 + self._config.shop[\"speed_factor\"]\n if (self.speed_factor <= 0):\n Logger.error(\"Can not use a speed factor less than negative 1!! Please update shop.ini. Exiting.\")\n os._exit(0)\n self.apply_pather_adjustment = self._config.shop[\"apply_pather_adjustment\"]\n\n self._screen = Screen()\n self._template_finder = TemplateFinder(self._screen, [\"assets\\\\templates\", \"assets\\\\npc\", \"assets\\\\shop\"], save_last_res=True)\n self._npc_manager = NpcManager(\n screen=self._screen, template_finder=self._template_finder\n )\n self.run_count = 0\n self.start_time = time.time()\n\n # items config\n self.roi_shop_item_stats = [0, 0, config.ui_pos[\"screen_width\"] // 2, config.ui_pos[\"screen_height\"] - 100]\n self.roi_vendor = config.ui_roi[\"left_inventory\"]\n self.rx, self.ry, _, _ = self.roi_vendor\n self.sb_x, self.sb_y = self._screen.convert_screen_to_monitor((180, 77))\n self.c_x, self.c_y = self._screen.convert_screen_to_monitor((config.ui_pos[\"center_x\"], config.ui_pos[\"center_y\"]))\n self.items_evaluated = 0\n self.items_bought = 0\n\n def run(self):\n Logger.info(\"Personal Drognan Shopper at your service! Hang on, running some errands...\")\n self.reset_shop()\n self.shop_loop()\n\n def shop_loop(self):\n\n # This is the main shopping loop. It can be further generalized to more easily support new items,\n # But this is sufficient for now.\n while True:\n self._npc_manager.open_npc_menu(Npc.DROGNAN)\n self._npc_manager.press_npc_btn(Npc.DROGNAN, \"trade\")\n time.sleep(0.1)\n img = self._screen.grab()\n\n if self.look_for_scepters is True:\n mouse.move(self.sb_x, self.sb_y, randomize=3, delay_factor=[0.6, 0.8])\n wait(0.05, 0.1)\n mouse.press(button=\"left\")\n wait(0.05, 0.1)\n mouse.release(button=\"left\")\n wait(0.3, 0.4)\n\n # Search for items\n item_pos = []\n img = self._screen.grab().copy()\n item_keys = [\"SCEPTER1\", \"SCEPTER2\", \"SCEPTER3\", \"SCEPTER4\", \"SCEPTER5\"]\n for ck in item_keys:\n template_match = self._template_finder.search(ck, img, roi=self.roi_vendor)\n if template_match.valid:\n (y, x) = np.where(self._template_finder.last_res >= 0.6)\n for (x, y) in zip(x, y):\n new_pos = [x + self.rx + 16, y + self.ry + 50]\n # check if pos already exists in item_pos\n exists_already = False\n for pos in item_pos:\n dist = math.dist(new_pos, pos)\n if dist < 10:\n exists_already = True\n if not exists_already:\n item_pos.append(new_pos)\n\n # check out each item\n for pos in item_pos:\n x_m, y_m = self._screen.convert_screen_to_monitor(pos)\n mouse.move(x_m, y_m, randomize=3, delay_factor=[0.5, 0.6])\n wait(0.5, 0.6)\n img_stats = self._screen.grab()\n\n # First check for +2 Paladin Skills. This weeds out most scepters right away.\n if self._template_finder.search(\"2_TO_PALADIN_SKILLS\", img_stats, roi=self.roi_shop_item_stats, threshold=0.94).valid:\n # Has 2 Pally skills, check blessed hammers next\n if self._template_finder.search(\"TO_BLESSED_HAMMERS\", img_stats, roi=self.roi_shop_item_stats, threshold=0.9).valid:\n # Has 2 Pally skills AND Blessed Hammers, check Concentration next\n if self._template_finder.search(\"TO_CONCENTRATION\", img_stats, roi=self.roi_shop_item_stats, threshold=0.9).valid:\n # Has 2 Pally skills AND Blessed Hammers AND Concentration. We're good! Buy it!\n mouse.click(button=\"right\")\n Logger.info(f\"Item bought!\")\n self.items_bought += 1\n time.sleep(1)\n\n self.items_evaluated += 1\n\n keyboard.send(\"space\")\n\n # Done with this shopping round\n self.reset_shop()\n self.run_count += 1\n\n def reset_shop(self):\n # We want to walk out the town exit to the top right and come back down to drognan\n # This can probably be tweaked but seems to work well enough for now.\n\n # Exit town\n pos_m = self._screen.convert_abs_to_monitor((200, -100))\n mouse.move(pos_m[0], pos_m[1])\n self.hold_move(pos_m, time_held=(3.0 / self.speed_factor))\n\n # Return to town\n pos_m = self._screen.convert_abs_to_monitor((-200, 100))\n mouse.move(pos_m[0], pos_m[1])\n self.hold_move(pos_m, time_held=(2.0 / self.speed_factor))\n\n # A variation of the move() function from pather.py\n def hold_move(self, pos_monitor: Tuple[float, float], time_held: float = 2.0):\n factor = self._config.advanced_options[\"pathing_delay_factor\"]\n # in case we want to walk we actually want to move a bit before the point cause d2r will always \"overwalk\"\n pos_screen = self._screen.convert_monitor_to_screen(pos_monitor)\n pos_abs = self._screen.convert_screen_to_abs(pos_screen)\n\n # This logic (from pather.py) sometimes negatively affects the shopper, so default is to skip this.\n if self.apply_pather_adjustment:\n dist = math.dist(pos_abs, (0, 0))\n min_wd = self._config.ui_pos[\"min_walk_dist\"]\n max_wd = random.randint(int(self._config.ui_pos[\"max_walk_dist\"] * 0.65), self._config.ui_pos[\"max_walk_dist\"])\n adjust_factor = max(max_wd, min(min_wd, dist - 50)) / dist\n pos_abs = [int(pos_abs[0] * adjust_factor), int(pos_abs[1] * adjust_factor)]\n\n x, y = self._screen.convert_abs_to_monitor(pos_abs)\n mouse.move(x, y, randomize=5, delay_factor=[factor*0.1, factor*0.14])\n wait(0.012, 0.02)\n mouse.press(button=\"left\")\n wait(time_held - 0.05, time_held + 0.05)\n mouse.release(button=\"left\")\n"
] |
[
[
"numpy.where"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MatteoPerotto/pointconv
|
[
"204a0d534c4d75e80bde7722c075a78365a64929"
] |
[
"utils/pointconv_util.py"
] |
[
"\"\"\"\nHelper Function for PointConv\nAuthor: Wenxuan Wu\nDate: July 2018\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport random\nimport numpy as np\nimport tensorflow as tf\nfrom transforms3d.euler import euler2mat\nimport os\nimport sys\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(BASE_DIR, '../tf_ops/sampling'))\nsys.path.append(os.path.join(BASE_DIR, '../tf_ops/grouping'))\nimport tf_sampling\nimport tf_grouping\nfrom sklearn.neighbors import KDTree\n\ndef knn_kdtree(nsample, xyz, new_xyz):\n batch_size = xyz.shape[0]\n n_points = new_xyz.shape[1]\n\n indices = np.zeros((batch_size, n_points, nsample), dtype=np.int32)\n for batch_idx in range(batch_size):\n X = xyz[batch_idx, ...]\n q_X = new_xyz[batch_idx, ...]\n kdt = KDTree(X, leaf_size=30)\n _, indices[batch_idx] = kdt.query(q_X, k = nsample)\n\n return indices\n\ndef kernel_density_estimation_ball(pts, radius, sigma, N_points = 128, is_norm = False):\n with tf.variable_scope(\"ComputeDensity\") as sc:\n idx, pts_cnt = tf_grouping.query_ball_point(radius, N_points, pts, pts)\n g_pts = tf_grouping.group_point(pts, idx)\n g_pts -= tf.tile(tf.expand_dims(pts, 2), [1, 1, N_points, 1])\n\n R = tf.sqrt(sigma)\n xRinv = tf.div(g_pts, R)\n quadform = tf.reduce_sum(tf.square(xRinv), axis = -1)\n logsqrtdetSigma = tf.log(R) * 3\n mvnpdf = tf.exp(-0.5 * quadform - logsqrtdetSigma - 3 * tf.log(2 * 3.1415926) / 2)\n\n first_val, _ = tf.split(mvnpdf, [1, N_points - 1], axis = 2)\n\n mvnpdf = tf.reduce_sum(mvnpdf, axis = 2, keepdims = True)\n\n num_val_to_sub = tf.expand_dims(tf.cast(tf.subtract(N_points, pts_cnt), dtype = tf.float32), axis = -1)\n\n val_to_sub = tf.multiply(first_val, num_val_to_sub)\n\n mvnpdf = tf.subtract(mvnpdf, val_to_sub)\n\n scale = tf.div(1.0, tf.expand_dims(tf.cast(pts_cnt, dtype = tf.float32), axis = -1))\n density = tf.multiply(mvnpdf, scale)\n\n if is_norm:\n #grouped_xyz_sum = tf.reduce_sum(grouped_xyz, axis = 1, keepdims = True)\n density_max = tf.reduce_max(density, axis = 1, keepdims = True)\n density = tf.div(density, density_max)\n\n return density\n\ndef kernel_density_estimation(pts, sigma, kpoint = 32, is_norm = False):\n with tf.variable_scope(\"ComputeDensity\") as sc:\n batch_size = pts.get_shape()[0]\n num_points = pts.get_shape()[1]\n if num_points < kpoint:\n kpoint = num_points.value - 1\n with tf.device('/cpu:0'):\n point_indices = tf.py_func(knn_kdtree, [kpoint, pts, pts], tf.int32)\n batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1, 1)), (1, num_points, kpoint, 1))\n idx = tf.concat([batch_indices, tf.expand_dims(point_indices, axis = 3)], axis = 3)\n idx.set_shape([batch_size, num_points, kpoint, 2])\n\n grouped_pts = tf.gather_nd(pts, idx)\n grouped_pts -= tf.tile(tf.expand_dims(pts, 2), [1,1,kpoint,1]) # translation normalization\n\n R = tf.sqrt(sigma)\n xRinv = tf.div(grouped_pts, R)\n quadform = tf.reduce_sum(tf.square(xRinv), axis = -1)\n logsqrtdetSigma = tf.log(R) * 3\n mvnpdf = tf.exp(-0.5 * quadform - logsqrtdetSigma - 3 * tf.log(2 * 3.1415926) / 2)\n mvnpdf = tf.reduce_sum(mvnpdf, axis = 2, keepdims = True)\n\n scale = 1.0 / kpoint\n density = tf.multiply(mvnpdf, scale)\n\n if is_norm:\n #grouped_xyz_sum = tf.reduce_sum(grouped_xyz, axis = 1, keepdims = True)\n density_max = tf.reduce_max(density, axis = 1, keepdims = True)\n density = tf.div(density, density_max)\n\n return density\n\ndef sampling(npoint, pts):\n '''\n inputs:\n npoint: scalar, number of points to sample\n pointcloud: B * N * 3, input point cloud\n output:\n sub_pts: B * npoint * 3, sub-sampled point cloud\n '''\n\n sub_pts = tf_sampling.gather_point(pts, tf_sampling.farthest_point_sample(npoint, pts))\n return sub_pts\n\ndef grouping(feature, K, src_xyz, q_xyz, use_xyz = True):\n '''\n K: neighbor size\n src_xyz: original point xyz (batch_size, ndataset, 3)\n q_xyz: query point xyz (batch_size, npoint, 3)\n '''\n\n batch_size = src_xyz.get_shape()[0]\n npoint = q_xyz.get_shape()[1]\n\n point_indices = tf.py_func(knn_kdtree, [K, src_xyz, q_xyz], tf.int32)\n batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1, 1)), (1, npoint, K, 1))\n idx = tf.concat([batch_indices, tf.expand_dims(point_indices, axis = 3)], axis = 3)\n idx.set_shape([batch_size, npoint, K, 2])\n\n grouped_xyz = tf.gather_nd(src_xyz, idx)\n grouped_xyz -= tf.tile(tf.expand_dims(q_xyz, 2), [1,1,K,1]) # translation normalization\n\n grouped_feature = tf.gather_nd(feature, idx)\n if use_xyz:\n new_points = tf.concat([grouped_xyz, grouped_feature], axis = -1)\n else:\n new_points = grouped_feature\n \n return grouped_xyz, new_points, idx\n\nif __name__=='__main__':\n #test KDE\n import time\n batch_size = 8\n num_point = 8192\n pts = np.random.randn(batch_size, num_point, 3).astype('float32')\n\n import pdb\n pdb.set_trace()\n\n with tf.device('/gpu:1'):\n points = tf.placeholder(tf.float32, shape=(batch_size, num_point, 3))\n density = kernel_density_estimation_ball(points, 1.0)\n #density = kernel_density_estimation(points, 1.0)\n init = tf.global_variables_initializer()\n with tf.Session('') as sess:\n \n sess.run(init)\n t1 = time.time()\n den = sess.run(density, feed_dict = {points:pts})\n\n print(time.time() - t1)\n\n #import scipy.io as sio \n\n #sio.savemat('density.mat', dict([('pts', pts), ('density', den)]))\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"tensorflow.device",
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.cast",
"sklearn.neighbors.KDTree",
"numpy.random.randn",
"tensorflow.py_func",
"tensorflow.subtract",
"tensorflow.div",
"tensorflow.Session",
"tensorflow.square",
"numpy.zeros",
"tensorflow.gather_nd",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.split",
"tensorflow.reduce_max",
"tensorflow.multiply",
"tensorflow.range",
"tensorflow.expand_dims",
"tensorflow.log",
"tensorflow.variable_scope",
"tensorflow.sqrt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"1.0",
"1.2"
]
}
] |
Fackor/NeMo
|
[
"941ef1fd71bd2515a4ba7092d65146edfddc1229"
] |
[
"nemo/core/classes/modelPT.py"
] |
[
"# Copyright (c) 2020, NVIDIA CORPORATION. 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 copy\nimport inspect\nimport os\nimport shutil\nimport tarfile\nimport tempfile\nfrom abc import abstractmethod\nfrom dataclasses import is_dataclass\nfrom os import path\nfrom typing import Callable, Dict, List, Optional, Union\n\nimport hydra\nimport torch\nfrom omegaconf import DictConfig, OmegaConf, open_dict\nfrom pytorch_lightning import LightningModule, Trainer\nfrom pytorch_lightning.utilities import rank_zero_only\n\nfrom nemo.core import optim\nfrom nemo.core.classes.common import Model\nfrom nemo.core.optim import prepare_lr_scheduler\nfrom nemo.utils import config_utils, logging, model_utils\nfrom nemo.utils.app_state import AppState\nfrom nemo.utils.get_rank import is_global_rank_zero\n\n# Need to set them before EFF import as it is using them.\n_MODEL_CONFIG_YAML = \"model_config.yaml\"\n_MODEL_WEIGHTS = \"model_weights.ckpt\"\n\ntry:\n # Try to import strategies for .nemo archive.\n from eff.cookbooks import NeMoCookbook\n\n _EFF_PRESENT_ = True\nexcept ImportError:\n _EFF_PRESENT_ = False\n\n__all__ = ['ModelPT']\n\n\"\"\"\nInternal global flags that determine core functionality of ModelPT.\n\n_MODEL_IS_RESTORED:\n This flag determines the context of the model - whether the model is currently being\n restored or not. \n - When set, it can be assumed that the model's will disable all automatic methods -\n setup_training_data(), setup_validation/test_data() and their multi equivalents.\n - If a model is being restored from a archive file (tarfile), it can be assumed that\n under this context, the cwd is *inside* the tarfile itself.\n\n_MODEL_RESTORE_PATH:\n A string path to a a file from which the model is being restored.\n This file can either be a PyTorch Lightning Checkpoint, or a archive (tarfile) that contains\n artifact objects.\n If it is an archive file, during restoration, the cwd will be temporarily moved to inside the\n archive itself.\n\n_MODEL_EFF_SAVE:\n A global flag that switches the format of the archive file that will be stored.\n This flag only enables EFF when the package support is available.\n\"\"\"\n_MODEL_IS_RESTORED = False\n_MODEL_RESTORE_PATH = None\n_MODEL_EFF_SAVE = True\n\n\nclass ModelPT(LightningModule, Model):\n \"\"\"\n Interface for Pytorch-lightning based NeMo models\n \"\"\"\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n \"\"\"\n Base class from which all NeMo models should inherit\n\n Args:\n cfg (DictConfig): configuration object.\n The cfg object should have (optionally) the following sub-configs:\n\n * train_ds - to instantiate training dataset\n * validation_ds - to instantiate validation dataset\n * test_ds - to instantiate testing dataset\n * optim - to instantiate optimizer with learning rate scheduler\n\n trainer (Optional): Pytorch Lightning Trainer instance\n \"\"\"\n if trainer is not None and not isinstance(trainer, Trainer):\n raise ValueError(\n f\"trainer constructor argument must be either None or pytroch_lightning.Trainer. But got {type(trainer)} instead.\"\n )\n super().__init__()\n\n # Convert config to a DictConfig\n cfg = model_utils.convert_model_config_to_dict_config(cfg)\n\n # Convert config to support Hydra 1.0+ instantiation\n cfg = model_utils.maybe_update_config_version(cfg)\n\n if 'target' not in cfg:\n # This is for Jarvis service.\n OmegaConf.set_struct(cfg, False)\n cfg.target = \"{0}.{1}\".format(self.__class__.__module__, self.__class__.__name__)\n OmegaConf.set_struct(cfg, True)\n\n self._cfg = cfg\n\n self.save_hyperparameters(self._cfg)\n self._train_dl = None\n self._validation_dl = None\n self._test_dl = None\n self._optimizer = None\n self._scheduler = None\n self._trainer = trainer\n\n # Set device_id in AppState\n if torch.cuda.is_available() and torch.cuda.current_device() is not None:\n app_state = AppState()\n app_state.device_id = torch.cuda.current_device()\n\n if self._cfg is not None and not self._is_model_being_restored():\n if 'train_ds' in self._cfg and self._cfg.train_ds is not None:\n self.setup_training_data(self._cfg.train_ds)\n\n if 'validation_ds' in self._cfg and self._cfg.validation_ds is not None:\n self.setup_multiple_validation_data(val_data_config=None)\n\n if 'test_ds' in self._cfg and self._cfg.test_ds is not None:\n self.setup_multiple_test_data(test_data_config=None)\n\n else:\n if 'train_ds' in self._cfg and self._cfg.train_ds is not None:\n logging.warning(\n f\"Please call the ModelPT.setup_training_data() method \"\n f\"and provide a valid configuration file to setup the train data loader.\\n\"\n f\"Train config : \\n{OmegaConf.to_yaml(self._cfg.train_ds)}\"\n )\n\n if 'validation_ds' in self._cfg and self._cfg.validation_ds is not None:\n logging.warning(\n f\"Please call the ModelPT.setup_validation_data() or ModelPT.setup_multiple_validation_data() method \"\n f\"and provide a valid configuration file to setup the validation data loader(s). \\n\"\n f\"Validation config : \\n{OmegaConf.to_yaml(self._cfg.validation_ds)}\"\n )\n\n if 'test_ds' in self._cfg and self._cfg.test_ds is not None:\n logging.warning(\n f\"Please call the ModelPT.setup_test_data() or ModelPT.setup_multiple_test_data() method \"\n f\"and provide a valid configuration file to setup the test data loader(s).\\n\"\n f\"Test config : \\n{OmegaConf.to_yaml(self._cfg.test_ds)}\"\n )\n\n # ModelPT wrappers over subclass implementations\n self.training_step = model_utils.wrap_training_step(self.training_step)\n\n def register_artifact(self, config_path: str, src: str):\n \"\"\"\n Register model artifacts with this function. These artifacts (files) will be included inside .nemo file\n when model.save_to(\"mymodel.nemo\") is called.\n\n WARNING: If you specified /example_folder/example.txt but ./example.txt exists, then ./example.txt will be used.\n\n Args:\n config_path: config path where artifact is used\n src: path to the artifact\n\n Returns:\n path to be used when accessing artifact. If src='' or None then '' or None will be returned\n \"\"\"\n if not hasattr(self, 'artifacts'):\n self.artifacts = {}\n if self.artifacts is None:\n self.artifacts = {}\n if src is not None and src.strip() != '':\n archive_item = model_utils.ArtifactItem()\n\n basename_src = os.path.basename(src)\n # filename exists in current workdir - use it and raise warning\n # this case is during model restoration or when file is written to cwd.\n if os.path.exists(basename_src):\n logging.warning(f\"Using {os.path.abspath(basename_src)} instead of {src}.\")\n used_src = basename_src\n\n # Case: register_artifact() called inside restoration context\n if self._is_model_being_restored() and self._is_restore_type_tarfile():\n archive_item.path_type = model_utils.ArtifactPathType.TAR_PATH\n else:\n archive_item.path_type = model_utils.ArtifactPathType.LOCAL_PATH\n\n else:\n used_src = src\n archive_item.path_type = model_utils.ArtifactPathType.LOCAL_PATH\n\n if not os.path.exists(used_src):\n # File not found in local path or by basename\n # Try to locate it inside the .nemo archive (if model was restored)\n # Case: register_artifact() called outside restoration context\n if self._is_restore_type_tarfile():\n # Get path where the command is executed - the artifacts will be \"retrieved\" there\n # (original .nemo behavior)\n cwd = os.getcwd()\n try:\n # Step into the nemo archive to try and find the file\n with tempfile.TemporaryDirectory() as tmpdir:\n self.__unpack_nemo_file(path2file=_MODEL_RESTORE_PATH, out_folder=tmpdir)\n os.chdir(tmpdir)\n if os.path.exists(basename_src):\n logging.warning(f\"Using {os.path.abspath(basename_src)} instead of {src}.\")\n used_src = basename_src\n\n archive_item.path = used_src\n archive_item.path_type = model_utils.ArtifactPathType.TAR_PATH\n else:\n # No further action can be taken, file not found anywhere\n raise FileNotFoundError(\n f\"Could not find {used_src} inside \"\n f\"tarfile {_MODEL_RESTORE_PATH} or under local\"\n )\n finally:\n # change back working directory\n os.chdir(cwd)\n else:\n # No further action can be taken, file not found anywhere\n raise FileNotFoundError(f\"Could not find {used_src}\")\n else:\n # Found filepath\n archive_item.path = used_src\n\n # But disregarding whether you use \"local\" or \"remote\" artifact - always store the original path.\n # This fixes issues raising when finetuning NLP models that create and register tokenizer vocabs.\n if config_path in self.artifacts:\n logging.warning(\n f\"Artifact {config_path} with value '{self.artifacts[config_path]}' \"\n f\"already exists and will be overwritten with value '{src}'!\"\n )\n\n self.artifacts[config_path] = archive_item\n return used_src\n else:\n return src\n\n def _default_save_to(self, save_path: str):\n \"\"\"\n Saves model instance (weights and configuration) into .nemo file.\n You can use \"restore_from\" method to fully restore instance from .nemo file.\n\n .nemo file is an archive (tar.gz) with the following:\n model_config.yaml - model configuration in .yaml format. You can deserialize this into cfg argument for model's constructor\n model_wights.chpt - model checkpoint\n\n Args:\n save_path: Path to .nemo file where model instance should be saved\n \"\"\"\n with tempfile.TemporaryDirectory() as tmpdir:\n config_yaml = path.join(tmpdir, _MODEL_CONFIG_YAML)\n model_weights = path.join(tmpdir, _MODEL_WEIGHTS)\n\n if hasattr(self, 'artifacts') and self.artifacts is not None:\n for (conf_path, src) in self.artifacts.items(): # type: (str, model_utils.ArtifactItem)\n try:\n if src.path_type == model_utils.ArtifactPathType.LOCAL_PATH and os.path.exists(src.path):\n shutil.copy2(src.path, tmpdir)\n elif src.path_type == model_utils.ArtifactPathType.TAR_PATH:\n # Need to step into nemo archive to extract file\n # Get path where the command is executed - the artifacts will be \"retrieved\" there\n # (original .nemo behavior)\n cwd = os.getcwd()\n try:\n # Step into the nemo archive to try and find the file\n with tempfile.TemporaryDirectory() as archive_dir:\n self.__unpack_nemo_file(path2file=_MODEL_RESTORE_PATH, out_folder=archive_dir)\n os.chdir(archive_dir)\n shutil.copy2(src.path, tmpdir)\n finally:\n # change back working directory\n os.chdir(cwd)\n else:\n raise ValueError(f\"Invalid ArchivePathType found: {src.path_type}\")\n except Exception:\n logging.error(f\"Could not copy artifact {src} used in {conf_path}\")\n\n self.to_config_file(path2yaml_file=config_yaml)\n torch.save(self.state_dict(), model_weights)\n self.__make_nemo_file_from_folder(filename=save_path, source_dir=tmpdir)\n\n def _eff_save_to(self, save_path: str):\n \"\"\"\n Saves model instance (weights, configuration and artifacts) into an EFF archive using\n the default `save_to` recipe from NeMoCookbook.\n\n .. note::\n For NVIDIA NeMo the EFF archives will also use .nemo postfix.\n\n Method creates an EFF-based file that is an archive (tar.gz) with the following:\n manifest.yaml - yaml file describing the content of the archive.\n model_config.yaml - model configuration in .yaml format.\n You can deserialize this into cfg argument for model's constructor\n model_wights.chpt - model checkpoint\n\n Args:\n save_path: Path to archive file where model instance should be saved.\n \"\"\"\n NeMoCookbook().save_to(obj=self, save_path=save_path)\n\n @rank_zero_only\n def save_to(self, save_path: str):\n \"\"\"\n Saves model instance (weights and configuration) into EFF archive or .\n You can use \"restore_from\" method to fully restore instance from .nemo file.\n\n .nemo file is an archive (tar.gz) with the following:\n model_config.yaml - model configuration in .yaml format. You can deserialize this into cfg argument for model's constructor\n model_wights.chpt - model checkpoint\n\n Args:\n save_path: Path to .nemo file where model instance should be saved\n \"\"\"\n\n # Add nemo rank check as well\n if not is_global_rank_zero():\n return\n\n if _EFF_PRESENT_ and self.use_eff_save():\n # Save EFF archive.\n self._eff_save_to(save_path)\n else:\n # Save .nemo tar archive.\n self._default_save_to(save_path)\n\n @classmethod\n def _default_restore_from(\n cls,\n restore_path: str,\n override_config_path: Optional[Union[OmegaConf, str]] = None,\n map_location: Optional[torch.device] = None,\n strict: bool = False,\n return_config: bool = False,\n ):\n \"\"\"\n Restores model instance (weights and configuration) into .nemo file\n Args:\n restore_path: path to .nemo file from which model should be instantiated\n override_config_path: path to a yaml config that will override the internal\n config file or an OmegaConf / DictConfig object representing the model config.\n map_location: Optional torch.device() to map the instantiated model to a device.\n By default (None), it will select a GPU if available, falling back to CPU otherwise.\n strict: Passed to load_state_dict.\n return_config: If set to true, will return just the underlying config of the restored\n model as an OmegaConf DictConfig object without instantiating the model.\n\n Example:\n ```\n model = nemo.collections.asr.models.EncDecCTCModel.restore_from('asr.nemo')\n assert isinstance(model, nemo.collections.asr.models.EncDecCTCModel)\n ```\n\n Returns:\n An instance of type cls or its underlying config (if return_config is set).\n \"\"\"\n # Get path where the command is executed - the artifacts will be \"retrieved\" there\n # (original .nemo behavior)\n cwd = os.getcwd()\n\n if map_location is None:\n if torch.cuda.is_available():\n map_location = torch.device('cuda')\n else:\n map_location = torch.device('cpu')\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n cls._set_model_restore_state(is_being_restored=True)\n cls.__unpack_nemo_file(path2file=restore_path, out_folder=tmpdir)\n os.chdir(tmpdir)\n if override_config_path is None:\n config_yaml = path.join(tmpdir, _MODEL_CONFIG_YAML)\n else:\n # can be str path or OmegaConf / DictConfig object\n config_yaml = override_config_path\n if not isinstance(config_yaml, (OmegaConf, DictConfig)):\n conf = OmegaConf.load(config_yaml)\n else:\n conf = config_yaml\n if override_config_path is not None:\n # Resolve the override config\n conf = OmegaConf.to_container(conf, resolve=True)\n conf = OmegaConf.create(conf)\n # If override is top level config, extract just `model` from it\n if 'model' in conf:\n conf = conf.model\n\n if return_config:\n instance = conf\n else:\n model_weights = path.join(tmpdir, _MODEL_WEIGHTS)\n OmegaConf.set_struct(conf, True)\n instance = cls.from_config_dict(config=conf)\n instance = instance.to(map_location)\n instance.load_state_dict(torch.load(model_weights, map_location=map_location), strict=strict)\n\n logging.info(f'Model {cls.__name__} was successfully restored from {restore_path}.')\n finally:\n cls._set_model_restore_state(is_being_restored=False)\n os.chdir(cwd)\n\n return instance\n\n @classmethod\n def _eff_restore_from(\n cls,\n restore_path: str,\n override_config_path: Optional[Union[OmegaConf, str]] = None,\n map_location: Optional[torch.device] = None,\n strict: bool = False,\n return_config: bool = False,\n ):\n \"\"\"\n Restores model instance (weights, configuration and artifacts) from EFF Archive using\n the default `restore_from` recipe from NeMoCookbook.\n\n Args:\n restore_path: path to file from which model should be instantiated\n override_config_path: path to a yaml config that will override the internal\n config file\n map_location: Optional torch.device() to map the instantiated model to a device.\n By default (None), it will select a GPU if available, falling back to CPU otherwise.\n strict: Passed to load_state_dict.\n return_config: If set to true, will return just the underlying config of the restored\n model as an OmegaConf DictConfig object without instantiating the model.\n\n Returns:\n An instance of type cls\n \"\"\"\n if return_config is True:\n raise NotImplementedError(\"`return_config` is not implemented for EFF based restoration of models.\")\n\n return NeMoCookbook().restore_from(\n restore_path=restore_path,\n obj_cls=cls,\n override_config_path=override_config_path,\n map_location=map_location,\n strict=strict,\n )\n\n @classmethod\n def restore_from(\n cls,\n restore_path: str,\n override_config_path: Optional[Union[OmegaConf, str]] = None,\n map_location: Optional[torch.device] = None,\n strict: bool = False,\n return_config: bool = False,\n ):\n \"\"\"\n Restores model instance (weights and configuration) from file.\n\n The methods tries to load it as EFF archive.\n If EFF library is not present in the system, or the indicated file is not EFF archive,\n the function defaults to the original .nemo restore method.\n\n Args:\n restore_path: path to .nemo file from which model should be instantiated\n override_config_path: path to a yaml config that will override the internal\n config file or an OmegaConf / DictConfig object representing the model config.\n map_location: Optional torch.device() to map the instantiated model to a device.\n By default (None), it will select a GPU if available, falling back to CPU otherwise.\n strict: Passed to load_state_dict.\n return_config: If set to true, will return just the underlying config of the restored\n model as an OmegaConf DictConfig object without instantiating the model.\n\n Example:\n ```\n model = nemo.collections.asr.models.EncDecCTCModel.restore_from('asr.nemo')\n assert isinstance(model, nemo.collections.asr.models.EncDecCTCModel)\n ```\n\n Returns:\n An instance of type cls or its underlying config (if return_config is set).\n \"\"\"\n if not path.exists(restore_path):\n raise FileNotFoundError(f\"Can't find {restore_path}\")\n\n global _MODEL_RESTORE_PATH\n _MODEL_RESTORE_PATH = os.path.abspath(os.path.expanduser(restore_path))\n\n if _EFF_PRESENT_:\n # Try to load the EFF archive.\n try:\n return cls._eff_restore_from(restore_path, override_config_path, map_location, strict, return_config)\n except (FileNotFoundError, TypeError):\n # Default to the old .nemo tar archive restore method.\n return cls._default_restore_from(\n restore_path, override_config_path, map_location, strict, return_config\n )\n else:\n # Load .nemo tar archive using the old restore method.\n return cls._default_restore_from(restore_path, override_config_path, map_location, strict, return_config)\n\n @classmethod\n def extract_state_dict_from(cls, restore_path: str, save_dir: str, split_by_module: bool = False):\n \"\"\"\n Extract the state dict(s) from a provided .nemo tarfile and save it to a directory.\n Args:\n restore_path: path to .nemo file from which state dict(s) should be extracted\n save_dir: directory in which the saved state dict(s) should be stored\n split_by_module: bool flag, which determins whether the output checkpoint should\n be for the entire Model, or the individual module's that comprise the Model\n\n Example:\n To convert the .nemo tarfile into a single Model level PyTorch checkpoint\n ```\n state_dict = nemo.collections.asr.models.EncDecCTCModel.extract_state_dict_from('asr.nemo', './asr_ckpts)\n ```\n\n To restore a model from a Model level checkpoint\n ```\n model = nemo.collections.asr.models.EncDecCTCModel(cfg) # or any other method of restoration\n model.load_state_dict(torch.load(\"./asr_ckpts/model_weights.ckpt\"))\n ```\n\n To convert the .nemo tarfile into multiple Module level PyTorch checkpoints\n ```\n state_dict = nemo.collections.asr.models.EncDecCTCModel.extract_state_dict_from('asr.nemo', './asr_ckpts,\n split_by_module=True)\n ```\n\n To restore a module from a Module level checkpoint\n ```\n model = model = nemo.collections.asr.models.EncDecCTCModel(cfg) # or any other method of restoration\n\n # load the individual components\n model.preprocessor.load_state_dict(torch.load(\"./asr_ckpts/preprocessor.ckpt\"))\n model.encoder.load_state_dict(torch.load(\"./asr_ckpts/encoder.ckpt\"))\n model.decoder.load_state_dict(torch.load(\"./asr_ckpts/decoder.ckpt\"))\n ```\n\n Returns:\n The state dict that was loaded from the original .nemo checkpoint\n \"\"\"\n if not path.exists(restore_path):\n raise FileExistsError(f\"Can't find {restore_path}\")\n\n cwd = os.getcwd()\n\n save_dir = os.path.abspath(save_dir)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir, exist_ok=True)\n\n with tempfile.TemporaryDirectory() as tmpdir:\n try:\n cls.__unpack_nemo_file(path2file=restore_path, out_folder=tmpdir)\n os.chdir(tmpdir)\n model_weights = path.join(tmpdir, _MODEL_WEIGHTS)\n state_dict = torch.load(model_weights)\n\n if not split_by_module:\n filepath = os.path.join(save_dir, _MODEL_WEIGHTS)\n torch.save(state_dict, filepath)\n\n else:\n key_set = set([key.split(\".\")[0] for key in state_dict.keys()])\n for primary_key in key_set:\n inner_keys = [key for key in state_dict.keys() if key.split(\".\")[0] == primary_key]\n state_dict_subset = {\n \".\".join(inner_key.split(\".\")[1:]): state_dict[inner_key] for inner_key in inner_keys\n }\n filepath = os.path.join(save_dir, f\"{primary_key}.ckpt\")\n torch.save(state_dict_subset, filepath)\n\n logging.info(f'Checkpoints from {restore_path} were successfully extracted into {save_dir}.')\n finally:\n os.chdir(cwd)\n\n return state_dict\n\n @classmethod\n def load_from_checkpoint(\n cls,\n checkpoint_path: str,\n *args,\n map_location: Optional[Union[Dict[str, str], str, torch.device, int, Callable]] = None,\n hparams_file: Optional[str] = None,\n strict: bool = True,\n **kwargs,\n ):\n \"\"\"\n Loads ModelPT from checkpoint, with some maintenance of restoration.\n For documentation, please refer to LightningModule.load_from_checkpoin() documentation.\n \"\"\"\n checkpoint = None\n try:\n cls._set_model_restore_state(is_being_restored=True)\n\n checkpoint = super().load_from_checkpoint(\n checkpoint_path=checkpoint_path,\n *args,\n map_location=map_location,\n hparams_file=hparams_file,\n strict=strict,\n **kwargs,\n )\n\n finally:\n cls._set_model_restore_state(is_being_restored=False)\n return checkpoint\n\n @abstractmethod\n def setup_training_data(self, train_data_config: Union[DictConfig, Dict]):\n \"\"\"\n Setups data loader to be used in training\n\n Args:\n train_data_layer_config: training data layer parameters.\n Returns:\n\n \"\"\"\n pass\n\n @abstractmethod\n def setup_validation_data(self, val_data_config: Union[DictConfig, Dict]):\n \"\"\"\n Setups data loader to be used in validation\n Args:\n\n val_data_layer_config: validation data layer parameters.\n Returns:\n\n \"\"\"\n pass\n\n def setup_test_data(self, test_data_config: Union[DictConfig, Dict]):\n \"\"\"\n (Optionally) Setups data loader to be used in test\n\n Args:\n test_data_layer_config: test data layer parameters.\n Returns:\n\n \"\"\"\n raise NotImplementedError()\n\n def setup_multiple_validation_data(self, val_data_config: Union[DictConfig, Dict]):\n \"\"\"\n (Optionally) Setups data loader to be used in validation, with support for multiple data loaders.\n\n Args:\n val_data_layer_config: validation data layer parameters.\n \"\"\"\n # Set some placeholder overriden by helper method\n self._val_dl_idx = 0\n self._validation_names = None\n self._validation_dl = None # type: torch.utils.data.DataLoader\n\n # preserve config\n self._update_dataset_config(dataset_name='validation', config=val_data_config)\n\n try:\n self._multi_dataset_mode = True\n model_utils.resolve_validation_dataloaders(model=self)\n finally:\n self._multi_dataset_mode = False\n\n if self._validation_names is None:\n if self._validation_dl is not None and type(self._validation_dl) in [list, tuple]:\n self._validation_names = ['val_{}_'.format(idx) for idx in range(len(self._validation_dl))]\n\n def setup_multiple_test_data(self, test_data_config: Union[DictConfig, Dict]):\n \"\"\"\n (Optionally) Setups data loader to be used in test, with support for multiple data loaders.\n\n Args:\n test_data_layer_config: test data layer parameters.\n \"\"\"\n # Set some placeholder overriden by helper method\n self._test_dl_idx = 0\n self._test_names = None\n self._test_dl = None # type: torch.utils.data.DataLoader\n\n # preserve config\n self._update_dataset_config(dataset_name='test', config=test_data_config)\n\n try:\n self._multi_dataset_mode = True\n model_utils.resolve_test_dataloaders(model=self)\n finally:\n self._multi_dataset_mode = False\n\n if self._test_names is None:\n if self._test_dl is not None and type(self._test_dl) in [list, tuple]:\n self._test_names = ['test_{}_'.format(idx) for idx in range(len(self._test_dl))]\n\n def setup_optimization(self, optim_config: Optional[Union[DictConfig, Dict]] = None):\n \"\"\"\n Prepares an optimizer from a string name and its optional config parameters.\n\n Args:\n optim_config: A dictionary containing the following keys:\n\n * \"lr\": mandatory key for learning rate. Will raise ValueError if not provided.\n * \"optimizer\": string name pointing to one of the available optimizers in the registry. \\\n If not provided, defaults to \"adam\".\n * \"opt_args\": Optional list of strings, in the format \"arg_name=arg_value\". \\\n The list of \"arg_value\" will be parsed and a dictionary of optimizer kwargs \\\n will be built and supplied to instantiate the optimizer.\n \"\"\"\n # If config was not explicitly passed to us\n if optim_config is None:\n # See if internal config has `optim` namespace\n if self._cfg is not None and hasattr(self._cfg, 'optim'):\n optim_config = self._cfg.optim\n\n # If config is still None, or internal config has no Optim, return without instantiation\n if optim_config is None:\n logging.info('No optimizer config provided, therefore no optimizer was created')\n return\n\n else:\n # Preserve the configuration\n if not isinstance(optim_config, DictConfig):\n optim_config = OmegaConf.create(optim_config)\n\n # See if internal config has `optim` namespace before preservation\n if self._cfg is not None and hasattr(self._cfg, 'optim'):\n if self._cfg.optim is None:\n self._cfg.optim = copy.deepcopy(optim_config)\n else:\n with open_dict(self._cfg.optim):\n self._cfg.optim = copy.deepcopy(optim_config)\n\n # Setup optimizer and scheduler\n if optim_config is not None and isinstance(optim_config, DictConfig):\n optim_config = OmegaConf.to_container(optim_config, resolve=True)\n\n if 'sched' in optim_config and self._trainer is not None:\n if not isinstance(self._trainer.accumulate_grad_batches, int):\n raise ValueError(\"We do not currently support gradient acculumation that is not an integer.\")\n if self._trainer.max_steps is None:\n # Store information needed to calculate max_steps\n optim_config['sched']['t_max_epochs'] = self._trainer.max_epochs\n optim_config['sched']['t_accumulate_grad_batches'] = self._trainer.accumulate_grad_batches\n optim_config['sched']['t_limit_train_batches'] = self._trainer.limit_train_batches\n if self._trainer.distributed_backend is None:\n optim_config['sched']['t_num_workers'] = self._trainer.num_gpus or 1\n elif self._trainer.distributed_backend == \"ddp_cpu\":\n optim_config['sched']['t_num_workers'] = self._trainer.num_processes * self._trainer.num_nodes\n elif self._trainer.distributed_backend == \"ddp\":\n optim_config['sched']['t_num_workers'] = self._trainer.num_gpus * self._trainer.num_nodes\n else:\n logging.warning(\n f\"The lightning trainer received accelerator: {self._trainer.distributed_backend}. We \"\n \"recommend to use 'ddp' instead.\"\n )\n optim_config['sched']['t_num_workers'] = self._trainer.num_gpus * self._trainer.num_nodes\n else:\n optim_config['sched']['max_steps'] = self._trainer.max_steps\n\n # Force into DictConfig from nested structure\n optim_config = OmegaConf.create(optim_config)\n # Get back nested dict so we its mutable\n optim_config = OmegaConf.to_container(optim_config, resolve=True)\n\n # Extract scheduler config if inside optimizer config\n if 'sched' in optim_config:\n scheduler_config = optim_config.pop('sched')\n else:\n scheduler_config = None\n\n # Check if caller provided optimizer name, default to Adam otherwise\n optimizer_cls = optim_config.get('_target_', None)\n\n if optimizer_cls is None:\n # Try to get optimizer name for dynamic resolution, defaulting to Adam\n optimizer_name = optim_config.get('name', 'adam')\n else:\n if inspect.isclass(optimizer_cls):\n optimizer_name = optimizer_cls.__name__.lower()\n else:\n # resolve the class name (lowercase) from the class path if not provided\n optimizer_name = optimizer_cls.split(\".\")[-1].lower()\n\n # We are guarenteed to have lr since it is required by the argparser\n # But maybe user forgot to pass it to this function\n lr = optim_config.get('lr', None)\n\n # Check if caller has optimizer kwargs, default to empty dictionary\n if 'args' in optim_config:\n optimizer_args = optim_config.pop('args')\n optimizer_args = optim.parse_optimizer_args(optimizer_name, optimizer_args)\n else:\n optimizer_args = copy.deepcopy(optim_config)\n\n # Remove extra parameters from optimizer_args nest\n # Assume all other parameters are to be passed into optimizer constructor\n optimizer_args.pop('name', None)\n optimizer_args.pop('cls', None)\n optimizer_args.pop('lr', None)\n\n # Adaptive schedulers don't need `lr`\n if lr is not None:\n optimizer_args['lr'] = lr\n\n # Actually instantiate the optimizer\n if optimizer_cls is not None:\n if inspect.isclass(optimizer_cls):\n optimizer = optimizer_cls(self.parameters(), **optimizer_args)\n logging.info(\"Optimizer config = %s\", str(optimizer))\n\n self._optimizer = optimizer\n\n else:\n # Attempt class path resolution\n try:\n optimizer_cls = OmegaConf.create({'_target_': optimizer_cls})\n if lr is not None:\n optimizer_config = {'lr': lr}\n else:\n optimizer_config = {}\n optimizer_config.update(optimizer_args)\n\n optimizer_instance = hydra.utils.instantiate(\n optimizer_cls, self.parameters(), **optimizer_config\n ) # type: DictConfig\n\n logging.info(\"Optimizer config = %s\", str(optimizer_instance))\n\n self._optimizer = optimizer_instance\n\n except Exception as e:\n logging.error(\n \"Could not instantiate class path - {} with kwargs {}\".format(\n optimizer_cls, str(optimizer_config)\n )\n )\n raise e\n\n else:\n optimizer = optim.get_optimizer(optimizer_name)\n optimizer = optimizer(self.parameters(), **optimizer_args)\n\n logging.info(\"Optimizer config = %s\", str(optimizer))\n\n self._optimizer = optimizer\n\n # Try to instantiate scheduler for optimizer\n self._scheduler = prepare_lr_scheduler(\n optimizer=self._optimizer, scheduler_config=scheduler_config, train_dataloader=self._train_dl\n )\n\n # Return the optimizer with/without scheduler\n # This return allows multiple optimizers or schedulers to be created\n return self._optimizer, self._scheduler\n\n def configure_optimizers(self):\n self.setup_optimization()\n\n if self._scheduler is None:\n return self._optimizer\n else:\n return [self._optimizer], [self._scheduler]\n\n def train_dataloader(self):\n if self._train_dl is not None:\n return self._train_dl\n\n def val_dataloader(self):\n if self._validation_dl is not None:\n return self._validation_dl\n\n def test_dataloader(self):\n if self._test_dl is not None:\n return self._test_dl\n\n def validation_epoch_end(\n self, outputs: Union[List[Dict[str, torch.Tensor]], List[List[Dict[str, torch.Tensor]]]]\n ) -> Optional[Dict[str, Dict[str, torch.Tensor]]]:\n \"\"\"\n Default DataLoader for Validation set which automatically supports multiple data loaders\n via `multi_validation_epoch_end`.\n\n If multi dataset support is not required, override this method entirely in base class.\n In such a case, there is no need to implement `multi_validation_epoch_end` either.\n\n .. note::\n If more than one data loader exists, and they all provide `val_loss`,\n only the `val_loss` of the first data loader will be used by default.\n This default can be changed by passing the special key `val_dl_idx: int`\n inside the `validation_ds` config.\n\n Args:\n outputs: Single or nested list of tensor outputs from one or more data loaders.\n\n Returns:\n A dictionary containing the union of all items from individual data_loaders,\n along with merged logs from all data loaders.\n \"\"\"\n # Case where we dont provide data loaders\n if outputs is not None and len(outputs) == 0:\n return {}\n\n # Case where we provide exactly 1 data loader\n if type(outputs[0]) == dict:\n output_dict = self.multi_validation_epoch_end(outputs, dataloader_idx=0)\n\n if output_dict is not None and 'log' in output_dict:\n self.log_dict(output_dict.pop('log'), on_epoch=True)\n\n return output_dict\n\n else: # Case where we provide more than 1 data loader\n output_dict = {'log': {}}\n\n # The output is a list of list of dicts, outer list corresponds to dataloader idx\n for dataloader_idx, val_outputs in enumerate(outputs):\n # Get prefix and dispatch call to multi epoch end\n dataloader_prefix = self.get_validation_dataloader_prefix(dataloader_idx)\n dataloader_logs = self.multi_validation_epoch_end(val_outputs, dataloader_idx=dataloader_idx)\n\n # If result was not provided, generate empty dict\n dataloader_logs = dataloader_logs or {}\n\n # Perform `val_loss` resolution first (if provided outside logs)\n if 'val_loss' in dataloader_logs:\n if 'val_loss' not in output_dict and dataloader_idx == self._val_dl_idx:\n output_dict['val_loss'] = dataloader_logs['val_loss']\n\n # For every item in the result dictionary\n for k, v in dataloader_logs.items():\n # If the key is `log`\n if k == 'log':\n # Parse every element of the log, and attach the prefix name of the data loader\n log_dict = {}\n\n for k_log, v_log in v.items():\n # If we are logging the metric, but dont provide it at result level,\n # store it twice - once in log and once in result level.\n # Also mark log with prefix name to avoid log level clash with other data loaders\n if k_log not in output_dict['log'] and dataloader_idx == self._val_dl_idx:\n new_k_log = k_log\n\n # Also insert duplicate key with prefix for ease of comparison / avoid name clash\n log_dict[dataloader_prefix + k_log] = v_log\n\n else:\n # Simply prepend prefix to key and save\n new_k_log = dataloader_prefix + k_log\n\n # Store log value\n log_dict[new_k_log] = v_log\n\n # Update log storage of individual data loader\n output_logs = output_dict['log']\n output_logs.update(log_dict)\n\n # Update global log storage\n output_dict['log'] = output_logs\n\n else:\n # If any values are stored outside 'log', simply prefix name and store\n new_k = dataloader_prefix + k\n output_dict[new_k] = v\n\n if 'log' in output_dict:\n self.log_dict(output_dict.pop('log'), on_epoch=True)\n\n # return everything else\n return output_dict\n\n def test_epoch_end(\n self, outputs: Union[List[Dict[str, torch.Tensor]], List[List[Dict[str, torch.Tensor]]]]\n ) -> Optional[Dict[str, Dict[str, torch.Tensor]]]:\n \"\"\"\n Default DataLoader for Test set which automatically supports multiple data loaders\n via `multi_test_epoch_end`.\n\n If multi dataset support is not required, override this method entirely in base class.\n In such a case, there is no need to implement `multi_test_epoch_end` either.\n\n .. note::\n If more than one data loader exists, and they all provide `test_loss`,\n only the `test_loss` of the first data loader will be used by default.\n This default can be changed by passing the special key `test_dl_idx: int`\n inside the `test_ds` config.\n\n Args:\n outputs: Single or nested list of tensor outputs from one or more data loaders.\n\n Returns:\n A dictionary containing the union of all items from individual data_loaders,\n along with merged logs from all data loaders.\n \"\"\"\n # Case where we dont provide data loaders\n if outputs is not None and len(outputs) == 0:\n return {}\n\n # Case where we provide exactly 1 data loader\n if type(outputs[0]) == dict:\n output_dict = self.multi_test_epoch_end(outputs, dataloader_idx=0)\n\n if output_dict is not None and 'log' in output_dict:\n self.log_dict(output_dict.pop('log'), on_epoch=True)\n\n return output_dict\n\n else: # Case where we provide more than 1 data loader\n output_dict = {'log': {}}\n\n # The output is a list of list of dicts, outer list corresponds to dataloader idx\n for dataloader_idx, test_outputs in enumerate(outputs):\n # Get prefix and dispatch call to multi epoch end\n dataloader_prefix = self.get_test_dataloader_prefix(dataloader_idx)\n dataloader_logs = self.multi_test_epoch_end(test_outputs, dataloader_idx=dataloader_idx)\n\n # If result was not provided, generate empty dict\n dataloader_logs = dataloader_logs or {}\n\n # Perform `test_loss` resolution first (if provided outside logs)\n if 'test_loss' in dataloader_logs:\n if 'test_loss' not in output_dict and dataloader_idx == self._test_dl_idx:\n output_dict['test_loss'] = dataloader_logs['test_loss']\n\n # For every item in the result dictionary\n for k, v in dataloader_logs.items():\n # If the key is `log`\n if k == 'log':\n # Parse every element of the log, and attach the prefix name of the data loader\n log_dict = {}\n for k_log, v_log in v.items():\n # If we are logging the loss, but dont provide it at result level,\n # store it twice - once in log and once in result level.\n # Also mark log with prefix name to avoid log level clash with other data loaders\n if k_log not in output_dict['log'] and dataloader_idx == self._test_dl_idx:\n new_k_log = k_log\n\n # Also insert duplicate key with prefix for ease of comparison / avoid name clash\n log_dict[dataloader_prefix + k_log] = v_log\n\n else:\n # Simply prepend prefix to key and save\n new_k_log = dataloader_prefix + k_log\n\n log_dict[new_k_log] = v_log\n\n # Update log storage of individual data loader\n output_logs = output_dict.get('log', {})\n output_logs.update(log_dict)\n\n # Update global log storage\n output_dict['log'] = output_logs\n\n else:\n # If any values are stored outside 'log', simply prefix name and store\n new_k = dataloader_prefix + k\n output_dict[new_k] = v\n\n if 'log' in output_dict:\n self.log_dict(output_dict.pop('log'), on_epoch=True)\n\n # return everything else\n return output_dict\n\n def multi_validation_epoch_end(\n self, outputs: List[Dict[str, torch.Tensor]], dataloader_idx: int = 0\n ) -> Optional[Dict[str, Dict[str, torch.Tensor]]]:\n logging.warning(\n \"Multi data loader support has been enabled, but \"\n \"`multi_validation_epoch_end(outputs, dataloader_idx) has not been implemented.\\n\"\n \"If you require multi data loader support for validation sets, please override this method.\\n\"\n \"If you do not require multi data loader support, please instead override \"\n \"`validation_epoch_end(outputs).\"\n )\n\n def multi_test_epoch_end(\n self, outputs: List[Dict[str, torch.Tensor]], dataloader_idx: int = 0\n ) -> Optional[Dict[str, Dict[str, torch.Tensor]]]:\n logging.warning(\n \"Multi data loader support has been enabled, but \"\n \"`multi_test_epoch_end(outputs, dataloader_idx) has not been implemented.\\n\"\n \"If you require multi data loader support for validation sets, please override this method.\\n\"\n \"If you do not require multi data loader support, please instead override \"\n \"`test_epoch_end(outputs).\"\n )\n\n def get_validation_dataloader_prefix(self, dataloader_idx: int = 0) -> str:\n \"\"\"\n Get the name of one or more data loaders, which will be prepended to all logs.\n\n Args:\n dataloader_idx: Index of the data loader.\n\n Returns:\n str name of the data loader at index provided.\n \"\"\"\n return self._validation_names[dataloader_idx]\n\n def get_test_dataloader_prefix(self, dataloader_idx: int = 0) -> str:\n \"\"\"\n Get the name of one or more data loaders, which will be prepended to all logs.\n\n Args:\n dataloader_idx: Index of the data loader.\n\n Returns:\n str name of the data loader at index provided.\n \"\"\"\n return self._test_names[dataloader_idx]\n\n def teardown(self, stage: str):\n \"\"\"\n Called at the end of fit and test.\n\n Args:\n stage: either 'fit' or 'test'\n \"\"\"\n if stage == 'fit':\n # Update env variable to bypass multi gpu issue after training\n # This fix affects usage of trainer.test() after trainer.train()\n # If trainer.train() was done on multiple GPUs, then trainer.test()\n # will try to do ddp, even if its a new Trainer object with just 1 GPU.\n # Temporary patch to fix that\n if 'PL_TRAINER_GPUS' in os.environ:\n os.environ.pop('PL_TRAINER_GPUS')\n\n super().teardown(stage)\n\n def prepare_test(self, trainer: 'Trainer') -> bool:\n \"\"\"\n Helper method to check whether the model can safely be tested\n on a dataset after training (or loading a checkpoint).\n\n # Usage:\n trainer = Trainer()\n if model.prepare_test(trainer):\n trainer.test(model)\n\n Returns:\n bool which declares the model safe to test. Provides warnings if it has to\n return False to guide the user.\n \"\"\"\n if not hasattr(self._cfg, 'test_ds'):\n logging.info(\"No `test_ds` config found within the manifest.\")\n return False\n\n # Replace ddp multi-gpu until PTL has a fix\n DDP_WARN = \"\"\"\\n\\nDuring testing, it is currently advisable to construct a new Trainer \"\n \"with single GPU and no DDP to obtain accurate results.\n \"Following pattern should be used: \"\n \"gpu = 1 if cfg.trainer.gpus != 0 else 0\"\n \"trainer = Trainer(gpus=gpu)\"\n \"if model.prepare_test(trainer):\"\n \" trainer.test(model)\\n\\n\"\"\"\n\n if trainer is not None:\n if trainer.num_gpus > 1:\n logging.warning(DDP_WARN)\n return False\n\n # Assign trainer to the model\n self.set_trainer(trainer)\n return True\n\n def set_trainer(self, trainer: Trainer):\n \"\"\"\n Set an instance of Trainer object.\n\n Args:\n trainer: PyTorch Lightning Trainer object.\n \"\"\"\n self._trainer = trainer\n self.set_world_size(self._trainer)\n\n def set_world_size(self, trainer: Trainer):\n \"\"\"\n Determines the world size from the PyTorch Lightning Trainer.\n And then updates AppState.\n\n Args:\n trainer (Trainer): PyTorch Lightning Trainer object\n \"\"\"\n # Update AppState with world information from trainer\n if isinstance(trainer, Trainer):\n app_state = AppState()\n if self._trainer.num_gpus and self._trainer.num_nodes:\n app_state.world_size = self._trainer.num_gpus * self._trainer.num_nodes\n else:\n logging.warning(f'World size can only be set by PyTorch Lightning Trainer.')\n\n def _update_dataset_config(self, dataset_name: str, config: Optional[Union[DictConfig, Dict]]):\n \"\"\"\n Update the config (if not None) of the dataset by given name.\n Preserves said config after updating.\n\n Args:\n dataset_name: str name of the dataset whose config is being updated.\n Can be one of `train`, `validation` and `test`.\n config: Optional DictConfig or dict. If None is passed, this method simply returns.\n If dict is passed, it is cast into a DictConfig.\n The internal config is updated with the passed config.\n \"\"\"\n if hasattr(self, '_multi_dataset_mode') and self._multi_dataset_mode is True:\n return\n\n if config is not None:\n if not isinstance(config, DictConfig):\n config = OmegaConf.create(config)\n\n if dataset_name in ['train', 'validation', 'test']:\n OmegaConf.set_struct(self.cfg, False)\n\n key_name = dataset_name + \"_ds\"\n self.cfg[key_name] = config\n\n OmegaConf.set_struct(self.cfg, True)\n\n # Update hyper parameters by calling property setter\n self.cfg = self._cfg\n else:\n raise ValueError(\"`dataset_name` when updating config must be one of [train, validation, test]\")\n\n @property\n def num_weights(self):\n return sum(p.numel() for p in self.parameters() if p.requires_grad)\n\n @property\n def cfg(self):\n return self._cfg\n\n @cfg.setter\n def cfg(self, cfg):\n self._cfg = cfg\n self._set_hparams(cfg)\n\n @staticmethod\n def __make_nemo_file_from_folder(filename, source_dir):\n with tarfile.open(filename, \"w:gz\") as tar:\n # tar.add(source_dir, arcname=path.basename(source_dir))\n tar.add(source_dir, arcname=\"./\")\n\n @staticmethod\n def __unpack_nemo_file(path2file: str, out_folder: str) -> str:\n if not path.exists(path2file):\n raise FileNotFoundError(f\"{path2file} does not exist\")\n tar = tarfile.open(path2file, \"r:gz\")\n tar.extractall(path=out_folder)\n tar.close()\n return out_folder\n\n @staticmethod\n def _is_model_being_restored() -> bool:\n global _MODEL_IS_RESTORED\n return _MODEL_IS_RESTORED\n\n @staticmethod\n def _set_model_restore_state(is_being_restored: bool):\n global _MODEL_IS_RESTORED\n _MODEL_IS_RESTORED = is_being_restored\n\n @staticmethod\n def _is_restore_type_tarfile() -> bool:\n \"\"\"\n Utility method that checks if the restore path of the underlying Model\n is a tarfile (can be any valid archive)._MODEL_EFF_SAVE\n \"\"\"\n global _MODEL_RESTORE_PATH\n\n if _MODEL_RESTORE_PATH is None:\n return False\n else:\n if tarfile.is_tarfile(_MODEL_RESTORE_PATH):\n return True\n else:\n return False\n\n @staticmethod\n def set_eff_save(use_eff_save: bool):\n global _MODEL_EFF_SAVE\n _MODEL_EFF_SAVE = use_eff_save\n\n @staticmethod\n def use_eff_save() -> bool:\n global _MODEL_EFF_SAVE\n return _MODEL_EFF_SAVE\n"
] |
[
[
"torch.load",
"torch.cuda.current_device",
"torch.cuda.is_available",
"torch.device",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
stevengt/whatwhy
|
[
"bf6f87fd20eebfc89240835c3121ec3079632133"
] |
[
"whatwhy/data_analysis/whatwhy_predictor.py"
] |
[
"import os\nimport pickle\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom .seq2seq_model import Seq2SeqModel\nfrom .vectorizer import TokenVectorizer\n\nclass WhatWhyPredictor():\n \"\"\"\n Predicts a sequence of text which answers the question 'why?' given some input 'what'.\n \n The prediction model is trained by vectorizing lists of token sequences and passing\n the results to a Seq2SeqModel and calling its fit() method. After training, the\n predict() methods can be used to predict 'why' text from 'what' text.\n\n The Seq2SeqModel, vectorizers, and vectorized data sets can be specified manually\n or saved and loaded from files using the save/load methods.\n \"\"\"\n\n def __init__( self, word2vec_model=None,\n max_num_tokens_per_sample=10,\n vocab_index=None ):\n \"\"\"\n Creates a WhatWhyPredictor instance using the specified parameters.\n If no parameters are specified, then they should be loaded from\n a file using the load() methods.\n\n Params:\n word2vec_model : [Optional] A pre-trained gensim Word2Vec model.\n max_num_tokens_per_sample : [Optional] Maximum number of tokens to include in a sample sequence.\n Any extra tokens will be truncated.\n vocab_index : [Optional] A pre-built VocabularyIndex of the data set. This can\n help reduce the size of one-hot encoded words in the\n vocabulary, compared to that of pre-trained word2vec models.\n \"\"\"\n\n self.word2vec_model = word2vec_model\n self.max_num_tokens_per_sample = max_num_tokens_per_sample\n self.vocab_index = vocab_index\n\n self.what_token_vectorizer = None\n self.why_token_vectorizer = None\n \n self.X_train = None\n self.X_test = None\n self.Y_train = None\n self.Y_test = None\n self.indeces_train = None\n self.indeces_test = None\n\n # If word2vec_model is None, then the decoder should be loaded from a pickle file instead.\n if word2vec_model is not None:\n self.decoder = TokenVectorizer( word2vec_model=word2vec_model,\n num_tokens_per_sample=self.max_num_tokens_per_sample,\n vocab_index=self.vocab_index )\n\n @staticmethod\n def load_from_pickle_file(dir_name):\n \"\"\"\n Loads a WhatWhyPredictor instance from a pickle\n file 'whatwhy_predictor.p' in the specified directory.\n \"\"\"\n with open( os.path.join(dir_name, \"whatwhy_predictor.p\") , \"rb\" ) as in_file:\n return pickle.load(in_file)\n\n def fit_tokens( self, lists_of_what_tokens=None,\n lists_of_why_tokens=None,\n epochs=1,\n batch_size=None ):\n \"\"\"Trains a Seq2SeqModel on lists that contain sequences (lists) of 'what' and 'why' tokens.\"\"\"\n\n X_train, X_test, Y_train, Y_test, indeces_train, indeces_test = self.get_train_and_test_data( lists_of_what_tokens=lists_of_what_tokens,\n lists_of_why_tokens=lists_of_why_tokens )\n self.seq2seq_model = Seq2SeqModel(X_train, X_test, Y_train, Y_test)\n self.seq2seq_model.fit(epochs=epochs, batch_size=batch_size)\n\n def predict(self, list_of_what_tokens):\n \"\"\"\n Predicts a string of 'why' text from an input sequence of 'what' tokens.\n \n The following instance fields should be initialized or loaded before calling this method.\n word2vec_model\n max_num_tokens_per_sample \n seq2seq_model\n decoder\n \"\"\"\n lists_of_what_tokens = [list_of_what_tokens]\n return self.predict_all(lists_of_what_tokens)[0]\n\n def predict_all(self, lists_of_what_tokens):\n \"\"\"\n Predicts strings of 'why' text from input sequences of 'what' tokens.\n \n The following instance fields should be initialized or loaded before calling this method.\n word2vec_model\n max_num_tokens_per_sample \n seq2seq_model\n decoder\n \"\"\"\n embedded_what_tokens = TokenVectorizer( word2vec_model=self.word2vec_model,\n tokens_lists=lists_of_what_tokens,\n num_tokens_per_sample=self.max_num_tokens_per_sample,\n vocab_index=self.vocab_index ).get_embeddings()\n one_hot_predictions = self.seq2seq_model.predict_all(embedded_what_tokens)\n predictions = self.decoder.decode_multiple_one_hot_samples(one_hot_predictions)\n return predictions\n\n def compare_predictions_to_actual(self, input_tokens, predictions, actual_vals):\n for i, prediction in enumerate(predictions):\n print(f\"'What' Input : { ' '.join(input_tokens[i]) }\")\n print(f\"'Why' Actual : { actual_vals[i] }\")\n print(f\"'Why' Predicted : { prediction }\")\n print(\"---------------------------------------------\")\n\n def compare_test_set_to_predictions(self, max_num_examples=None):\n if max_num_examples is None:\n max_num_examples = self.X_test.shape[0]\n X_test = self.X_test[:max_num_examples,:,:]\n Y_test = self.Y_test[:max_num_examples,:,:]\n indeces_test = self.indeces_test[:max_num_examples]\n input_tokens_test = [ self.what_token_vectorizer.tokens_lists[index] for index in indeces_test ]\n actual_vals = self.decoder.decode_multiple_one_hot_samples(Y_test)\n one_hot_predictions = self.seq2seq_model.predict_all(X_test)\n predictions = self.decoder.decode_multiple_one_hot_samples(one_hot_predictions)\n self.compare_predictions_to_actual(input_tokens_test, predictions, actual_vals)\n\n def compare_train_set_to_predictions(self, max_num_examples=None):\n if max_num_examples is None:\n max_num_examples = self.X_train.shape[0]\n X_train = self.X_train[:max_num_examples,:,:]\n Y_train = self.Y_train[:max_num_examples,:,:]\n indeces_train = self.indeces_train[:max_num_examples]\n input_tokens_train = [ self.what_token_vectorizer.tokens_lists[index] for index in indeces_train ]\n actual_vals = self.decoder.decode_multiple_one_hot_samples(Y_train)\n one_hot_predictions = self.seq2seq_model.predict_all(X_train)\n predictions = self.decoder.decode_multiple_one_hot_samples(one_hot_predictions)\n self.compare_predictions_to_actual(input_tokens_train, predictions, actual_vals)\n\n def get_what_and_why_token_vectorizers(self, lists_of_what_tokens=None, lists_of_why_tokens=None):\n \"\"\"\n Returns TokenVectorizers for the lists of what/why token sequences.\n \n The instance fields 'word2vec_model', 'max_num_tokens_per_sample', and\n optionally 'vocab_index' should be initialized before calling this method.\n \"\"\"\n if self.what_token_vectorizer is None or self.why_token_vectorizer is None:\n self.set_what_and_why_token_vectorizers_from_lists(lists_of_what_tokens, lists_of_why_tokens)\n return self.what_token_vectorizer, self.why_token_vectorizer\n\n def set_what_and_why_token_vectorizers_from_lists(self, lists_of_what_tokens, lists_of_why_tokens):\n \"\"\"\n Initializes TokenVectorizers for the lists of what/why token sequences.\n \n The instance fields 'word2vec_model', 'max_num_tokens_per_sample', and\n optionally 'vocab_index' should be initialized before calling this method.\n \"\"\"\n self.what_token_vectorizer = TokenVectorizer( word2vec_model=self.word2vec_model,\n tokens_lists=lists_of_what_tokens,\n num_tokens_per_sample=self.max_num_tokens_per_sample,\n vocab_index=self.vocab_index )\n \n self.why_token_vectorizer = TokenVectorizer( word2vec_model=self.word2vec_model,\n tokens_lists=lists_of_why_tokens,\n num_tokens_per_sample=self.max_num_tokens_per_sample,\n vocab_index=self.vocab_index )\n\n def get_train_and_test_data( self, lists_of_what_tokens=None,\n lists_of_why_tokens=None,\n test_size=0.20,\n random_state=42 ):\n \"\"\"\n Splits a data set of what/why tokens into test and train sets\n if they have not already been separated.\n \"\"\"\n\n if self.X_train is None or self.X_test is None or self.Y_train is None or self.Y_test is None:\n what_token_vectorizer, why_token_vectorizer = self.get_what_and_why_token_vectorizers(lists_of_what_tokens, lists_of_why_tokens)\n embedded_what_tokens = what_token_vectorizer.get_embeddings()\n one_hot_why_tokens = why_token_vectorizer.get_one_hot_encodings()\n indeces = np.arange( len(what_token_vectorizer.tokens_lists) )\n self.X_train, self.X_test, self.Y_train, self.Y_test, self.indeces_train, self.indeces_test = train_test_split( embedded_what_tokens,\n one_hot_why_tokens,\n indeces,\n test_size=test_size,\n random_state=random_state )\n return self.X_train, self.X_test, self.Y_train, self.Y_test, self.indeces_train, self.indeces_test\n\n def save_to_pickle_file(self, dir_name):\n \"\"\"\n Saves the WhatWhyPredictor instance to a pickle\n file 'whatwhy_predictor.p' in the specified directory.\n \"\"\"\n if not os.path.isdir(dir_name):\n os.mkdir(dir_name)\n with open( os.path.join(dir_name, \"whatwhy_predictor.p\") , \"wb\" ) as out_file:\n pickle.dump(self, out_file, protocol=4)\n\n def save_seq2seq_model(self, model_dir):\n \"\"\"\n Saves the underlying tensorflow.keras model's weights to\n a file 'model.h5' in the specified directory.\n \"\"\"\n self.seq2seq_model.save_model(model_dir)\n\n def load_seq2seq_model_from_saved_tf_model(self, model_dir):\n \"\"\"\n Intializes the Seq2SeqModel by loading weights from\n a file 'model.h5' in the specified directory.\n \"\"\"\n X_train, X_test, Y_train, Y_test, indeces_train, indeces_test = self.get_train_and_test_data()\n self.seq2seq_model = Seq2SeqModel(X_train, X_test, Y_train, Y_test).load_from_saved_tf_model(model_dir)\n\n def save_train_and_test_data_to_pickle_files(self, dir_name, lists_of_what_tokens=None, lists_of_why_tokens=None):\n \"\"\"\n Splits a data set of what/why tokens into test and train sets\n if they have not already been separated and saves them in pickle files.\n \"\"\"\n X_train, X_test, Y_train, Y_test, indeces_train, indeces_test = self.get_train_and_test_data( lists_of_what_tokens=lists_of_what_tokens,\n lists_of_why_tokens=lists_of_why_tokens )\n if not os.path.isdir(dir_name):\n os.mkdir(dir_name)\n with open( os.path.join(dir_name, \"X_train.p\") , \"wb\" ) as out_file:\n pickle.dump(X_train, out_file, protocol=4)\n with open( os.path.join(dir_name, \"X_test.p\") , \"wb\" ) as out_file:\n pickle.dump(X_test, out_file, protocol=4)\n with open( os.path.join(dir_name, \"Y_train.p\") , \"wb\" ) as out_file:\n pickle.dump(Y_train, out_file, protocol=4)\n with open( os.path.join(dir_name, \"Y_test.p\") , \"wb\" ) as out_file:\n pickle.dump(Y_test, out_file, protocol=4)\n with open( os.path.join(dir_name, \"indeces_train.p\") , \"wb\" ) as out_file:\n pickle.dump(indeces_train, out_file, protocol=4)\n with open( os.path.join(dir_name, \"indeces_test.p\") , \"wb\" ) as out_file:\n pickle.dump(indeces_test, out_file, protocol=4)\n\n def load_train_and_test_data_from_pickle_files(self, dir_name):\n with open( os.path.join(dir_name, \"X_train.p\") , \"rb\" ) as in_file:\n self.X_train = pickle.load(in_file)\n with open( os.path.join(dir_name, \"X_test.p\") , \"rb\" ) as in_file:\n self.X_test = pickle.load(in_file)\n with open( os.path.join(dir_name, \"Y_train.p\") , \"rb\" ) as in_file:\n self.Y_train = pickle.load(in_file)\n with open( os.path.join(dir_name, \"Y_test.p\") , \"rb\" ) as in_file:\n self.Y_test = pickle.load(in_file)\n with open( os.path.join(dir_name, \"indeces_train.p\") , \"rb\" ) as in_file:\n self.indeces_train = pickle.load(in_file)\n with open( os.path.join(dir_name, \"indeces_test.p\") , \"rb\" ) as in_file:\n self.indeces_test = pickle.load(in_file)\n\n def save_token_vectorizers_to_pickle_files(self, target_dir, lists_of_what_tokens=None, lists_of_why_tokens=None):\n if not os.path.isdir(target_dir):\n os.mkdir(target_dir)\n\n what_token_vectorizer, why_token_vectorizer = self.get_what_and_why_token_vectorizers(lists_of_what_tokens, lists_of_why_tokens)\n\n what_token_vectorizer.get_embeddings()\n why_token_vectorizer.get_one_hot_encodings()\n\n what_token_vectorizer.save_to_pickle_file( os.path.join(target_dir, \"what_tokenizer.p\") )\n why_token_vectorizer.save_to_pickle_file( os.path.join(target_dir, \"why_tokenizer.p\") )\n self.decoder.save_to_pickle_file( os.path.join(target_dir, \"decoder.p\") )\n\n def load_token_vectorizers_from_pickle_files(self, dir_name):\n self.what_token_vectorizer = TokenVectorizer.load_from_pickle_file( os.path.join(dir_name, \"what_tokenizer.p\") )\n self.why_token_vectorizer = TokenVectorizer.load_from_pickle_file( os.path.join(dir_name, \"why_tokenizer.p\") )\n self.decoder = TokenVectorizer.load_from_pickle_file( os.path.join(dir_name, \"decoder.p\") )\n self.word2vec_model = self.decoder.word2vec_model\n self.vocab_index = self.decoder.vocab_index\n self.max_num_tokens_per_sample = self.decoder.num_tokens_per_sample\n"
] |
[
[
"sklearn.model_selection.train_test_split"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhao-tong/DeepFD-pyTorch
|
[
"584c00d5814d6803be45433905a4140a6bd4fd18"
] |
[
"src/models.py"
] |
[
"__author__ = 'Tong Zhao'\n__email__ = '[email protected]'\n\nimport os\nimport sys\nimport copy\nimport torch\nimport random\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Classification(nn.Module):\n def __init__(self, emb_size):\n super(Classification, self).__init__()\n\n self.fc1 = nn.Linear(emb_size, 64)\n self.fc2 = nn.Linear(64, 2)\n\n def init_params(self):\n for param in self.parameters():\n if len(param.size()) == 2:\n nn.init.xavier_uniform_(param)\n else:\n # initialize all bias as zeros\n nn.init.constant_(param, 0.0)\n\n def forward(self, embeds):\n x = F.elu_(self.fc1(embeds))\n x = F.elu_(self.fc2(x))\n logists = torch.log_softmax(x, 1)\n return logists\n\nclass DeepFD(nn.Module):\n def __init__(self, features, feat_size, hidden_size, emb_size):\n super(DeepFD, self).__init__()\n self.features = features\n\n self.fc1 = nn.Linear(feat_size, hidden_size)\n self.fc2 = nn.Linear(hidden_size, emb_size)\n self.fc3 = nn.Linear(emb_size, hidden_size)\n self.fc4 = nn.Linear(hidden_size, feat_size)\n\n def init_params(self):\n for param in self.parameters():\n if len(param.size()) == 2:\n nn.init.xavier_uniform_(param)\n else:\n # initialize all bias as zeros\n nn.init.constant_(param, 0.0)\n\n def forward(self, nodes_batch):\n feats = self.features[nodes_batch]\n x_en = F.relu_(self.fc1(feats))\n embs = F.relu_(self.fc2(x_en))\n x_de = F.relu_(self.fc3(embs))\n recon = F.relu_(self.fc4(x_de))\n return embs, recon\n\nclass Loss_DeepFD():\n def __init__(self, features, graph_simi, device, alpha, beta, gamma):\n self.features = features\n self.graph_simi = graph_simi\n self.device = device\n self.alpha = alpha\n self.beta = beta\n self.gamma = gamma\n self.node_pairs = {}\n self.original_nodes_batch = None\n self.extended_nodes_batch = None\n\n def extend_nodes(self, nodes_batch, training_cps):\n self.original_nodes_batch = copy.deepcopy(nodes_batch)\n self.node_pairs = {}\n self.extended_nodes_batch = set(nodes_batch)\n\n for node in nodes_batch:\n cps = training_cps[node]\n self.node_pairs[node] = cps\n for cp in cps:\n self.extended_nodes_batch.add(cp[1])\n self.extended_nodes_batch = list(self.extended_nodes_batch)\n return self.extended_nodes_batch\n\n def get_loss(self, nodes_batch, embs_batch, recon_batch):\n # calculate loss_simi and loss+recon,\n # loss_reg is included in SGD optimizer as weight_decay\n loss_recon = self.get_loss_recon(nodes_batch, recon_batch)\n loss_simi = self.get_loss_simi(embs_batch)\n loss = loss_recon + self.alpha * loss_simi\n return loss\n\n def get_loss_simi(self, embs_batch):\n node2index = {n:i for i,n in enumerate(self.extended_nodes_batch)}\n simi_feat = []\n simi_embs = []\n for node, cps in self.node_pairs.items():\n for i, j in cps:\n simi_feat.append(torch.FloatTensor([self.graph_simi[i, j]]))\n dis_ij = (embs_batch[node2index[i]] - embs_batch[node2index[j]]) ** 2\n dis_ij = torch.exp(-dis_ij.sum())\n simi_embs.append(dis_ij.view(1))\n simi_feat = torch.cat(simi_feat, 0).to(self.device)\n simi_embs = torch.cat(simi_embs, 0)\n L = simi_feat * ((simi_embs - simi_feat) ** 2)\n return L.mean()\n\n def get_loss_recon(self, nodes_batch, recon_batch):\n feats_batch = self.features[nodes_batch]\n H_batch = (feats_batch * (self.beta - 1)) + 1\n assert feats_batch.size() == recon_batch.size() == H_batch.size()\n L = ((recon_batch - feats_batch) * H_batch) ** 2\n return L.mean()"
] |
[
[
"torch.cat",
"torch.nn.init.constant_",
"torch.log_softmax",
"torch.nn.Linear",
"torch.FloatTensor",
"torch.nn.init.xavier_uniform_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vinay-swamy/clustereval
|
[
"d199cf0f8f232c35602633d8821249e6578d080a"
] |
[
"clustereval/stability.py"
] |
[
"#%%\nimport pandas as pd\nimport numpy as np \nimport glob\nimport os \nimport re\nimport pickle\nfrom multiprocessing import Pool\n\ndef entropy(exp): # both are dfs with two columsn, Barcode,cluster\n # calc H_tot\n entropy = (exp\n .groupby(\"labels\")\n .count()\n .reset_index(drop=True)\n .assign(prop=lambda x: x/exp.shape[0],\n H=lambda x: x['prop'] * np.log(x['prop']))\n ['H'].sum()*-1)\n return entropy\n \n\ndef H_k(ref, exp):\n exp = exp[exp.Barcode.isin(ref['Barcode']) ]\n if exp.shape[0] == 0:\n return 0\n else:\n h_k = entropy(exp)\n return h_k\n\n\ndef calc_stability(tup):\n ref = tup[0]\n meta_df = tup[1]\n exp_df_list = tup[2]\n runname = tup[3]\n # try:\n H_k_scores = np.asarray([\n [H_k(group[1], exp) for exp in exp_df_list] / meta_df['H_tot']\n for group in ref.groupby(\"labels\")\n ]).sum(axis=1)\n H_k_scores = 1 - (H_k_scores / len(exp_df_list))\n clusters = [group[0] for group in ref.groupby(\"labels\")]\n return pd.DataFrame.from_dict({runname: clusters, 'H_k_scores': H_k_scores})\n# %%\n"
] |
[
[
"numpy.log",
"pandas.DataFrame.from_dict"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.